From 7e2e1d4410b2022ac6c0eab9b1681b003afc774c Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Tue, 18 Nov 2014 20:59:28 -0800 Subject: [PATCH 01/18] Class notes and lab for 11/18 --- Students/SSchwafel/Notes/11182014.notes | 114 ++++++++++++++++++ .../SSchwafel/session07/circle_class_lab.py | 33 +++++ 2 files changed, 147 insertions(+) create mode 100644 Students/SSchwafel/Notes/11182014.notes create mode 100644 Students/SSchwafel/session07/circle_class_lab.py diff --git a/Students/SSchwafel/Notes/11182014.notes b/Students/SSchwafel/Notes/11182014.notes new file mode 100644 index 00000000..39810549 --- /dev/null +++ b/Students/SSchwafel/Notes/11182014.notes @@ -0,0 +1,114 @@ +Notes - November 18, 2014 +==================== + + + Subclassing is not for specialization, it's for reusing code + + The subclass is in charge + + + Multiple inheritance - inheriting from more than one class + +class Combined(Super1, Super2, Super3): + +method resolution order - class order of operations + + is it an instance attribute? + Is it a class attribute? + Is it a superclass attribute? + + Is it an attributed of the left-most superclass? + Next? + +Mixins - classes that are designed to add functionality to a class, but can't do much on its own + + animal + + mammal + givebirth() + + Bird + layeggs() + + Where do you put platypus? + + Real world example: FloatCanvas + + + +All of the lcass definitions we've been showing inherit from object + +This is referred to as a "new style" class + +Always subclass from Object + + +super(): <--- use it to call a superclass method, rather than explicitly callin the unbound method on the superclass + +read manpages on super() + +Properties + +Attributes are simple and concise + +But what if you need to add extra behavior? + +class C(object): + _x = None + @property + def x(self): + return self._x + @x.setter + def x(self, value): + self._x = value + +@ <----decoration + +Syntax for wrapping up function with special syntax + +getters/setters/deleters + + +Static and Class Methods: + + Static method is a method that doesn't get 'self' + + @staticmethod + def(a,b): + return a+b + + +Why are static methods useful? They aren't, usually. + +99% of the time you just want a module-level function + +Class Methods + +A class method gets the class object, rather than an instance, as the first argument + +Why? Unlike static methods, class methods are quite common. They are friendly to subclassing + +Properties, Satic Methods, and Class Methods are powerful features of Python's OO model. + + Descriptor Protocol! + +Special Methods! MAgic Methods are the secret sauce to Python's Duck typing. Defining the appropriate special methods in your classes is how you make your classes behave like python Builtins. + +__init__ <---special method + +object.__str__ is what happens when you ask for a string version of an object, for example + + +Protocols + + THe set of special methods needed to emulate a particular type of Python object is called a protocol. + +Your classes can "become" like Python builtins by implementing methods in a given protocol + + +Use special methods when you want your class to act like a "standard" class in some way. + +Look up the special methods you need and define them + + Guide to Python's Magic Methods + diff --git a/Students/SSchwafel/session07/circle_class_lab.py b/Students/SSchwafel/session07/circle_class_lab.py new file mode 100644 index 00000000..35b61ed0 --- /dev/null +++ b/Students/SSchwafel/session07/circle_class_lab.py @@ -0,0 +1,33 @@ +#!/usr/bin/python +from math import pi + +class Circle(object): + def __init__(self, radius): + self.radius = float(radius) + + @classmethod + def from_diameter(cls, diameter): + + return cls(diameter/2.0) + + + + @property + def diameter(self): + return self.radius*2.0 + @diameter.setter + def diameter(self, value): + self.radius = value/2.0 + @property + def area(self): + return self.radius**2*pi + def __repr__(self): + return "Circle{}".format(self.radius) + +c = Circle(4) + +print c.radius +print c.diameter +print c.area +print c.__repr__ + From a30fb6f80a1b6f226febd63614e019774c099193 Mon Sep 17 00:00:00 2001 From: saschwafel Date: Tue, 25 Nov 2014 14:13:41 -0800 Subject: [PATCH 02/18] Adding adding, mul, functions; adding tests --- .../SSchwafel/session07/circle_class_lab.py | 33 ++++++++++++++++++- Students/SSchwafel/session07/test_circles.py | 26 +++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 Students/SSchwafel/session07/test_circles.py diff --git a/Students/SSchwafel/session07/circle_class_lab.py b/Students/SSchwafel/session07/circle_class_lab.py index 35b61ed0..904647e6 100644 --- a/Students/SSchwafel/session07/circle_class_lab.py +++ b/Students/SSchwafel/session07/circle_class_lab.py @@ -10,7 +10,31 @@ def from_diameter(cls, diameter): return cls(diameter/2.0) + def __add__(self, other): + + return Circle(self.radius + other.radius) + + def __mul__(self, other): + try: + return Circle(self.radius * other.radius) + except AttributeError: + + return Circle(self.radius * other) + + __rmul__ = __mul__ + + def __lt__(self, other): + + return self.radius < other.radius + + def __gt__(self, other): + + return self.radius > other.radius + + def __eq__(self, other): + + return self.radius == other.radius @property def diameter(self): @@ -25,9 +49,16 @@ def __repr__(self): return "Circle{}".format(self.radius) c = Circle(4) +c2 = Circle(5) print c.radius print c.diameter print c.area -print c.__repr__ +#print c.__repr__ + +print c + c2 +print c2 * 2 +print 2 * c2 +print c2 < c2 +print c2 * c2 diff --git a/Students/SSchwafel/session07/test_circles.py b/Students/SSchwafel/session07/test_circles.py new file mode 100644 index 00000000..e6739acd --- /dev/null +++ b/Students/SSchwafel/session07/test_circles.py @@ -0,0 +1,26 @@ +#!/usr/bin/python + +from circle_class_lab import Circle + +def test_area(): + + circle1 = Circle(4) + circle2 = Circle(5) + + assert circle1.area < circle2.area + +def test_adding(): + + circle1 = Circle(4) + circle2 = Circle(5) + + assert circle1+circle2 == Circle(9) + + +def test_mul(): + + circle1 = Circle(4) + circle2 = Circle(5) + + assert circle1*circle2 == Circle(20) + #assert circle1*2 == Circle8 From b7e95ab0f12df4ff6e9a1f91672677abc9d9c358 Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Tue, 25 Nov 2014 21:10:16 -0800 Subject: [PATCH 03/18] Adding session08 labs and notes --- Students/SSchwafel/Notes/11252014.notes | 68 ++++++++++++++++++++ Students/SSchwafel/session08/callable_lab.py | 18 ++++++ Students/SSchwafel/session08/iterator_lab.py | 37 +++++++++++ Students/SSchwafel/session08/sparse_array.py | 59 +++++++++++++++++ 4 files changed, 182 insertions(+) create mode 100644 Students/SSchwafel/Notes/11252014.notes create mode 100644 Students/SSchwafel/session08/callable_lab.py create mode 100644 Students/SSchwafel/session08/iterator_lab.py create mode 100644 Students/SSchwafel/session08/sparse_array.py diff --git a/Students/SSchwafel/Notes/11252014.notes b/Students/SSchwafel/Notes/11252014.notes new file mode 100644 index 00000000..65e1e9ec --- /dev/null +++ b/Students/SSchwafel/Notes/11252014.notes @@ -0,0 +1,68 @@ +Notes - Nov 25, 2014 + +__iadd__ + + augmented assignment, used for in-place addition; changes object in place + +Making your class behave like builtins! + +callable classes + +a_result = something(some_arguments) + + something <---Class + + __call__)*args, **kwargs) + + if you define a __call__ method, that method will be used when code "calls" an instance of your class + +Non-built-in sequence classes! + +You can create a class that looks like a regular sequence, just add __len__, __getitem_, __setitem__, __delitem__, etc. + + +Iterators and generators + +What goes on in for loops? + + iterators are what makes Python so readable + + an_iterator.__iter__() + + returns the iterator object itself + + an_iterator.next() + + returns next item until there are none, then returns StopIteration + + + What do for loops do? + + itertools -> build cool iterators out of sequences you have + + + +Generators + + generators give you the iterator immediately + + + conceptually - iterators are about various ways to loop over data, + generators generate the data on the fly + + practically - you can use either one either way (and generator is a type of + iterator + + def a_generator_function(params): + some_stuff + yield something + + + a function with 'yield' is a factory for a generator + + gen_a = a_generator() + gen_b a_generator() + + + + diff --git a/Students/SSchwafel/session08/callable_lab.py b/Students/SSchwafel/session08/callable_lab.py new file mode 100644 index 00000000..d657a793 --- /dev/null +++ b/Students/SSchwafel/session08/callable_lab.py @@ -0,0 +1,18 @@ +#!/usr/bin/python + +class Quadratic(object): + + def __init__(self, a, b,c): + + self.a = a + self.b = b + self.c = c + + def __call__(self,x): + self.x = x + + return self.a * self.x**2 + self.b * self.x + self.c + +my_quad = Quadratic(a=2, b=3, c=1) + +my_quad(0) diff --git a/Students/SSchwafel/session08/iterator_lab.py b/Students/SSchwafel/session08/iterator_lab.py new file mode 100644 index 00000000..bd81d554 --- /dev/null +++ b/Students/SSchwafel/session08/iterator_lab.py @@ -0,0 +1,37 @@ +#!/usr/bin/python + +class IterateMe(object): + + def __init__(self, stop, *args): + + + if not args: + + self.start = -1 + self.stop = stop + + else: + + self.start = stop-1 + self.stop = args[0] + + if len(args) == 2: + self.step = args[1] + self.start = stop-self.step + + def __iter__(self): + self.current = self.start + + def next(self): + + self.current += self.step + + if self.current < self.stop: + return self.current + + else: + raise StopIteration + + + + diff --git a/Students/SSchwafel/session08/sparse_array.py b/Students/SSchwafel/session08/sparse_array.py new file mode 100644 index 00000000..dae53737 --- /dev/null +++ b/Students/SSchwafel/session08/sparse_array.py @@ -0,0 +1,59 @@ +#!/usr/bin/python + + +#class sparse_array(object): +# +# def __init__(self, values=None): +# if values == None: +# +# self.values = [] +# +# else: +# +# self.values = values +# +# def len(self): +# +# return len(self.values) +# +# def getitem(self, key): +# +# return self.values[key] +# +#sample = sparse_array(0,1,2) +# +#print sample + +class sparse_array(object): + + def __init__(self,iterable): + self.values{} + self.length = len(iterable) + + for i, val in enumerate(iterable): + if val: + self.values[i] = val + + print self.values + + def __getitem__(self,index): + + if index >= self.length: + raise IndexError("Sparse array index out of range") + + else: + + self.values.get(index, 0) + + def __len__(self): + return self.length + + def __setitem__(self, index, value): + + if index >= self.length: + raise IndexError("Sparse array index out of range") + else: + if value == 0: + self..values.pop(index, None) + else: + self.values[index] = valu From 87c8460fbb88ff7a305f37f8ece81c0a7e5c26ac Mon Sep 17 00:00:00 2001 From: saschwafel Date: Fri, 28 Nov 2014 18:24:04 -0800 Subject: [PATCH 04/18] Starting on 'Informed Voter' Project, getting a .json return value, still need to fix the return output and print in a friendly format --- Students/SSchwafel/Project/InformedVoter.py | 22 +++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Students/SSchwafel/Project/InformedVoter.py diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py new file mode 100644 index 00000000..fb86d0aa --- /dev/null +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -0,0 +1,22 @@ +#!/usr/bin/python + +import urllib2 +import simplejson as json + +##url = urlopen('https://www.govtrack.us/api/v2/vote?created__gt=2012-01-01T00:00:00') +url = 'https://www.govtrack.us/api/v2/bill' + +# open the url and the screen name +# (The screen name is the screen name of the user for whom to return results for) +#url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=python" + +# this takes a python object and dumps it to a string which is a JSON +# representation of that object +data = json.load(urllib2.urlopen(url)) +print type(data) + +# print the result +#print data + +for key in data.iteritems(): + print "{} : {}".format(key,data[key]) From 64d91a9ef73a79518c3646bf73ae8c56e703a874 Mon Sep 17 00:00:00 2001 From: saschwafel Date: Tue, 2 Dec 2014 15:08:58 -0800 Subject: [PATCH 05/18] Wasn't able to finish labs, added some work to project. Generator lab mostly finished --- Students/SSchwafel/Project/InformedVoter.py | 8 +- Students/SSchwafel/session08/generator_lab.py | 74 +++++++++++++++++++ Students/SSchwafel/session08/sparse_array.py | 17 ++++- 3 files changed, 91 insertions(+), 8 deletions(-) create mode 100644 Students/SSchwafel/session08/generator_lab.py diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index fb86d0aa..f5e30946 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from pprint import pprint import urllib2 import simplejson as json @@ -15,8 +16,7 @@ data = json.load(urllib2.urlopen(url)) print type(data) -# print the result -#print data +pprint(data) -for key in data.iteritems(): - print "{} : {}".format(key,data[key]) +#for key in data.keys(): +# print "{} : {}\n".format(key,data[key]) diff --git a/Students/SSchwafel/session08/generator_lab.py b/Students/SSchwafel/session08/generator_lab.py new file mode 100644 index 00000000..699aab46 --- /dev/null +++ b/Students/SSchwafel/session08/generator_lab.py @@ -0,0 +1,74 @@ +#!/usr/bin/python + + +def sum_generator(number_range): + + counter = list(range(number_range)) + + new_value = 0 + i = new_value + + while i < number_range: + + try: + + item = counter.pop(0)+counter.pop(0) + yield item + counter.insert(0,item) + + except IndexError: + + break + + +sum_gen = sum_generator(10) +print next(sum_gen) +print next(sum_gen) +print next(sum_gen) +print next(sum_gen) +print next(sum_gen) +print next(sum_gen) + +def doubler(number_range): + i = 0 + while i= self.length: + raise IndexError("Sparse array index out of range") + else: + self.values.pop(index,None) + self.length -= 1 + + From 3a0971170c468efa2605bcb9ff273b7bf2f32dd0 Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Tue, 2 Dec 2014 21:00:08 -0800 Subject: [PATCH 06/18] Adding class notes and in-class lab --- Students/SSchwafel/Notes/12022014.notes | 16 +++++++++++++ .../session09/context_manager_lab.py | 15 ++++++++++++ Students/SSchwafel/session09/p_wrapper_lab.py | 24 +++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 Students/SSchwafel/Notes/12022014.notes create mode 100644 Students/SSchwafel/session09/context_manager_lab.py create mode 100644 Students/SSchwafel/session09/p_wrapper_lab.py diff --git a/Students/SSchwafel/Notes/12022014.notes b/Students/SSchwafel/Notes/12022014.notes new file mode 100644 index 00000000..1179adea --- /dev/null +++ b/Students/SSchwafel/Notes/12022014.notes @@ -0,0 +1,16 @@ +Notes 11/02/2014 +==================== + +You can bind a function to a symbol and return/pass them to functions + +Decorator - function takes function as an argument, gives a function as a return value + +Rebinding the name of a function to the result of calling a decorator on that function is called decoration + +@ <---special operator + +Decorators can be used with anything that is callable + + A decorator is a callable that takes a callable as an argument and returns a callable as a return value. + + diff --git a/Students/SSchwafel/session09/context_manager_lab.py b/Students/SSchwafel/session09/context_manager_lab.py new file mode 100644 index 00000000..8c027240 --- /dev/null +++ b/Students/SSchwafel/session09/context_manager_lab.py @@ -0,0 +1,15 @@ +#!/usr/bin/python + +class Timer(object): + + def __enter__(self): + print "In __enter__" + self.start = time.time() + return self + + def __exit__(self, err_type, err_val, err_trc): + + print "In __exit__" + self.elapsed = time.time() - self.start + print "Run took {} seconds".format(self.elapsed) + print err_type, err_val, err_trc diff --git a/Students/SSchwafel/session09/p_wrapper_lab.py b/Students/SSchwafel/session09/p_wrapper_lab.py new file mode 100644 index 00000000..26cb6b18 --- /dev/null +++ b/Students/SSchwafel/session09/p_wrapper_lab.py @@ -0,0 +1,24 @@ +#!/usr/bin/python + +def p_wrapper_func(func, tag): + + def tagger(tag): + + tag_type = raw_input("Tag? ") + tag_type = tag_type.title() + + return tag_type + + def p_wrapper(*args, **kwargs): + tag_type = tag + user_input = func(*args, **kwargs) + #return "

