<commit_before># -*- coding: UTF-8 -*-
from django.conf import settings
from django.db.models import Count, Q

from conference.models import Conference, Ticket
from p3 import models

import datetime
import os.path
from collections import defaultdict

def conference_stats(conference, stat=None):
    stats = []
    tickets = Ticket.objects.filter(
        orderitem__order___complete=True,
        fare__ticket_type='conference',
        fare__conference=conference,
    ).select_related('p3_conference', 'orderitem__order__user__user')
    compiled = tickets.exclude(p3_conference=None).exclude(name='')
    not_compiled = tickets.exclude(p3_conference=None).filter(name='') | tickets.filter(p3_conference=None)
    if stat in (None, 'all'):
        stats.append({
            'code': 'all',
            'title': 'Biglietti venduti',
            'count': tickets.count(),
            'have_details': True,
            'details': tickets,
        })
    if stat in (None, 'not_compiled'):
        stats.append({
            'code': 'not_compiled',
            'title': 'Biglietti non compilati',
            'count': not_compiled.count(),
            'have_details': True,
            'details': not_compiled,
        })
    if stat in (None, 'compiled'):
        stats.append({
            'code': 'compiled',
            'title': 'Biglietti compilati',
            'count': compiled.count(),
            'have_details': True,
            'details': compiled,
        })
    if stat is None or stat.startswith('tshirt_'):
        sizes = dict(models.TICKET_CONFERENCE_SHIRT_SIZES)
        for x in compiled.values('p3_conference__shirt_size').annotate(c=Count('id')):
            scode = 'tshirt_%s' % x['p3_conference__shirt_size']
            if stat in (None, scode):
                stats.append({
                    'code': scode,
                    'title': 'Taglia maglietta: %s' % sizes.get(x['p3_conference__shirt_size']),
                    'count': x['c'], 
                    'have_details': True,
                    'details': compiled.filter(p3_conference__shirt_size=x['p3_conference__shirt_size']),
                })
    if stat is None or stat.startswith('diet_'):
        diets = dict(models.TICKET_CONFERENCE_DIETS)
        for x in compiled.values('p3_conference__diet').annotate(c=Count('id')):
            scode = 'diet_%s' % x['p3_conference__diet']
            if stat in (None, scode):
                stats.append({
                    'code': scode,
                    'title': 'Dieta: %s' % diets.get(x['p3_conference__diet']),
                    'count': x['c'], 
                    'have_details': True,
                    'details': compiled.filter(p3_conference__diet=x['p3_conference__diet']),
                })
    def _days_stats(compiled, not_compiled):
        output = []
        days = defaultdict(lambda: 0)
        for x in compiled:
            data = filter(None, map(lambda x: x.strip(), x.p3_conference.days.split(',')))
            if not data:
                days['x'] += 1
            else:
                for v in data:
                    days[v] += 1
        compiled_count = compiled.count()
        not_compiled_count = not_compiled.count()
        for day, count in days.items():
            scode = 'days_%s' % day
            if day != 'x':
                info = float(count) / (compiled_count - days['x']) * (compiled_count + not_compiled_count)
            else:
                info = 0.0
            output.append({
                'code': scode,
                'title': 'Giorno di presenza: %s' % day,
                'count': count,
                'have_details': False,
                'additional_info': info,
            })
        return output

    if stat is None or stat.startswith('days_'):
        ds = _days_stats(compiled, not_compiled)
        for s in ds:
            if stat in (None, s['code']):
                stats.append(s)
    if stat is None or stat.startswith('nostaff_days_'):
        ds = _days_stats(compiled.exclude(ticket_type='staff'), not_compiled.exclude(ticket_type='staff'))
        for s in ds:
            if stat in (None, 'nostaff_' + s['code']):
                s['code'] = 'nostaff_' + s['code']
                s['title'] = s['title'] + ' (escluso staff)'
                stats.append(s)
    if stat in (None, 'sim_not_compiled'):
        tickets = Ticket.objects.filter(
            orderitem__order___complete=True,
            fare__code__startswith='SIM',
            fare__conference=conference,
        ).select_related('p3_conference_sim', 'orderitem__order__user__user')
        qs = tickets.exclude(p3_conference_sim=None).filter(Q(name='')|Q(p3_conference_sim__document='')) | tickets.filter(p3_conference_sim=None)
        stats.append({
            'code': 'sim_not_compiled',
            'title': 'Biglietti SIM non completi',
            'count': qs.count(),
            'have_details': True,
            'details': qs,
        })
    return stats

