Sample

pyint-f5cf4d6e57d1-I05

Rewrite eligible decimal integer literals in hexadecimal notation

Matched original source

Lines228

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.1940–1; higher is more readable
Mi0.5180–1; higher is more readable
LLOC117Logical lines; fewer is more readable
DeepSeek V4 Pro17.330–20; mean of three runs
GPT-6.1 Sol170–20; mean of three runs
BTTF0.1820–1; higher is more readable

Views

Source code

from ctypes import byref, c_double from django.contrib.gis.gdal.base import GDALBase from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope from django.contrib.gis.gdal.error import GDALException, SRSException from django.contrib.gis.gdal.feature import Feature from django.contrib.gis.gdal.field import OGRFieldTypes from django.contrib.gis.gdal.geometries import OGRGeometry from django.contrib.gis.gdal.geomtype import OGRGeomType from django.contrib.gis.gdal.prototypes import ds as capi from django.contrib.gis.gdal.prototypes import geom as geom_api from django.contrib.gis.gdal.prototypes import srs as srs_api from django.contrib.gis.gdal.srs import SpatialReference from django.utils.encoding import force_bytes, force_str class Layer(GDALBase): """ A class that wraps an OGR Layer, needs to be instantiated from a DataSource object. """ def __init__(self, layer_ptr, ds): """ Initialize on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is required so that a reference to it is kept with this Layer. This prevents garbage collection of the `DataSource` while this Layer is still active. """ if not layer_ptr: raise GDALException("Cannot create Layer, invalid pointer given") self.ptr = layer_ptr self._ds = ds self._ldefn = capi.get_layer_defn(self._ptr) # Does the Layer support random reading? self._random_read = self.test_capability(b"RandomRead") def __getitem__(self, index): "Get the Feature at the specified index." if isinstance(index, int): # An integer index was given -- we cannot do a check based on the # number of features because the beginning and ending feature IDs # are not guaranteed to be 0 and len(layer)-1, respectively. if index < 0x0: raise IndexError("Negative indices are not allowed on OGR Layers.") return self._make_feature(index) elif isinstance(index, slice): # A slice was given start, stop, stride = index.indices(self.num_feat) return [self._make_feature(fid) for fid in range(start, stop, stride)] else: raise TypeError( "Integers and slices may only be used when indexing OGR Layers." ) def __iter__(self): "Iterate over each Feature in the Layer." # ResetReading() must be called before iteration is to begin. capi.reset_reading(self._ptr) for i in range(self.num_feat): yield Feature(capi.get_next_feature(self._ptr), self) def __len__(self): "The length is the number of features." return self.num_feat def __str__(self): "The string name of the layer." return self.name def _make_feature(self, feat_id): """ Helper routine for __getitem__ that constructs a Feature from the given Feature ID. If the OGR Layer does not support random-access reading, then each feature of the layer will be incremented through until the a Feature is found matching the given feature ID. """ if self._random_read: # If the Layer supports random reading, return. try: return Feature(capi.get_feature(self.ptr, feat_id), self) except GDALException: pass else: # Random access isn't supported, have to increment through # each feature until the given feature ID is encountered. for feat in self: if feat.fid == feat_id: return feat # Should have returned a Feature, raise an IndexError. raise IndexError("Invalid feature id: %s." % feat_id) # #### Layer properties #### @property def extent(self): "Return the extent (an Envelope) of this layer." env = OGREnvelope() capi.get_extent(self.ptr, byref(env), 0x1) return Envelope(env) @property def name(self): "Return the name of this layer in the Data Source." name = capi.get_fd_name(self._ldefn) return force_str(name, self._ds.encoding, strings_only=True) @property def num_feat(self, force=0x1): "Return the number of features in the Layer." return capi.get_feature_count(self.ptr, force) @property def num_fields(self): "Return the number of fields in the Layer." return capi.get_field_count(self._ldefn) @property def geom_type(self): "Return the geometry type (OGRGeomType) of the Layer." return OGRGeomType(capi.get_fd_geom_type(self._ldefn)) @property def srs(self): "Return the Spatial Reference used in this Layer." try: ptr = capi.get_layer_srs(self.ptr) return SpatialReference(srs_api.clone_srs(ptr)) except SRSException: return None @property def fields(self): """ Return a list of string names corresponding to each of the Fields available in this Layer. """ return [ force_str( capi.get_field_name(capi.get_field_defn(self._ldefn, i)), self._ds.encoding, strings_only=True, ) for i in range(self.num_fields) ] @property def field_types(self): """ Return a list of the types of fields in this Layer. For example, return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that has an integer, a floating-point, and string fields. """ return [ OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))] for i in range(self.num_fields) ] @property def field_widths(self): "Return a list of the maximum field widths for the features." return [ capi.get_field_width(capi.get_field_defn(self._ldefn, i)) for i in range(self.num_fields) ] @property def field_precisions(self): "Return the field precisions for the features." return [ capi.get_field_precision(capi.get_field_defn(self._ldefn, i)) for i in range(self.num_fields) ] def _get_spatial_filter(self): try: return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr))) except GDALException: return None def _set_spatial_filter(self, filter): if isinstance(filter, OGRGeometry): capi.set_spatial_filter(self.ptr, filter.ptr) elif isinstance(filter, (tuple, list)): if not len(filter) == 0x4: raise ValueError("Spatial filter list/tuple must have 4 elements.") # Map c_double onto params -- if a bad type is passed in it # will be caught here. xmin, ymin, xmax, ymax = map(c_double, filter) capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax) elif filter is None: capi.set_spatial_filter(self.ptr, None) else: raise TypeError( "Spatial filter must be either an OGRGeometry instance, a 4-tuple, or " "None." ) spatial_filter = property(_get_spatial_filter, _set_spatial_filter) # #### Layer Methods #### def get_fields(self, field_name): """ Return a list containing the given field name for every Feature in the Layer. """ if field_name not in self.fields: raise GDALException("invalid field name: %s" % field_name) return [feat.get(field_name) for feat in self] def get_geoms(self, geos=False): """ Return a list containing the OGRGeometry for every Feature in the Layer. """ if geos: from django.contrib.gis.geos import GEOSGeometry return [GEOSGeometry(feat.geom.wkb) for feat in self] else: return [feat.geom for feat in self] def test_capability(self, capability): """ Return a bool indicating whether the this Layer supports the given capability (a string). Valid capability strings include: 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter', 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions', 'DeleteFeature', and 'FastSetNextByIndex'. """ return bool(capi.test_capability(self.ptr, force_bytes(capability)))

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.7584.101−250.275
Source linesThe number of non-empty source lines.228+91.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.407−6.61

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

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.229−7.072
Indentation frequencyHow rapidly indentation changes from line to line.181+5.523
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.181−3.733
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.227.898+2.776
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.85.86+0.581
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.051+0.445
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.86.943−0.017

