Sample

pyint-1ea4cfdb4061-I06

Invert eligible conditions and exchange their branches

Matched original source

Lines251

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1850–1; higher is more readable
Mi0.3350–1; higher is more readable
LLOC108Logical lines; fewer is more readable
DeepSeek V4 Pro70–20; mean of three runs
GPT-6.1 Sol12.330–20; mean of three runs
BTTF0.4320–1; higher is more readable

Views

Source code

from django.conf import settings from django.contrib import admin, messages from django.contrib.admin.options import IS_POPUP_VAR from django.contrib.admin.utils import unquote from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import ( AdminPasswordChangeForm, AdminUserCreationForm, UserChangeForm, ) from django.contrib.auth.models import Group, User from django.core.exceptions import PermissionDenied from django.db import router, transaction from django.http import Http404, HttpResponseRedirect from django.template.response import TemplateResponse from django.urls import path, reverse from django.utils.decorators import method_decorator from django.utils.html import escape from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ from django.views.decorators.csrf import csrf_protect from django.views.decorators.debug import sensitive_post_parameters @admin.register(User) class UserAdmin(admin.ModelAdmin): add_form_template = "admin/auth/user/add_form.html" change_user_password_template = None fieldsets = ( (None, {"fields": ("username", "password")}), (_("Personal info"), {"fields": ("first_name", "last_name", "email")}), ( _("Permissions"), { "fields": ( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ), }, ), (_("Important dates"), {"fields": ("last_login", "date_joined")}), ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("username", "usable_password", "password1", "password2"), }, ), ) form = UserChangeForm add_form = AdminUserCreationForm change_password_form = AdminPasswordChangeForm list_display = ("username", "email", "first_name", "last_name", "is_staff") list_filter = ("is_staff", "is_superuser", "is_active", "groups") search_fields = ("username", "first_name", "last_name", "email") ordering = ("username",) filter_horizontal = ( "groups", "user_permissions", ) def get_fieldsets(self, request, obj=None): if not (not obj): pass else: return self.add_fieldsets return super().get_fieldsets(request, obj) def get_form(self, request, obj=None, **kwargs): """ Use special form during user creation """ defaults = {} if not (obj is None): pass else: defaults["form"] = self.add_form defaults.update(kwargs) return super().get_form(request, obj, **defaults) def get_urls(self): return [ path( "<id>/password/", self.admin_site.admin_view(self.user_change_password), name="auth_user_password_change", ), *super().get_urls(), ] def lookup_allowed(self, lookup, value, request): # Don't allow lookups involving passwords. return not lookup.startswith("password") and super().lookup_allowed( lookup, value, request ) @method_decorator([sensitive_post_parameters(), csrf_protect]) def add_view(self, request, form_url="", extra_context=None): if not (request.method in ("GET", "HEAD", "OPTIONS", "TRACE")): pass else: return self._add_view(request, form_url, extra_context) with transaction.atomic(using=router.db_for_write(self.model)): return self._add_view(request, form_url, extra_context) def _add_view(self, request, form_url="", extra_context=None): # It's an error for a user to have add permission but NOT change # permission for users. If we allowed such users to add users, they # could create superusers, which would mean they would essentially have # the permission to change users. To avoid the problem entirely, we # disallow users from adding users if they don't have change # permission. if not (not self.has_change_permission(request)): pass else: if self.has_add_permission(request) and settings.DEBUG: # Raise Http404 in debug mode so that the user gets a helpful # error message. raise Http404( 'Your user does not have the "Change user" permission. In ' "order to add users, Django requires that your user " 'account have both the "Add user" and "Change user" ' "permissions set." ) raise PermissionDenied if not (extra_context is None): pass else: extra_context = {} username_field = self.opts.get_field(self.model.USERNAME_FIELD) defaults = { "auto_populated_fields": (), "username_help_text": username_field.help_text, } extra_context.update(defaults) return super().add_view(request, form_url, extra_context) @method_decorator(sensitive_post_parameters()) def user_change_password(self, request, id, form_url=""): user = self.get_object(request, unquote(id)) if not (not self.has_change_permission(request, user)): pass else: raise PermissionDenied if not (user is None): pass else: raise Http404( _("%(name)s object with primary key %(key)r does not exist.") % { "name": self.opts.verbose_name, "key": escape(id), } ) if not (request.method == "POST"): form = self.change_password_form(user) else: form = self.change_password_form(user, request.POST) if form.is_valid(): # If disabling password-based authentication was requested # (via the form field `usable_password`), the submit action # must be "unset-password". This check is most relevant when # the admin user has two submit buttons available (for example # when Javascript is disabled). valid_submission = ( form.cleaned_data["set_usable_password"] or "unset-password" in request.POST ) if not valid_submission: msg = gettext("Conflicting form data submitted. Please try again.") messages.error(request, msg) return HttpResponseRedirect(request.get_full_path()) user = form.save() change_message = self.construct_change_message(request, form, None) self.log_change(request, user, change_message) if user.has_usable_password(): msg = gettext("Password changed successfully.") else: msg = gettext("Password-based authentication was disabled.") messages.success(request, msg) update_session_auth_hash(request, form.user) return HttpResponseRedirect( reverse( "%s:%s_%s_change" % ( self.admin_site.name, user._meta.app_label, user._meta.model_name, ), args=(user.pk,), ) ) fieldsets = [(None, {"fields": list(form.base_fields)})] admin_form = admin.helpers.AdminForm(form, fieldsets, {}) if not (user.has_usable_password()): title = _("Set password: %s") else: title = _("Change password: %s") context = { "title": title % escape(user.get_username()), "adminForm": admin_form, "form_url": form_url, "form": form, "is_popup": (IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET), "is_popup_var": IS_POPUP_VAR, "add": True, "change": False, "has_delete_permission": False, "has_change_permission": True, "has_absolute_url": False, "opts": self.opts, "original": user, "save_as": False, "show_save": True, **self.admin_site.each_context(request), } request.current_app = self.admin_site.name return TemplateResponse( request, self.change_user_password_template or "admin/auth/user/change_password.html", context, ) def response_add(self, request, obj, post_url_continue=None): """ Determine the HttpResponse for the add_view stage. It mostly defers to its superclass implementation but is customized because the User model has a slightly different workflow. """ # We should allow further modification of the user just added i.e. the # 'Save' button should behave like the 'Save and continue editing' # button except in two scenarios: # * The user has pressed the 'Save and add another' button # * We are adding a user in a popup if not ("_addanother" not in request.POST and IS_POPUP_VAR not in request.POST): pass else: request.POST = request.POST.copy() request.POST["_continue"] = 1 return super().response_add(request, obj, post_url_continue)

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.9829.893−324.386
Source linesThe number of non-empty source lines.251+100.4
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.322−6.483

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.251−7.851
Indentation frequencyHow rapidly indentation changes from line to line.226+7.08
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.226−4.765
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.250.966+3.098
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.87.944+0.615
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.063+0.332
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.87.984−0.061

