<commit_before>import json
from datetime import timedelta

from django.contrib.gis.geos import Polygon
from django.db.models import Case, When, Value, BooleanField, Q, Count
from django.utils.timezone import now
from django.utils.translation import ugettext as _
from django.utils.html import mark_safe
from django.views.generic import TemplateView, DetailView
from django.views.decorators import cache
from django.views.decorators.clickjacking import xframe_options_exempt
from rest_framework.generics import ListAPIView
from rest_framework.exceptions import ValidationError
import django_filters
from django_filters.rest_framework.backends import DjangoFilterBackend
from django.http import QueryDict, Http404

from ..events.models import Event, EventSubtype
from ..groups.models import SupportGroup, SupportGroupSubtype

from . import serializers


def parse_bounds(bounds):
    if not bounds:
        return None

    try:
        bbox = json.loads(bounds)
    except json.JSONDecodeError:
        return None

    if not len(bbox) == 4:
        return None

    try:
        bbox = [float(c) for c in bbox]
    except ValueError:
        return None

    if not (-180.0 <= bbox[0] < bbox[2] <= 180.0) or not (
        -90.0 <= bbox[1] < bbox[3] <= 90
    ):
        return None

    return bbox


class BBoxFilterBackend(object):
    error_message = _(
        "Le paramètre bbox devrait être un tableau de 4 flottants [lon1, lat1, lon2, lat2]."
    )

    def filter_queryset(self, request, queryset, view):
        if not "bbox" in request.query_params:
            return queryset

        bbox = request.query_params["bbox"]

        if bbox is None:
            raise ValidationError(self.error_message)

        bbox = Polygon.from_bbox(bbox)

        return queryset.filter(coordinates__intersects=bbox)


class FixedModelMultipleChoiceFilter(django_filters.ModelMultipleChoiceFilter):
    def get_filter_predicate(self, v):
        return {self.field_name: v}


class EventFilterSet(django_filters.rest_framework.FilterSet):
    subtype = FixedModelMultipleChoiceFilter(
        field_name="subtype", to_field_name="label", queryset=EventSubtype.objects.all()
    )
    include_past = django_filters.BooleanFilter(
        "start_time",
        label="Inclure les événements passés",
        method="filter_include_past",
    )

    def __init__(self, data=None, *args, **kwargs):
        if data is not None:
            data = data.copy()
            if data.get("include_past") is None:
                data["include_past"] = False

        super().__init__(data, *args, **kwargs)

    def filter_include_past(self, queryset, name, value):
        if not value:
            return queryset.upcoming()
        else:
            return queryset

    class Meta:
        model = Event
        fields = ("subtype", "include_past")


class EventsView(ListAPIView):
    serializer_class = serializers.MapEventSerializer
    filter_backends = (BBoxFilterBackend, DjangoFilterBackend)
    filterset_class = EventFilterSet
    authentication_classes = []

    def get_queryset(self):
        return (
            Event.objects.published()
            .filter(coordinates__isnull=False)
            .select_related("subtype")
        )[:5000]

    @cache.cache_control(max_age=300, public=True)
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)


class GroupFilterSet(django_filters.rest_framework.FilterSet):
    subtype = FixedModelMultipleChoiceFilter(
        field_name="subtypes",
        to_field_name="label",
        queryset=SupportGroupSubtype.objects.all(),
    )

    class Meta:
        model = SupportGroup
        fields = ("subtype",)


class GroupsView(ListAPIView):<commit_msg>fix un bug dans l'EventView de la map<commit_after>import json
from datetime import timedelta

from django.contrib.gis.geos import Polygon
from django.db.models import Case, When, Value, BooleanField, Q, Count
from django.utils.timezone import now
from django.utils.translation import ugettext as _
from django.utils.html import mark_safe
from django.views.generic import TemplateView, DetailView
from django.views.decorators import cache
from django.views.decorators.clickjacking import xframe_options_exempt
from rest_framework.generics import ListAPIView
from rest_framework.exceptions import ValidationError
import django_filters
from django_filters.rest_framework.backends import DjangoFilterBackend
from django.http import QueryDict, Http404

from ..events.models import Event, EventSubtype
from ..groups.models import SupportGroup, SupportGroupSubtype

from . import serializers


def parse_bounds(bounds):
    if not bounds:
        return None

    try:
        bbox = json.loads(bounds)
    except json.JSONDecodeError:
        return None

    if not len(bbox) == 4:
        return None

    try:
        bbox = [float(c) for c in bbox]
    except ValueError:
        return None

    if not (-180.0 <= bbox[0] < bbox[2] <= 180.0) or not (
        -90.0 <= bbox[1] < bbox[3] <= 90
    ):
        return None

    return bbox


class BBoxFilterBackend(object):
    error_message = _(
        "Le paramètre bbox devrait être un tableau de 4 flottants [lon1, lat1, lon2, lat2]."
    )

    def filter_queryset(self, request, queryset, view):
        if not "bbox" in request.query_params:
            return queryset

        bbox = request.query_params["bbox"]

        if bbox is None:
            raise ValidationError(self.error_message)

        bbox = Polygon.from_bbox(bbox)

        return queryset.filter(coordinates__intersects=bbox)


class FixedModelMultipleChoiceFilter(django_filters.ModelMultipleChoiceFilter):
    def get_filter_predicate(self, v):
        return {self.field_name: v}


class EventFilterSet(django_filters.rest_framework.FilterSet):
    subtype = FixedModelMultipleChoiceFilter(
        field_name="subtype", to_field_name="label", queryset=EventSubtype.objects.all()
    )
    include_past = django_filters.BooleanFilter(
        "start_time",
        label="Inclure les événements passés",
        method="filter_include_past",
    )

    def __init__(self, data=None, *args, **kwargs):
        if data is not None:
            data = data.copy()
            if data.get("include_past") is None:
                data["include_past"] = False

        super().__init__(data, *args, **kwargs)

    def filter_include_past(self, queryset, name, value):
        if not value:
            return queryset.upcoming()
        else:
            return queryset[:5000]

    class Meta:
        model = Event
        fields = ("subtype", "include_past")


class EventsView(ListAPIView):
    serializer_class = serializers.MapEventSerializer
    filter_backends = (BBoxFilterBackend, DjangoFilterBackend)
    filterset_class = EventFilterSet
    authentication_classes = []

    def get_queryset(self):
        return (
            Event.objects.published()
            .filter(coordinates__isnull=False)
            .select_related("subtype")
        )

    @cache.cache_control(max_age=300, public=True)
    def get(self, request, *args, **kwargs):
        return super().get(request, *args, **kwargs)


class GroupFilterSet(django_filters.rest_framework.FilterSet):
    subtype = FixedModelMultipleChoiceFilter(
        field_name="subtypes",
        to_field_name="label",
        queryset=SupportGroupSubtype.objects.all(),
    )

    class Meta:
        model = SupportGroup
        fields = ("subtype",)


class GroupsView(ListAPIView):
{'fraction_non_alphanumeric': 0.08864965443912812, 'fraction_numerical': 0.008771929824561403, 'mean_word_length': 3.0985838779956425, 'pattern_counts': {'":': 0, '<': 15, '<?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': '4582503', 'n_tokens_mistral': 2265, 'n_tokens_neox': 2160, 'n_words': 549}