<commit_before>from builtins import str
from builtins import object
from collections import defaultdict

from django.conf.urls import url
from django.contrib import admin, messages
from django.core.urlresolvers import reverse
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext_lazy as _

from bluebottle.fsm.forms import StateMachineModelForm
from bluebottle.fsm.triggers import TriggerMixin
from bluebottle.fsm.state import TransitionNotPossible
from bluebottle.notifications.effects import BaseNotificationEffect
from bluebottle.utils.forms import TransitionConfirmationForm


def log_action(obj, user, change_message='Changed', action_flag=CHANGE):
    LogEntry.objects.log_action(
        user_id=user.id,
        content_type_id=ContentType.objects.get_for_model(obj).pk,
        object_id=obj.pk,
        object_repr=str(obj),
        action_flag=action_flag,
        change_message=change_message
    )


def get_effects(effects):
    displayed_effects = [effect for effect in effects if effect.display]
    displayed_effects.sort(key=lambda x: x.__class__.__name__)
    grouped_effects = defaultdict(list)

    for effect in displayed_effects:
        grouped_effects[(effect.__class__, effect.instance.__class__)].append(effect)

    return [cls.render(grouped) for (cls, instance_cls), grouped in list(grouped_effects.items())]


class StateMachineAdminMixin(object):
    form = StateMachineModelForm

    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        """
        Determines the HttpResponse for the change_view stage.
        """
        if object_id and request.method == 'POST' and not request.POST.get('confirm', False):
            obj = self.model.objects.get(pk=object_id)
            ModelForm = self.get_form(request, obj)
            form = ModelForm(request.POST, request.FILES, instance=obj)
            # If there are form errors, then don't go to the confirm page yet.
            if not form.is_valid():
                return super(StateMachineAdminMixin, self).changeform_view(request, object_id, form_url, extra_context)

            new_obj = self.save_form(request, form, change=True)

            send_messages = request.POST.get('enable_messages') == 'on'
            effects = new_obj.execute_triggers(user=request.user, send_messages=send_messages)

            formsets, inline_instances = self._create_formsets(request, new_obj, change=True)

            for formset in formsets:
                for form in formset:
                    if isinstance(form.instance, TriggerMixin):
                        self.save_form(request, form, change=True)
                        effects += form.instance.execute_triggers(user=request.user, send_messages=send_messages)

            if effects:
                rendered_effects = get_effects(effects)

                cancel_link = reverse(
                    'admin:{}_{}_change'.format(
                        self.model._meta.app_label, self.model._meta.model_name
                    ),
                    args=(object_id, )
                )
                action_text = ' and '.join(
                    unicode(trigger.title) for trigger in obj._triggers
                ) or _('perform changes')

                context = dict(
                    obj=obj,
                    title=_('Are you sure'),
                    cancel_url=cancel_link,
                    post=request.POST,
                    opts=self.model._meta,
                    action_text=action_text,
                    media=self.media,
                    has_notifications=any(
                        isinstance(effect, BaseNotificationEffect)
                        for effect in effects
                    ),
                    effects=rendered_effects
                )

                return TemplateResponse(
                    request, "admin/change_effects_confirmation.html", context
                )

        return super(StateMachineAdminMixin, self).changeform_view(request, object_id, form_url, extra_context)

    def save_model(self, request, obj, form, change):
        """
        Given a model instance save it to the database.
        """
        send_messages = request.POST.get('send_messages') == 'on'
        obj.execute_triggers(user=request.user, send_messages=send_messages)
        obj.save()
<commit_msg>Use str not unicode<commit_after>from builtins import str
from builtins import object
from collections import defaultdict

from django.conf.urls import url
from django.contrib import admin, messages
from django.core.urlresolvers import reverse
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.contenttypes.models import ContentType
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.translation import ugettext_lazy as _

from bluebottle.fsm.forms import StateMachineModelForm
from bluebottle.fsm.triggers import TriggerMixin
from bluebottle.fsm.state import TransitionNotPossible
from bluebottle.notifications.effects import BaseNotificationEffect
from bluebottle.utils.forms import TransitionConfirmationForm


def log_action(obj, user, change_message='Changed', action_flag=CHANGE):
    LogEntry.objects.log_action(
        user_id=user.id,
        content_type_id=ContentType.objects.get_for_model(obj).pk,
        object_id=obj.pk,
        object_repr=str(obj),
        action_flag=action_flag,
        change_message=change_message
    )


def get_effects(effects):
    displayed_effects = [effect for effect in effects if effect.display]
    displayed_effects.sort(key=lambda x: x.__class__.__name__)
    grouped_effects = defaultdict(list)

    for effect in displayed_effects:
        grouped_effects[(effect.__class__, effect.instance.__class__)].append(effect)

    return [cls.render(grouped) for (cls, instance_cls), grouped in list(grouped_effects.items())]


class StateMachineAdminMixin(object):
    form = StateMachineModelForm

    def changeform_view(self, request, object_id=None, form_url='', extra_context=None):
        """
        Determines the HttpResponse for the change_view stage.
        """
        if object_id and request.method == 'POST' and not request.POST.get('confirm', False):
            obj = self.model.objects.get(pk=object_id)
            ModelForm = self.get_form(request, obj)
            form = ModelForm(request.POST, request.FILES, instance=obj)
            # If there are form errors, then don't go to the confirm page yet.
            if not form.is_valid():
                return super(StateMachineAdminMixin, self).changeform_view(request, object_id, form_url, extra_context)

            new_obj = self.save_form(request, form, change=True)

            send_messages = request.POST.get('enable_messages') == 'on'
            effects = new_obj.execute_triggers(user=request.user, send_messages=send_messages)

            formsets, inline_instances = self._create_formsets(request, new_obj, change=True)

            for formset in formsets:
                for form in formset:
                    if isinstance(form.instance, TriggerMixin):
                        self.save_form(request, form, change=True)
                        effects += form.instance.execute_triggers(user=request.user, send_messages=send_messages)

            if effects:
                rendered_effects = get_effects(effects)

                cancel_link = reverse(
                    'admin:{}_{}_change'.format(
                        self.model._meta.app_label, self.model._meta.model_name
                    ),
                    args=(object_id, )
                )
                action_text = ' and '.join(
                    str(trigger.title) for trigger in obj._triggers
                ) or _('perform changes')

                context = dict(
                    obj=obj,
                    title=_('Are you sure'),
                    cancel_url=cancel_link,
                    post=request.POST,
                    opts=self.model._meta,
                    action_text=action_text,
                    media=self.media,
                    has_notifications=any(
                        isinstance(effect, BaseNotificationEffect)
                        for effect in effects
                    ),
                    effects=rendered_effects
                )

                return TemplateResponse(
                    request, "admin/change_effects_confirmation.html", context
                )

        return super(StateMachineAdminMixin, self).changeform_view(request, object_id, form_url, extra_context)

    def save_model(self, request, obj, form, change):
        """
        Given a model instance save it to the database.
        """
        send_messages = request.POST.get('send_messages') == 'on'
        obj.execute_triggers(user=request.user, send_messages=send_messages)
        obj.save()

{'fraction_non_alphanumeric': 0.08021038790269559, 'fraction_numerical': 0.0, 'mean_word_length': 2.3853857566765577, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '201673', 'n_tokens_mistral': 2466, 'n_tokens_neox': 2333, 'n_words': 541}