Sample

pyint-361115d35406-I05

Rewrite eligible decimal integer literals in hexadecimal notation

Matched original source

Lines170

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1920–1; higher is more readable
Mi0.4250–1; higher is more readable
LLOC78Logical lines; fewer is more readable
DeepSeek V4 Pro14.330–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.420–1; higher is more readable

Views

Source code

from __future__ import annotations import importlib.metadata import typing as t from contextlib import contextmanager from contextlib import ExitStack from copy import copy from types import TracebackType from urllib.parse import urlsplit import werkzeug.test from click.testing import CliRunner from click.testing import Result from werkzeug.test import Client from werkzeug.wrappers import Request as BaseRequest from .cli import ScriptInfo from .sessions import SessionMixin class FlaskClient(Client): """Works like a regular Werkzeug test client, with additional behavior for Flask. Can defer the cleanup of the request context until the end of a ``with`` block. For general information about how to use this class refer to :class:`werkzeug.test.Client`. .. versionchanged:: 0.12 `app.test_client()` includes preset default environment, which can be set after instantiation of the `app.test_client()` object in `client.environ_base`. Basic usage is outlined in the :doc:`/testing` chapter. """ application: Flask def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: super().__init__(*args, **kwargs) self.preserve_context = False self._new_contexts: list[t.ContextManager[t.Any]] = [] self._context_stack = ExitStack() self.environ_base = { "REMOTE_ADDR": "127.0.0.1", "HTTP_USER_AGENT": f"Werkzeug/{_get_werkzeug_version()}", } @contextmanager def session_transaction( self, *args: t.Any, **kwargs: t.Any ) -> t.Iterator[SessionMixin]: """When used in combination with a ``with`` statement this opens a session transaction. This can be used to modify the session that the test client uses. Once the ``with`` block is left the session is stored back. :: with client.session_transaction() as session: session['value'] = 42 Internally this is implemented by going through a temporary test request context and since session handling could depend on request variables this function accepts the same arguments as :meth:`~flask.Flask.test_request_context` which are directly passed through. """ if self._cookies is None: raise TypeError( "Cookies are disabled. Create a client with 'use_cookies=True'." ) app = self.application ctx = app.test_request_context(*args, **kwargs) self._add_cookies_to_wsgi(ctx.request.environ) with ctx: sess = app.session_interface.open_session(app, ctx.request) if sess is None: raise RuntimeError("Session backend did not open a session.") yield sess resp = app.response_class() if app.session_interface.is_null_session(sess): return with ctx: app.session_interface.save_session(app, sess, resp) self._update_cookies_from_response( urlsplit(ctx.request.host_url).hostname or "localhost", ctx.request.path, resp.headers.getlist("Set-Cookie"), ) def _copy_environ(self, other: WSGIEnvironment) -> WSGIEnvironment: out = {**self.environ_base, **other} if self.preserve_context: out["werkzeug.debug.preserve_context"] = self._new_contexts.append return out def _request_from_builder_args( self, args: tuple[t.Any, ...], kwargs: dict[str, t.Any] ) -> BaseRequest: kwargs["environ_base"] = self._copy_environ(kwargs.get("environ_base", {})) builder = EnvironBuilder(self.application, *args, **kwargs) try: return builder.get_request() finally: builder.close() def open( self, *args: t.Any, buffered: bool = False, follow_redirects: bool = False, **kwargs: t.Any, ) -> TestResponse: if args and isinstance( args[0x0], (werkzeug.test.EnvironBuilder, dict, BaseRequest) ): if isinstance(args[0x0], werkzeug.test.EnvironBuilder): builder = copy(args[0x0]) builder.environ_base = self._copy_environ(builder.environ_base or {}) # type: ignore[arg-type] request = builder.get_request() elif isinstance(args[0x0], dict): request = EnvironBuilder.from_environ( args[0x0], app=self.application, environ_base=self._copy_environ({}) ).get_request() else: # isinstance(args[0], BaseRequest) request = copy(args[0x0]) request.environ = self._copy_environ(request.environ) else: # request is None request = self._request_from_builder_args(args, kwargs) # Pop any previously preserved contexts. This prevents contexts # from being preserved across redirects or multiple requests # within a single block. self._context_stack.close() response = super().open( request, buffered=buffered, follow_redirects=follow_redirects, ) response.json_module = self.application.json # type: ignore[assignment] # Re-push contexts that were preserved during the request. for cm in self._new_contexts: self._context_stack.enter_context(cm) self._new_contexts.clear() return response def __enter__(self) -> FlaskClient: if self.preserve_context: raise RuntimeError("Cannot nest client invocations") self.preserve_context = True return self def __exit__( self, exc_type: type | None, exc_value: BaseException | None, tb: TracebackType | None, ) -> None: self.preserve_context = False self._context_stack.close()

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.5435.556−179.373
Source linesThe number of non-empty source lines.170+68
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.522−6.783

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.171−5.018
Indentation frequencyHow rapidly indentation changes from line to line.136+3.967
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.136−2.7
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.169.777+1.963
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.110.977−1.035
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.110.959+0.986
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.063+0.33

