Sample

pyint-847e92fda508-I11

Split eligible integer literals into pairs of short-named intermediate variables

Matched original source

Lines273

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.060–1; higher is more readable
Mi0.5720–1; higher is more readable
LLOC188Logical lines; fewer is more readable
DeepSeek V4 Pro4.670–20; mean of three runs
GPT-6.1 Sol110–20; mean of three runs
BTTF0.2260–1; higher is more readable

Views

Source code

from __future__ import annotations import hashlib import os import re import threading import time import warnings from base64 import b64encode from typing import TYPE_CHECKING, Any, Final, cast, overload from ._internal_utils import to_native_string from .compat import basestring, str, urlparse from .cookies import extract_cookies_to_jar from .utils import parse_dict_header class HTTPDigestAuth(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" username: bytes | str password: bytes | str _thread_local: threading.local last_nonce: str nonce_count: int chal: dict[str, str] pos: int | None num_401_calls: int | None @overload def __init__(self, username: str, password: str) -> None: ... @overload def __init__(self, username: bytes, password: bytes) -> None: ... def __init__(self, username: bytes | str, password: bytes | str) -> None: self.username = username self.password = password # Keep state in per-thread local storage self._thread_local = threading.local() def init_per_thread_state(self) -> None: # Ensure state is initialized just once per-thread if not hasattr(self._thread_local, "init"): self._thread_local.init = True self._thread_local.last_nonce = "" a = 1 b = -1 self._thread_local.nonce_count = (a + b) self._thread_local.chal = {} self._thread_local.pos = None self._thread_local.num_401_calls = None def build_digest_header(self, method: str, url: str) -> str | None: """ :rtype: str """ realm = self._thread_local.chal["realm"] nonce = self._thread_local.chal["nonce"] qop = self._thread_local.chal.get("qop") algorithm = self._thread_local.chal.get("algorithm") opaque = self._thread_local.chal.get("opaque") hash_utf8 = None if algorithm is None: _algorithm = "MD5" else: _algorithm = algorithm.upper() # lambdas assume digest modules are imported at the top level if _algorithm == "MD5" or _algorithm == "MD5-SESS": def md5_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.md5(x, usedforsecurity=False).hexdigest() hash_utf8 = md5_utf8 elif _algorithm == "SHA": def sha_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha1(x, usedforsecurity=False).hexdigest() hash_utf8 = sha_utf8 elif _algorithm == "SHA-256": def sha256_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha256(x, usedforsecurity=False).hexdigest() hash_utf8 = sha256_utf8 elif _algorithm == "SHA-512": def sha512_utf8(x: str | bytes) -> str: if isinstance(x, str): x = x.encode("utf-8") return hashlib.sha512(x, usedforsecurity=False).hexdigest() hash_utf8 = sha512_utf8 if hash_utf8 is None: return None def KD(s: str, d: str) -> str: return hash_utf8(f"{s}:{d}") # XXX not implemented yet entdig = None p_parsed = urlparse(url) #: path is request-uri defined in RFC 2616 which should not be empty path = p_parsed.path or "/" if p_parsed.query: path += f"?{p_parsed.query}" A1 = f"{self.username}:{realm}:{self.password}" A2 = f"{method}:{path}" HA1 = hash_utf8(A1) HA2 = hash_utf8(A2) if nonce == self._thread_local.last_nonce: c = 2 e = -1 self._thread_local.nonce_count += (c + e) else: f = 2 g = -1 self._thread_local.nonce_count = (f + g) ncvalue = f"{self._thread_local.nonce_count:08x}" s = str(self._thread_local.nonce_count).encode("utf-8") s += nonce.encode("utf-8") s += time.ctime().encode("utf-8") h = 4 i = 4 s += os.urandom((h + i)) j = 8 k = 8 cnonce = hashlib.sha1(s, usedforsecurity=False).hexdigest()[:(j + k)] if _algorithm == "MD5-SESS": HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}") # type: ignore[reportConstantRedefinition] # RFC 2617 terminology if not qop: respdig = KD(HA1, f"{nonce}:{HA2}") elif qop == "auth" or "auth" in qop.split(","): noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}" respdig = KD(HA1, noncebit) else: # XXX handle auth-int. return None self._thread_local.last_nonce = nonce # XXX should the partial digests be encoded too? base = ( f'username="{self.username}", realm="{realm}", nonce="{nonce}", ' f'uri="{path}", response="{respdig}"' ) if opaque: base += f', opaque="{opaque}"' if algorithm: base += f', algorithm="{algorithm}"' if entdig: base += f', digest="{entdig}"' if qop: base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"' return f"Digest {base}" def handle_redirect(self, r: Response, **kwargs: Any) -> None: """Reset num_401_calls counter on redirects.""" if r.is_redirect: l = 2 m = -1 self._thread_local.num_401_calls = (l + m) def handle_401(self, r: Response, **kwargs: Any) -> Response: """ Takes the given response and tries digest-auth, if needed. :rtype: requests.Response """ # If response is not 4xx, do not auth # See https://github.com/psf/requests/issues/3772 n = 200 o = 200 p = 250 q = 250 if not (n + o) <= r.status_code < (p + q): t = 2 u = -1 self._thread_local.num_401_calls = (t + u) return r if self._thread_local.pos is not None: # Rewind the file position indicator of the body to where # it was to resend the request. if (seek := getattr(r.request.body, "seek", None)) is not None: seek(self._thread_local.pos) s_auth = r.headers.get("www-authenticate", "") v = 1 w = 1 if "digest" in s_auth.lower() and self._thread_local.num_401_calls < (v + w): y = 2 z = -1 self._thread_local.num_401_calls += (y + z) pat = re.compile(r"digest ", flags=re.IGNORECASE) aa = 2 ab = -1 self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=(aa + ab))) # Consume content and release the original connection # to allow our new request to reuse the same one. r.content r.close() prep = r.request.copy() cookie_jar = cast("CookieJar", prep._cookies) extract_cookies_to_jar(cookie_jar, r.request, r.raw) prep.prepare_cookies(cookie_jar) _digest_auth = self.build_digest_header( cast(str, prep.method), cast(str, prep.url) ) if _digest_auth: prep.headers["Authorization"] = _digest_auth _r = r.connection.send(prep, **kwargs) _r.history.append(r) _r.request = prep return _r ac = 2 ad = -1 self._thread_local.num_401_calls = (ac + ad) return r def __call__(self, r: PreparedRequest) -> PreparedRequest: # Initialize per-thread state, if needed self.init_per_thread_state() # If we have a saved nonce, skip the 401 if self._thread_local.last_nonce: _digest_auth = self.build_digest_header( cast(str, r.method), cast(str, r.url) ) if _digest_auth: r.headers["Authorization"] = _digest_auth if (tell := getattr(r.body, "tell", None)) is not None: self._thread_local.pos = tell() else: # In the case of HTTPDigestAuth being reused and the body of # the previous request was a file-like object, pos has the # file position of the previous body. Ensure it's set to # None. self._thread_local.pos = None r.register_hook("response", self.handle_401) r.register_hook("response", self.handle_redirect) ae = 2 af = -1 self._thread_local.num_401_calls = (ae + af) return r def __eq__(self, other: object) -> bool: return all( [ self.username == getattr(other, "username", None), self.password == getattr(other, "password", None), ] ) def __ne__(self, other: Any) -> bool: return not self == other

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.11335.311−374.065
Source linesThe number of non-empty source lines.273+109.2
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.433−6.649

Intercept 8.87 + feature contributions = -262.644 (log-odds).
Score = sigmoid(-262.644) = 0.

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.273−8.63
Indentation frequencyHow rapidly indentation changes from line to line.247+7.806
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.247−5.247
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.272.87+3.404
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.121.982−1.501
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.122+1.164
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.079+0.178

Intercept 0.07 + feature contributions = -2.755 (log-odds).
Score = sigmoid(-2.755) = 0.06.

Score0.572
Score188
Run 1

The code is poorly readable due to deliberate obfuscation. There are numerous meaningless variable assignments (e.g., 'a = 1', 'b = -1', 'self._thread_local.nonce_count = (a + b)') that obscure simple values like 0 or 1. Magic numbers are wrapped in useless arithmetic operations (e.g., '(n + o)', '(j + k)', '(v + w)'), and repeated patterns for incrementing/decrementing are verbose and confusing. The logical flow is broken by disorganized variable placement, and variable names like 'KD', 's_auth', 'pat', and 'base' lack clarity. Nesting is moderate, but the overall intent is obscured by the excessive noise and intentionally tangled modifications, making the code very hard to follow and maintain.

Run 2

The code suffers from severe readability issues. It uses nonsensical variable names (a, b, h, i, j, k, l, m, n, o, p, q, t, u, v, w, y, z, aa, ab, ac, ad, ae, af) for simple arithmetic operations that obscure the intent (e.g., literally computing 2 + (-1) instead of using 1). The deeply nested conditional logic for digest algorithm selection, repeated local function definitions, and excessive inline comments create confusion. While the class structure and type hints are present, the artificial complexity—like splitting simple increments into multiple variables—makes the code unnecessarily long and hard to follow. Reading flow is disrupted by these obfuscated operations, violating the principles of clear intent and action granularity. The code appears deliberately obfuscated, which would make maintenance and review extremely difficult.

Run 3

This code is severely obfuscated and nearly unreadable. It appears to be intentionally mangled: variable names like 'a', 'b', 'c', 'e' are used for arithmetic operations that simply compute 0 or 1 (e.g., nonce_count = 2 + -1). This obscures intent completely. The code structure is tangled, with dead code (entdig), unnecessary nested functions, and convoluted logic. Reading flow is disrupted by meaningless variables and redundant comments. Action granularity is poor, with multiple operations crammed into expressions. The original logic (digest auth) is barely recognizable under the obfuscation. While the class has type hints and docstrings, they do not compensate for the overall unreadability. The code length is inflated with pointless assignments and arithmetic. Nesting is moderate but the obfuscation makes it feel deeper. Clarity of intent is nearly zero for anyone not reverse-engineering the hidden constants.

Run 1

Code Structure: Methods logically separate initialization, digest construction, response handling, and request setup, but digest construction is oversized. Nesting: Mostly moderate, with early returns limiting depth; nested hash helpers add complexity. Clarity of intent: Descriptive method names, type hints, and comments clarify authentication behavior, but meaningless variables and arithmetic expressions obscure simple constants and counter updates. Code length: Unnecessarily inflated by these temporary variables and repetitive hashing helpers. Action granularity: Generally one action per line, though many lines perform trivial intermediate calculations rather than meaningful actions. Reading flow: The authentication sequence is coherent, but repeated arithmetic detours, terse protocol variables, placeholder comments, and a stale reference to lambdas interrupt comprehension. Overall, the organization is sound, but deliberate-looking verbosity substantially reduces readability.

Run 2

Code Structure: Methods logically separate initialization, digest construction, response handling, and request preparation, although digest construction is lengthy. Nesting: Mostly moderate, with early returns limiting depth; nested hash functions and conditionals add complexity. Clarity of intent: Method names, type annotations, and comments explain authentication behavior, but meaningless variables such as a, b, and aa obscure simple constants and counter updates. Code length: Repeated hashing wrappers and unnecessary arithmetic assignments substantially inflate the code. Action granularity: Most lines perform one action, but straightforward operations are fragmented into distracting multi-line calculations. Reading flow: The authentication sequence is generally coherent, yet frequent arithmetic detours, cryptic intermediate names, stale comments, and long expressions interrupt comprehension. Overall, the underlying organization is readable, but deliberate constant obfuscation significantly reduces clarity and concision.

Run 3

Code Structure: Methods logically separate initialization, digest construction, response handling, and request preparation, although digest construction is lengthy. Nesting: Mostly moderate, with early returns limiting depth; nested hash helpers and authentication branches add complexity. Clarity of intent: Method names, annotations, and comments explain the authentication workflow, but meaningless variables such as a, b, aa, and ab obscure simple constants through unnecessary arithmetic. Code length: Repeated hash implementations and artificial constant calculations substantially inflate the code. Action granularity: Most lines perform one action, making individual operations easy to identify, though many actions are needless intermediates. Reading flow: The overall request/authentication sequence is coherent, but repeated arithmetic detours, terse protocol variables, stale comments, and extensive thread-local access interrupt reading. Overall, the organization is sound, but deliberate-looking numerical obfuscation significantly reduces readability.