def index_by_country(request, country_code): meps_by_country = list(MEP.view("meps/by_country", key=country_code)) country_infos = MEP.view("meps/countries", key=country_code) meps_by_country.sort(key=lambda mep: mep["last"]) context = {"meps": meps_by_country, "country": list(country_infos)[0]["value"]["name"]} return direct_to_template(request, "index.html", context)
def home(request): #Les 7 lignes a venir sont un peu degueu homes = Edito.objects.all() if homes: edito_title = homes[0].edito_title edito = homes[0].edito else: edito_title = '' edito = '' groups = list(MEP.view('meps/groups', group=True)) groups.sort(key=lambda group: group['value']['count'], reverse=True) countries = list(MEP.view('meps/countries', group=True)) countries.sort(key=lambda group: group['value']['count'], reverse=True) votes = Vote.view('votes/all', descending=True) context = { 'groups': groups, 'countries': countries, 'votes': votes, 'edito_title': edito_title, 'edito' : edito } return direct_to_template(request, 'home.html', context)
def index_by_group(request, group): meps_by_group = MEP.view('meps/by_group', key=group) group_infos = MEP.view('meps/groups', key=group) context = { 'meps': meps_by_group, 'group': list(group_infos)[0]['value']['name'], } return direct_to_template(request, 'index.html', context)
def index_by_group(request, group): meps_by_group = list(MEP.view('meps/by_group', key=group)) group_infos = MEP.view('meps/groups', key=group) meps_by_group.sort(key=lambda mep: mep['last']) context = { 'meps': meps_by_group, 'group': group_infos.first()['value'], } return direct_to_template(request, 'meps/by_group.html', context)
def index_by_country(request, country_code): meps_by_country = MEP.view('meps/by_country', key=country_code) country_infos = MEP.view('meps/countries', key=country_code) context = { 'meps': meps_by_country, 'country': list(country_infos)[0]['value']['name'], } return direct_to_template(request, 'index.html', context)
def index_countries(request): countries = MEP.view('meps/countries') countries = list(MEP.view('meps/countries', group=True)) countries.sort(key=lambda group: group['value']['count'], reverse=True) context = { 'countries': countries, } return direct_to_template(request, 'index.html', context)
def mep(request, mep_id): mep_ = MEP.view('meps/by_id', key=mep_id).first() positions = Position.objects.filter(mep_id=mep_id) score_list = mep_.scores print score_list print "XXX" score_list.sort(key = lambda k : k['value']) print score_list scores = [s['value'] for s in mep_.scores] #AAAWWWFFFUUUUUULLLLLLL i=0 for score in score_list: score_list[i] = {'label': score['label'], 'value': score['value'], 'couleur': score['value']/10} i+=1 context = { 'mep_id': mep_id, 'mep': mep_, 'positions': positions, 'visible_count': len([x for x in positions if x.visible]), 'average': sum(scores)/len(scores) if len(scores) > 0 else "", 'score_list' : score_list, 'color_index' : map(lambda i : int(float(i))/10 , scores), ## TODO color_index 'vote_colors' : ['#ff0000', '#dd0022', '#bb0044', '#dd0022', '#bb0044', '#990066', '#770088', '#5500aa', '#3300cc', '#0000ff'], } return direct_to_template(request, 'meps/mep.html', context)
def index_groups(request): groups = list(MEP.view("meps/groups", group=True)) groups.sort(key=lambda group: group["value"]["count"], reverse=True) context = {"groups": groups} return direct_to_template(request, "index.html", context)
def mep_addposition(request, mep_id): if not request.is_ajax(): return HttpResponseServerError() results = {'success':False} # make sure the mep exists mep_ = MEP.view('meps/by_id', key=mep_id).first() # For testing purpose: add the possibility to cause a failure in the js (if # in debug) to see what's would happened for the user try: text = request.GET.get(u'text', '') if settings.DEBUG: if 'slow' in text: time.sleep(10) if 'fail' in text: raise Exception("Simulated failure ! (input contains 'fail' and DEBUG is on)") pos = Position(mep_id=mep_id, content=text) pos.submitter_username = request.user.username pos.submitter_ip = request.META["REMOTE_ADDR"] pos.submit_datetime = datetime.today() pos.moderated = False pos.visible = False pos.save() results = {'success':True} except: pass return HttpResponse(simplejson.dumps(results), mimetype='application/json')
def index_groups(request): groups = list(MEP.view('meps/groups', group=True)) groups.sort(key=lambda group: group['value']['count'], reverse=True) context = { 'groups': groups, } return direct_to_template(request, 'index.html', context)
def mep_raw(request, mep_id): mep_ = MEP.view('meps/by_id', key=mep_id).first() jsonstr = simplejson.dumps(dict(mep_), indent=4) context = { 'mep_id': mep_id, 'mep': mep_, 'jsonstr': jsonstr, } return direct_to_template(request, 'meps/mep_raw.html', context)
def mep_raw(request, mep_id): mep_ = MEP.get(mep_id) jsonstr = simplejson.dumps(dict(mep_), indent=4, use_decimal=True) context = { 'mep_id': mep_id, 'mep': mep_, 'jsonstr': jsonstr, } return direct_to_template(request, 'meps/mep_raw.html', context)
def retrieve_meps_choices(): """ Dynamically retrieve MEPs ids from CouchDB to propose choices in Django. """ meps = MEP.view('meps/all') try: return [(mep.id, mep.doc['infos']['name']['full']) for mep in meps] except ResourceNotFound: return []
def mep(request, mep_id): mep_ = MEP.view('meps/by_id', key=mep_id).first() positions = Position.objects.filter(mep_id=mep_id) context = { 'mep_id': mep_id, 'mep': mep_, 'positions': positions, 'visible_count': len([x for x in positions if x.visible]), } return direct_to_template(request, 'meps/mep.html', context)
def query(request): form = QueryForm(request.GET) if not form.is_valid(): return render_to_response('query.html') key=[] for fltr in ['commitee_filter', 'political_filter', 'country_filter']: val=form.cleaned_data.get(fltr) if val: key.append(val) meps = MEP.view('meps/query', startkey=key) return render_to_response('query.html', { 'meps': meps})
def test_trophies_retrieval_from_mep(self): """ Test that meps' CouchDB model can retrieve associated Django trophies. """ # Initialization a_mep = MEP.get('AlainLipietz') manual_trophy = ManualTrophy.objects.create(label="A manual trophy") auto_trophy = AutoTrophy.objects.create(label="An auto trophy") self.failUnlessEqual(a_mep.trophies, []) # Let's create a reward and attribute it to verify CouchDB's update reward = Reward.objects.create(mep_wikiname=a_mep._id, trophy=manual_trophy, reason="test") a_mep = MEP.get('AlainLipietz') self.failUnlessEqual(repr(a_mep.trophies), "[<ManualTrophy: A manual trophy>]") # OK, now we verify that deletion is triggered to CouchDB reward.delete() a_mep = MEP.get('AlainLipietz') self.failUnlessEqual(a_mep.trophies, [])
def test_trophies_attribution(self): """ Test that trophies' models can interact with CouchDB. """ # Initialization a_mep = MEP.get('AlainLipietz') manual_trophy = ManualTrophy.objects.create(label="A manual trophy") auto_trophy = AutoTrophy.objects.create(label="An auto trophy") self.failUnlessEqual(a_mep.trophies_ids, []) # Let's create a reward and attribute it to verify CouchDB's update reward = Reward.objects.create(mep_wikiname=a_mep._id, trophy=manual_trophy, reason="test") a_mep = MEP.get('AlainLipietz') self.failUnlessEqual(a_mep.trophies_ids, [1]) # OK, now we verify that deletion is triggered to CouchDB reward.delete() a_mep = MEP.get('AlainLipietz') self.failUnlessEqual(a_mep.trophies_ids, [])
def query(request): form = QueryForm(request.GET) if not form.is_valid(): return render_to_response('query.html') key=[] #for fltr in ('commitee_filter', 'group_filter', 'country_filter'): # val=form.cleaned_data.get(fltr) # if val: key.append(val) key=[form.cleaned_data.get('country_filter') or u'DE', form.cleaned_data.get('group_filter') or u'PPE', form.cleaned_data.get('commitee_filter',None)] print key meps = MEP.view('meps/query', key=key) return render_to_response('query.html', { 'meps': meps})
def big_mess(request): meps = MEP.view('meps/by_name') #positions = Position.objects.filter(mep_id=mep_id) for mep_ in meps: import matplotlib matplotlib.use("Agg") from matplotlib import pyplot score_list = mep_.scores pyplot.plot([x['value'] for x in score_list]) pyplot.xlabel("%s %s" % (mep_.last, mep_.first)) pyplot.savefig(realpath("./%simg/trends/%s.png" % (settings.MEDIA_URL, mep_.id)), format="png") pyplot.clf() context = { 'trends' : [m.id for m in meps], } return direct_to_template(request, 'trends.html', context)
def create_mep(mep_json): mep = MEP() mep.id = create_uniq_id(mep_json) mep.picture = mep.id + ".jpg" mep.active = True change_mep_details(mep, mep_json) add_missing_details(mep, mep_json) add_addrs(mep, mep_json["Addresses"]) mep.save() add_committees(mep, mep_json["Committees"]) add_delegations(mep, mep_json.get("Delegations", [])) add_countries(mep, mep_json["Constituencies"]) add_groups(mep, mep_json["Groups"]) add_organizations(mep, mep_json.get("Staff", [])) add_mep_email(mep, mep_json["Mail"]) add_mep_website(mep, mep_json["Homepage"]) add_mep_cv(mep, mep_json.get("CV", [])) print " save mep modifications" mep.save()
def mep(request, mep_id): mep_ = MEP.get(mep_id) mep_["achievements"] = autoTrophies(mep_) positions = Position.objects.filter(mep_id=mep_id) score_list = mep_.scores for score in score_list: score["color"] = score_to_color(int(score["value"])) score_list.sort(key=lambda k: datetime.strptime(k["date"], "%d/%m/%Y")) scores = [s["value"] for s in mep_.scores] if score_list: try: import numpy import matplotlib matplotlib.use("Agg") from matplotlib import pyplot pyplot.plot(scores, "bo") a, b = numpy.polyfit(range(len(scores)), [int(x) for x in scores], 1) pyplot.plot([a * int(x) + b for x in range(len(scores))]) pyplot.legend(("Scores", "Mediane"), "best", shadow=True) pyplot.plot(scores) pyplot.axis([0, len(scores) - 1, 0, 102]) pyplot.title("%s - Votes notes evolution over time" % (mep_.infos["name"]["full"])) pyplot.xticks(range(len(scores)), [k["date"] for k in score_list]) pyplot.xlabel("Votes dates") pyplot.ylabel("Scores on votes") pyplot.savefig( realpath("./memopol2/%simg/trends/meps/%s-scores.png" % (settings.MEDIA_URL, mep_id)), format="png" ) pyplot.clf() except ImportError: pass context = { "mep_id": mep_id, "mep": mep_, "positions": positions, "visible_count": len([x for x in positions if x.visible]), "average": sum(scores) / len(scores) if len(scores) > 0 else "", "score_list": score_list, } return direct_to_template(request, "meps/mep.html", context)
def index_groups(request): groups = MEP.view('meps/groups') # TODO: find a way to do the reduce at the couchdb level from collections import defaultdict py_groups = defaultdict(dict) for group in groups: py_groups[group.code].setdefault('count', 0) py_groups[group.code]['count'] += 1 py_groups[group.code]['code'] = group.code py_groups[group.code]['name'] = group.name groups = list(py_groups.values()) groups.sort(key=lambda dic: dic['name']) # /TODO context = { 'groups': groups, } return direct_to_template(request, 'index.html', context)
def index_countries(request): countries = MEP.view('meps/countries') # TODO: find a way to do the reduce at the couchdb level from collections import defaultdict py_countries = defaultdict(dict) for country in countries: py_countries[country.code].setdefault('count', 0) py_countries[country.code]['count'] += 1 py_countries[country.code]['code'] = country.code py_countries[country.code]['name'] = country.name countries = list(py_countries.values()) countries.sort(key=lambda dic: dic['name']) # /TODO context = { 'countries': countries, } return direct_to_template(request, 'index.html', context)
def mep(request, mep_id): mep_ = MEP.get(mep_id) positions = Position.objects.filter(mep_id=mep_id) score_list = mep_.scores for score in score_list: score['color'] = score_to_color(int(score['value'])) score_list.sort(key = lambda k : datetime.strptime(k['date'], "%d/%m/%Y")) scores = [s['value'] for s in mep_.scores] if score_list: try: import numpy import matplotlib matplotlib.use("Agg") from matplotlib import pyplot pyplot.plot(scores, 'bo') a, b = numpy.polyfit(range(len(scores)), [int(x) for x in scores], 1) pyplot.plot([a*int(x) + b for x in range(len(scores))]) pyplot.legend(('Scores', 'Mediane'), 'best', shadow=True) pyplot.plot(scores) pyplot.axis([0, len(scores) - 1, 0, 102]) pyplot.title("%s - Votes notes evolution over time" % (mep_.infos['name']['full'])) pyplot.xticks(range(len(scores)), [k['date'] for k in score_list]) pyplot.xlabel("Votes dates") pyplot.ylabel("Scores on votes") pyplot.savefig(realpath(".%simg/trends/meps/%s-scores.png" % (settings.MEDIA_URL, mep_id)), format="png") pyplot.clf() except ImportError: pass context = { 'mep_id': mep_id, 'mep': mep_, 'positions': positions, 'visible_count': len([x for x in positions if x.visible]), 'average': sum(scores)/len(scores) if len(scores) > 0 else "", 'score_list' : score_list, } return direct_to_template(request, 'meps/mep.html', context)
def mep(self): return MEP.get(self.mep_wikiname)
def index_by_group(request, group): meps_by_group = list(MEP.view("meps/by_group", key=group)) group_infos = MEP.view("meps/groups", key=group) meps_by_group.sort(key=lambda mep: mep["last"]) context = {"meps": meps_by_group, "group": group_infos.first()["value"]} return direct_to_template(request, "meps/by_group.html", context)
def index_by_group(request, group): meps_by_group = MEP.view('meps/by_group', key=group) context = { 'meps': meps_by_group, } return direct_to_template(request, 'index.html', context)
def index_by_country(request, country_code): meps_by_country = MEP.view('meps/by_country', key=country_code) context = { 'meps': meps_by_country, } return direct_to_template(request, 'index.html', context)
def index_names(request): meps_by_name = MEP.view('meps/by_name') context = { 'meps': meps_by_name, } return direct_to_template(request, 'index.html', context)
def setUp(self): # Delete all trophies for the test user a_mep = MEP.get('AlainLipietz') a_mep.trophies_ids = [] a_mep.save()