<commit_before>"""
Contains all the Django fields for Select2.
"""

import logging

logger = logging.getLogger(__name__)


class AutoViewFieldMixin(object):
    """
    Registers itself with AutoResponseView.

    All Auto fields must sub-class this mixin, so that they are registered.

    .. warning:: Do not forget to include ``'django_select2.urls'`` in your url conf, else,
        central view used to serve Auto fields won't be available.
    """
    def __init__(self, *args, **kwargs):
        """
        Class constructor.

        :param auto_id: The key to use while registering this field. If it is not provided then
            an auto generated key is used.

            .. tip::
                This mixin uses full class name of the field to register itself. This is
                used like key in a :py:obj:`dict` by :py:func:`.util.register_field`.

                If that key already exists then the instance is not registered again. So, eventually
                all instances of an Auto field share one instance to respond to the Ajax queries for
                its fields.

                If for some reason any instance needs to be isolated then ``auto_id`` can be used to
                provide a unique key which has never occured before.

        :type auto_id: :py:obj:`unicode`

        """
        name = kwargs.pop('auto_id', u"%s.%s" % (self.__module__, self.__class__.__name__))
        if logger.isEnabledFor(logging.INFO):
            logger.info("Registering auto field: %s", name)

        from . import util

        rf = util.register_field
        if logger.isEnabledFor(logging.DEBUG):
            rf = util.timer(rf)

        id_ = rf(name, self)
        self.field_id = id_
        super(AutoViewFieldMixin, self).__init__(*args, **kwargs)

    def security_check(self, request, *args, **kwargs):
        """
        Returns ``False`` if security check fails.

        :param request: The Ajax request object.
        :type request: :py:class:`django.http.HttpRequest`

        :param args: The ``*args`` passed to :py:meth:`django.views.generic.base.View.dispatch`.
        :param kwargs: The ``**kwargs`` passed to :py:meth:`django.views.generic.base.View.dispatch`.

        :return: A boolean value, signalling if check passed or failed.
        :rtype: :py:obj:`bool`

        .. warning:: Sub-classes should override this. You really do not want random people making
            Http reqeusts to your server, be able to get access to sensitive information.
        """
        return True

    def get_results(self, request, term, page, context):
        "See :py:meth:`.views.Select2View.get_results`."
        raise NotImplementedError


import copy

from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.forms.models import ModelChoiceIterator
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode, force_unicode

from .widgets import Select2Widget, Select2MultipleWidget,\
    HeavySelect2Widget, HeavySelect2MultipleWidget, AutoHeavySelect2Widget, \
    AutoHeavySelect2MultipleWidget, AutoHeavySelect2Mixin, AutoHeavySelect2TagWidget, \
    HeavySelect2TagWidget
from .views import NO_ERR_RESP
from .util import extract_some_key_val


### Light general fields ###

class Select2ChoiceField(forms.ChoiceField):
    """
    Drop-in Select2 replacement for :py:class:`forms.ChoiceField`.
    """
    widget = Select2Widget


class Select2MultipleChoiceField(forms.MultipleChoiceField):
    """
    Drop-in Select2 replacement for :py:class:`forms.MultipleChoiceField`.
    """
    widget = Select2MultipleWidget


### Model fields related mixins ###

class ModelResultJsonMixin(object):
    """
    Makes ``heavy_data.js`` parsable JSON response for queries on its model.

    On query it uses :py:meth:`.prepare_qs_params` to prepare query attributes
    which it then passes to ``self.queryset.filter()`` to get the results.

    It is expected that sub-classes will defined a class field variable
    ``search_fields``, which should be a list of field names to search for.

    ..note:: As of version 3.1.3, ``search_fields`` is optional if sub-class
        overrides ``get_results``.
    """

    def __init__(self, *args, **kwargs):
        """
        Class constructor.

        :param queryset: This can be passed as kwarg here or defined as field variabel,
            like ``search_fields``.
        :type queryset: :py:class:`django.db.models.query.QuerySet` or None

        :param max_results: Maximum number to results to return per Ajax query.
        :type max_results: :py:obj:`int`

        :param to_field_name: Which field's value should be returned as result tuple's
            value. (Default is ``pk``, i.e. the id field of the model)
        :type to_field_name: :py:obj:`str`
        """
        self.max_results = getattr(self, 'max_results', None)
        self.to_field_name = getattr(self, 'to_field_name', 'pk')

        super(ModelResultJsonMixin, self).__init__(*args, **kwargs)

    def get_queryset(self):
        if self.queryset is None:
            raise ValueError('queryset is required.')

        return self.queryset
<commit_msg>Added doc to get_queryset.<commit_after>"""
Contains all the Django fields for Select2.
"""

import logging

logger = logging.getLogger(__name__)


