django.utils.six.moves.range

Here are the examples of the python api django.utils.six.moves.range taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

122 Examples 7

Example 1

Project: Django--an-app-at-a-time Source File: geometries.py
Function: listarr
    def _listarr(self, func):
        """
        Internal routine that returns a sequence (list) corresponding with
        the given function.
        """
        return [func(self.ptr, i) for i in range(len(self))]

Example 2

Project: Django--an-app-at-a-time Source File: source.py
Function: bands
    @cached_property
    def bands(self):
        bands = []
        for idx in range(1, capi.get_ds_raster_count(self.ptr) + 1):
            bands.append(GDALBand(self, idx))
        return bands

Example 3

Project: Django--an-app-at-a-time Source File: formsets.py
    @property
    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]

Example 4

Project: cgstudiomap Source File: formsets.py
Function: forms
    @cached_property
    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

Example 5

Project: Django--an-app-at-a-time Source File: polygon.py
Function: kml
    @property
    def kml(self):
        "Returns the KML representation of this Polygon."
        inner_kml = ''.join("<innerBoundaryIs>%s</innerBoundaryIs>" % self[i + 1].kml
            for i in range(self.num_interior_rings))
        return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)

Example 6

Project: Django--an-app-at-a-time Source File: layer.py
Function: get_item
    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.')

Example 7

Project: cgstudiomap Source File: adapter.py
    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

Example 8

Project: Misago Source File: test_useradmin_views.py
    def test_mass_delete_accounts(self):
        """users list deletes users"""
        User = get_user_model()

        user_pks = []
        for i in range(10):
            test_user = User.objects.create_user(
                'Bob%s' % i,
                'bob%[email protected]' % i,
                'pass123',
                requires_activation=1
            )
            user_pks.append(test_user.pk)

        response = self.client.post(
            reverse('misago:admin:users:accounts:index'),
            data={'action': 'delete_accounts', 'selected_items': user_pks})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)

Example 9

Project: Misago Source File: test_user_username_api.py
    def test_change_username_no_changes_left(self):
        """api returns error 400 if there are no username changes left"""
        response = self.client.get(self.link)
        self.assertEqual(response.status_code, 200)

        response_json = json.loads(smart_str(response.content))
        for i in range(response_json['changes_left']):
            self.user.set_username('NewName%s' % i, self.user)

        response = self.client.get(self.link)
        response_json = json.loads(smart_str(response.content))
        self.assertEqual(response_json['changes_left'], 0)

        response = self.client.post(self.link, data={
            'username': 'Pointless'
        })

        self.assertContains(response, 'change your username now', status_code=400)
        self.assertTrue(self.user.username != 'Pointless')

Example 10

Project: django Source File: tests.py
    def test_large_delete(self):
        TEST_SIZE = 2000
        objs = [Avatar() for i in range(0, TEST_SIZE)]
        Avatar.objects.bulk_create(objs)
        # Calculate the number of queries needed.
        batch_size = connection.ops.bulk_batch_size(['pk'], objs)
        # The related fetches are done in batches.
        batches = int(ceil(float(len(objs)) / batch_size))
        # One query for Avatar.objects.all() and then one related fast delete for
        # each batch.
        fetches_to_mem = 1 + batches
        # The Avatar objects are going to be deleted in batches of GET_ITERATOR_CHUNK_SIZE
        queries = fetches_to_mem + TEST_SIZE // GET_ITERATOR_CHUNK_SIZE
        self.assertNumQueries(queries, Avatar.objects.all().delete)
        self.assertFalse(Avatar.objects.exists())

Example 11

Project: Django--an-app-at-a-time Source File: mutable_list.py
Function: get_item
    def __getitem__(self, index):
        "Get the item(s) at the specified index/slice."
        if isinstance(index, slice):
            return [self._get_single_external(i) for i in range(*index.indices(len(self)))]
        else:
            index = self._checkindex(index)
            return self._get_single_external(index)

Example 12

Project: Django--an-app-at-a-time Source File: mutable_list.py
    def _assign_extended_slice(self, start, stop, step, valueList):
        'Assign an extended slice by re-assigning individual items'
        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)))

        for i, val in zip(indexList, valueList):
            self._set_single(i, val)

Example 13

Project: reviewboard Source File: mixins.py
    @add_fixtures(['test_site'])
    @webapi_test_template
    def test_get_with_restrict_site_and_allowed(self):
        """Testing the GET <URL> API with access to a local site
        and session restricted to the site
        """
        user, url, mimetype, items = self._setup_test_get_list_with_site(
            with_webapi_token=True,
            webapi_token_local_site_id=self.local_site_id)

        rsp = self.api_get(url, expected_mimetype=mimetype)
        self.assertEqual(rsp['stat'], 'ok')
        self.assertIn(self.resource.list_result_key, rsp)

        items_rsp = rsp[self.resource.list_result_key]
        self.assertEqual(len(items), len(items_rsp))

        for i in range(len(items)):
            self.compare_item(items_rsp[i], items[i])

