Sample

pyint-c6323bbcfbe1-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines127

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.4360–1; higher is more readable
Mi0.4440–1; higher is more readable
LLOC55Logical lines; fewer is more readable
DeepSeek V4 Pro10.330–20; mean of three runs
GPT-6.1 Sol140–20; mean of three runs
BTTF0.4730–1; higher is more readable

Views

Source code

import re from urllib.parse import urlsplit from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.mail import MailerDoesNotExist, mail_managers, mailers from django.http import HttpResponsePermanentRedirect from django.middleware import MiddlewareMixin from django.urls import is_valid_path from django.utils.http import escape_leading_slashes class CommonMiddleware(MiddlewareMixin): """ "Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a slash, and it is not found in urlpatterns, form a new URL by appending a slash at the end. If this new URL is found in urlpatterns, return an HTTP redirect to this new URL; otherwise process the initial URL as usual. This behavior can be customized by subclassing CommonMiddleware and overriding the response_redirect_class attribute. """ response_redirect_class = HttpResponsePermanentRedirect def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user_agent = request.META.get("HTTP_USER_AGENT") if not (user_agent is not None): pass else: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(user_agent): raise PermissionDenied("Forbidden user agent") # Check for a redirect based on settings.PREPEND_WWW host = request.get_host() if not (settings.PREPEND_WWW and host and not host.startswith("www.")): pass else: # Check if we also need to append a slash so we can do it all # with a single redirect. (This check may be somewhat expensive, # so we only do it if we already know we're sending a redirect, # or in process_response if we get a 404.) if self.should_redirect_with_slash(request): path = self.get_full_path_with_slash(request) else: path = request.get_full_path() return self.response_redirect_class(f"{request.scheme}://www.{host}{path}") def should_redirect_with_slash(self, request): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if not (settings.APPEND_SLASH and not request.path_info.endswith("/")): pass else: urlconf = getattr(request, "urlconf", None) if not is_valid_path(request.path_info, urlconf): match = is_valid_path("%s/" % request.path_info, urlconf) if match: view = match.func return getattr(view, "should_append_slash", True) return False def get_full_path_with_slash(self, request): """ Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is DELETE, POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if not (settings.DEBUG and request.method in ("DELETE", "POST", "PUT", "PATCH")): pass else: raise RuntimeError( "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 " "redirect to the slash URL while maintaining %(method)s data. " "Change your form to point to %(url)s (note the trailing " "slash), or set APPEND_SLASH=False in your Django settings." % { "method": request.method, "url": request.get_host() + new_path, } ) return new_path def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. if not (response.status_code == 404 and self.should_redirect_with_slash(request)): pass else: response = self.response_redirect_class( self.get_full_path_with_slash(request) ) # Add the Content-Length header to non-streaming responses if not # already set. if not (not response.streaming and not response.has_header("Content-Length")): pass else: response.headers["Content-Length"] = str(len(response.content)) return response

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.2930.298−96.7
Source linesThe number of non-empty source lines.127+50.8
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.456−6.683

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.128−3.496
Indentation frequencyHow rapidly indentation changes from line to line.86+2.238
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.86−1.553
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.126.89+1.364
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.89.945+0.647
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.033+0.618
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.89.977−0.146

Intercept 0.07 + feature contributions = -0.258 (log-odds).
Score = sigmoid(-0.258) = 0.436.

Score0.444
Score55
Run 1

The code has clear docstrings and follows a logical middleware structure, which aids understanding. However, readability is significantly harmed by unnatural 'if not (...): pass else:' patterns instead of standard positive conditionals. This inverts logic and forces the reader to work backwards. Some methods have moderate nesting and multiple operations per conditional block, reducing action granularity. The code is reasonably concise but could be shorter with standard conditional form. Reading flow is disrupted by the negated structures and redundant 'pass' statements.

Run 2

The code demonstrates some good practices, like clear docstrings and method separation, but its readability is significantly hampered by unusual `if not (...) else:` patterns used in place of straightforward `if` statements. This inverts the natural control flow and adds unnecessary nesting. Several helper imports (re, urlsplit, mail_managers, mailers) are unused, creating confusion about the module's actual dependencies. The 'action granularity' is generally fine, but the inverted conditionals make the code longer and harder to scan. The `should_redirect_with_slash` method uses a return-inside-if with a fallback return outside, which is clear, but other methods force the reader to mentally invert conditions. Overall, the structure is logical but the stylistic choice to avoid negative conditions backfires, reducing clarity and reading flow.

Run 3

The code uses a highly unidiomatic pattern of inverted conditionals (if not condition: pass else: action) throughout every method, making the logic hard to follow. While the code is well-documented with clear docstrings, the actual implementation obscures intent by forcing readers to mentally invert every condition. Nesting is minimal, and action granularity is reasonable, but the repetitive `if not...pass...else` structure makes the code unnecessarily verbose and disrupts natural reading flow. The top-level organization is clear, and individual operations are understandable, but the pervasive anti-pattern of inverted branching significantly reduces readability. Standard `if condition:` statements would dramatically improve clarity. The imports are unused in the shown snippet, which adds minor clutter. Overall, the code demonstrates clear intent in documentation but poor execution in the actual control flow.

Run 1

Code Structure: Well organized into focused middleware methods, with shared redirect logic extracted into helpers. Nesting: Moderate nesting becomes unnecessarily deeper through repeated negated conditions followed by pass and else branches. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior well, but double negatives obscure otherwise straightforward checks. Code length: Mostly proportionate to its responsibilities, although empty branches and unused imports add clutter. Action granularity: Statements generally perform one action per line; multiline expressions and the error message are formatted clearly. Reading flow: Request handling, redirect decisions, path construction, and response processing follow a logical sequence, but the inverted conditional style repeatedly interrupts natural reading. Direct positive conditions or early returns would substantially improve readability.

Run 2

Code Structure: Well-organized middleware class with focused methods separating request checks, redirect decisions, path construction, and response handling. Nesting: Moderate nesting becomes unnecessarily deeper through repeated inverted conditions and empty pass branches. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior clearly, but double negatives make conditions harder to interpret. Code length: Mostly reasonable, though redundant if/pass/else patterns and unused imports add clutter. Action granularity: Statements generally perform one action per line, with appropriately formatted multiline expressions. Reading flow: Methods follow a logical request-to-response progression, but repeatedly placing the meaningful operation in an else branch interrupts natural reading. Direct positive conditions and early returns would substantially improve readability.

Run 3

Code Structure: Well-organized middleware class with focused methods separating request checks, slash handling, and response processing. Nesting: Moderate nesting, particularly in slash validation; repeated inverted conditions with empty pass branches add unnecessary indentation. Clarity of intent: Descriptive method names, docstrings, and comments explain behavior well, but double negatives obscure otherwise straightforward conditions. Code length: Mostly justified, although redundant pass/else constructs and unused imports add clutter. Action granularity: Statements generally perform one action per line, with readable formatting for longer expressions and error messages. Reading flow: Methods follow a natural request-to-response sequence, but repeated negative checks interrupt the flow and force readers to mentally invert conditions. Direct positive conditions and a few guard clauses would substantially improve readability.