<commit_before># -*- coding: utf-8 -*-
import inspect
import copy

from django import forms
from django.forms.formsets import formset_factory
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _
from django.forms.formsets import BaseFormSet

from pybb.models import (Topic, Post, Attachment, TopicRedirection,
                         PollAnswer, Forum, Poll)
from pybb.compat import User
from pybb.proxies import UserObjectPermission
from pybb import defaults
from pybb.util import tznow, load_class

from autoslug.settings import slugify


class AttachmentForm(forms.ModelForm):
    class Meta(object):
        model = Attachment
        fields = ('file', )

    def clean_file(self):
        if self.cleaned_data['file'].size > defaults.PYBB_ATTACHMENT_SIZE_LIMIT:
            raise forms.ValidationError(_('Attachment is too big'))
        return self.cleaned_data['file']

AttachmentFormSet = inlineformset_factory(Post, Attachment, extra=1, form=AttachmentForm)


class PollAnswerForm(forms.ModelForm):
    class Meta:
        model = PollAnswer
        fields = ('text', )


class BasePollAnswerFormset(BaseInlineFormSet):
    def clean(self):
        if any(self.errors):
            return

        forms_cnt = len(self.initial_forms) + len([form for form in self.extra_forms if form.has_changed()]) - len(self.deleted_forms)

        if forms_cnt > defaults.PYBB_POLL_MAX_ANSWERS:
            raise forms.ValidationError(_('You can''t add more than %s answers for poll') % defaults.PYBB_POLL_MAX_ANSWERS)
        if forms_cnt < 2:
            raise forms.ValidationError(_('Add two or more answers for this poll'))


PollAnswerFormSet = inlineformset_factory(Poll, PollAnswer, extra=2, max_num=defaults.PYBB_POLL_MAX_ANSWERS,
                                          form=PollAnswerForm, formset=BasePollAnswerFormset)


class PostForm(forms.ModelForm):
    error_messages = {
        'duplicate': _("A topic with that name already exists."),
    }

    name = forms.CharField(label=_('Subject'))
    poll_type = forms.TypedChoiceField(label=_('Poll type'),
                                       choices=Poll.TYPE_CHOICES,
                                       coerce=int,
                                       initial=Poll.TYPE_NONE)
    poll_question = forms.CharField(label=_('Poll question'),
                                    required=False,
                                    widget=forms.Textarea(attrs={'class': 'no-markitup'}))
    body = forms.CharField(label=_('Message'),
                           widget=forms.Textarea(attrs={'class': 'pretty_editor'}))

    hash = forms.CharField(label=_('Hash'),
                           widget=forms.HiddenInput())

    class Meta(object):
        model = Post
        fields = ('body',)

    def __init__(self, *args, **kwargs):
        if args:
            kwargs.update(dict(zip(inspect.getargspec(super(PostForm, self).__init__)[0][1:], args)))

        self.user = kwargs.pop('user', None)
        self.ip = kwargs.pop('ip', None)
        self.topic = kwargs.pop('topic', None)
        self.forum = kwargs.pop('forum', None)
        self.actor = kwargs.pop('actor', None)

            #Handle topic subject, poll type and question if editing topic head
        if ('instance' in kwargs) and kwargs['instance'] and (kwargs['instance'].topic.head == kwargs['instance']):
            kwargs.setdefault('initial', {})['name'] = kwargs['instance'].topic.name

            if kwargs['instance'].topic.poll:
                kwargs.setdefault('initial', {})['poll_type'] = kwargs['instance'].topic.poll.type
                kwargs.setdefault('initial', {})['poll_question'] = kwargs['instance'].topic.poll.question

        super(PostForm, self).__init__(**kwargs)

        self.fields['hash'].initial = self.instance.get_hash()

        # remove topic specific fields
        if not (self.forum or (self.instance.pk and (self.instance.topic.head == self.instance))):
            if self.topic:
                del self.fields['name']
            else:
                self.fields['forum'] = forms.ModelChoiceField(label=_('Forum'),
                                                              queryset=Forum.objects.all(),
                                                              required=True)
            del self.fields['poll_type']
            del self.fields['poll_question']

    def clean_name(self):
        name = self.cleaned_data['name']

        if self.topic:
            return name<commit_msg>Sort list of forums by name<commit_after># -*- coding: utf-8 -*-
import inspect
import copy