Example 14

Project: Django--an-app-at-a-time Source File: cache.py
Function: create
    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.")

Example 15

Project: Misago Source File: test_bansmaintenance.py
    def test_expired_bans_handling(self):
        """expired bans are flagged as such"""
        # create 5 bans then update their valid date to past one
        for i in range(5):
            Ban.objects.create(banned_value="abcd")
        expired_date = (timezone.now() - timedelta(days=10))
        Ban.objects.all().update(expires_on=expired_date, is_checked=True)

        self.assertEqual(Ban.objects.filter(is_checked=True).count(), 5)

        command = bansmaintenance.Command()

        out = StringIO()
        command.execute(stdout=out)
        command_output = out.getvalue().splitlines()[0].strip()

        self.assertEqual(command_output, 'Bans invalidated: 5')

        self.assertEqual(Ban.objects.filter(is_checked=True).count(), 0)

Example 16

Project: django-mysql Source File: test_settextfield.py
Function: test_int_easy
    def test_int_easy(self):
        big_set = {i ** 2 for i in six.moves.range(1000)}
        mymodel = BigIntSetModel.objects.create(field=big_set)
        assert mymodel.field == big_set
        mymodel = BigIntSetModel.objects.get(id=mymodel.id)
        assert mymodel.field == big_set

Example 17

Project: Django--an-app-at-a-time Source File: layer.py
Function: fields
    @property
    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)]

Example 18

Project: cgstudiomap Source File: mutable_list.py
Function: lt
    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

Example 19

Project: Misago Source File: test_subscriptions.py
Function: test_threads_no_subscription
    def test_threads_no_subscription(self):
        """make mulitple threads sub aware for authenticated"""
        threads = []
        for i in range(10):
            threads.append(
                self.post_thread(timezone.now() - timedelta(days=10)))

        make_subscription_aware(self.user, threads)

        for thread in threads:
            self.assertIsNone(thread.subscription)

Example 20

Project: django Source File: tests.py
Function: test_bulk
    def test_bulk(self):
        s = S.objects.create(r=R.objects.create())
        for i in range(2 * GET_ITERATOR_CHUNK_SIZE):
            T.objects.create(s=s)
        #   1 (select related `T` instances)
        # + 1 (select related `U` instances)
        # + 2 (delete `T` instances in batches)
        # + 1 (delete `s`)
        self.assertNumQueries(5, s.delete)
        self.assertFalse(S.objects.exists())

Example 21

Project: Django--an-app-at-a-time Source File: coordseq.py
Function: tuple
    @property
    def tuple(self):
        "Returns a tuple version of this coordinate sequence."
        n = self.size
        if n == 1:
            return self[0]
        else:
            return tuple(self[i] for i in range(n))

Example 22

Project: Django--an-app-at-a-time Source File: linestring.py
Function: listarr
    def _listarr(self, func):
        """
        Internal routine that returns a sequence (list) corresponding with
        the given function.  Will return a numpy array if possible.
        """
        lst = [func(i) for i in range(len(self))]
        if numpy:
            return numpy.array(lst)  # ARRRR!
        else:
            return lst

Example 23

Project: Misago Source File: test_thread_postmerge_api.py
    def test_merge_limit(self):
        """api rejects more posts than merge limit"""
        response = self.client.post(self.api_link, json.dumps({
            'posts': list(range(MERGE_LIMIT + 1))
        }), content_type="application/json")
        self.assertContains(response, "No more than {} posts can be merged".format(MERGE_LIMIT), status_code=400)

Example 24

Project: reviewboard Source File: scmtool.py
    def get_commits(self, branch=None, start=None):
        return [
            Commit('user%d' % i, six.text_type(i),
                   '2013-01-01T%02d:00:00.0000000' % i,
                   'Commit %d' % i,
                   six.text_type(i - 1))
            for i in range(int(start or 10), 0, -1)
        ]

Example 25

Project: Django--an-app-at-a-time Source File: mutable_list.py
    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)

Example 26

Project: Django--an-app-at-a-time Source File: mutable_list.py
Function: i_mul
    def __imul__(self, n):
        'multiply'
        if n <= 0:
            del self[:]
        else:
            cache = list(self)
            for i in range(n - 1):
                self.extend(cache)
        return self

Example 27