{}

".format(user_input) + return "<{}> {} ".format(tag, user_input, tag) + return p_wrapper + +@p_wrapper_func +def print_test_string(): + test_text = "this is a test string" + return test_text + +print print_test_string() From d26d8608e062eefea41876b5872fc7f01636d226 Mon Sep 17 00:00:00 2001 From: saschwafel Date: Wed, 3 Dec 2014 20:24:25 -0800 Subject: [PATCH 07/18] Adding fix to return list of representatives --- Students/SSchwafel/Project/InformedVoter.py | 22 ++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index f5e30946..e623f5af 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -4,19 +4,23 @@ import urllib2 import simplejson as json -##url = urlopen('https://www.govtrack.us/api/v2/vote?created__gt=2012-01-01T00:00:00') -url = 'https://www.govtrack.us/api/v2/bill' +#Bills +#url = 'https://www.govtrack.us/api/v2/bill' -# open the url and the screen name -# (The screen name is the screen name of the user for whom to return results for) -#url = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=python" +#Current Members of Congress +url = 'https://www.govtrack.us/api/v2/role?current=true' + +#One Particular Congressman +#url = 'https://www.govtrack.us/api/v2/person/400054' # this takes a python object and dumps it to a string which is a JSON # representation of that object data = json.load(urllib2.urlopen(url)) -print type(data) +#print data["lastname"] +#print data -pprint(data) +objects = data['objects'] +for representative in objects: + print representative['person']['name'].encode('utf-8') +#pprint(data) -#for key in data.keys(): -# print "{} : {}\n".format(key,data[key]) From 51941f55bbb566c56dee755752da7e05fc44ae4e Mon Sep 17 00:00:00 2001 From: saschwafel Date: Thu, 4 Dec 2014 21:46:47 -0800 Subject: [PATCH 08/18] Messing with another API, return values based on lat/long --- Students/SSchwafel/Project/InformedVoter.py | 44 +++++++++++++++++---- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index e623f5af..079debaa 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -8,19 +8,47 @@ #url = 'https://www.govtrack.us/api/v2/bill' -#Current Members of Congress -url = 'https://www.govtrack.us/api/v2/role?current=true' +#List Current Members of Congress +congresspeople_url = 'https://www.govtrack.us/api/v2/role?current=true&limit=600' #One Particular Congressman #url = 'https://www.govtrack.us/api/v2/person/400054' # this takes a python object and dumps it to a string which is a JSON # representation of that object -data = json.load(urllib2.urlopen(url)) -#print data["lastname"] -#print data +data = json.load(urllib2.urlopen(congresspeople_url)) objects = data['objects'] -for representative in objects: - print representative['person']['name'].encode('utf-8') -#pprint(data) +#for representative in objects: +# print representative['person']['name'].encode('utf-8') +#pprint(objects[0][person]['sortname']) +representatives = [] + +for i in objects: + representatives.append(i['person']['sortname'].encode('utf-8')) + +#representatives = sorted(representatives) +#pprint(representatives) + + +print """ + +You can get your latitude and longitude from http://www.latlong.net/ + +""" + +#user_lat = raw_input('Please enter your Latitude: \n') +#user_long = raw_input('Please enter your Longitude: \n') + +user_lat = '47.653098' +user_long = '-122.353731' + +lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long) + +congressional_district = json.load(urllib2.urlopen(lat_long_url)) + + +senators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) + +print senators +print type(senators) From b295b04c36328bf09a911ed0b0b63867fa1cd96f Mon Sep 17 00:00:00 2001 From: saschwafel Date: Fri, 5 Dec 2014 19:02:30 -0800 Subject: [PATCH 09/18] Fixing printing and adding some verbiage. Make sure to add an if/else to print "Congressman" or "Senator" --- Students/SSchwafel/Project/InformedVoter.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index 079debaa..0f9e0a58 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -48,7 +48,11 @@ congressional_district = json.load(urllib2.urlopen(lat_long_url)) -senators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) - -print senators -print type(senators) +legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) + +#pprint(senators['results']) +print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' +for i in legislators['results']: + first = i['first_name'] + last = i['last_name'] + print '{} {}\n'.format(first,last) From d19bde98af6921367fc7fd024e820a27355c7ef9 Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Sat, 6 Dec 2014 14:07:11 -0800 Subject: [PATCH 10/18] Splitting project between APIs, fixed title/gender printing --- .../Project/GovTrack_InformedVoter.py | 23 ++++++ Students/SSchwafel/Project/InformedVoter.py | 71 ++++++++++--------- 2 files changed, 60 insertions(+), 34 deletions(-) create mode 100644 Students/SSchwafel/Project/GovTrack_InformedVoter.py diff --git a/Students/SSchwafel/Project/GovTrack_InformedVoter.py b/Students/SSchwafel/Project/GovTrack_InformedVoter.py new file mode 100644 index 00000000..119ca07a --- /dev/null +++ b/Students/SSchwafel/Project/GovTrack_InformedVoter.py @@ -0,0 +1,23 @@ + +#List Current Members of Congress with GovTrack +#congresspeople_url = 'https://www.govtrack.us/api/v2/role?current=true&limit=600' + +#One Particular Congressman +#url = 'https://www.govtrack.us/api/v2/person/400054' +# this takes a python object and dumps it to a string which is a JSON +# representation of that object +data = json.load(urllib2.urlopen(congresspeople_url)) + +objects = data['objects'] +#for representative in objects: +# print representative['person']['name'].encode('utf-8') +#pprint(objects[0][person]['sortname']) + +representatives = [] + +for i in objects: + representatives.append(i['person']['sortname'].encode('utf-8')) + +#representatives = sorted(representatives) +#pprint(representatives) + diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index 0f9e0a58..0f5a4d13 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -4,55 +4,58 @@ import urllib2 import simplejson as json -#Bills -#url = 'https://www.govtrack.us/api/v2/bill' +user_local_data = json.load(urllib2.urlopen('http://freegeoip.net/json/')) +user_lat = user_local_data['latitude'] +user_long = user_local_data['longitude'] -#List Current Members of Congress -congresspeople_url = 'https://www.govtrack.us/api/v2/role?current=true&limit=600' +#print gathered lat/long +#print user_lat,user_long -#One Particular Congressman -#url = 'https://www.govtrack.us/api/v2/person/400054' -# this takes a python object and dumps it to a string which is a JSON -# representation of that object -data = json.load(urllib2.urlopen(congresspeople_url)) +#print """ +# +#You can get your latitude and longitude from http://www.latlong.net/ +# +#""" -objects = data['objects'] -#for representative in objects: -# print representative['person']['name'].encode('utf-8') -#pprint(objects[0][person]['sortname']) +#user_lat = raw_input('Please enter your Latitude: \n') +#user_long = raw_input('Please enter your Longitude: \n') -representatives = [] +#user_lat = '47.653098' +#user_long = '-122.353731' -for i in objects: - representatives.append(i['person']['sortname'].encode('utf-8')) +lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long) -#representatives = sorted(representatives) -#pprint(representatives) +congressional_district = json.load(urllib2.urlopen(lat_long_url)) -print """ +legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) -You can get your latitude and longitude from http://www.latlong.net/ -""" +#All Legislators, irrespective of location -#user_lat = raw_input('Please enter your Latitude: \n') -#user_long = raw_input('Please enter your Longitude: \n') +#House only +#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?chamber=house&per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) -user_lat = '47.653098' -user_long = '-122.353731' +#All Legislators +#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) -lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long) - -congressional_district = json.load(urllib2.urlopen(lat_long_url)) +#pprint(senators['results']) +#print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' -legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) +#Prints Congressman/Congresswoman + First, Last -#pprint(senators['results']) -print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' +#for i in legislators['results']: +# pprint(i) for i in legislators['results']: - first = i['first_name'] - last = i['last_name'] - print '{} {}\n'.format(first,last) + if i['chamber'] == 'house' and i['gender'] == 'M': + print 'Congressman ' + i['first_name'] + ' ' + i ['last_name'] + '\n' + elif i['chamber'] == 'senate': + print 'Senator ' + i['first_name'] + ' ' + i ['last_name'] + '\n' + + +#for i in legislators['results']: +# first = i['first_name'] +# last = i['last_name'] +# print '{} {}\n'.format(first,last) From 6cf5b7abe9d6d86075aa037ba0518c90781d5695 Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Sat, 6 Dec 2014 14:51:50 -0800 Subject: [PATCH 11/18] Fixing the printing of the legislator to return title, first, last, then began adding functionality to return their last several votes --- Students/SSchwafel/Project/InformedVoter.py | 39 ++++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index 0f5a4d13..b75140ac 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -46,16 +46,29 @@ #Prints Congressman/Congresswoman + First, Last -#for i in legislators['results']: -# pprint(i) -for i in legislators['results']: - if i['chamber'] == 'house' and i['gender'] == 'M': - print 'Congressman ' + i['first_name'] + ' ' + i ['last_name'] + '\n' - elif i['chamber'] == 'senate': - print 'Senator ' + i['first_name'] + ' ' + i ['last_name'] + '\n' - - -#for i in legislators['results']: -# first = i['first_name'] -# last = i['last_name'] -# print '{} {}\n'.format(first,last) +def find_legislators(): + + for i in legislators['results']: + print i['last_name'] + ' ' + i['bioguide_id'] + #legislator_ids.append(i) + +#find_legislators() + +#votes_url = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/votes?voter_ids.{}__exists=true&apikey=15f4679bdc124cd6a2c6be8666253000')).format( __ THIS IS WHERE THE UNIQUE ID OF THE LEGISLATOR NEEDS TO BE __ ) + +pprint(votes_url) + +#def recent_votes(): + + ##THIS IS WHERE YOU ARE GOING TO RETURN THE LAST 10 VOTES BY var = LEGISLATOR + +def print_legislators(): + + #FIX THE FORMATTING BELOW!!! + + for i in legislators['results']: + if i['chamber'] == 'house' and i['gender'] == 'M': + print 'Congressman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' + elif i['chamber'] == 'senate': + print 'Senator ' + i['first_name'] + ' ' + i ['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' + From 749c6ae549eb11c40a69b7a24902ad0e1e245afa Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Sat, 6 Dec 2014 15:01:25 -0800 Subject: [PATCH 12/18] Need to fix unicode in order for all legislators to print successfully --- Students/SSchwafel/Project/InformedVoter.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index b75140ac..dc3e44d1 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -38,7 +38,7 @@ #legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?chamber=house&per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) #All Legislators -#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) +legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) #pprint(senators['results']) #print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' @@ -56,7 +56,7 @@ def find_legislators(): #votes_url = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/votes?voter_ids.{}__exists=true&apikey=15f4679bdc124cd6a2c6be8666253000')).format( __ THIS IS WHERE THE UNIQUE ID OF THE LEGISLATOR NEEDS TO BE __ ) -pprint(votes_url) +#pprint(votes_url) #def recent_votes(): @@ -65,10 +65,14 @@ def find_legislators(): def print_legislators(): #FIX THE FORMATTING BELOW!!! + #Also, be sure to add .encode('utf-8') for i in legislators['results']: if i['chamber'] == 'house' and i['gender'] == 'M': print 'Congressman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' + if i['chamber'] == 'house' and i['gender'] == 'F': + print 'Congresswoman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' elif i['chamber'] == 'senate': print 'Senator ' + i['first_name'] + ' ' + i ['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' +print_legislators() From cd036a2fee12e97eb07ad2c3c60bf5db0ca69bb5 Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Tue, 9 Dec 2014 20:00:37 -0800 Subject: [PATCH 13/18] May have fixed unicode errors by adding from __future__ line, now trying to fix NEW problems --- Students/SSchwafel/Project/InformedVoter.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index dc3e44d1..9691f11e 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import unicode_literals from pprint import pprint import urllib2 import simplejson as json From 81e85d3291357228e3c22e097aff0278a5e4f438 Mon Sep 17 00:00:00 2001 From: Schuyler Schwafel Date: Tue, 9 Dec 2014 20:57:09 -0800 Subject: [PATCH 14/18] adding class notes and beginning of unicode lab --- Students/SSchwafel/Notes/12092014.notes | 75 +++++++++++++++++++ .../session10/ICanEatGlass.utf81.txt | 23 ++++++ Students/SSchwafel/session10/unicode_lab.py | 21 ++++++ Students/SSchwafel/session10/unicode_lab.py~ | 21 ++++++ 4 files changed, 140 insertions(+) create mode 100644 Students/SSchwafel/Notes/12092014.notes create mode 100644 Students/SSchwafel/session10/ICanEatGlass.utf81.txt create mode 100644 Students/SSchwafel/session10/unicode_lab.py create mode 100644 Students/SSchwafel/session10/unicode_lab.py~ diff --git a/Students/SSchwafel/Notes/12092014.notes b/Students/SSchwafel/Notes/12092014.notes new file mode 100644 index 00000000..fb2e499d --- /dev/null +++ b/Students/SSchwafel/Notes/12092014.notes @@ -0,0 +1,75 @@ +Notes - 12/9/2014 +==================== + +Unicode and the Persistence of Serialization +--- + + Projects Due at the end of this week! - Friday + +Anything is bytes <-- if it's stored on a disk or sent over a network, it's bytes + +Unicode makes it easier to deal with bytes + +Used to be able to fit everything into a two byte integer, (65,536 chars.) + +Variety of encodings -> way of going between the canonical name of a character, and how it's stored in memory + +Py2 strings are a sequence of bytes - Unicode strings are sequences of platonic characters + +Platonic characters cannot be written to disk or network + + +Python has both str and unicode + +Two ways to work with binary data: + +str and bytes() and bytearray + +In Python 3 bytes and strings are completely different! + +Unicode object lets you work with characters - all the same methods as the string object + + Encoding is converting from unicode object to bytes + + Decoding is converting from bytes to a unicode object + + +import codects +#encoding and decoding stuff + +codecs.encode() +codecs.decode() +codecs.open() #better to use io.open + +Use Unicode in your source files - + + #-*- coding: utf-8 -*- + +The Trick in Using Unicode - Be Consistent: + + Always unicode, never Python strings + + Do the decoding when you input your data + + Decode on input + + Encode on output + + + get default encoding - sys.getdefaultencoding() + + +from __future__ import unicode_literals #<----after running this line u'' is assumed! + + -be aware that you can still get Python 2 strings from other places... + +JSON Requires UTF-8! + +In Python 3, all strings are unicode + +Py3 has two distinct concepts: + + text - uses str object + binary data - uses bytes + + diff --git a/Students/SSchwafel/session10/ICanEatGlass.utf81.txt b/Students/SSchwafel/session10/ICanEatGlass.utf81.txt new file mode 100644 index 00000000..49a44fd9 --- /dev/null +++ b/Students/SSchwafel/session10/ICanEatGlass.utf81.txt @@ -0,0 +1,23 @@ +I Can Eat Glass: + +And from the sublime to the ridiculous, here is a certain phrase in an assortment of languages: + +Sanskrit: काचं शक्नोम्यत्तुम् । नोपहिनस्ति माम् ॥ + +Sanskrit (standard transcription): kācaṃ śaknomyattum; nopahinasti mām. + +Classical Greek: ὕαλον ϕαγεῖν δύναμαι· τοῦτο οὔ με βλάπτει. + +Greek (monotonic): Μπορώ να φάω σπασμένα γυαλιά χωρίς να πάθω τίποτα. + +Greek (polytonic): Μπορῶ νὰ φάω σπασμένα γυαλιὰ χωρὶς νὰ πάθω τίποτα. + +Latin: Vitrum edere possum; mihi non nocet. + +Old French: Je puis mangier del voirre. Ne me nuit. + +French: Je peux manger du verre, ça ne me fait pas mal. + +Provençal / Occitan: Pòdi manjar de veire, me nafrariá pas. + +Québécois: J'peux manger d'la vitre, ça m'fa pas mal. diff --git a/Students/SSchwafel/session10/unicode_lab.py b/Students/SSchwafel/session10/unicode_lab.py new file mode 100644 index 00000000..5d0a42a2 --- /dev/null +++ b/Students/SSchwafel/session10/unicode_lab.py @@ -0,0 +1,21 @@ +#!/usr/bin/python + +file = open('/home/schuyler/PythonFolder/session10/ICanEatGlass.utf81.txt', 'rw') + +unicode_string = u'bananas'.encode('utf-8') + +unicode_chess_piece = u'\u2654' + +unicode_chess_piece = unicode_chess_piece.encode('utf-8') + +print unicode_chess_piece + +#print unicode_string + +print file.read() + +file.write(unicode_chess_piece) + +print file.read() + +file.close() diff --git a/Students/SSchwafel/session10/unicode_lab.py~ b/Students/SSchwafel/session10/unicode_lab.py~ new file mode 100644 index 00000000..5d0a42a2 --- /dev/null +++ b/Students/SSchwafel/session10/unicode_lab.py~ @@ -0,0 +1,21 @@ +#!/usr/bin/python + +file = open('/home/schuyler/PythonFolder/session10/ICanEatGlass.utf81.txt', 'rw') + +unicode_string = u'bananas'.encode('utf-8') + +unicode_chess_piece = u'\u2654' + +unicode_chess_piece = unicode_chess_piece.encode('utf-8') + +print unicode_chess_piece + +#print unicode_string + +print file.read() + +file.write(unicode_chess_piece) + +print file.read() + +file.close() From 34e31c50704df7debe6cfd1ca3077f427f9a62a1 Mon Sep 17 00:00:00 2001 From: saschwafel Date: Wed, 10 Dec 2014 15:14:02 -0800 Subject: [PATCH 15/18] Changing API for geolocation, working on why printing the complete list doesn't work --- Students/SSchwafel/Project/InformedVoter.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index 9691f11e..e845bb4e 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -5,7 +5,8 @@ import urllib2 import simplejson as json -user_local_data = json.load(urllib2.urlopen('http://freegeoip.net/json/')) +#user_local_data = json.load(urllib2.urlopen('http://freegeoip.net/json/')) +user_local_data = json.load(urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=a648bf3844359d401197bcaa214dd01e0f8c0c6d623ec57f3716fbcafc8262bd&format=json')) user_lat = user_local_data['latitude'] user_long = user_local_data['longitude'] @@ -41,7 +42,7 @@ #All Legislators legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) -#pprint(senators['results']) +#pprint(legislators['results']) #print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' @@ -69,11 +70,15 @@ def print_legislators(): #Also, be sure to add .encode('utf-8') for i in legislators['results']: + #Troubleshooting output + #print i['first_name'] + i['last_name'] + if i['chamber'] == 'house' and i['gender'] == 'M': - print 'Congressman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' - if i['chamber'] == 'house' and i['gender'] == 'F': - print 'Congresswoman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' - elif i['chamber'] == 'senate': - print 'Senator ' + i['first_name'] + ' ' + i ['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' + print i['first_name'] + i['last_name'] + # print 'Congressman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' + #if i['chamber'] == 'house' and i['gender'] == 'F': + # print 'Congresswoman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' + #elif i['chamber'] == 'senate': + # print 'Senator ' + i['first_name'] + ' ' + i ['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' print_legislators() From 4257e2f9c97e705bdedcd64983d8a395dc0035e9 Mon Sep 17 00:00:00 2001 From: saschwafel Date: Wed, 10 Dec 2014 15:45:38 -0800 Subject: [PATCH 16/18] String formatting fixed NoneType issues --- Students/SSchwafel/Project/InformedVoter.py | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index e845bb4e..800e684a 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -66,19 +66,13 @@ def find_legislators(): def print_legislators(): - #FIX THE FORMATTING BELOW!!! - #Also, be sure to add .encode('utf-8') - for i in legislators['results']: - #Troubleshooting output - #print i['first_name'] + i['last_name'] if i['chamber'] == 'house' and i['gender'] == 'M': - print i['first_name'] + i['last_name'] - # print 'Congressman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' - #if i['chamber'] == 'house' and i['gender'] == 'F': - # print 'Congresswoman ' + i['first_name'] + ' ' + i['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' - #elif i['chamber'] == 'senate': - # print 'Senator ' + i['first_name'] + ' ' + i ['last_name'] + ' - ' + i['party']+ '\n' + 'Phone: ' + i['phone'] + '\n' + 'Website: ' + i['website'] + '\n' + print 'Congressman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + if i['chamber'] == 'house' and i['gender'] == 'F': + print 'Congresswoman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + elif i['chamber'] == 'senate': + print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) print_legislators() From 082c2ec3639f9acd38b919157ac7da281fd15eed Mon Sep 17 00:00:00 2001 From: saschwafel Date: Thu, 11 Dec 2014 10:16:37 -0800 Subject: [PATCH 17/18] Troubleshooting geolocation --- Students/SSchwafel/Project/InformedVoter.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index 800e684a..b4531183 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -33,6 +33,8 @@ legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) +for i in legislators['results']: + print i['last_name'] + ' ' + i['bioguide_id'] #All Legislators, irrespective of location @@ -40,9 +42,8 @@ #legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?chamber=house&per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) #All Legislators -legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) +#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) -#pprint(legislators['results']) #print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' @@ -75,4 +76,4 @@ def print_legislators(): elif i['chamber'] == 'senate': print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) -print_legislators() +#print_legislators() From 8869c1a9b3e4e1c0677e3c79273fb71ebc0dcad6 Mon Sep 17 00:00:00 2001 From: saschwafel Date: Thu, 11 Dec 2014 21:08:01 -0800 Subject: [PATCH 18/18] Final commit of project files. --- .../SSchwafel/Project/Draft_InformedVoter.py | 79 +++++++++++++ Students/SSchwafel/Project/InformedVoter.py | 107 ++++++++++-------- Students/SSchwafel/Project/README | 10 ++ Students/SSchwafel/Project/test.py | 9 ++ 4 files changed, 159 insertions(+), 46 deletions(-) create mode 100644 Students/SSchwafel/Project/Draft_InformedVoter.py create mode 100644 Students/SSchwafel/Project/README create mode 100644 Students/SSchwafel/Project/test.py diff --git a/Students/SSchwafel/Project/Draft_InformedVoter.py b/Students/SSchwafel/Project/Draft_InformedVoter.py new file mode 100644 index 00000000..b4531183 --- /dev/null +++ b/Students/SSchwafel/Project/Draft_InformedVoter.py @@ -0,0 +1,79 @@ +#!/usr/bin/python + +from __future__ import unicode_literals +from pprint import pprint +import urllib2 +import simplejson as json + +#user_local_data = json.load(urllib2.urlopen('http://freegeoip.net/json/')) +user_local_data = json.load(urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=a648bf3844359d401197bcaa214dd01e0f8c0c6d623ec57f3716fbcafc8262bd&format=json')) + +user_lat = user_local_data['latitude'] +user_long = user_local_data['longitude'] + +#print gathered lat/long +#print user_lat,user_long + +#print """ +# +#You can get your latitude and longitude from http://www.latlong.net/ +# +#""" + +#user_lat = raw_input('Please enter your Latitude: \n') +#user_long = raw_input('Please enter your Longitude: \n') + +#user_lat = '47.653098' +#user_long = '-122.353731' + +lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long) + +congressional_district = json.load(urllib2.urlopen(lat_long_url)) + + +legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) + +for i in legislators['results']: + print i['last_name'] + ' ' + i['bioguide_id'] + +#All Legislators, irrespective of location + +#House only +#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?chamber=house&per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) + +#All Legislators +#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) + +#print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' + + +#Prints Congressman/Congresswoman + First, Last + +def find_legislators(): + + for i in legislators['results']: + print i['last_name'] + ' ' + i['bioguide_id'] + #legislator_ids.append(i) + +#find_legislators() + +#votes_url = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/votes?voter_ids.{}__exists=true&apikey=15f4679bdc124cd6a2c6be8666253000')).format( __ THIS IS WHERE THE UNIQUE ID OF THE LEGISLATOR NEEDS TO BE __ ) + +#pprint(votes_url) + +#def recent_votes(): + + ##THIS IS WHERE YOU ARE GOING TO RETURN THE LAST 10 VOTES BY var = LEGISLATOR + +def print_legislators(): + + for i in legislators['results']: + + if i['chamber'] == 'house' and i['gender'] == 'M': + print 'Congressman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + if i['chamber'] == 'house' and i['gender'] == 'F': + print 'Congresswoman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + elif i['chamber'] == 'senate': + print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + +#print_legislators() diff --git a/Students/SSchwafel/Project/InformedVoter.py b/Students/SSchwafel/Project/InformedVoter.py index b4531183..ac050868 100644 --- a/Students/SSchwafel/Project/InformedVoter.py +++ b/Students/SSchwafel/Project/InformedVoter.py @@ -2,71 +2,77 @@ from __future__ import unicode_literals from pprint import pprint -import urllib2 import simplejson as json +import sys +import urllib2 + +#This allows printing to the console, including being able to pipe ( | ) the input +reload(sys) +sys.setdefaultencoding("utf-8") -#user_local_data = json.load(urllib2.urlopen('http://freegeoip.net/json/')) +#Making sure that there is at least one command line argument, if not, is none +if len(sys.argv) == 1: + command_line_argument = None +else: + command_line_argument = sys.argv[1] + +#Finds out the user's IP address for lookup user_local_data = json.load(urllib2.urlopen('http://api.ipinfodb.com/v3/ip-city/?key=a648bf3844359d401197bcaa214dd01e0f8c0c6d623ec57f3716fbcafc8262bd&format=json')) +#Set variables for detected lat/long user_lat = user_local_data['latitude'] user_long = user_local_data['longitude'] -#print gathered lat/long -#print user_lat,user_long - -#print """ -# -#You can get your latitude and longitude from http://www.latlong.net/ -# -#""" - -#user_lat = raw_input('Please enter your Latitude: \n') -#user_long = raw_input('Please enter your Longitude: \n') - -#user_lat = '47.653098' -#user_long = '-122.353731' - -lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long) - -congressional_district = json.load(urllib2.urlopen(lat_long_url)) - +#lat_long_url = 'https://congress.api.sunlightfoundation.com/districts/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long) +#Look up legislators from API with given lat/long, then store in a var. for later use legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) -for i in legislators['results']: - print i['last_name'] + ' ' + i['bioguide_id'] - -#All Legislators, irrespective of location - -#House only -#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?chamber=house&per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) - -#All Legislators -#legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) - -#print 'Based on the latitude and longitude provided, your United States Congresspeople are: \n' - - -#Prints Congressman/Congresswoman + First, Last +#Remnant of abandoned functionality def find_legislators(): - + """This function returns the legislator's last name and unique bioguide id, this would be useful for further, unimplemented features""" for i in legislators['results']: - print i['last_name'] + ' ' + i['bioguide_id'] - #legislator_ids.append(i) + print '{} {}'.format(i['last_name'], i['bioguide_id']) -#find_legislators() +def print_all_legislators(): + """This function prints all the legislators, then formats according to gender and title""" + + legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=15f4679bdc124cd6a2c6be8666253000')) + for i in legislators['results']: -#votes_url = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/votes?voter_ids.{}__exists=true&apikey=15f4679bdc124cd6a2c6be8666253000')).format( __ THIS IS WHERE THE UNIQUE ID OF THE LEGISLATOR NEEDS TO BE __ ) + if i['chamber'] == 'house' and i['gender'] == 'M': + print 'Congressman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + if i['chamber'] == 'house' and i['gender'] == 'F': + print 'Congresswoman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + elif i['chamber'] == 'senate': + print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) -#pprint(votes_url) +def print_manual_legislators(): + """This function prints the legislators of the given lat/long, then formats according to gender and title""" + + print """ + + You can get your latitude and longitude from http://www.latlong.net/ + + """ -#def recent_votes(): + user_lat = raw_input('Please enter your Latitude: \n') + user_long = raw_input('Please enter your Longitude: \n') - ##THIS IS WHERE YOU ARE GOING TO RETURN THE LAST 10 VOTES BY var = LEGISLATOR + legislators = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/legislators/locate?latitude={}&longitude={}&apikey=15f4679bdc124cd6a2c6be8666253000'.format(user_lat, user_long))) + + for i in legislators['results']: -def print_legislators(): + if i['chamber'] == 'house' and i['gender'] == 'M': + print 'Congressman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + if i['chamber'] == 'house' and i['gender'] == 'F': + print 'Congresswoman {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) + elif i['chamber'] == 'senate': + print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) +def print_detected_legislators(): + """This function prints the legislators local to the IP address of the user, then formats according to gender and title""" for i in legislators['results']: if i['chamber'] == 'house' and i['gender'] == 'M': @@ -76,4 +82,13 @@ def print_legislators(): elif i['chamber'] == 'senate': print 'Senator {} {} - {} \nPhone: {}\nWebsite: {}\n'.format(i['first_name'],i['last_name'],i['party'],i['phone'],i['website'] ) -#print_legislators() +if command_line_argument == '--all-legislators': + print_all_legislators() + +elif command_line_argument == None: + print 'Based on the latitude and longitude detected, your United States Congresspeople are: \n' + print_detected_legislators() + +elif command_line_argument == '--manual': + print_manual_legislators() + diff --git a/Students/SSchwafel/Project/README b/Students/SSchwafel/Project/README new file mode 100644 index 00000000..168b9463 --- /dev/null +++ b/Students/SSchwafel/Project/README @@ -0,0 +1,10 @@ +README +====== + +Welcome to the Informed Voter app! Right now, it provides the following functionality: + +Lists YOUR legislators based on an IP lookup, by running the program with no argument, these are returned + +Listing ALL legislators currently in Congress (run with the command line argument --all-legislators + +Finding out the representatives of a location via lat/long (access this functionality by running it with the --manual option) diff --git a/Students/SSchwafel/Project/test.py b/Students/SSchwafel/Project/test.py new file mode 100644 index 00000000..ea15c3a0 --- /dev/null +++ b/Students/SSchwafel/Project/test.py @@ -0,0 +1,9 @@ +#!/usr/bin/python + +from __future__ import unicode_literals +from pprint import pprint +import urllib2 +import simplejson as json + +url = json.load(urllib2.urlopen('https://congress.api.sunlightfoundation.com/votes?fields=voters&apikey=15f4679bdc124cd6a2c6be8666253000')) +pprint(url)