class AutoViewFieldMixin(object):
    """
    Registers itself with AutoResponseView.

    All Auto fields must sub-class this mixin, so that they are registered.

    .. warning:: Do not forget to include ``'django_select2.urls'`` in your url conf, else,
        central view used to serve Auto fields won't be available.
    """
    def __init__(self, *args, **kwargs):
        """
        Class constructor.

        :param auto_id: The key to use while registering this field. If it is not provided then
            an auto generated key is used.

            .. tip::
                This mixin uses full class name of the field to register itself. This is
                used like key in a :py:obj:`dict` by :py:func:`.util.register_field`.

                If that key already exists then the instance is not registered again. So, eventually
                all instances of an Auto field share one instance to respond to the Ajax queries for
                its fields.

                If for some reason any instance needs to be isolated then ``auto_id`` can be used to
                provide a unique key which has never occured before.

        :type auto_id: :py:obj:`unicode`

        """
        name = kwargs.pop('auto_id', u"%s.%s" % (self.__module__, self.__class__.__name__))
        if logger.isEnabledFor(logging.INFO):
            logger.info("Registering auto field: %s", name)

        from . import util

        rf = util.register_field
        if logger.isEnabledFor(logging.DEBUG):
            rf = util.timer(rf)

        id_ = rf(name, self)
        self.field_id = id_
        super(AutoViewFieldMixin, self).__init__(*args, **kwargs)

    def security_check(self, request, *args, **kwargs):
        """
        Returns ``False`` if security check fails.

        :param request: The Ajax request object.
        :type request: :py:class:`django.http.HttpRequest`

        :param args: The ``*args`` passed to :py:meth:`django.views.generic.base.View.dispatch`.
        :param kwargs: The ``**kwargs`` passed to :py:meth:`django.views.generic.base.View.dispatch`.

        :return: A boolean value, signalling if check passed or failed.
        :rtype: :py:obj:`bool`

        .. warning:: Sub-classes should override this. You really do not want random people making
            Http reqeusts to your server, be able to get access to sensitive information.
        """
        return True

    def get_results(self, request, term, page, context):
        "See :py:meth:`.views.Select2View.get_results`."
        raise NotImplementedError


import copy

from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.forms.models import ModelChoiceIterator
from django.db.models import Q
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode, force_unicode

from .widgets import Select2Widget, Select2MultipleWidget,\
    HeavySelect2Widget, HeavySelect2MultipleWidget, AutoHeavySelect2Widget, \
    AutoHeavySelect2MultipleWidget, AutoHeavySelect2Mixin, AutoHeavySelect2TagWidget, \
    HeavySelect2TagWidget
from .views import NO_ERR_RESP
from .util import extract_some_key_val


### Light general fields ###

class Select2ChoiceField(forms.ChoiceField):
    """
    Drop-in Select2 replacement for :py:class:`forms.ChoiceField`.
    """
    widget = Select2Widget


class Select2MultipleChoiceField(forms.MultipleChoiceField):
    """
    Drop-in Select2 replacement for :py:class:`forms.MultipleChoiceField`.
    """
    widget = Select2MultipleWidget


### Model fields related mixins ###

class ModelResultJsonMixin(object):
    """
    Makes ``heavy_data.js`` parsable JSON response for queries on its model.

    On query it uses :py:meth:`.prepare_qs_params` to prepare query attributes
    which it then passes to ``self.queryset.filter()`` to get the results.

    It is expected that sub-classes will defined a class field variable
    ``search_fields``, which should be a list of field names to search for.

    ..note:: As of version 3.1.3, ``search_fields`` is optional if sub-class
        overrides ``get_results``.
    """

    def __init__(self, *args, **kwargs):
        """
        Class constructor.

        :param queryset: This can be passed as kwarg here or defined as field variabel,
            like ``search_fields``.
        :type queryset: :py:class:`django.db.models.query.QuerySet` or None

        :param max_results: Maximum number to results to return per Ajax query.
        :type max_results: :py:obj:`int`

        :param to_field_name: Which field's value should be returned as result tuple's
            value. (Default is ``pk``, i.e. the id field of the model)
        :type to_field_name: :py:obj:`str`
        """
        self.max_results = getattr(self, 'max_results', None)
        self.to_field_name = getattr(self, 'to_field_name', 'pk')

        super(ModelResultJsonMixin, self).__init__(*args, **kwargs)

    def get_queryset(self):
        """
        Returns the queryset.
        
        The default implementation returns the ``self.queryset``, which is usually the
        one set by sub-classes at class-level. However, if that is ``None``
        then ``ValueError`` is thrown.
        
        :return: queryset
        :rtype: :py:class:`django.db.models.QuerySet`
        """
        if self.queryset is None:
            raise ValueError('queryset is required.')

        return self.queryset

{'fraction_non_alphanumeric': 0.09397017110440113, 'fraction_numerical': 0.0038429865495470767, 'mean_word_length': 2.8216783216783217, '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': '3709002', 'n_tokens_mistral': 3062, 'n_tokens_neox': 2951, 'n_words': 1051}