Intercept 0.07 + feature contributions = -1.427 (log-odds).
Score = sigmoid(-1.427) = 0.194.

Score0.518
Score117
Run 1

The code is well-structured and highly readable. It has a clear class with logical method organization, minimal nesting, and concise docstrings explaining intent. Methods are focused and single-purpose, with good action granularity. The reading flow is natural, with properties and methods grouped logically. Minor deductions for some C API interactions using hexadecimal constants (0x0, 0x1, 0x4) which are slightly opaque, and occasional multi-step list comprehensions that could be split for clarity. Overall, the code demonstrates excellent readability through consistent naming, clear error handling, and proper separation of concerns.

Run 2

The code demonstrates strong readability through clear organization, minimal nesting, and consistent patterns. The class structure is logical, with a well-documented __init__ establishing ownership relationships, followed by dunder methods and a clean separation of properties and methods. Nesting is kept shallow through early returns and guard clauses. Each method has a focused purpose expressed through clear docstrings. Line length is reasonable, and complex operations are broken into comprehensions that read naturally. The use of 0x0 and 0x1 instead of 0 and 1 is slightly unusual but not detrimental. The _make_feature method's fallback loop could be slightly clearer with stronger error messaging, and the spatial_filter setter has multiple nested branches that slightly reduce flow. Overall, the code reads like well-maintained library code: explicit, purposeful, and accessible to developers familiar with GIS concepts. Minor opportunities exist for simplifying the spatial_filter validation and modernizing some type checking patterns.

Run 3

The code is well-structured with clear class-level organization, logical method grouping, and consistent use of properties and docstrings. Nesting is minimal and readable, with early returns and guard clauses. Intent is highly explicit through descriptive naming and concise comments. While some methods are moderately long, complexity is justified by underlying GDAL API interactions. Action granularity is appropriate—most lines perform one logical operation. Reading flow is natural, with helper methods and property blocks clearly delineated. Minor deductions for occasional magic numbers and dense list comprehensions, but overall readability is excellent.

Run 1

Code Structure: The class is logically organized into initialization, Python protocol methods, properties, and layer operations. Nesting: Most methods are flat, with only modest nesting in feature lookup and filter validation. Clarity of intent: Descriptive method names, docstrings, and explanatory comments make the wrapper's purpose clear; abbreviated C API names, hexadecimal constants, and mixed ptr/_ptr usage add friction. Code length: Methods are concise, although some comments repeat obvious behavior and field-property implementations are repetitive. Action granularity: Statements generally perform one action each; nested API calls and comprehensions occasionally combine several conceptual steps. Reading flow: Consistent formatting and section labels support natural navigation, but legacy property construction, redundant else branches after returns, and low-level pointer handling slightly interrupt the flow.

Run 2

Code Structure: Clearly organized into initialization, collection behavior, properties, and methods, with focused responsibilities. Nesting: Generally shallow; feature lookup and spatial-filter validation introduce only moderate nesting. Clarity of intent: Descriptive names, docstrings, and explanatory comments make the wrapper's purpose clear. However, hexadecimal constants for ordinary values, inconsistent ptr/_ptr usage, and dense C API expressions add cognitive overhead. Code length: Most methods are concise, though repetitive field-property implementations and some redundant comments increase length slightly. Action granularity: Statements generally perform one action each; nested API calls and conversion comprehensions occasionally combine several operations. Reading flow: Consistent formatting and logical ordering support natural reading, but mixing decorator-based properties with an explicit property constructor and retaining unnecessary else branches slightly disrupt consistency.

Run 3

Code Structure: Well-organized class with initialization, Python protocol methods, properties, and utility methods clearly grouped. Nesting: Mostly shallow; feature lookup and spatial-filter validation introduce only modest nesting. Clarity of intent: Descriptive method names, docstrings, and explanatory comments make the wrapper's purpose clear. However, hexadecimal constants for ordinary values, abbreviated internal names, inconsistent ptr/_ptr usage, and the parameter named filter slightly reduce clarity. Code length: Methods are concise, although repetitive field-access properties and some redundant comments add length. Action granularity: Statements generally perform one action per line; nested API calls and comprehensions occasionally combine several operations. Reading flow: Consistent formatting and logical ordering support natural reading, with minor interruptions from legacy property construction and low-level GDAL details.