Project: Django--an-app-at-a-time Source File: mutable_list.py
Function: index
    def index(self, val):
        "Standard list index method"
        for i in range(0, len(self)):
            if self[i] == val:
                return i
        raise ValueError('%s not found in object' % str(val))

Example 28

Project: reviewboard Source File: mixins.py
Function: test_get_with_site
    @add_fixtures(['test_site'])
    @webapi_test_template
    def test_get_with_site(self):
        """Testing the GET <URL> API with access to a local site"""
        user, url, mimetype, items = self._setup_test_get_list_with_site()

        rsp = self.api_get(url, expected_mimetype=mimetype)
        self.assertEqual(rsp['stat'], 'ok')
        self.assertIn(self.resource.list_result_key, rsp)

        items_rsp = rsp[self.resource.list_result_key]
        self.assertEqual(len(items), len(items_rsp))

        for i in range(len(items)):
            self.compare_item(items_rsp[i], items[i])

Example 29

Project: Django--an-app-at-a-time Source File: mutable_list.py
Function: assign_simple_slice
    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())

Example 30

Project: Misago Source File: test_thread_postsplit_api.py
    def test_split_limit(self):
        """api rejects more posts than split limit"""
        response = self.client.post(self.api_link, json.dumps({
            'posts': list(range(SPLIT_LIMIT + 1))
        }), content_type="application/json")
        self.assertContains(response, "No more than {} posts can be split".format(SPLIT_LIMIT), status_code=400)

Example 31

Project: Django--an-app-at-a-time Source File: misc.py
def dbl_from_geom(func, num_geom=1):
    """
    Argument is a Geometry, return type is double that is passed
    in by reference as the last argument.
    """
    argtypes = [GEOM_PTR for i in range(num_geom)]
    argtypes += [POINTER(c_double)]
    func.argtypes = argtypes
    func.restype = c_int  # Status code returned
    func.errcheck = check_dbl
    return func

Example 32

Project: Django--an-app-at-a-time Source File: mutable_list.py
Function: eq
    def __eq__(self, other):
        olen = len(other)
        for i in range(olen):
            try:
                c = self[i] == other[i]
            except self._IndexError:
                # self must be shorter
                return False
            if not c:
                return False
        return len(self) == olen

Example 33

Project: Django--an-app-at-a-time Source File: formsets.py
Function: forms
    @cached_property
    def forms(self):
        """
        Instantiate forms at first property access.
        """
        # DoS protection is included in total_form_count()
        forms = [self._construct_form(i) for i in range(self.total_form_count())]
        return forms

Example 34

Project: Misago Source File: test_subscriptions.py
    def test_anon_threads_subscription(self):
        """make multiple threads list sub aware for anon"""
        threads = []
        for i in range(10):
            threads.append(
                self.post_thread(timezone.now() - timedelta(days=10)))

        make_subscription_aware(self.anon, threads)

        for thread in threads:
            self.assertIsNone(thread.subscription)

Example 35

Project: django-mysql Source File: test_cache.py
    @override_cache_settings(options={'MAX_ENTRIES': -1})
    def test_cull_max_entries_minus_one(self):
        # cull with MAX_ENTRIES = -1 should never clear anything that is not
        # expired

        # one expired key
        cache.set('key', 'value', 0.1)
        time.sleep(0.2)

        # 90 non-expired keys
        for n in six.moves.range(9):
            cache.set_many({
                str(n * 10 + i): True
                for i in six.moves.range(10)
            })

        cache.cull()
        assert self.table_count() == 90

Example 36

Project: Django--an-app-at-a-time Source File: layer.py
Function: iter
    def __iter__(self):
        "Iterates 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)

Example 37

Project: cgstudiomap Source File: adapter.py
    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

Example 38

Project: Misago Source File: test_lists_views.py
    def test_active_posters_list(self):
        """active posters page has no showstoppers"""
        view_link = reverse('misago:users-active-posters')

        response = self.client.get(view_link)
        self.assertEqual(response.status_code, 200)

        # Create 200 test users and see if errors appeared
        User = get_user_model()
        for i in range(200):
            User.objects.create_user(
                'Bob%s' % i, 'm%[email protected]' % i, 'Pass.123', posts=12345)

        response = self.client.get(view_link)
        self.assertEqual(response.status_code, 200)

Example 39

Project: cgstudiomap Source File: mutable_list.py
Function: eq
    def __eq__(self, other):
        olen = len(other)
        for i in range(olen):
            try:
                c = self[i] == other[i]
            except IndexError:
                # self must be shorter
                return False
            if not c:
                return False
        return len(self) == olen

Example 40