def conference_ticket_badge(tickets):
    conferences = {}
    for c in Conference.objects.all():
        conferences[c.code] = {
            'obj': c,
            'days': c.days(),
        }
    groups = {}
    qs = tickets\
            .filter(orderitem__order___complete=True)\
            .select_related('fare', 'p3_conference', 'orderitem__order__user__user')
    for t in qs:
        if t.fare.conference not in groups:
            groups[t.fare.conference] = {
                'args': ['-c', os.path.join(settings.OTHER_STUFF, 'badge', t.fare.conference, 'conf.py'), ],
                'tickets': []
            }
        if t.p3_conference is None:
            tagline = ''
            days = '1'
            experience = 0
        else:
            tagline = t.p3_conference.tagline
            experience = t.p3_conference.python_experience
            tdays = map(lambda x: datetime.date(*map(int, x.split('-'))), filter(None, t.p3_conference.days.split(',')))
            cdays = conferences[t.fare.conference]['days']
            days = ','.join(map(str,[cdays.index(x)+1 for x in tdays]))
        groups[t.fare.conference]['tickets'].append({
            'name': t.name or t.orderitem.order.user.name(),
            'tagline': tagline,
            'days': days,
            'fare': {
                'code': t.fare.code,
                'type': t.fare.recipient_type,
            },
            'experience': experience,
            'staff': t.ticket_type == 'staff',
        })
    return groups.values()

def gravatar(email, size=80, default='identicon', rating='r', protocol='https'):
    import urllib, hashlib

    if protocol == 'https':
        host = 'https://secure.gravatar.com'
    else:
        host = 'http://www.gravatar.com'
    gravatar_url = host + "/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"
    gravatar_url += urllib.urlencode({
        'default': default,
        'size': size,
        'rating': rating,
    })
    return gravatar_url<commit_msg>utility function per calcolare il nome di una cache di un frammento html<commit_after># -*- coding: UTF-8 -*-
from django.conf import settings
from django.db.models import Count, Q

from conference.models import Conference, Ticket
from p3 import models

import datetime
import os.path
from collections import defaultdict

def conference_stats(conference, stat=None):
    stats = []
    tickets = Ticket.objects.filter(
        orderitem__order___complete=True,
        fare__ticket_type='conference',
        fare__conference=conference,
    ).select_related('p3_conference', 'orderitem__order__user__user')
    compiled = tickets.exclude(p3_conference=None).exclude(name='')
    not_compiled = tickets.exclude(p3_conference=None).filter(name='') | tickets.filter(p3_conference=None)
    if stat in (None, 'all'):
        stats.append({
            'code': 'all',
            'title': 'Biglietti venduti',
            'count': tickets.count(),
            'have_details': True,
            'details': tickets,
        })
    if stat in (None, 'not_compiled'):
        stats.append({
            'code': 'not_compiled',
            'title': 'Biglietti non compilati',
            'count': not_compiled.count(),
            'have_details': True,
            'details': not_compiled,
        })
    if stat in (None, 'compiled'):
        stats.append({
            'code': 'compiled',
            'title': 'Biglietti compilati',
            'count': compiled.count(),
            'have_details': True,
            'details': compiled,
        })
    if stat is None or stat.startswith('tshirt_'):
        sizes = dict(models.TICKET_CONFERENCE_SHIRT_SIZES)
        for x in compiled.values('p3_conference__shirt_size').annotate(c=Count('id')):
            scode = 'tshirt_%s' % x['p3_conference__shirt_size']
            if stat in (None, scode):
                stats.append({
                    'code': scode,
                    'title': 'Taglia maglietta: %s' % sizes.get(x['p3_conference__shirt_size']),
                    'count': x['c'], 
                    'have_details': True,
                    'details': compiled.filter(p3_conference__shirt_size=x['p3_conference__shirt_size']),
                })
    if stat is None or stat.startswith('diet_'):
        diets = dict(models.TICKET_CONFERENCE_DIETS)
        for x in compiled.values('p3_conference__diet').annotate(c=Count('id')):
            scode = 'diet_%s' % x['p3_conference__diet']
            if stat in (None, scode):
                stats.append({
                    'code': scode,
                    'title': 'Dieta: %s' % diets.get(x['p3_conference__diet']),
                    'count': x['c'], 
                    'have_details': True,
                    'details': compiled.filter(p3_conference__diet=x['p3_conference__diet']),
                })
    def _days_stats(compiled, not_compiled):
        output = []
        days = defaultdict(lambda: 0)
        for x in compiled:
            data = filter(None, map(lambda x: x.strip(), x.p3_conference.days.split(',')))
            if not data:
                days['x'] += 1
            else:
                for v in data:
                    days[v] += 1
        compiled_count = compiled.count()
        not_compiled_count = not_compiled.count()
        for day, count in days.items():
            scode = 'days_%s' % day
            if day != 'x':
                info = float(count) / (compiled_count - days['x']) * (compiled_count + not_compiled_count)
            else:
                info = 0.0
            output.append({
                'code': scode,
                'title': 'Giorno di presenza: %s' % day,
                'count': count,
                'have_details': False,
                'additional_info': info,
            })
        return output

    if stat is None or stat.startswith('days_'):
        ds = _days_stats(compiled, not_compiled)
        for s in ds:
            if stat in (None, s['code']):
                stats.append(s)
    if stat is None or stat.startswith('nostaff_days_'):
        ds = _days_stats(compiled.exclude(ticket_type='staff'), not_compiled.exclude(ticket_type='staff'))
        for s in ds:
            if stat in (None, 'nostaff_' + s['code']):
                s['code'] = 'nostaff_' + s['code']
                s['title'] = s['title'] + ' (escluso staff)'
                stats.append(s)
    if stat in (None, 'sim_not_compiled'):
        tickets = Ticket.objects.filter(
            orderitem__order___complete=True,
            fare__code__startswith='SIM',
            fare__conference=conference,
        ).select_related('p3_conference_sim', 'orderitem__order__user__user')
        qs = tickets.exclude(p3_conference_sim=None).filter(Q(name='')|Q(p3_conference_sim__document='')) | tickets.filter(p3_conference_sim=None)
        stats.append({
            'code': 'sim_not_compiled',
            'title': 'Biglietti SIM non completi',
            'count': qs.count(),
            'have_details': True,
            'details': qs,
        })
    return stats

