python类range()的实例源码

formsets.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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]
cache.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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.")
mutable_list.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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 ##
mutable_list.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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())
mutable_list.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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())
zoom.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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
zoom.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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
lookups.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
crypto.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 72 收藏 0 点赞 0 评论 0
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))
formsets.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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]
cache.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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.")
mutable_list.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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 ##
mutable_list.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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())
mutable_list.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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())
zoom.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
zoom.py 文件源码 项目:NarshaTech 作者: KimJangHyeon 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
formsets.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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]
cache.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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.")
storage.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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))
mutable_list.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
mutable_list.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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 ##
mutable_list.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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())
mutable_list.py 文件源码 项目:Scrum 作者: prakharchoudhary 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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())
formsets.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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]
cache.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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.")
storage.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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))
mutable_list.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
mutable_list.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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 ##
mutable_list.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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())
mutable_list.py 文件源码 项目:django 作者: alexsukhrin 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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())


问题


面经


文章

微信
公众号

扫码关注公众号