<commit_before>"""Feeds for badge"""
import datetime
import hashlib
import urllib

import jingo

from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.utils.feedgenerator import (SyndicationFeed, Rss201rev2Feed,
                                        Atom1Feed, get_tag_uri)
import django.utils.simplejson as json
from django.shortcuts import get_object_or_404

from django.contrib.auth.models import User
from django.conf import settings

try:
    from tower import ugettext_lazy as _
except ImportError, e:
    from django.utils.translation import ugettext_lazy as _

try:
    from commons.urlresolvers import reverse
except ImportError, e:
    from django.core.urlresolvers import reverse

from . import validate_jsonp
from .models import (Badge, Award, Progress,
        BadgeAwardNotAllowedException)


MAX_FEED_ITEMS = getattr(settings, 'BADGER_MAX_FEED_ITEMS', 15)


class BaseJSONFeedGenerator(SyndicationFeed):
    """JSON feed generator"""
    # TODO:liberate - Can this class be a generally-useful lib?

    mime_type = 'application/json'

    def _encode_complex(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()

    def build_item(self, item):
        """Simple base item formatter.
        Omit some named keys and any keys with false-y values"""
        omit_keys = ('obj', 'unique_id', )
        return dict((k,v) for k,v in item.items()
                    if v and k not in omit_keys)

    def build_feed(self):
        """Simple base feed formatter.
        Omit some named keys and any keys with false-y values"""
        omit_keys = ('obj', 'request', 'id', )
        feed_data = dict((k,v) for k,v in self.feed.items()
                         if v and k not in omit_keys)
        feed_data['items'] = [self.build_item(item) for item in self.items]
        return feed_data

    def write(self, outfile, encoding):
        request = self.feed['request']

        # Check for a callback param, validate it before use
        callback = request.GET.get('callback', None)
        if callback is not None:
            if not validate_jsonp.is_valid_jsonp_callback_value(callback):
                callback = None

        # Build the JSON string, wrapping it in a callback param if necessary.
        json_string = json.dumps(self.build_feed(),
                                 default=self._encode_complex)
        if callback:
            outfile.write('%s(%s)' % (callback, json_string))
        else:
            outfile.write(json_string)


class BaseFeed(Feed):
    """Base feed for all of badger, allows switchable generator from URL route
    and other niceties"""
    # TODO:liberate - Can this class be a generally-useful lib?

    json_feed_generator = BaseJSONFeedGenerator
    rss_feed_generator = Rss201rev2Feed
    atom_feed_generator = Atom1Feed

    def __call__(self, request, *args, **kwargs):
        self.request = request
        return super(BaseFeed, self).__call__(request, *args, **kwargs)

    def get_object(self, request, format):
        self.link = request.build_absolute_uri('/')
        if format == 'json':
            self.feed_type = self.json_feed_generator
        elif format == 'rss':
            self.feed_type = self.rss_feed_generator
        else:
            self.feed_type = self.atom_feed_generator
        return super(BaseFeed, self).get_object(request)

    def feed_extra_kwargs(self, obj):
        return {'request': self.request, 'obj': obj, }

    def item_extra_kwargs(self, obj):
        return {'obj': obj, }

    def item_pubdate(self, obj):
        return obj.created

    def item_author_link(self, obj):
        if not obj.creator or not hasattr('get_absolute_url', obj.creator):
            return None
        else:
            return self.request.build_absolute_uri(
                obj.creator.get_absolute_url())<commit_msg>Oops. hasattr() does not work that way<commit_after>"""Feeds for badge"""
import datetime
import hashlib
import urllib

import jingo

from django.contrib.syndication.views import Feed, FeedDoesNotExist
from django.utils.feedgenerator import (SyndicationFeed, Rss201rev2Feed,
                                        Atom1Feed, get_tag_uri)
import django.utils.simplejson as json
from django.shortcuts import get_object_or_404

from django.contrib.auth.models import User
from django.conf import settings

try:
    from tower import ugettext_lazy as _
except ImportError, e:
    from django.utils.translation import ugettext_lazy as _

try:
    from commons.urlresolvers import reverse
except ImportError, e:
    from django.core.urlresolvers import reverse

from . import validate_jsonp
from .models import (Badge, Award, Progress,
        BadgeAwardNotAllowedException)


MAX_FEED_ITEMS = getattr(settings, 'BADGER_MAX_FEED_ITEMS', 15)


class BaseJSONFeedGenerator(SyndicationFeed):
    """JSON feed generator"""
    # TODO:liberate - Can this class be a generally-useful lib?

    mime_type = 'application/json'

    def _encode_complex(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.isoformat()

    def build_item(self, item):
        """Simple base item formatter.
        Omit some named keys and any keys with false-y values"""
        omit_keys = ('obj', 'unique_id', )
        return dict((k,v) for k,v in item.items()
                    if v and k not in omit_keys)

    def build_feed(self):
        """Simple base feed formatter.
        Omit some named keys and any keys with false-y values"""
        omit_keys = ('obj', 'request', 'id', )
        feed_data = dict((k,v) for k,v in self.feed.items()
                         if v and k not in omit_keys)
        feed_data['items'] = [self.build_item(item) for item in self.items]
        return feed_data

    def write(self, outfile, encoding):
        request = self.feed['request']

        # Check for a callback param, validate it before use
        callback = request.GET.get('callback', None)
        if callback is not None:
            if not validate_jsonp.is_valid_jsonp_callback_value(callback):
                callback = None

        # Build the JSON string, wrapping it in a callback param if necessary.
        json_string = json.dumps(self.build_feed(),
                                 default=self._encode_complex)
        if callback:
            outfile.write('%s(%s)' % (callback, json_string))
        else:
            outfile.write(json_string)


class BaseFeed(Feed):
    """Base feed for all of badger, allows switchable generator from URL route
    and other niceties"""
    # TODO:liberate - Can this class be a generally-useful lib?

    json_feed_generator = BaseJSONFeedGenerator
    rss_feed_generator = Rss201rev2Feed
    atom_feed_generator = Atom1Feed

    def __call__(self, request, *args, **kwargs):
        self.request = request
        return super(BaseFeed, self).__call__(request, *args, **kwargs)

    def get_object(self, request, format):
        self.link = request.build_absolute_uri('/')
        if format == 'json':
            self.feed_type = self.json_feed_generator
        elif format == 'rss':
            self.feed_type = self.rss_feed_generator
        else:
            self.feed_type = self.atom_feed_generator
        return super(BaseFeed, self).get_object(request)

    def feed_extra_kwargs(self, obj):
        return {'request': self.request, 'obj': obj, }

    def item_extra_kwargs(self, obj):
        return {'obj': obj, }

    def item_pubdate(self, obj):
        return obj.created

    def item_author_link(self, obj):
        if not obj.creator or not hasattr(obj.creator, 'get_absolute_url'):
            return None
        else:
            return self.request.build_absolute_uri(
                obj.creator.get_absolute_url())
{'fraction_non_alphanumeric': 0.08901734104046242, 'fraction_numerical': 0.0038535645472061657, 'mean_word_length': 2.672641509433962, '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': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4843639', 'n_tokens_mistral': 2290, 'n_tokens_neox': 2209, 'n_words': 657}