def conference_ticket_badge(tickets):
    conferences = {}
    for c in Conference.objects.all():
        conferences[c.code] = {
            'obj': c,
            'days': c.days(),
        }
    groups = {}
    qs = tickets\
            .filter(orderitem__order___complete=True)\
            .select_related('fare', 'p3_conference', 'orderitem__order__user__user')
    for t in qs:
        if t.fare.conference not in groups:
            groups[t.fare.conference] = {
                'args': ['-c', os.path.join(settings.OTHER_STUFF, 'badge', t.fare.conference, 'conf.py'), ],
                'tickets': []
            }
        if t.p3_conference is None:
            tagline = ''
            days = '1'
            experience = 0
        else:
            tagline = t.p3_conference.tagline
            experience = t.p3_conference.python_experience
            tdays = map(lambda x: datetime.date(*map(int, x.split('-'))), filter(None, t.p3_conference.days.split(',')))
            cdays = conferences[t.fare.conference]['days']
            days = ','.join(map(str,[cdays.index(x)+1 for x in tdays]))
        groups[t.fare.conference]['tickets'].append({
            'name': t.name or t.orderitem.order.user.name(),
            'tagline': tagline,
            'days': days,
            'fare': {
                'code': t.fare.code,
                'type': t.fare.recipient_type,
            },
            'experience': experience,
            'staff': t.ticket_type == 'staff',
        })
    return groups.values()

def gravatar(email, size=80, default='identicon', rating='r', protocol='https'):
    import urllib, hashlib

    if protocol == 'https':
        host = 'https://secure.gravatar.com'
    else:
        host = 'http://www.gravatar.com'
    gravatar_url = host + "/avatar/" + hashlib.md5(email.lower()).hexdigest() + "?"
    gravatar_url += urllib.urlencode({
        'default': default,
        'size': size,
        'rating': rating,
    })
    return gravatar_url


from django.core.cache import cache
from django.utils.http import urlquote
from django.utils.hashcompat import md5_constructor

def template_cache_name(fragment_name, *variables):
    args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    return 'template.cache.%s.%s' % (fragment_name, args.hexdigest())

def invalidate_template_cache(fragment_name, *variables):
    args = md5_constructor(u':'.join([urlquote(var) for var in variables]))
    cache_key = 'template.cache.%s.%s' % (fragment_name, args.hexdigest())
    cache.delete(cache_key)
    return
{'fraction_non_alphanumeric': 0.1352981494174092, 'fraction_numerical': 0.005277587388622344, 'mean_word_length': 2.04932079414838, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, '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': '5176942', 'n_tokens_mistral': 4523, 'n_tokens_neox': 4355, 'n_words': 907}