Project: Django--an-app-at-a-time Source File: layer.py
Function: field_types
    @property
    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)]

Example 41

Project: cgstudiomap Source File: paginator.py
Function: get_page_range
    def _get_page_range(self):
        """
        Returns a 1-based range of pages for iterating through within
        a template for loop.
        """
        return six.moves.range(1, self.num_pages + 1)

Example 42

Project: PyClassLessons Source File: paginator.py
Function: get_page_range
    def _get_page_range(self):
        """
        Returns a 1-based range of pages for iterating through within
        a template for loop.
        """
        return list(six.moves.range(1, self.num_pages + 1))

Example 43

Project: django Source File: polygon.py
Function: kml
    @property
    def kml(self):
        "Returns the KML representation of this Polygon."
        inner_kml = ''.join(
            "<innerBoundaryIs>%s</innerBoundaryIs>" % self[i + 1].kml
            for i in range(self.num_interior_rings)
        )
        return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)

Example 44

Project: Django--an-app-at-a-time Source File: coordseq.py
Function: kml
    @property
    def kml(self):
        "Returns the KML representation for the coordinates."
        # Getting the substitution string depending on whether the coordinates have
        #  a Z dimension.
        if self.hasz:
            substr = '%s,%s,%s '
        else:
            substr = '%s,%s,0 '
        return '<coordinates>%s</coordinates>' % \
            ''.join(substr % self[i] for i in range(len(self))).strip()

Example 45

Project: Misago Source File: test_useradmin_views.py
    def test_mass_delete_all(self):
        """users list deletes users and their content"""
        User = get_user_model()

        user_pks = []
        for i in range(10):
            test_user = User.objects.create_user(
                'Bob%s' % i,
                'bob%[email protected]' % i,
                'pass123',
                requires_activation=1
            )
            user_pks.append(test_user.pk)

        response = self.client.post(
            reverse('misago:admin:users:accounts:index'),
            data={'action': 'delete_accounts', 'selected_items': user_pks})
        self.assertEqual(response.status_code, 302)
        self.assertEqual(User.objects.count(), 1)

Example 46

Project: jobtastic Source File: tasks.py
Function: calculate_result
    def calculate_result(self, bloat_factor, **kwargs):
        """
        Let's bloat our thing!
        """
        global leaky_global

        for _ in six.moves.range(bloat_factor):
            # 1 million bytes for a MB
            new_str = u'X' * (1000000 * per_character_factor)
            # Add something new to it so python can't just point to the same
            # memory location
            new_str += random.choice(string.ascii_letters)
            leaky_global.append(new_str)

        return bloat_factor

Example 47

Project: Misago Source File: test_serializer.py
    def test_serializer_handles_paddings(self):
        """serializer handles missing paddings"""
        for i in range(100):
            wet = 'Lorem ipsum %s' % ('a' * i)
            dry = serializer.dumps(wet)
            self.assertFalse(dry.endswith('='))
            self.assertEqual(wet, serializer.loads(dry))

Example 48

Project: Misago Source File: test_thread_postmove_api.py
    def test_move_limit(self):
        """api rejects more posts than move limit"""
        other_thread = testutils.post_thread(self.category)

        response = self.client.post(self.api_link, json.dumps({
            'thread_url': other_thread.get_absolute_url(),
            'posts': list(range(MOVE_LIMIT + 1))
        }), content_type="application/json")
        self.assertContains(response, "No more than {} posts can be moved".format(MOVE_LIMIT), status_code=400)

Example 49

Project: reviewboard Source File: mixins.py
Function: test_get
    @webapi_test_template
    def test_get(self):
        """Testing the GET <URL> API"""
        self.load_fixtures(self.basic_get_fixtures)
        self._login_user(admin=self.basic_get_use_admin)

        url, mimetype, items = self.setup_basic_get_test(self.user, False,
                                                         None, True)
        self.assertFalse(url.startswith('/s/' + self.local_site_name))

        rsp = self.api_get(url, expected_mimetype=mimetype)
        self.assertEqual(rsp['stat'], 'ok')
        self.assertIn(self.resource.list_result_key, rsp)

        items_rsp = rsp[self.resource.list_result_key]
        self.assertEqual(len(items), len(items_rsp))

        for i in range(len(items)):
            self.compare_item(items_rsp[i], items[i])

Example 50

Project: Django--an-app-at-a-time Source File: mutable_list.py
Function: lt
    def __lt__(self, other):
        olen = len(other)
        for i in range(olen):
            try:
                c = self[i] < other[i]
            except self._IndexError:
                # self must be shorter
                return True
            if c:
                return c
            elif other[i] < self[i]:
                return False
        return len(self) < olen
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3