<commit_before>from builtins import object

from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework_json_api.relations import ResourceRelatedField
from rest_framework_json_api.serializers import ModelSerializer

from geopy.distance import distance, lonlat

from bluebottle.activities.models import Activity, Contributor, Contribution
from bluebottle.impact.models import ImpactGoal
from bluebottle.members.models import Member
from bluebottle.fsm.serializers import AvailableTransitionsField
from bluebottle.utils.fields import FSMField, ValidationErrorsField, RequiredErrorsField

from bluebottle.utils.serializers import ResourcePermissionField


class MatchingPropertiesField(serializers.ReadOnlyField):
    def __init__(self, **kwargs):
        kwargs['source'] = '*'
        super().__init__(**kwargs)

    def to_representation(self, obj):
        user = self.context['request'].user
        matching = {'skill': False, 'theme': False, 'location': False}

        if user.is_authenticated:
            if 'skills' not in self.context:
                self.context['skills'] = user.skills.all()

            if 'themes' not in self.context:
                self.context['themes'] = user.favourite_themes.all()

            if 'location' not in self.context:
                self.context['location'] = user.location or user.place

            try:
                if obj.expertise in self.context['skills']:
                    matching['skill'] = True
            except AttributeError:
                pass

            try:
                if obj.initiative.theme in self.context['themes']:
                    matching['theme'] = True
            except AttributeError:
                pass

            positions = []
            try:
                if obj.location:
                    positions = [obj.location.position.tuple]
            except AttributeError:
                try:
                    positions = [
                        slot.location.position.tuple for slot in obj.slots.all() if slot.location
                    ]
                except AttributeError:
                    pass

            if self.context['location'] and positions:
                dist = min(
                    distance(
                        lonlat(*pos),
                        lonlat(*self.context['location'].position.tuple)
                    ) for pos in positions
                )

                if dist.km < 20:
                    matching['location'] = True

        print('!!!!', matching)
        return matching


# This can't be in serializers because of circular imports
class BaseActivitySerializer(ModelSerializer):
    title = serializers.CharField(allow_blank=True, required=False)
    status = FSMField(read_only=True)
    owner = ResourceRelatedField(read_only=True)
    permissions = ResourcePermissionField('activity-detail', view_args=('pk',))
    transitions = AvailableTransitionsField(source='states')
    is_follower = serializers.SerializerMethodField()
    type = serializers.CharField(read_only=True, source='JSONAPIMeta.resource_name')
    stats = serializers.OrderedDict(read_only=True)
    goals = ResourceRelatedField(required=False, many=True, queryset=ImpactGoal.objects.all())
    slug = serializers.CharField(read_only=True)

    matching_properties = MatchingPropertiesField()
<commit_msg>Remove debugging code<commit_after>from builtins import object

from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework_json_api.relations import ResourceRelatedField
from rest_framework_json_api.serializers import ModelSerializer

from geopy.distance import distance, lonlat

from bluebottle.activities.models import Activity, Contributor, Contribution
from bluebottle.impact.models import ImpactGoal
from bluebottle.members.models import Member
from bluebottle.fsm.serializers import AvailableTransitionsField
from bluebottle.utils.fields import FSMField, ValidationErrorsField, RequiredErrorsField

from bluebottle.utils.serializers import ResourcePermissionField


class MatchingPropertiesField(serializers.ReadOnlyField):
    def __init__(self, **kwargs):
        kwargs['source'] = '*'
        super().__init__(**kwargs)

    def to_representation(self, obj):
        user = self.context['request'].user
        matching = {'skill': False, 'theme': False, 'location': False}

        if user.is_authenticated:
            if 'skills' not in self.context:
                self.context['skills'] = user.skills.all()

            if 'themes' not in self.context:
                self.context['themes'] = user.favourite_themes.all()

            if 'location' not in self.context:
                self.context['location'] = user.location or user.place

            try:
                if obj.expertise in self.context['skills']:
                    matching['skill'] = True
            except AttributeError:
                pass

            try:
                if obj.initiative.theme in self.context['themes']:
                    matching['theme'] = True
            except AttributeError:
                pass

            positions = []
            try:
                if obj.location:
                    positions = [obj.location.position.tuple]
            except AttributeError:
                try:
                    positions = [
                        slot.location.position.tuple for slot in obj.slots.all() if slot.location
                    ]
                except AttributeError:
                    pass

            if self.context['location'] and positions:
                dist = min(
                    distance(
                        lonlat(*pos),
                        lonlat(*self.context['location'].position.tuple)
                    ) for pos in positions
                )

                if dist.km < 20:
                    matching['location'] = True

        return matching


# This can't be in serializers because of circular imports
class BaseActivitySerializer(ModelSerializer):
    title = serializers.CharField(allow_blank=True, required=False)
    status = FSMField(read_only=True)
    owner = ResourceRelatedField(read_only=True)
    permissions = ResourcePermissionField('activity-detail', view_args=('pk',))
    transitions = AvailableTransitionsField(source='states')
    is_follower = serializers.SerializerMethodField()
    type = serializers.CharField(read_only=True, source='JSONAPIMeta.resource_name')
    stats = serializers.OrderedDict(read_only=True)
    goals = ResourceRelatedField(required=False, many=True, queryset=ImpactGoal.objects.all())
    slug = serializers.CharField(read_only=True)

    matching_properties = MatchingPropertiesField()

{'fraction_non_alphanumeric': 0.08483328415461788, 'fraction_numerical': 0.0005901445854234287, 'mean_word_length': 2.357602773650322, 'pattern_counts': {'":': 0, '<': 5, '<?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': '337101', 'n_tokens_mistral': 1752, 'n_tokens_neox': 1650, 'n_words': 396}