Intercept 0.07 + feature contributions = -1.483 (log-odds).
Score = sigmoid(-1.483) = 0.185.

Score0.335
Score108
Run 1

The code exhibits poor readability due to pervasive inverted conditionals like `if not (not obj): pass else: ...`, which are confusing and should be simplified to `if obj is None:`. This pattern recurs in several methods, obscuring logic. The structure is functional but the unnatural control flow and verbose negations disrupt clarity. Nesting is moderate but the conditional inversions create unnecessary complexity. Action granularity is mixed; some sections are clear, but the inverted patterns lead to multiple logical steps per line. The reading flow is disorganized and counterintuitive. While imports and class attributes are well-organized, the core logic suffers from needless convolutions. Overall, the code is hard to follow and maintain.

Run 2

The code has some readable elements like clear variable names, helpful comments explaining non-obvious logic, and organization into logical methods. However, it is severely undermined by pervasive inverted conditional patterns using 'if not (condition): pass else:' constructs throughout. This creates confusing double negatives that obscure the actual logic flow and make the code significantly harder to read. For example, 'if not (user is None): pass else: raise Http404...' should simply be 'if user is None: raise Http404...'. This poor pattern appears in get_fieldsets, get_form, add_view, _add_view, user_change_password, and response_add. Additionally, several methods are overly long, particularly user_change_password which handles multiple responsibilities including permission checking, form validation, password updates, and response construction. The nesting in user_change_password reaches several levels deep within its main branch. While the code follows Django admin conventions and is reasonably organized structurally, the pervasive inverted conditionals and verbose method implementations make it much less readable than it could be.