from django import forms
from django.forms.formsets import formset_factory
from django.forms.models import inlineformset_factory, BaseInlineFormSet
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext as _
from django.forms.formsets import BaseFormSet

from pybb.models import (Topic, Post, Attachment, TopicRedirection,
                         PollAnswer, Forum, Poll)
from pybb.compat import User
from pybb.proxies import UserObjectPermission
from pybb import defaults
from pybb.util import tznow, load_class

from autoslug.settings import slugify


class AttachmentForm(forms.ModelForm):
    class Meta(object):
        model = Attachment
        fields = ('file', )

    def clean_file(self):
        if self.cleaned_data['file'].size > defaults.PYBB_ATTACHMENT_SIZE_LIMIT:
            raise forms.ValidationError(_('Attachment is too big'))
        return self.cleaned_data['file']

AttachmentFormSet = inlineformset_factory(Post, Attachment, extra=1, form=AttachmentForm)


class PollAnswerForm(forms.ModelForm):
    class Meta:
        model = PollAnswer
        fields = ('text', )


class BasePollAnswerFormset(BaseInlineFormSet):
    def clean(self):
        if any(self.errors):
            return

        forms_cnt = len(self.initial_forms) + len([form for form in self.extra_forms if form.has_changed()]) - len(self.deleted_forms)

        if forms_cnt > defaults.PYBB_POLL_MAX_ANSWERS:
            raise forms.ValidationError(_('You can''t add more than %s answers for poll') % defaults.PYBB_POLL_MAX_ANSWERS)
        if forms_cnt < 2:
            raise forms.ValidationError(_('Add two or more answers for this poll'))


PollAnswerFormSet = inlineformset_factory(Poll, PollAnswer, extra=2, max_num=defaults.PYBB_POLL_MAX_ANSWERS,
                                          form=PollAnswerForm, formset=BasePollAnswerFormset)


class PostForm(forms.ModelForm):
    error_messages = {
        'duplicate': _("A topic with that name already exists."),
    }

    name = forms.CharField(label=_('Subject'))
    poll_type = forms.TypedChoiceField(label=_('Poll type'),
                                       choices=Poll.TYPE_CHOICES,
                                       coerce=int,
                                       initial=Poll.TYPE_NONE)
    poll_question = forms.CharField(label=_('Poll question'),
                                    required=False,
                                    widget=forms.Textarea(attrs={'class': 'no-markitup'}))
    body = forms.CharField(label=_('Message'),
                           widget=forms.Textarea(attrs={'class': 'pretty_editor'}))

    hash = forms.CharField(label=_('Hash'),
                           widget=forms.HiddenInput())

    class Meta(object):
        model = Post
        fields = ('body',)

    def __init__(self, *args, **kwargs):
        if args:
            kwargs.update(dict(zip(inspect.getargspec(super(PostForm, self).__init__)[0][1:], args)))

        self.user = kwargs.pop('user', None)
        self.ip = kwargs.pop('ip', None)
        self.topic = kwargs.pop('topic', None)
        self.forum = kwargs.pop('forum', None)
        self.actor = kwargs.pop('actor', None)

            #Handle topic subject, poll type and question if editing topic head
        if ('instance' in kwargs) and kwargs['instance'] and (kwargs['instance'].topic.head == kwargs['instance']):
            kwargs.setdefault('initial', {})['name'] = kwargs['instance'].topic.name

            if kwargs['instance'].topic.poll:
                kwargs.setdefault('initial', {})['poll_type'] = kwargs['instance'].topic.poll.type
                kwargs.setdefault('initial', {})['poll_question'] = kwargs['instance'].topic.poll.question

        super(PostForm, self).__init__(**kwargs)

        self.fields['hash'].initial = self.instance.get_hash()

        # remove topic specific fields
        if not (self.forum or (self.instance.pk and (self.instance.topic.head == self.instance))):
            if self.topic:
                del self.fields['name']
            else:
                self.fields['forum'] = forms.ModelChoiceField(label=_('Forum'),
                                                              queryset=Forum.objects.all().order_by('name'),
                                                              required=True)
            del self.fields['poll_type']
            del self.fields['poll_question']

    def clean_name(self):
        name = self.cleaned_data['name']

        if self.topic:
            return name
{'fraction_non_alphanumeric': 0.1129119394921664, 'fraction_numerical': 0.0012965964343598054, 'mean_word_length': 2.376869755563663, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1259327', 'n_tokens_mistral': 2535, 'n_tokens_neox': 2501, 'n_words': 558}