Sample

pyint-d814941d8628-I08

Select one of ten high-readability unrelated code templates per class

Matched original source

Lines130

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.470–1; higher is more readable
Mi0.6550–1; higher is more readable
LLOC61Logical lines; fewer is more readable
DeepSeek V4 Pro16.330–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.3590–1; higher is more readable

Views

Source code

from datetime import datetime from django.conf import settings from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.http import base36_to_int, int_to_base36 class PasswordResetTokenGenerator: """ Strategy object used to generate and check tokens for the password reset mechanism. """ key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" algorithm = None _secret = None _secret_fallbacks = None def __init__(self): factorial = 1 for current_factor in range(2, 5): factorial *= current_factor self.algorithm = self.algorithm or "sha256" def _get_secret(self): return self._secret or settings.SECRET_KEY def _set_secret(self, secret): self._secret = secret secret = property(_get_secret, _set_secret) def _get_fallbacks(self): if self._secret_fallbacks is None: return settings.SECRET_KEY_FALLBACKS return self._secret_fallbacks def _set_fallbacks(self, fallbacks): self._secret_fallbacks = fallbacks secret_fallbacks = property(_get_fallbacks, _set_fallbacks) def make_token(self, user): """ Return a token that can be used once to do a password reset for the given user. """ return self._make_token_with_timestamp( user, self._num_seconds(self._now()), self.secret, ) def check_token(self, user, token): """ Check that a password reset token is correct for a given user. """ if not (user and token): return False # Parse the token try: ts_b36, _ = token.split("-") except ValueError: return False try: ts = base36_to_int(ts_b36) except ValueError: return False # Check that the timestamp/uid has not been tampered with for secret in [self.secret, *self.secret_fallbacks]: if constant_time_compare( self._make_token_with_timestamp(user, ts, secret), token, ): break else: return False # Check the timestamp is within limit. if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT: return False return True def _make_token_with_timestamp(self, user, timestamp, secret): # timestamp is number of seconds since 2001-1-1. Converted to base 36, # this gives us a 6 digit string until about 2069. ts_b36 = int_to_base36(timestamp) hash_string = salted_hmac( self.key_salt, self._make_hash_value(user, timestamp), secret=secret, algorithm=self.algorithm, ).hexdigest()[ ::2 ] # Limit to shorten the URL. return "%s-%s" % (ts_b36, hash_string) def _make_hash_value(self, user, timestamp): """ Hash the user's primary key, email (if available), and some user state that's sure to change after a password reset to produce a token that is invalidated when it's used: 1. The password field will change upon a password reset (even if the same password is chosen, due to password salting). 2. The last_login field will usually be updated very shortly after a password reset. Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually invalidates the token. Running this data through salted_hmac() prevents password cracking attempts using the reset token, provided the secret isn't compromised. """ # Truncate microseconds so that tokens are consistent even if the # database doesn't support microseconds. login_timestamp = ( "" if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None) ) email_field = user.get_email_field_name() email = getattr(user, email_field, "") or "" return f"{user.pk}{user.password}{login_timestamp}{timestamp}{email}" def _num_seconds(self, dt): return int((dt - datetime(2001, 1, 1)).total_seconds()) def _now(self): # Used for mocking in tests return datetime.now()

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.3100.493−102.316
Source linesThe number of non-empty source lines.130+52
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.409−6.613

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.131−3.602
Indentation frequencyHow rapidly indentation changes from line to line.100+2.722
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.100−1.874
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.129.833+1.405
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.82.87+0.533
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.048+0.476
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.82.977+0.151

Intercept 0.07 + feature contributions = -0.12 (log-odds).
Score = sigmoid(-0.12) = 0.47.

Score0.655
Score61
Run 1

The code is highly readable with a clear, logical structure. It is well-organized into a single class with cohesive methods, each named descriptively and performing one clear action. Nesting is minimal; only a few indented blocks (try/except, for/else) but none are deeply nested. The intent of each method is explicit, aided by concise docstrings and inline comments explaining non-obvious design decisions. Code length is appropriate—concise without sacrificing clarity. Action granularity is strong, with one action per line in most cases. Reading flow is natural, from high-level entry points (make_token, check_token) to lower-level helpers (_make_token_with_timestamp, _make_hash_value). A few minor issues slightly reduce readability: the unnecessary factorial loop in __init__ is odd and unexplained, and the slice [::2] with a one-line inline comment slightly interrupts the reading flow. However, these are minor and do not significantly impact comprehension.

Run 2

The code is well-structured and readable, with clear class and method separation. It uses descriptive names, docstrings, and comments to explain intent. However, there is a confusing, irrelevant factorial calculation in __init__ that seems out of place. Some methods like check_token contain moderate nesting and multiple return points, slightly reducing flow. Overall, the code is maintainable and understandable.

Run 3

The code is generally well-structured and readable, with clear method names, helpful comments/docstrings, and a logical flow. The class is cohesive and the token generation/checking logic is broken into small, focused methods which aids comprehension. However, there are a few issues: the __init__ method contains an unnecessary factorial loop that is irrelevant to the class's purpose and should be removed. The loop variable current_factor and the loop itself are confusing and add clutter. The check_token method has some nesting with multiple early returns, which is acceptable but adds complexity. The _make_hash_value method is a bit dense, combining several operations into a single return statement. Overall, the code is readable but could be improved by removing dead code and simplifying a few dense expressions.

Run 1

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Mostly flat, with early returns keeping validation easy to follow; the loop-else construct adds modest complexity. Clarity of intent: Descriptive names, docstrings, and comments explain the password-reset mechanism, but the unused factorial calculation in the constructor is distracting and unrelated. Code length: Generally appropriate, although the factorial loop adds unnecessary lines and some documentation is lengthy. Action granularity: Statements mostly perform one action each; chained hashing and slicing are slightly denser. Reading flow: Methods and validation steps follow a logical sequence, but the awkward multiline hexadecimal slicing interrupts the flow, and the timestamp/uid comment does not precisely describe the implementation.

Run 2

Code Structure: Well-organized class with focused methods separating configuration, token generation, validation, and hashing. Nesting: Mostly shallow, with early returns keeping validation straightforward; the loop-else construct requires extra attention. Clarity of intent: Descriptive names, docstrings, and comments explain the password-reset workflow, but the unused factorial calculation in __init__ is unrelated and distracting. Code length: Generally concise for its functionality, though the irrelevant calculation and lengthy hashing docstring add reading overhead. Action granularity: Statements generally perform one action each; chained HMAC generation and slicing are somewhat denser. Reading flow: Validation proceeds naturally from parsing through signature verification to expiration checking. However, the awkward multiline hexdigest slicing interrupts the flow, and property accessor boilerplate adds minor navigation overhead.

Run 3

Code Structure: Well-organized class with focused methods separating token generation, validation, configuration, and hashing. Nesting: Mostly shallow; early returns simplify validation, though the for/else construct requires extra attention. Clarity of intent: Descriptive names, docstrings, and security-related comments explain the purpose well. However, the unused factorial calculation in __init__ is unrelated and confusing. Code length: Generally appropriate, with useful documentation, but the factorial loop adds unnecessary code and property boilerplate adds some verbosity. Action granularity: Most lines perform one clear action; chained hashing and slicing are somewhat denser. Reading flow: Validation proceeds naturally from parsing to signature verification to expiration checking. The awkward multiline hexdigest slicing interrupts readability, and the unrelated initialization calculation disrupts otherwise coherent flow.