Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Based on the snippet: <|code_start|> class FakeQueryset: def __init__(self, objs): self.objects = objs def __len__(self): return len(self.objects) def __iter__(self): return self.objects.__iter__() def filter(self, pk__in): return FakeQueryset([o for o in self.objects...
class NormalProjList(PermissionRequiredMixin, BaseProjList):
Given the following code snippet before the placeholder: <|code_start|># org1/proj1 P X X # org1/proj2 P X X # org1/proj3 P X X # org1/proj4 P X # org1/proj5 P X # org1/proj6 P # org1/proj7 (P) P # org2/proj8 X X...
user = UserFactory.create(username='user{}'.format(i))
Given snippet: <|code_start|># proj.detail (P=+proj.detail_private) # # org1/proj1 P X X # org1/proj2 P X X # org1/proj3 P X X # org1/proj4 P X # org1/proj5 P X # org1/proj6 P # org1/proj7 (P) P # org2/proj8 X X ...
PolicyFactory.set_directory(str(datadir))
Based on the snippet: <|code_start|># org1 X X X # org2 X X X # # proj.detail (P=+proj.detail_private) # # org1/proj1 P X X # org1/proj2 P X X # org1/proj3 P X X # org1/proj4 P X # org1/proj5 P ...
def setup(datadir, db):
Given the code snippet: <|code_start|># org2/proj10 (P) X X X # # proj.delete # # org1/proj1 X X # org1/proj2 X # org1/proj3 X # org1/proj4 X # org1/proj5 X # org1/proj6 X # org1/proj7 X # org2/proj8 X X # org2/proj9 X X # org...
orgs.append(Org(pk=i, name='org{}'.format(i)))
Here is a snippet: <|code_start|> class FakeQueryset: def __init__(self, objs): self.objects = objs def __len__(self): return len(self.objects) def __iter__(self): return self.objects.__iter__() def filter(self, pk__in): return FakeQueryset([o for o in self.objects...
model = Proj
Using the snippet: <|code_start|> fields = ('name', 'org') depth = 1 class FakeQueryset: def __init__(self, objs): self.objects = objs def __len__(self): return len(self.objects) def __iter__(self): return self.objects.__iter__() def filter(self, pk__in): ...
class NormalProjList(APIPermissionRequiredMixin, BaseProjList):
Based on the snippet: <|code_start|>class FakeQueryset: def __init__(self, objs): self.objects = objs def __len__(self): return len(self.objects) def __iter__(self): return self.objects.__iter__() def filter(self, pk__in): return FakeQueryset([o for o in self.objects i...
class NormalPermissionsProjList(PermissionsFilterMixin,
Continue the code snippet: <|code_start|># org1/proj1 P X X # org1/proj2 P X X # org1/proj3 P X X # org1/proj4 P X # org1/proj5 P X # org1/proj6 P # org1/proj7 (P) P # org2/proj8 X X X # org2/proj9 (P) X ...
user = UserFactory.create(username='user{}'.format(i))
Here is a snippet: <|code_start|># proj.detail (P=+proj.detail_private) # # org1/proj1 P X X # org1/proj2 P X X # org1/proj3 P X X # org1/proj4 P X # org1/proj5 P X # org1/proj6 P # org1/proj7 (P) P # org2/proj8 X ...
PolicyFactory.set_directory(str(datadir))
Here is a snippet: <|code_start|># org1 X X X # org2 X X X # # proj.detail (P=+proj.detail_private) # # org1/proj1 P X X # org1/proj2 P X X # org1/proj3 P X X # org1/proj4 P X # org1/proj5 P X...
def setup(datadir, db):
Continue the code snippet: <|code_start|> class OrgSerializer(serializers.ModelSerializer): class Meta: model = Org fields = ('name',) class ProjSerializer(serializers.ModelSerializer): class Meta: <|code_end|> . Use current file imports: from rest_framework import serializers from tutela...
model = Proj
Predict the next line after this snippet: <|code_start|> ('parcel.delete', {'description': "Delete parcels"}) ] def get_absolute_url(self): return reverse('parcel-detail', kwargs={'pk': self.pk}) permissioned_model( Policy, perm_type='policy', path_fields=['name'], actions=[ ...
Action.register('statistics')
Predict the next line for this snippet: <|code_start|> def get_absolute_url(self): return reverse('party-detail', kwargs={'pk': self.pk}) @permissioned_model class Parcel(models.Model): project = models.ForeignKey(Project) address = models.CharField(max_length=200) class Meta: ordering...
Policy, perm_type='policy', path_fields=['name'],
Using the snippet: <|code_start|> """ policy = models.ForeignKey('Policy', on_delete=models.PROTECT) role = models.ForeignKey('Role', on_delete=models.CASCADE) index = models.IntegerField() """Integer index used to order the sequence of policies composing a role. """ class Meta: ...
raise RoleVariableException("missing variable in role definition")
Predict the next line after this snippet: <|code_start|> class Backend: """Custom authentication backend: dispatches ``has_perm`` queries to the user's permission set. """ @staticmethod def _obj_ok(obj): return obj is None or callable(obj) or isinstance(obj, Object) def has_perm(self,...
raise InvalidPermissionObjectException
Continue the code snippet: <|code_start|> class Backend: """Custom authentication backend: dispatches ``has_perm`` queries to the user's permission set. """ @staticmethod def _obj_ok(obj): return obj is None or callable(obj) or isinstance(obj, Object) def has_perm(self, user, perm, ob...
return user.permset_tree.allow(Action(perm), obj)
Using the snippet: <|code_start|> class Backend: """Custom authentication backend: dispatches ``has_perm`` queries to the user's permission set. """ @staticmethod def _obj_ok(obj): <|code_end|> , determine the next line of code. You have imports: from django.core.exceptions import ObjectDoesNotEx...
return obj is None or callable(obj) or isinstance(obj, Object)
Predict the next line for this snippet: <|code_start|> {'effect': 'allow', 'action': ['organisation.list']}, {'effect': 'allow', 'action': ['organisation.detail'], 'object': ['organisation/*']}, {'effect': 'allow', 'action': ['project.list'], 'object...
default_p = Policy(name='default', body=json.dumps(default_p_body))
Given the code snippet: <|code_start|> u.assign_policies(*pols) u.save() for p, i in zip(pols, itertools.count()): attrs = {} if isinstance(p, tuple): attrs = p[1] p = p[0] org = None proj = None if 'organisation' in attrs: org = Org...
assign_user_policies(None, default_p)
Predict the next line for this snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') user4 = UserFactory.create(username='user4') ...
assign_user_policies(None, def_pol)
Given snippet: <|code_start|> prj_pol = PolicyFactory.create(name='prj', file='project-policy.json') deny_pol = PolicyFactory.create(name='prj', file='deny-policy.json') Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view', 'party.edit', 'parcel.edit']) assign_...
obj1 = Object('parcel/Cadasta/TestProj/123')
Predict the next line for this snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') user4 = UserFactory.create(username='user4') ...
Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view',
Here is a snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') user4 = UserFactory.create(username='user4') user5 = UserFactory...
PolicyFactory.set_directory(str(datadir))
Given snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') <|code_end|> , continue by predicting the next line. Consider current file ...
PolicyFactory.set_directory(str(datadir))
Given snippet: <|code_start|> def get_path_fields(cls, base=[]): """Get object fields used for calculation of django-tutelary object paths. """ pfs = [] for pf in cls.TutelaryMeta.path_fields: if pf == 'pk': pfs.append(base + ['pk']) else: f = cls._meta.get_...
return Object([get_one(pf) for pf in obj.__class__.TutelaryMeta.pfs])
Given the code snippet: <|code_start|> """ if not issubclass(cls, models.Model): raise DecoratorException( 'permissioned_model', "class '" + cls.__name__ + "' is not a Django model" ) added = False try: if not hasattr(cls, 'TutelaryMeta'): if p...
Action.register(an)
Given the following code snippet before the placeholder: <|code_start|> def permission_required(*actions, obj=None, raise_exception=False): """Permission checking decorator -- works like the ``permission_required`` decorator in the default Django authentication system, except that it takes a sequence of a...
if user.is_authenticated() and check_perms(user, actions, [obj]):
Given the code snippet: <|code_start|> return Object([get_one(pf) for pf in obj.__class__.TutelaryMeta.pfs]) def make_get_perms_object(perms_objs): """Make a function to delegate permission object rendering to some other (foreign key) field of an object. """ def retfn(obj, action): if acti...
raise DecoratorException(
Continue the code snippet: <|code_start|> try: if not hasattr(cls, 'TutelaryMeta'): if perm_type is None or path_fields is None or actions is None: raise DecoratorException( 'permissioned_model', ("missing argument: all of perm_type, path_fi...
raise PermissionObjectException(po)
Given snippet: <|code_start|> return (user1, user2, user3, user4, user5, def_pol, org_pol, prj_pol, deny_pol) def test_roles_creation(datadir, setup): # noqa u1, u2, u3, u4, u5, def_pol, org_pol, prj_pol, deny_pol = setup cadasta_org_role = Role.objects.create( name='cadasta_org', po...
assign_user_policies(None, cadasta_org_role)
Predict the next line after this snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') user4 = UserFactory.create(username='user4') ...
cadasta_org_role = Role.objects.create(
Given snippet: <|code_start|> name='cadasta_org', policies=[def_pol, org_pol], variables={'organisation': 'Cadasta'} ) cadasta_org_role.save() assert str(cadasta_org_role) == 'cadasta_org' testproj_proj_role = Role.objects.create( name='testproj_proj', policies=[def_pol, org_pol, ...
obj1 = Object('parcel/Cadasta/TestProj/123')
Based on the snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') user4 = UserFactory.create(username='user4') user5 = UserFact...
Action.register(['party.list', 'party.view', 'parcel.list', 'parcel.view',
Using the snippet: <|code_start|> obj2 = Object('parcel/Cadasta/Proj2/114') assert not u1.has_perm('parcel.view', obj2) assert u2.has_perm('parcel.view', obj2) assert u3.has_perm('parcel.view', obj2) obj3 = Object('parcel/SkunkWorks/SR-71/Area51') assert not u1.has_perm('parcel.view', obj3) ...
with pytest.raises(RoleVariableException):
Here is a snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') user4 = UserFactory.create(username='user4') user5 = UserFactory...
PolicyFactory.set_directory(str(datadir))
Given snippet: <|code_start|> variables={'org': 'Org1', 'proj': 'Proj1'} ) proj_mgr_2_r = RoleFactory.create( name='proj-mgr', policies=[pols[2]], variables={'org': 'Org2', 'proj': 'Proj2'} ) roles = [sys_admin_r, org_admin_1_r, org_admin_2_r, proj_mgr_1_...
assert list(Role.objects.filter(name='sys-admin')) == [sys_admin_r]
Predict the next line for this snippet: <|code_start|> assert (list(Role.objects.filter(name='org-admin', variables={'org': 'Org1'})) == [org_admin_1_r]) assert (list(Role.objects.filter(name='org-admin', variables={'org': 'Org...
assign_user_policies(None, (org_admin_p, {'org': 'Sandbox'}))
Continue the code snippet: <|code_start|> set([org_admin_1_r, org_admin_2_r])) assert (list(Role.objects.filter(name='org-admin', variables={'org': 'Org1'})) == [org_admin_1_r]) assert (list(Role.objects.filter(name='org-admin', ...
assert user_assigned_policies(None) == []
Given the code snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): users = [] for i in range(1, 11): <|code_end|> , generate the next line using the imports in this file: from tutelary.models import Role, assign_user_policies, user_assigned_policies from .datadir import...
users.append(UserFactory.create(username='user{}'.format(i)))
Using the snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): users = [] for i in range(1, 11): users.append(UserFactory.create(username='user{}'.format(i))) <|code_end|> , determine the next line of code. You have imports: from tutelary.models import Role, ass...
PolicyFactory.set_directory(str(datadir))
Continue the code snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): users = [] for i in range(1, 11): users.append(UserFactory.create(username='user{}'.format(i))) PolicyFactory.set_directory(str(datadir)) sys_admin_p = PolicyFactory.create(name='sys-a...
sys_admin_r = RoleFactory.create(
Here is a snippet: <|code_start|> def test_sequence_creation_empty(): seq1 = SimpleSeparated(None) assert len(seq1) == 0 assert seq1.components == [] def test_sequence_creation_components(): seq2 = SimpleSeparated(['parcel', 'list']) assert len(seq2) == 2 assert seq2.components == ['parcel',...
act1 = Action('parcel.edit')
Continue the code snippet: <|code_start|> def test_sequence_creation_empty(): seq1 = SimpleSeparated(None) assert len(seq1) == 0 assert seq1.components == [] def test_sequence_creation_components(): seq2 = SimpleSeparated(['parcel', 'list']) assert len(seq2) == 2 assert seq2.components == ['...
obj1 = Object('Cadasta/Batangas/parcel/123')
Given the following code snippet before the placeholder: <|code_start|> perms = perms(self, self.request) if isinstance(perms, str): perms = (perms, ) return perms def get_permission_denied_message(self, default=None): if hasattr(self, 'permission_denied_message'): ...
return check_perms(self.request.user, check_actions,
Predict the next line for this snippet: <|code_start|> class BasePermissionRequiredMixin: def get_permission_required(self): if (not hasattr(self, 'permission_required') or self.permission_required is None): raise ImproperlyConfigured( '{0} is missing the permission_...
return action_error_message(self.model.TutelaryMeta.actions,
Given the following code snippet before the placeholder: <|code_start|> class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User class PolicyFactory(factory.django.DjangoModelFactory): class Meta: <|code_end|> , predict the next line using imports from the current file: import...
model = Policy
Given the following code snippet before the placeholder: <|code_start|> class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User class PolicyFactory(factory.django.DjangoModelFactory): class Meta: model = Policy @classmethod def set_directory(cls, dir): ...
model = Role
Here is a snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') <|code_end|> . Write the next line using the current file imports: from django.core.exceptions import ImproperlyConf...
PolicyFactory.set_directory(str(datadir))
Given the following code snippet before the placeholder: <|code_start|> @pytest.fixture(scope="function") # noqa def debug(db): def fn(s): print(s) psets = PermissionSet.objects.all() print('PSets:', list(map( lambda pset: str(pset.pk) + ': ' + repr(pset.tree()), ps...
assert Policy.objects.count() == npol
Predict the next line after this snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') user3 = UserFactory.create(username='user3') <|code_end|> using the current file's imports: ...
PolicyFactory.set_directory(str(datadir))
Continue the code snippet: <|code_start|> @pytest.fixture(scope="function") # noqa def setup(datadir, db): user1 = UserFactory.create(username='user1') user2 = UserFactory.create(username='user2') <|code_end|> . Use current file imports: import pytest import django.views.generic as generic from tutelary.eng...
PolicyFactory.set_directory(str(datadir))
Given the code snippet: <|code_start|> class Meta: ordering = ['name'] class State(models.Model): """Top-level window into state data Intended as a resource to track general state information and as a skeleton for admin inlines such as election data and FOIA logs """ STATUS_OPTIONS =...
objects = StateManager()
Using the snippet: <|code_start|> class Command(BaseCommand): help = ("Creates a json file of the project status of each state to be " "consumed be the front-end website.") def handle(self, *args, **options): <|code_end|> , determine the next line of code. You have imports: from django.core.manag...
self.stdout.write(State.objects.status_json())
Using the snippet: <|code_start|> gop_prez_primary.primary_type = "other" self.assertRaises(ValidationError, gop_prez_primary.clean) class LogTest(TestCase): fixtures = [ 'test_log_model', ] def test_log_key(self): """Log key returns info on state, date...
contact = Contact.objects.all()[0]
Continue the code snippet: <|code_start|> class ElectionTest(TestCase): fixtures = [ 'test_elecdata_model' ] def test_offices(self): "Election.offices should return tuple of offices up for election" # Florida 2012 races <|code_end|> . Use current file imports: import unittest im...
general = Election.objects.get(pk=4)
Given the following code snippet before the placeholder: <|code_start|> # Primary race_type must have a primary_type (e.g. closed, open, blanket) gop_prez_primary.primary_type = "" self.assertRaises(ValidationError, gop_prez_primary.clean) # Primary race_type of other represents an edge...
log = Log(**kwargs)
Given the code snippet: <|code_start|> def filter_method(*args, **kwargs): count_val = 0 try: q_obj = args[0] if isinstance(q_obj, Q): filter_kwargs = {k:v for k, v in q_obj.children} except IndexError: filte...
s = State(postal="MD")
Continue the code snippet: <|code_start|> "user_id": 9, "formal_request": False, "date": "2013-03-28", "org_id": 15, "subject": "Test subject line" } log = Log(**kwargs) log.save() self.assertE...
v = Volunteer.objects.get(user__username="testuser")
Given the following code snippet before the placeholder: <|code_start|> class TestStateManager(TestCase): fixtures = [ 'test_state_status', ] def test_status_json(self): <|code_end|> , predict the next line using imports from the current file: import json from django.test import TestCase from .....
status_json = State.objects.status_json()
Based on the snippet: <|code_start|> class Command(BaseCommand): help = "Reset access log records older than given days." def add_arguments(self, parser): parser.add_argument( "--age", type=int, default=30, help="Maximum age for records to keep in days"...
count = AxesProxyHandler.reset_logs(age_days=options["age"])
Here is a snippet: <|code_start|> """ Checks if the request or given credentials are blacklisted from access. """ if is_client_ip_address_blacklisted(request): return True return False def is_whitelisted(self, request, credentials: dict = None) -> bool: ...
if settings.AXES_LOCK_OUT_AT_FAILURE:
Given the code snippet: <|code_start|> if is_client_ip_address_blacklisted(request): return True return False def is_whitelisted(self, request, credentials: dict = None) -> bool: """ Checks if the request or given credentials are whitelisted for access. """ ...
) >= get_failure_limit(request, credentials)
Based on the snippet: <|code_start|> This method is abstract and other backends can specialize it as needed, but the default implementation checks if the user has attempted to authenticate into the site too many times through the Django authentication backends and returns ``False`` if user exceed...
if is_client_ip_address_blacklisted(request):
Given the code snippet: <|code_start|> if self.is_blacklisted(request, credentials): return False if self.is_whitelisted(request, credentials): return True if self.is_locked(request, credentials): return False return True def is_blacklisted(sel...
if is_client_ip_address_whitelisted(request):
Predict the next line for this snippet: <|code_start|> if self.is_whitelisted(request, credentials): return True if self.is_locked(request, credentials): return False return True def is_blacklisted(self, request, credentials: dict = None) -> bool: """ ...
if is_client_method_whitelisted(request):
Continue the code snippet: <|code_start|> if self.is_admin_site(request): return True if self.is_blacklisted(request, credentials): return False if self.is_whitelisted(request, credentials): return True if self.is_locked(request, credentials): ...
if is_user_attempt_whitelisted(request, credentials):
Continue the code snippet: <|code_start|> "username", "user_agent", "path_info", ) list_filter = ["attempt_time", "logout_time", "path_info"] search_fields = ["ip_address", "user_agent", "username", "path_info"] date_hierarchy = "attempt_time" fieldsets = ( (None, ...
if settings.AXES_ENABLE_ADMIN:
Given snippet: <|code_start|> "user_agent", "path_info", ) list_filter = ["attempt_time", "logout_time", "path_info"] search_fields = ["ip_address", "user_agent", "username", "path_info"] date_hierarchy = "attempt_time" fieldsets = ( (None, {"fields": ("path_info",)}), ...
admin.site.register(AccessAttempt, AccessAttemptAdmin)
Here is a snippet: <|code_start|> "path_info", ) list_filter = ["attempt_time", "logout_time", "path_info"] search_fields = ["ip_address", "user_agent", "username", "path_info"] date_hierarchy = "attempt_time" fieldsets = ( (None, {"fields": ("path_info",)}), (_("Meta Data...
admin.site.register(AccessLog, AccessLogAdmin)
Next line prediction: <|code_start|> log = getLogger(__name__) def get_cache() -> BaseCache: """ Get the cache instance Axes is configured to use with ``settings.AXES_CACHE`` and use ``'default'`` if not set. """ <|code_end|> . Use current file imports: (from datetime import timedelta from hashlib imp...
return caches[getattr(settings, "AXES_CACHE", "default")]
Given the code snippet: <|code_start|> else: if settings.AXES_LOCK_OUT_BY_USER_OR_IP: # One of `username` or `IP address` is used filter_query = [{"username": username}, {"ip_address": ip_address}] elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: # 2. A comb...
request_or_attempt: Union[HttpRequest, AccessBase], credentials: dict = None
Given the following code snippet before the placeholder: <|code_start|> class Command(BaseCommand): help = "Reset all access attempts and lockouts for given IP addresses" def add_arguments(self, parser): parser.add_argument("ip", nargs="+", type=str) def handle(self, *args, **options): c...
count += reset(ip=ip)
Given snippet: <|code_start|> if attempt_time is None: return now() - cool_off return attempt_time - cool_off def filter_user_attempts(request, credentials: dict = None) -> List[QuerySet]: """ Return a list querysets of AccessAttempts that match the given request and credentials. """ ...
if settings.AXES_COOLOFF_TIME is None:
Continue the code snippet: <|code_start|> log = getLogger(__name__) def get_cool_off_threshold(attempt_time: datetime = None) -> datetime: """ Get threshold for fetching access attempts from the database. """ cool_off = get_cool_off() if cool_off is None: raise TypeError( "C...
username = get_client_username(request, credentials)
Continue the code snippet: <|code_start|> log = getLogger(__name__) def get_cool_off_threshold(attempt_time: datetime = None) -> datetime: """ Get threshold for fetching access attempts from the database. """ cool_off = get_cool_off() if cool_off is None: raise TypeError( "C...
filter_kwargs_list = get_client_parameters(
Using the snippet: <|code_start|> log = getLogger(__name__) def get_cool_off_threshold(attempt_time: datetime = None) -> datetime: """ Get threshold for fetching access attempts from the database. """ <|code_end|> , determine the next line of code. You have imports: from logging import getLogger from ...
cool_off = get_cool_off()
Predict the next line for this snippet: <|code_start|>log = getLogger(__name__) def get_cool_off_threshold(attempt_time: datetime = None) -> datetime: """ Get threshold for fetching access attempts from the database. """ cool_off = get_cool_off() if cool_off is None: raise TypeError( ...
AccessAttempt.objects.filter(**filter_kwargs)
Using the snippet: <|code_start|> class Command(BaseCommand): help = "Reset all access attempts and lockouts" def handle(self, *args, **options): <|code_end|> , determine the next line of code. You have imports: from django.core.management.base import BaseCommand from axes.utils import reset and context (c...
count = reset()
Next line prediction: <|code_start|> and maps lockout signals into readable HTTP 403 Forbidden responses. If a project uses ``django rest framework`` then the middleware updates the request and checks whether the limit has been exceeded. It's needed only for integration with DRF because it uses its own ...
response = get_lockout_response(request, credentials) # type: ignore
Given snippet: <|code_start|>""" log = getLogger(__name__) def reset(ip: str = None, username: str = None, ip_or_username=False) -> int: """ Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API. "...
ip_or_username = settings.AXES_LOCK_OUT_BY_USER_OR_IP
Using the snippet: <|code_start|>""" Axes utility functions that are publicly available. This module is separate for historical reasons and offers a backwards compatible import path. """ log = getLogger(__name__) def reset(ip: str = None, username: str = None, ip_or_username=False) -> int: """ Reset reco...
return AxesProxyHandler.reset_attempts(
Based on the snippet: <|code_start|> This module is separate for historical reasons and offers a backwards compatible import path. """ log = getLogger(__name__) def reset(ip: str = None, username: str = None, ip_or_username=False) -> int: """ Reset records that match IP or username, and return the count o...
ip: Optional[str] = get_client_ip_address(request)
Next line prediction: <|code_start|> class Command(BaseCommand): help = "List access attempts" def handle(self, *args, **options): <|code_end|> . Use current file imports: (from django.core.management.base import BaseCommand from axes.models import AccessAttempt) and context including class names, function...
for obj in AccessAttempt.objects.all():
Based on the snippet: <|code_start|> if "axes.middleware.AxesMiddleware" not in settings.MIDDLEWARE: warnings.append( Warning( msg=Messages.MIDDLEWARE_INVALID, hint=Hints.MIDDLEWARE_INVALID, id=Codes.MIDDLEWARE_INVALID, ) ) ...
if issubclass(backend, AxesBackend):
Predict the next line after this snippet: <|code_start|> "You are using the django-axes cache handler for login attempt tracking." " Your cache configuration is however invalid and will not work correctly with django-axes." " This can leave security holes in your login systems as attempts are not...
axes_handler = getattr(settings, "AXES_HANDLER", "")
Predict the next line for this snippet: <|code_start|> class Command(BaseCommand): help = "Reset all access attempts and lockouts for given usernames" def add_arguments(self, parser): parser.add_argument("username", nargs="+", type=str) def handle(self, *args, **options): count = 0 ...
count += reset(username=username)
Using the snippet: <|code_start|> log = getLogger(__name__) # This signal provides the following arguments to any listeners: # request - The current Request object. # username - The username of the User who has been locked out. # ip_address - The IP of the user who has been locked out. user_locked_out = Signal() ...
AxesProxyHandler.user_login_failed(*args, **kwargs)
Using the snippet: <|code_start|> log = getLogger(__name__) # This signal provides the following arguments to any listeners: # request - The current Request object. # username - The username of the User who has been locked out. # ip_address - The IP of the user who has been locked out. user_locked_out = Signal() ...
@receiver(post_save, sender=AccessAttempt)
Predict the next line after this snippet: <|code_start|> def cover_task(): ###################### IMAGE_SCALE = 0.4 screen, spots = initialize_kelpy(dimensions=(1920,1200), bg=(255, 255, 255)) #game.init() #screen = game.display.set_mode([500, 500]) gameon = True background_color = pygame.color.Color("black") ...
thing = DragSprite(screen, spots.cu, imagepath, scale=IMAGE_SCALE)
Next line prediction: <|code_start|> def cover_task(): ###################### IMAGE_SCALE = 0.4 screen, spots = initialize_kelpy(dimensions=(1920,1200), bg=(255, 255, 255)) #game.init() #screen = game.display.set_mode([500, 500]) gameon = True background_color = pygame.color.Color("black") #while gameon: BL...
blicket_detector = DropSprite(screen, BLICKET_DETECTOR_POSITION, blicketd_image_path, scale=.3)
Based on the snippet: <|code_start|> python runkelpy.py <yourscriptname>.py <<< exactly like this. removing the < > and replacing yourscriptname with your script name (of course). """ run_script = None print "Attempting to run your kelpy script!" if len(sys.argv)==1: ##You didn't input the filename! print "ERROR:...
video_directory = lastdir()
Continue the code snippet: <|code_start|> # Additional TFDS metadata VERSION = tfds.core.Version('1.0.0') RELEASE_NOTES = { '1.0.0': 'Initial version', } CONFIGS = [ tfds.core.BuilderConfig(name=scene_name) for scene_name in SCENE_NAMES ] DATASET_INFO_KWARGS = dict( description="""Nerf synthetic dataset."""...
def camera_intrinsics(scene_data: Json) -> sunds.specs_utils.CameraIntrinsics:
Here is a snippet: <|code_start|> class DatasetBuilder: """Wrapper around `tfds.core.DatasetBuilder`.""" def __init__( self, *, scene_builder: LazyBuilder, frame_builder: LazyBuilder, ): """Constructor. Args: scene_builder: Dataset builder containing the scenes. frame...
task: Optional[tasks_lib.Task] = None,
Continue the code snippet: <|code_start|> class DatasetBuilder: """Wrapper around `tfds.core.DatasetBuilder`.""" def __init__( self, *, scene_builder: LazyBuilder, frame_builder: LazyBuilder, ): """Constructor. Args: scene_builder: Dataset builder containing the scenes. ...
split: Tree[Split],
Given the following code snippet before the placeholder: <|code_start|> class DatasetBuilder: """Wrapper around `tfds.core.DatasetBuilder`.""" def __init__( self, *, scene_builder: LazyBuilder, frame_builder: LazyBuilder, ): """Constructor. Args: scene_builder: Dataset bui...
split: Tree[Split],
Next line prediction: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and...
feature=normal.NormalImage(),
Predict the next line after this snippet: <|code_start|># Copyright 2022 The sunds Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
return cameras.PinholeCamera(
Predict the next line for this snippet: <|code_start|># Copyright 2022 The sunds Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # ...
return isometry.Isometry(R=random_rotation, t=tf.random.uniform(shape=[3]))
Based on the snippet: <|code_start|> """Use QR decomposition of random (normal) matrix to get random rotation.""" random_rotation, _ = tf.linalg.qr(tf.random.normal(shape=[3, 3])) return isometry.Isometry(R=random_rotation, t=tf.random.uniform(shape=[3])) def pinhole_camera_with_random_pose(): return { '...
ray_origins, ray_directions = rays.rays_from_image_grid(