<commit_before>import json
import requests
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from opencivicdata.models import Person, Bill

from tot import settings
from preferences.models import PersonFollow
from bills.views import bill_list_latest


def find_legislator(request):
    senator = request.session.get('sen_from_address')
    representative = request.session.get('rep_from_address')
    address = request.session.get('address')
    lat = request.session.get('lat') or '30.4'
    lon = request.session.get('lon') or '-84.3'

    senator_contact_details = None
    representative_contact_details = None
    senator_sponsorships = None
    rep_sponsorships = None

    if senator and representative:
        senator = json.loads(senator)
        if senator['name'] != 'none found':
            senator_obj = Person.objects.get(id=senator['id'])
            senator_contact_details = get_contact_details(senator_obj)
            senator_sponsorships = senator_obj.billsponsorship_set.all().prefetch_related(
                'bill'
            ).prefetch_related(
                'bill__legislative_session'
            )[:settings.NUMBER_OF_LATEST_ACTIONS]

        representative = json.loads(representative)
        if representative['name'] != 'none found':
            rep_obj = Person.objects.get(id=representative['id'])
            representative_contact_details = get_contact_details(rep_obj)
            rep_sponsorships = rep_obj.billsponsorship_set.all().prefetch_related(
                'bill'
            ).prefetch_related(
                'bill__legislative_session'
            )[:settings.NUMBER_OF_LATEST_ACTIONS]
    return render(
        request,
        'legislators/find_legislator.html', {
            'address_senator': senator,
            'address_representative': representative,
            'address': address,
            'lat': float(lat),
            'lng': float(lon),
            'senator_contact_details': senator_contact_details,
            'representative_contact_details': representative_contact_details,
            'rep_sponsorships': rep_sponsorships,
            'senator_sponsorships': senator_sponsorships
        }
    )


def get_contact_details(legislator):
    # Parsed out seperately for nicer rendering in the templates
    raw_contact_details = legislator.contact_details.all()
    contact_details = {'email': '', 'capitol': [], 'district': []}
    for entry in raw_contact_details:
        if entry.type == 'email':
            contact_details['email'] = entry.value
        if entry.note == 'capitol':
            contact_details['capitol'].append(entry)
        if entry.note == 'district':
            contact_details['district'].append(entry)

    return contact_details


def legislator_detail(request, legislator_id):
    legislator = Person.objects.get(id=legislator_id)
    memberships = legislator.memberships.all().select_related(
        'organization__classification'
    ).select_related('post')
    post = memberships.filter(post__isnull=False)[0]
    party = memberships.filter(organization__classification='party')[0].organization.name
    if party == 'Democratic':
        party = 'Democrat'

    contact_details = get_contact_details(legislator)

    member_since = 'To Be Entered'  # TODO - will come from manual spreadsheet

    all_votes = legislator.votes.all().prefetch_related(
        'vote_event__bill__legislative_session'
    ).order_by(
        '-vote_event__start_date'
    )  # TODO - how to handle vote history pagination?

    paginator = Paginator(all_votes, 10)
    page = request.GET.get('page')

    try:
        votes = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        votes = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        votes = paginator.page(paginator.num_pages)

    recent_votes = votes[:settings.NUMBER_OF_LATEST_ACTIONS]
    sponsored_bills = [
        sponsorship.bill for sponsorship in legislator.billsponsorship_set.all().prefetch_related(
            'bill__actions'
        ).prefetch_related('bill__sponsorships')
    ]
    for bill in sponsored_bills:
        bill.latest_action = list(bill.actions.all())[-1]

    message = ''
    if request.method == 'POST':
        try:
            PersonFollow.objects.get(user=request.user, person_id=legislator_id)
            message = 'You are already following {}.'.format(legislator.name)<commit_msg>optimizes queries, relates to #182<commit_after>import json
import requests
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from opencivicdata.models import Person, Bill

from tot import settings
from preferences.models import PersonFollow
from bills.views import bill_list_latest


