<commit_before>from __future__ import unicode_literals

import itertools
from copy import copy

from django.db.models import Q
from permission_chain.signals import get_additional_chains, \
    get_additional_chain_queries, process_additional_chain
from rest_framework import status
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import BasePermission
from rest_framework.response import Response

OBJECT_ACTIONS = ["retrieve", "update", "partial_update", "destroy"]

ALL_DJANGO_ACTIONS = {
    "create": "add",
    "update": "change",
    "partial_update": "change",
    "list": "view",
    "retrieve": "view",
    "destroy": "delete"
}


ALL_ACTION_NAMES = ALL_DJANGO_ACTIONS.keys()


def ConfigurablePermission(*args, **kwargs):

    django_action_map = kwargs.pop("django_actions", {})

    class CP(BasePermission):
        django_permission_pattern = kwargs.pop("django_permission_pattern",
                                               None)
        """
        A format string of the form ``"<app name>.%s_<model name>"`` where
        ``<app
        name>``
        and ``<model name>`` are the app and model names used to define the
        ``add``, ``change``, ``view``, and ``delete`` permissions on the model
        this permission is for.  Leave undefined if we should not grant access
        according to Django permissions.
        """

        django_actions = django_action_map
        """
        A list of actions that we should allow using the Django permissions
        model.
        Must be either "standard", a list of keys to the ALL_DJANGO_PERMS dic
        to include, or a dict mapping actions to corresponding
        Django permission type.  Actions not in this list
        will not be allowed using the Django permissions models.  For example,
        an entry in the standard list is "list": "view".

        A value of "standard" will include all standard actions.
        """
        if django_action_map == "standard":
            django_actions = ALL_DJANGO_ACTIONS
        elif isinstance(django_action_map, list):
            django_actions = {k: v for (k, v) in ALL_DJANGO_ACTIONS.items()
                              if k in django_action_map}
        elif not isinstance(django_action_map, dict):
            raise ValueError("Invalid setting for django_actions")

        staff_actions = kwargs.pop("staff_actions", [])
        """
        A list of actions that we should allow to users with ``is_staff`` set to
        ``True``.  Must be one of ``"create"``, ``"update"``,
        ``"partial_update"``,
        ``"list"``, ``"retrieve"``, ``"destroy"``.
        """
        if staff_actions == "standard":
            staff_actions = ALL_ACTION_NAMES

        unconstrained_actions = kwargs.pop("unconstrained_actions", [])
        """
        A list of actions that we should allow to anyone.
        Must be one of ``"create"``, ``"update"``, ``"partial_update"``,
        ``"list"``, ``"retrieve"``, ``"destroy"``.
        """
        if unconstrained_actions == "standard":
            staff_actions = ALL_ACTION_NAMES

        object_actions = \
            [a for a in OBJECT_ACTIONS
             if a in (django_actions.keys() + unconstrained_actions +
                      staff_actions)] + \
             kwargs.pop("additional_object_actions", [])

        def is_allowed_django_action(self, view, action):
            return view.action == action and \
                   action in self.django_actions.keys()

        def has_django_permission(self, request, view):
            if self.django_permission_pattern is None:
                return False

            for a in self.django_actions.keys():
                if self.is_allowed_django_action(view, a):
                    return request.user.has_perm(
                        self.django_permission_pattern % self.django_actions[a]
                    )

            return False

        def has_staff_permission(self, request, view):
            return view.action in self.staff_actions and request.user.is_staff

        def has_object_permission(self, request, view, obj):<commit_msg>bugfix for python3<commit_after>from __future__ import unicode_literals

import itertools
from copy import copy
from six import string_types as basestring

from django.db.models import Q
from permission_chain.signals import get_additional_chains, \
    get_additional_chain_queries, process_additional_chain
from rest_framework import status
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import BasePermission
from rest_framework.response import Response

OBJECT_ACTIONS = ["retrieve", "update", "partial_update", "destroy"]

ALL_DJANGO_ACTIONS = {
    "create": "add",
    "update": "change",
    "partial_update": "change",
    "list": "view",
    "retrieve": "view",
    "destroy": "delete"
}


ALL_ACTION_NAMES = ALL_DJANGO_ACTIONS.keys()


def ConfigurablePermission(*args, **kwargs):

    django_action_map = kwargs.pop("django_actions", {})

    class CP(BasePermission):
        django_permission_pattern = kwargs.pop("django_permission_pattern",
                                               None)
        """
        A format string of the form ``"<app name>.%s_<model name>"`` where
        ``<app
        name>``
        and ``<model name>`` are the app and model names used to define the
        ``add``, ``change``, ``view``, and ``delete`` permissions on the model
        this permission is for.  Leave undefined if we should not grant access
        according to Django permissions.
        """

        django_actions = django_action_map
        """
        A list of actions that we should allow using the Django permissions
        model.
        Must be either "standard", a list of keys to the ALL_DJANGO_PERMS dic
        to include, or a dict mapping actions to corresponding
        Django permission type.  Actions not in this list
        will not be allowed using the Django permissions models.  For example,
        an entry in the standard list is "list": "view".

        A value of "standard" will include all standard actions.
        """
        if django_action_map == "standard":
            django_actions = ALL_DJANGO_ACTIONS
        elif isinstance(django_action_map, list):
            django_actions = {k: v for (k, v) in ALL_DJANGO_ACTIONS.items()
                              if k in django_action_map}
        elif not isinstance(django_action_map, dict):
            raise ValueError("Invalid setting for django_actions")

        staff_actions = kwargs.pop("staff_actions", [])
        """
        A list of actions that we should allow to users with ``is_staff`` set to
        ``True``.  Must be one of ``"create"``, ``"update"``,
        ``"partial_update"``,
        ``"list"``, ``"retrieve"``, ``"destroy"``.
        """
        if staff_actions == "standard":
            staff_actions = ALL_ACTION_NAMES

        unconstrained_actions = kwargs.pop("unconstrained_actions", [])
        """
        A list of actions that we should allow to anyone.
        Must be one of ``"create"``, ``"update"``, ``"partial_update"``,
        ``"list"``, ``"retrieve"``, ``"destroy"``.
        """
        if unconstrained_actions == "standard":
            staff_actions = ALL_ACTION_NAMES

        @property
        def object_actions(self):
            return [a for a in OBJECT_ACTIONS if a in (list(self.django_actions.keys()) +
                                                       self.unconstrained_actions +
                                                       self.staff_actions)] + \
                   kwargs.get("additional_object_actions", [])

        def is_allowed_django_action(self, view, action):
            return view.action == action and \
                   action in self.django_actions.keys()

        def has_django_permission(self, request, view):
            if self.django_permission_pattern is None:
                return False

            for a in self.django_actions.keys():
                if self.is_allowed_django_action(view, a):
                    return request.user.has_perm(
                        self.django_permission_pattern % self.django_actions[a]
                    )

            return False

        def has_staff_permission(self, request, view):
            return view.action in self.staff_actions and request.user.is_staff

        def has_object_permission(self, request, view, obj):
{'fraction_non_alphanumeric': 0.09598421541318478, 'fraction_numerical': 0.0008124419684308263, 'mean_word_length': 2.4072756030051403, 'pattern_counts': {'":': 20, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5085578', 'n_tokens_mistral': 2307, 'n_tokens_neox': 2244, 'n_words': 698}