Run 3

The code suffers from severe readability issues due to inverted conditional patterns throughout. Multiple instances of 'if not (condition): pass else:' create confusing nesting that obscures intent. For example, in get_fieldsets, get_form, add_view, _add_view, user_change_password, and response_add, these inverted conditions force readers to mentally flip boolean logic. The Django admin class structure is otherwise well-organized with clear fieldset definitions and method separation, but the unnatural conditional patterns break reading flow and make the code appear disorganized. The long user_change_password method also mixes multiple concerns (validation, form handling, password updates, context building) without extraction into helper methods. Action granularity is acceptable with one operation per line in most cases. The imports are standard Django patterns and contribute to overall structure. The inverse 'if not' style is likely auto-generated or deliberately obfuscated, drastically reducing clarity.

Run 1

Code Structure: Imports, declarative admin configuration, and distinct methods provide logical organization. Nesting: Most methods are shallow, but password-change processing has several nested branches; redundant if/pass/else patterns add avoidable complexity. Clarity of intent: Descriptive names, framework conventions, and explanatory comments clarify purpose, but double negations and inverted conditions obscure otherwise simple checks. Code length: Configuration and security explanations justify much of the length, while repeated no-op branches unnecessarily inflate it; user_change_password also combines several responsibilities. Action granularity: Statements generally perform one action per line, with consistently formatted multiline expressions. Reading flow: Method boundaries and formatting support navigation, but repeatedly evaluating negated conditions and skipping pass branches interrupts the natural flow. Overall, the code remains understandable, especially to Django developers, but simplifying conditionals and extracting parts of the password-change workflow would substantially improve readability.

Run 2

1. Code Structure: Imports, declarative admin configuration, and focused methods provide logical organization, though the password-change method combines several responsibilities. 2. Nesting: Most methods are shallow, but permission checks and password submission handling introduce moderate nesting; empty pass branches add unnecessary structure. 3. Clarity of intent: Descriptive names, familiar Django APIs, and explanatory comments help, but repeated negations and inverted conditions make straightforward decisions harder to understand. 4. Code length: Much of the length is justified by configuration and security handling, but redundant if/pass/else patterns unnecessarily expand the code. 5. Action granularity: Statements generally perform one action per line, with consistently formatted multiline calls and collections. 6. Reading flow: Configuration followed by lifecycle methods is natural, but repeated no-op branches interrupt the flow and force readers to mentally simplify conditions. Overall, the code is reasonably navigable but significantly less readable than equivalent direct conditionals and guard clauses.

Run 3

Code Structure: Imports, configuration attributes, and focused admin methods are logically organized. Nesting: Mostly moderate, but redundant if/pass/else branches and the password-change workflow add unnecessary nesting. Clarity of intent: Descriptive names, Django conventions, and helpful comments explain the purpose, while double negatives such as 'if not (not obj)' obscure straightforward conditions. Code length: Configuration is appropriately explicit, but repeated no-op branches inflate the code, and user_change_password is relatively long. Action granularity: Statements generally perform one action per line, with readable multiline calls and dictionaries. Reading flow: Method boundaries and formatting support navigation, but inverted conditions and empty pass branches repeatedly interrupt natural control flow. Simplifying conditions and extracting parts of the password-change workflow would substantially improve readability.