def find_legislator(request):
    senator = request.session.get('sen_from_address')
    representative = request.session.get('rep_from_address')
    address = request.session.get('address')
    lat = request.session.get('lat') or '30.4'
    lon = request.session.get('lon') or '-84.3'

    senator_contact_details = None
    representative_contact_details = None
    senator_sponsorships = None
    rep_sponsorships = None

    if senator and representative:
        senator = json.loads(senator)
        if senator['name'] != 'none found':
            senator_obj = Person.objects.get(id=senator['id'])
            senator_contact_details = get_contact_details(senator_obj)
            senator_sponsorships = senator_obj.billsponsorship_set.all().prefetch_related(
                'bill'
            ).prefetch_related(
                'bill__legislative_session'
            )[:settings.NUMBER_OF_LATEST_ACTIONS]

        representative = json.loads(representative)
        if representative['name'] != 'none found':
            rep_obj = Person.objects.get(id=representative['id'])
            representative_contact_details = get_contact_details(rep_obj)
            rep_sponsorships = rep_obj.billsponsorship_set.all().prefetch_related(
                'bill'
            ).prefetch_related(
                'bill__legislative_session'
            )[:settings.NUMBER_OF_LATEST_ACTIONS]
    return render(
        request,
        'legislators/find_legislator.html', {
            'address_senator': senator,
            'address_representative': representative,
            'address': address,
            'lat': float(lat),
            'lng': float(lon),
            'senator_contact_details': senator_contact_details,
            'representative_contact_details': representative_contact_details,
            'rep_sponsorships': rep_sponsorships,
            'senator_sponsorships': senator_sponsorships
        }
    )


def get_contact_details(legislator):
    # Parsed out seperately for nicer rendering in the templates
    raw_contact_details = legislator.contact_details.all()
    contact_details = {'email': '', 'capitol': [], 'district': []}
    for entry in raw_contact_details:
        if entry.type == 'email':
            contact_details['email'] = entry.value
        if entry.note == 'capitol':
            contact_details['capitol'].append(entry)
        if entry.note == 'district':
            contact_details['district'].append(entry)

    return contact_details


def legislator_detail(request, legislator_id):
    legislator = Person.objects.get(id=legislator_id)
    memberships = list(legislator.memberships.all().select_related(
        'organization__classification'
    ).select_related('post'))
    post = [m for m in memberships if m.post][0]
    party = [m for m in memberships if m.organization.classification == 'party'][0].organization.name
    if party == 'Democratic':
        party = 'Democrat'

    contact_details = get_contact_details(legislator)

    member_since = 'To Be Entered'  # TODO - will come from manual spreadsheet

    all_votes = legislator.votes.all().prefetch_related(
        'vote_event__bill__legislative_session'
    ).order_by(
        '-vote_event__start_date'
    )  # TODO - how to handle vote history pagination?

    paginator = Paginator(all_votes, 10)
    page = request.GET.get('page')

    try:
        votes = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        votes = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        votes = paginator.page(paginator.num_pages)

    recent_votes = votes[:settings.NUMBER_OF_LATEST_ACTIONS]
    sponsored_bills = [
        sponsorship.bill for sponsorship in legislator.billsponsorship_set.all().select_related(
            'bill__legislative_session').prefetch_related(
            'bill__actions', 'bill__sponsorships', 'bill__sponsorships__person',
        )
    ]
    for bill in sponsored_bills:
        bill.latest_action = list(bill.actions.all())[-1]

    message = ''
    if request.method == 'POST':
        try:
            PersonFollow.objects.get(user=request.user, person_id=legislator_id)
            message = 'You are already following {}.'.format(legislator.name)
{'fraction_non_alphanumeric': 0.09749303621169916, 'fraction_numerical': 0.0037497321619884296, 'mean_word_length': 3.0358841331603976, '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': '3472877', 'n_tokens_mistral': 2774, 'n_tokens_neox': 2639, 'n_words': 544}