Intercept 0.07 + feature contributions = -1.438 (log-odds).
Score = sigmoid(-1.438) = 0.192.

Score0.425
Score78
Run 1

The code is generally well-structured and readable, with clear class and method definitions, good docstrings, and logical organization. It scores positively on structure, clarity of intent, and reading flow. However, some areas reduce readability. Nesting is moderate but acceptable; the `open` method contains an if-elif-else chain that adds complexity. Code length is reasonable for the functionality, though some methods could be shortened. Action granularity is mostly good, but the `open` method mixes multiple actions in conditional branches and contains inline comments and a hex index `args[0x0]` that seems cryptic. The `session_transaction` method is clear but lengthy. Overall, the code is professional and maintainable, but minor issues with conditional complexity and a few non-obvious expressions prevent a higher score.

Run 2

The code is generally well-structured and readable, with clear separation of methods, descriptive naming, and helpful docstrings. The `open` method handles multiple input types with a somewhat verbose conditional chain, but each branch is logically isolated and commented. Nesting is moderate, mostly within context managers and a single if-else chain. Intent is clear throughout, particularly in `session_transaction` and `__enter__`/`__exit__`. Line length is mostly reasonable except for the `_copy_environ` call inside `open`, which is long and includes a type ignore comment. Action granularity is mostly one action per line, though some argument-heavy calls stack multiple parameters. Reading flow is natural, with higher-level methods first and internal helpers grouped logically. A few minor issues like the magic number `0x0` for index zero and the long conditional block slightly reduce readability, but overall the code is maintainable and easy to follow.

Run 3

The code is structured but suffers from complexity and readability issues. It has clear sections and docstrings, but methods like `open` contain multiple nested conditionals and multi-responsibility blocks, reducing clarity. Nesting reaches up to 3 levels, with mixed action granularity; some lines combine multiple logical operations. The intent is mostly clear, especially in commented branches, but the use of magic numbers (args[0x0]) harms readability. The code length is moderate for its functionality, but several methods handle too many edge cases at once, affecting reading flow. Context manager handling is straightforward, yet the loop and context stack manipulation in `open` disrupt natural progression. Overall, it is functional but would benefit from refactoring into smaller helper methods and simplifying conditionals.

Run 1

Code Structure: Well-organized class with focused methods and reusable helpers; request handling and context management are clearly separated. Nesting: Generally shallow, although open() contains a moderately nested type-dispatch branch. Clarity of intent: Descriptive method names, type annotations, docstrings, and lifecycle comments clarify behavior. However, args[0x0] is unnecessarily unusual, some referenced types and helpers are not defined in the snippet, and the 'request is None' comment is misleading. Code length: Mostly proportionate to functionality; detailed documentation adds useful context, though repeated argument indexing and long expressions add minor clutter. Action granularity: Statements generally perform one action per line, with a few chained calls requiring extra parsing. Reading flow: Initialization, session operations, request preparation, and context entry/exit follow a natural progression. Context preservation requires some framework knowledge, but comments explain the key transitions.

Run 2

Code Structure: Well-organized class with focused methods and helper functions separating environment preparation, request construction, and context management. Nesting: Mostly shallow, although open() has a moderately nested type-dispatch block. Clarity of intent: Descriptive method names, type annotations, docstrings, and lifecycle comments explain behavior well. However, hexadecimal indexing (args[0x0]) is distracting, some abbreviated names reduce clarity, and several referenced types and helpers are not defined in the excerpt. Code length: Generally appropriate for the functionality; lengthy docstrings provide useful context rather than unnecessary implementation verbosity. Action granularity: Statements generally perform one action per line, with a few dense chained calls and long argument expressions. Reading flow: Initialization, session handling, request processing, and context-manager methods follow a logical sequence. Context preservation requires careful tracking of state, and comments such as 'request is None' do not accurately describe the visible code.

Run 3

Code Structure: Well-organized class with focused methods separating session management, request construction, and context cleanup. Nesting: Mostly shallow, although open() contains a moderately nested type-dispatch branch. Clarity of intent: Descriptive method names, annotations, docstrings, and lifecycle comments explain most behavior. Repeated args[0x0], abbreviated variables, and names not defined in the snippet reduce immediate clarity. Code length: Generally appropriate for the functionality; documentation is useful, but request-dispatch repetition adds some verbosity. Action granularity: Most lines perform one clear action, with a few chained builder calls and a long assignment requiring extra effort. Reading flow: Methods follow natural setup, execution, and cleanup sequences. Context preservation requires careful tracking, and the misleading 'request is None' comment slightly disrupts understanding.