我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.six.moves.range()。
def deleted_forms(self): """ Returns a list of forms that have been marked for deletion. """ if not self.is_valid() or not self.can_delete: return [] # construct _deleted_form_indexes which is just a list of form indexes # that have had their deletion widget set to True if not hasattr(self, '_deleted_form_indexes'): self._deleted_form_indexes = [] for i in range(0, self.total_form_count()): form = self.forms[i] # if this is an extra form and hasn't changed, don't consider it if i >= self.initial_form_count() and not form.has_changed(): continue if self._should_delete_form(form): self._deleted_form_indexes.append(i) return [self.forms[i] for i in self._deleted_form_indexes]
def create(self): # Because a cache can fail silently (e.g. memcache), we don't know if # we are failing to create a new session because of a key collision or # because the cache is missing. So we try for a (large) number of times # and then raise an exception. That's the risk you shoulder if using # cache backing. for i in range(10000): self._session_key = self._get_new_session_key() try: self.save(must_create=True) except CreateError: continue self.modified = True return raise RuntimeError( "Unable to create a new session key. " "It is likely that the cache is unavailable.")
def __lt__(self, other): olen = len(other) for i in range(olen): try: c = self[i] < other[i] except IndexError: # self must be shorter return True if c: return c elif other[i] < self[i]: return False return len(self) < olen # ### Public list interface Methods ### # ## Non-mutating ##
def _assign_extended_slice_rebuild(self, start, stop, step, valueList): 'Assign an extended slice by rebuilding entire list' indexList = range(start, stop, step) # extended slice, only allow assigning slice of same size if len(valueList) != len(indexList): raise ValueError('attempt to assign sequence of size %d ' 'to extended slice of size %d' % (len(valueList), len(indexList))) # we're not changing the length of the sequence newLen = len(self) newVals = dict(zip(indexList, valueList)) def newItems(): for i in range(newLen): if i in newVals: yield newVals[i] else: yield self._get_single_internal(i) self._rebuild(newLen, newItems())
def _assign_simple_slice(self, start, stop, valueList): 'Assign a simple slice; Can assign slice of any length' origLen = len(self) stop = max(start, stop) newLen = origLen - stop + start + len(valueList) def newItems(): for i in range(origLen + 1): if i == start: for val in valueList: yield val if i < origLen: if i < start or i >= stop: yield self._get_single_internal(i) self._rebuild(newLen, newItems())
def __init__(self, num_zoom=19, tilesize=256): "Initializes the Google Zoom object." # Google's tilesize is 256x256, square tiles are assumed. self._tilesize = tilesize # The number of zoom levels self._nzoom = num_zoom # Initializing arrays to hold the parameters for each one of the # zoom levels. self._degpp = [] # Degrees per pixel self._radpp = [] # Radians per pixel self._npix = [] # 1/2 the number of pixels for a tile at the given zoom level # Incrementing through the zoom levels and populating the parameter arrays. z = tilesize # The number of pixels per zoom level. for i in range(num_zoom): # Getting the degrees and radians per pixel, and the 1/2 the number of # for every zoom level. self._degpp.append(z / 360.) # degrees per pixel self._radpp.append(z / (2 * pi)) # radians per pixel self._npix.append(z / 2) # number of pixels to center of tile # Multiplying `z` by 2 for the next iteration. z *= 2
def get_zoom(self, geom): "Returns the optimal Zoom level for the given geometry." # Checking the input type. if not isinstance(geom, GEOSGeometry) or geom.srid != 4326: raise TypeError('get_zoom() expects a GEOS Geometry with an SRID of 4326.') # Getting the envelope for the geometry, and its associated width, height # and centroid. env = geom.envelope env_w, env_h = self.get_width_height(env.extent) center = env.centroid for z in range(self._nzoom): # Getting the tile at the zoom level. tile_w, tile_h = self.get_width_height(self.tile(center, z).extent) # When we span more than one tile, this is an approximately good # zoom level. if (env_w > tile_w) or (env_h > tile_h): if z == 0: raise GoogleMapException('Geometry width and height should not exceed that of the Earth.') return z - 1 # Otherwise, we've zoomed in to the max. return self._nzoom - 1
def split_parameter_list_as_sql(self, compiler, connection): # This is a special case for databases which limit the number of # elements which can appear in an 'IN' clause. max_in_list_size = connection.ops.max_in_list_size() lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.batch_process_rhs(compiler, connection) in_clause_elements = ['('] params = [] for offset in range(0, len(rhs_params), max_in_list_size): if offset > 0: in_clause_elements.append(' OR ') in_clause_elements.append('%s IN (' % lhs) params.extend(lhs_params) sqls = rhs[offset: offset + max_in_list_size] sqls_params = rhs_params[offset: offset + max_in_list_size] param_group = ', '.join(sqls) in_clause_elements.append(param_group) in_clause_elements.append(')') params.extend(sqls_params) in_clause_elements.append(')') return ''.join(in_clause_elements), params
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), settings.SECRET_KEY)).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length))
def stored_name(self, name): cleaned_name = self.clean_name(name) hash_key = self.hash_key(cleaned_name) cache_name = self.hashed_files.get(hash_key) if cache_name: return cache_name # No cached name found, recalculate it from the files. intermediate_name = name for i in range(self.max_post_process_passes + 1): cache_name = self.clean_name( self.hashed_name(name, content=None, filename=intermediate_name) ) if intermediate_name == cache_name: # Store the hashed name if there was a miss. self.hashed_files[hash_key] = cache_name return cache_name else: # Move on to the next intermediate file. intermediate_name = cache_name # If the cache name can't be determined after the max number of passes, # the intermediate files on disk may be corrupt; avoid an infinite loop. raise ValueError("The name '%s' could not be hashed with %r." % (name, self))
def __delitem__(self, index): "Delete the item(s) at the specified index/slice." if not isinstance(index, six.integer_types + (slice,)): raise TypeError("%s is not a legal index" % index) # calculate new length and dimensions origLen = len(self) if isinstance(index, six.integer_types): index = self._checkindex(index) indexRange = [index] else: indexRange = range(*index.indices(origLen)) newLen = origLen - len(indexRange) newItems = (self._get_single_internal(i) for i in range(origLen) if i not in indexRange) self._rebuild(newLen, newItems)
def __init__(self, attrs=None, years=None, months=None, empty_label=None): self.attrs = attrs or {} # Optional list or tuple of years to use in the "year" select box. if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year + 10) # Optional dict of months to use in the "month" select box. if months: self.months = months else: self.months = MONTHS # Optional string, list, or tuple to use as empty_label. if isinstance(empty_label, (list, tuple)): if not len(empty_label) == 3: raise ValueError('empty_label list/tuple must have 3 elements.') self.year_none_value = (0, empty_label[0]) self.month_none_value = (0, empty_label[1]) self.day_none_value = (0, empty_label[2]) else: if empty_label is not None: self.none_value = (0, empty_label) self.year_none_value = self.none_value self.month_none_value = self.none_value self.day_none_value = self.none_value
def render(self, name, value, attrs=None): try: year_val, month_val, day_val = value.year, value.month, value.day except AttributeError: year_val = month_val = day_val = None if isinstance(value, six.string_types): if settings.USE_L10N: try: input_format = get_format('DATE_INPUT_FORMATS')[0] v = datetime.datetime.strptime(force_str(value), input_format) year_val, month_val, day_val = v.year, v.month, v.day except ValueError: pass if year_val is None: match = self.date_re.match(value) if match: year_val, month_val, day_val = [int(val) for val in match.groups()] html = {} choices = [(i, i) for i in self.years] html['year'] = self.create_select(name, self.year_field, value, year_val, choices, self.year_none_value) choices = list(self.months.items()) html['month'] = self.create_select(name, self.month_field, value, month_val, choices, self.month_none_value) choices = [(i, i) for i in range(1, 32)] html['day'] = self.create_select(name, self.day_field, value, day_val, choices, self.day_none_value) output = [] for field in self._parse_date_fmt(): output.append(html[field]) return mark_safe('\n'.join(output))
def forms(self): """ Instantiate forms at first property access. """ # DoS protection is included in total_form_count() forms = [self._construct_form(i, **self.get_form_kwargs(i)) for i in range(self.total_form_count())] return forms
def ordered_forms(self): """ Returns a list of form in the order specified by the incoming data. Raises an AttributeError if ordering is not allowed. """ if not self.is_valid() or not self.can_order: raise AttributeError("'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__) # Construct _ordering, which is a list of (form_index, order_field_value) # tuples. After constructing this list, we'll sort it by order_field_value # so we have a way to get to the form indexes in the order specified # by the form data. if not hasattr(self, '_ordering'): self._ordering = [] for i in range(0, self.total_form_count()): form = self.forms[i] # if this is an extra form and hasn't changed, don't consider it if i >= self.initial_form_count() and not form.has_changed(): continue # don't add data marked for deletion to self.ordered_data if self.can_delete and self._should_delete_form(form): continue self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME])) # After we're done populating self._ordering, sort it. # A sort function to order things numerically ascending, but # None should be sorted below anything else. Allowing None as # a comparison value makes it so we can leave ordering fields # blank. def compare_ordering_key(k): if k[1] is None: return (1, 0) # +infinity, larger than any number return (0, k[1]) self._ordering.sort(key=compare_ordering_key) # Return a list of form.cleaned_data dicts in the order specified by # the form data. return [self.forms[i[0]] for i in self._ordering]
def full_clean(self): """ Cleans all of self.data and populates self._errors and self._non_form_errors. """ self._errors = [] self._non_form_errors = self.error_class() if not self.is_bound: # Stop further processing. return for i in range(0, self.total_form_count()): form = self.forms[i] self._errors.append(form.errors) try: if (self.validate_max and self.total_form_count() - len(self.deleted_forms) > self.max_num) or \ self.management_form.cleaned_data[TOTAL_FORM_COUNT] > self.absolute_max: raise ValidationError(ungettext( "Please submit %d or fewer forms.", "Please submit %d or fewer forms.", self.max_num) % self.max_num, code='too_many_forms', ) if (self.validate_min and self.total_form_count() - len(self.deleted_forms) < self.min_num): raise ValidationError(ungettext( "Please submit %d or more forms.", "Please submit %d or more forms.", self.min_num) % self.min_num, code='too_few_forms') # Give self.clean() a chance to do cross-form validation. self.clean() except ValidationError as e: self._non_form_errors = self.error_class(e.error_list)
def _fix_polygon(self, poly): # Fix single polygon orientation as described in __init__() if self._isClockwise(poly.exterior_ring): poly.exterior_ring = list(reversed(poly.exterior_ring)) for i in range(1, len(poly)): if not self._isClockwise(poly[i]): poly[i] = list(reversed(poly[i])) return poly
def _isClockwise(self, coords): # A modified shoelace algorithm to determine polygon orientation. # See https://en.wikipedia.org/wiki/Shoelace_formula n = len(coords) area = 0.0 for i in range(n): j = (i + 1) % n area += coords[i][0] * coords[j][1] area -= coords[j][0] * coords[i][1] return area < 0.0
def __getitem__(self, index): "Gets the Feature at the specified index." if isinstance(index, six.integer_types): # 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 < 0: raise OGRIndexError('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 fields(self): """ Returns a list of string names corresponding to each of the Fields available in this Layer. """ return [force_text(capi.get_field_name(capi.get_field_defn(self._ldefn, i)), self._ds.encoding, strings_only=True) for i in range(self.num_fields)]
def field_types(self): """ Returns a list of the types of fields in this Layer. For example, the list [OFTInteger, OFTReal, OFTString] would be returned for an OGR layer that had 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)]
def field_widths(self): "Returns 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)]
def field_precisions(self): "Returns 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 __getitem__(self, index): """ Gets the Field object at the specified index, which may be either an integer or the Field's string label. Note that the Field object is not the field's _value_ -- use the `get` method instead to retrieve the value (e.g. an integer) instead of a Field instance. """ if isinstance(index, six.string_types): i = self.index(index) else: if index < 0 or index > self.num_fields: raise OGRIndexError('index out of range') i = index return Field(self, i)
def fields(self): "Returns a list of fields in the Feature." return [capi.get_field_name(capi.get_field_defn(self._layer._ldefn, i)) for i in range(self.num_fields)]
def __iter__(self): for idx in range(1, len(self) + 1): yield GDALBand(self.source, idx)
def __getitem__(self, index): "Returns the Point at the given index." if index >= 0 and index < self.point_count: x, y, z = c_double(), c_double(), c_double() capi.get_point(self.ptr, index, byref(x), byref(y), byref(z)) dim = self.coord_dim if dim == 1: return (x.value,) elif dim == 2: return (x.value, y.value) elif dim == 3: return (x.value, y.value, z.value) else: raise OGRIndexError('index out of range: %s' % str(index))
def __iter__(self): "Iterates over each point in the LineString." for i in range(self.point_count): yield self[i]
def tuple(self): "Returns the tuple representation of this LineString." return tuple(self[i] for i in range(len(self)))
def __iter__(self): "Iterates through each ring in the Polygon." for i in range(self.geom_count): yield self[i]
def __getitem__(self, index): "Gets the ring at the specified index." if index < 0 or index >= self.geom_count: raise OGRIndexError('index out of range: %s' % index) else: return OGRGeometry(capi.clone_geom(capi.get_geom_ref(self.ptr, index)), self.srs) # Polygon Properties