Просмотр исходного кода

Merged DrkSephy/django-hackathon-starter into default

Eswari Pravallika Swarna 10 лет назад
Родитель
Сommit
d3b6e6d248
30 измененных файлов с 1372 добавлено и 122 удалено
  1. 2 2
      .hgignore
  2. 390 0
      .pylintrc
  3. 6 0
      README.md
  4. 1 0
      angular/addons/nav.html
  5. 1 0
      angular/index.html
  6. 43 0
      angular/partials/instagramUser.partial.html
  7. 11 1
      angular/scripts/app.js
  8. 19 0
      angular/scripts/controllers/instagramUserController.js
  9. 12 0
      angular/scripts/factories/instagramUserFactory.js
  10. 12 0
      angular/scripts/factories/instagramUserMediaFactory.js
  11. 3 3
      hackathon_starter/hackathon/scripts/census.py
  12. 50 48
      hackathon_starter/hackathon/scripts/github.py
  13. 69 3
      hackathon_starter/hackathon/scripts/instagram.py
  14. 120 0
      hackathon_starter/hackathon/scripts/paypal.py
  15. 27 0
      hackathon_starter/hackathon/scripts/quandl.py
  16. 55 53
      hackathon_starter/hackathon/scripts/steam.py
  17. 84 0
      hackathon_starter/hackathon/scripts/twitter.py
  18. 6 1
      hackathon_starter/hackathon/templates/hackathon/api_examples.html
  19. 109 0
      hackathon_starter/hackathon/templates/hackathon/facebook.html
  20. 35 0
      hackathon_starter/hackathon/templates/hackathon/instagram_q.html
  21. 7 0
      hackathon_starter/hackathon/templates/hackathon/paypal.html
  22. 87 0
      hackathon_starter/hackathon/templates/hackathon/quandl.html
  23. 7 0
      hackathon_starter/hackathon/templates/hackathon/twitter.html
  24. 70 1
      hackathon_starter/hackathon/tests.py
  25. 1 1
      hackathon_starter/hackathon/unittests/testgithub.py
  26. 11 2
      hackathon_starter/hackathon/urls.py
  27. 125 6
      hackathon_starter/hackathon/views.py
  28. 8 0
      hackathon_starter/hackathon_starter/settings.py
  29. 0 1
      ionic/www/templates/instagramUser.html
  30. 1 0
      requirements.txt

+ 2 - 2
.hgignore

@@ -5,10 +5,10 @@ db.sqlite3
 *.pyc
 bower_components/
 migrations/
-*.coverage
 Thumbs.db
 */vendor
 ionic/platforms
 hackathon_starter/_build
 hackathon_starter/_static
-hackathon_starter/_templates
+hackathon_starter/_templates
+.coverage

+ 390 - 0
.pylintrc

@@ -0,0 +1,390 @@
+[MASTER]
+
+# Specify a configuration file.
+#rcfile=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Profiled execution.
+profile=no
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=CVS
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Deprecated. It was used to include message's id in output. Use --msg-template
+# instead.
+include-ids=no
+
+# Deprecated. It was used to include symbolic ids of messages in output. Use
+# --msg-template instead.
+symbols=no
+
+# Use multiple processes to speed up Pylint.
+jobs=1
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code
+extension-pkg-whitelist=
+
+# Allow optimization of some AST trees. This will activate a peephole AST
+# optimizer, which will apply various small optimizations. For instance, it can
+# be used to obtain the result of joining multiple strings with the addition
+# operator. Joining a lot of strings can lead to a maximum recursion error in
+# Pylint and this flag can prevent that. It has one side effect, the resulting
+# AST will be different than the one from reality.
+optimize-ast=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
+confidence=
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time. See also the "--disable" option for examples.
+#enable=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once).You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use"--disable=all --enable=classes
+# --disable=W"
+disable=E1608,W1627,E1601,E1603,E1602,E1605,E1604,E1607,E1606,W1621,W1620,W1623,W1622,W1625,W1624,W1609,W1608,W1607,W1606,W1605,W1604,W1603,W1602,W1601,W1639,W1640,I0021,W1638,I0020,W1618,W1619,W1630,W1626,W1637,W1634,W1635,W1610,W1611,W1612,W1613,W1614,W1615,W1616,W1617,W1632,W1633,W0704,W1628,W1629,W1636
+
+
+[REPORTS]
+
+# Set the output format. Available formats are text, parseable, colorized, msvs
+# (visual studio) and html. You can also give a reporter class, eg
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Put messages in a separate file for each module / package specified on the
+# command line instead of printing them on stdout. Reports (if any) will be
+# written in a file name "pylint_global.[txt|html]".
+files-output=no
+
+# Tells whether to display a full report or only the messages
+reports=yes
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Add a comment according to your evaluation note. This is used by the global
+# evaluation report (RP0004).
+comment=no
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details
+#msg-template=
+
+
+[BASIC]
+
+# Required attributes for module, separated by a comma
+required-attributes=
+
+# List of builtins function names that should not be used, separated by a comma
+bad-functions=map,filter,input
+
+# Good variable names which should always be accepted, separated by a comma
+good-names=i,j,k,ex,Run,_
+
+# Bad variable names which should always be refused, separated by a comma
+bad-names=foo,bar,baz,toto,tutu,tata
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Include a hint for the correct naming format with invalid-name
+include-naming-hint=no
+
+# Regular expression matching correct function names
+function-rgx=[a-z][A-Za-z0-9]{1,30}$
+
+# Naming hint for function names
+function-name-hint=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression matching correct variable names
+variable-rgx=[a-z][A-Za-z0-9]{1,30}$
+
+# Naming hint for variable names
+variable-name-hint=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression matching correct constant names
+const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
+
+# Naming hint for constant names
+const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
+
+# Regular expression matching correct attribute names
+attr-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Naming hint for attribute names
+attr-name-hint=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression matching correct argument names
+argument-rgx=[a-z][A-Za-z0-9]{1,30}$
+
+# Naming hint for argument names
+argument-name-hint=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression matching correct class attribute names
+class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
+
+# Naming hint for class attribute names
+class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
+
+# Regular expression matching correct inline iteration names
+inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
+
+# Naming hint for inline iteration names
+inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
+
+# Regular expression matching correct class names
+class-rgx=[A-Z_][a-zA-Z0-9]+$
+
+# Naming hint for class names
+class-name-hint=[A-Z_][a-zA-Z0-9]+$
+
+# Regular expression matching correct module names
+module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
+
+# Naming hint for module names
+module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
+
+# Regular expression matching correct method names
+method-rgx=[a-z_][a-z0-9_]{2,30}$
+
+# Naming hint for method names
+method-name-hint=[a-z_][a-z0-9_]{2,30}$
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=__.*__
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+
+[FORMAT]
+
+# Maximum number of characters on a single line.
+max-line-length=100
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )?<?https?://\S+>?$
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+# List of optional constructs for which whitespace checking is disabled
+no-space-check=trailing-comma,dict-separator
+
+# Maximum number of lines in a module
+max-module-lines=1000
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string='    '
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+
+[LOGGING]
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format
+logging-modules=logging
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,XXX,TODO
+
+
+[SIMILARITIES]
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+
+[SPELLING]
+
+# Spelling dictionary name. Available dictionaries: none. To make it working
+# install python-enchant package.
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[TYPECHECK]
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis
+ignored-modules=
+
+# List of classes names for which member attributes should not be checked
+# (useful for classes with attributes dynamically set).
+ignored-classes=SQLObject
+
+# When zope mode is activated, add a predefined set of Zope acquired attributes
+# to generated-members.
+zope=no
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E0201 when accessed. Python regular
+# expressions are accepted.
+generated-members=REQUEST,acl_users,aq_parent
+
+
+[VARIABLES]
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# A regular expression matching the name of dummy variables (i.e. expectedly
+# not used).
+dummy-variables-rgx=_$|dummy
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid to define new builtins when possible.
+additional-builtins=
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,_cb
+
+
+[CLASSES]
+
+# List of interface methods to ignore, separated by a comma. This is used for
+# instance to not check methods defines in Zope's Interface base class.
+ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,__new__,setUp
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=mcs
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,_fields,_replace,_source,_make
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method
+max-args=5
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore
+ignored-argument-names=_.*
+
+# Maximum number of locals for function / method body
+max-locals=15
+
+# Maximum number of return / yield for function / method body
+max-returns=6
+
+# Maximum number of branch for function / method body
+max-branches=12
+
+# Maximum number of statements in function / method body
+max-statements=50
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+
+[IMPORTS]
+
+# Deprecated modules which should not be used, separated by a comma
+deprecated-modules=regsub,TERMIOS,Bastion,rexec
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled)
+import-graph=
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled)
+ext-import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled)
+int-import-graph=
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "Exception"
+overgeneral-exceptions=Exception

+ 6 - 0
README.md

@@ -60,6 +60,12 @@ To run the tests:
 
 In order to write clean code with a consistent style guide, we'll be using `Pylint` to maintain our code. Pylint will display a ton of messages regarding things that should be fixed. 
 
+This project will use the camel-case naming convention for variables and function names, which PyLint complains about by default. As such, I have created a pylint configuration file within the home directory of the project (the same directory which contains `ionic`, `angular`, `hackathon_starter`.) To run pylint while supplying a pylint configuration file:
+
+    pylint --rcfile path/to/pylintrcfile/.pylintrc hackathon_starter/hackathon/scripts/github.py
+
+Where you can substitute `github.py` with the script you'd like to evaluate. 
+
 
 ## RESTful endpoints
 

+ 1 - 0
angular/addons/nav.html

@@ -4,6 +4,7 @@
       <li><a href="#/steamSales">Steam Sales <span class="icon"></span></a></li>
       <li><a href="#/githubUser">Github User <span class="icon"></span></a></li>
       <li><a href="#/githubTopContributions">Github Resume <span class="icon"></span></a></li>
+      <li><a href="#/instagramUser">Instagram User <span class="icon"></span></a></li>
       <li><a href="#">Dropdown</a>
         <ul class="list-unstyled">
             <li class="sub-nav"><a href="#">Sub Menu One <span class="icon"></span></a></li>

+ 1 - 0
angular/index.html

@@ -76,6 +76,7 @@
         <script src="scripts/factories/githubTopContributionsFactory.js"></script>
         <script src="scripts/factories/steamSalesFactory.js"></script>
         <script src="scripts/factories/instagramUserFactory.js"></script>
+        <script src="scripts/factories/instagramUserMediaFactory.js"></script>
 
     </head>
 

+ 43 - 0
angular/partials/instagramUser.partial.html

@@ -0,0 +1,43 @@
+<div class="jumbotron">
+  <div class="container">
+
+    <div class="row text-center"> 
+        <h1> Instagram User Data </h1>
+    </div>
+
+	    <div class="col-lg-12">
+	        <div class="table-responsive">
+	            <table class="table table-bordered table-hover table-striped tablesorter">
+	                <thead> 
+	                	<tr>
+	                		<th>Username</th>
+	                		<th>ID</th>
+	                		<th>Bio</th>
+	                		<th>Website</th>
+	                		<th>Profile Image</th>
+	                		<th>Full Name</th>
+	                		<th>Following</th>
+	                		<th>Followers</th>
+	                		<th>Total Media</th>
+	                	</tr>
+	                </thead>
+	                <tbody>
+	                	<tr data-ng-repeat="data in instagramUserData">
+	                		<td>{{data.username}}</td>
+	                		<td>{{data.id}}</td>
+	                		<td>{{data.bio}}</td>
+	                		<td>{{data.website}}</td>
+	                		<td><img src="{{data.profile_picture}}"></td>
+	                		<td>{{data.full_name}}</td>
+	                		<td>{{data.counts.follows}}</td>
+	                		<td>{{data.counts.followed_by}}</td>
+	                		<td>{{data.counts.media}}</td>
+	                	</tr>
+	                </tbody>
+	            </table>
+
+	        	<img data-ng-repeat= "i in instagramUserMediaData.data" src="{{i.images.thumbnail.url}}">
+	        </div>
+	    </div>	    
+	</div>
+</div>

+ 11 - 1
angular/scripts/app.js

@@ -40,5 +40,15 @@ var restApp = angular.module('restApp', [
             data: {
                 pageTitle: 'Top Contributions on Github'
             }
-        });
+        })
+
+        .state('instagramUser',{
+            url:'/instagramUser',
+            templateUrl: 'partials/instagramUser.partial.html',
+            controller: 'instagramUserController',
+            data : {
+                pageTitle: 'Instagram User Data'
+            }
+        });   
+
 });

+ 19 - 0
angular/scripts/controllers/instagramUserController.js

@@ -0,0 +1,19 @@
+'use strict';
+
+restApp.controller('instagramUserController', function($scope, instagramUserFactory, instagramUserMediaFactory){
+	$scope.instagramUserData = {};
+	$scope.instagramUserMediaData = {};
+
+	$scope.instagramUserData = instagramUserFactory.get().success(function(data){
+		$scope.instagramUserData = data;
+
+		console.log(data);
+	});
+	
+	$scope.instagramUserMediaData = instagramUserMediaFactory.get().success(function(data){
+		$scope.instagramUserMediaData = data;
+
+		console.log(data);
+	});
+
+})

+ 12 - 0
angular/scripts/factories/instagramUserFactory.js

@@ -0,0 +1,12 @@
+'use strict';
+
+restApp.factory('instagramUserFactory', function($http){
+	return {
+		get: function(){
+			return $http({
+				url: 'http://localhost:8000/hackathon/instagramUser/',
+				method: 'GET',
+			});
+		}
+	};
+});

+ 12 - 0
angular/scripts/factories/instagramUserMediaFactory.js

@@ -0,0 +1,12 @@
+'use strict';
+
+restApp.factory('instagramUserMediaFactory', function($http){
+	return {
+		get: function(){
+			return $http({
+				url: 'http://localhost:8000/hackathon/instagramUserMedia/',
+				method: 'GET',
+			});
+		}
+	};
+});

+ 3 - 3
hackathon_starter/hackathon/scripts/census.py

@@ -14,7 +14,7 @@ API_BASE_URL = 'http://api.census.gov/data/2013/pep/natstprc'
 
 def getPopulationEstimate(url):
 	req = requests.get(url)
-	print len(req.text)
-	#print req.text
+	#print len(req.text)
+	print req.text
 
-getPopulationEstimate('http://api.census.gov/data/2013/pep/monthlynatchar5?get=AGE,SEX,DATE,RACE5,HISP,POP,UNIVERSE&key=1286203d2772de1f09f13392cc42a0197b2cd414')
+getPopulationEstimate('http://api.census.gov/data/2013/pep/monthlynatchar5?get=AGE,SEX,DATE,RACE5,HISP&key=1286203d2772de1f09f13392cc42a0197b2cd414')

+ 50 - 48
hackathon_starter/hackathon/scripts/github.py

@@ -1,5 +1,5 @@
 '''
-github.py contains a handful of methods for interacting 
+github.py contains a handful of methods for interacting
 with Github data and returning the responses as JSON.
 '''
 
@@ -14,19 +14,19 @@ API_BASE_URL = 'https://api.github.com/users/DrkSephy'
 
 def getUserData(clientID, clientSecret):
     '''
-    Returns data found on a Github User's public profile. 
+    Returns data found on a Github User's public profile.
     This includes information such as number of followers,
-    e-mail, number of repositories and more. 
+    e-mail, number of repositories and more.
 
     Parameters:
-        clientID: String 
+        clientID: String
             - The clientID from registering this application
               on Github.
         clientSecret: String
             - The clientSecret from registering this application
             on Github.
 
-    Returns: 
+    Returns:
         parsedData: Dictionary
             - A dictionary containing the following data:
                 - userData['name']
@@ -36,13 +36,13 @@ def getUserData(clientID, clientSecret):
                 - userData['email']
                     - The user's public e-mail on Github
                 - userData['public_gists']
-                    - The number of the user's public gists 
+                    - The number of the user's public gists
                 - userData['public_repos']
                     - The number of public repositories owned
                 - userData['avatar_url']
-                    - Link to user's public avatar 
+                    - Link to user's public avatar
                 - userData['followers']
-                    - Number of followers 
+                    - Number of followers
                 - userData['following']
                     - Number of users being followed
     '''
@@ -52,7 +52,7 @@ def getUserData(clientID, clientSecret):
     jsonList.append(json.loads(req.content))
     parsedData = []
     userData = {}
-    for data in jsonList: 
+    for data in jsonList:
         userData['name'] = data['name']
         userData['blog'] = data['blog']
         userData['email'] = data['email']
@@ -64,15 +64,14 @@ def getUserData(clientID, clientSecret):
     parsedData.append(userData)
 
     return parsedData
-    
 
 def getUserRepositories(clientID, clientSecret):
     '''
-    Returns a list of all the public repositories 
-    owned by a User. 
+    Returns a list of all the public repositories
+    owned by a User.
 
     Parameters:
-        clientID: String 
+        clientID: String
             - The clientID from registering this application
               on Github.
         clientSecret: String.
@@ -80,8 +79,8 @@ def getUserRepositories(clientID, clientSecret):
             on Github.
 
     Returns:
-        repositories: List 
-            - A list containing all public repository names 
+        repositories: List
+            - A list containing all public repository names
               belonging to a user.
     '''
     pageNumber = 1
@@ -89,27 +88,25 @@ def getUserRepositories(clientID, clientSecret):
     repositories = []
 
     while True:
-        req = requests.get('https://api.github.com/users/DrkSephy/repos?page=' + str(pageNumber) + '&' + clientID + '&' + clientSecret)
+        req = requests.get('https://api.github.com/users/DrkSephy/repos?page=' \
+            + str(pageNumber) + '&' + clientID + '&' + clientSecret)
         jsonList.append(json.loads(req.content))
         if len(json.loads(req.content)) < 30:
             break
         elif len(json.loads(req.content)) >= 30:
             pageNumber += 1
-
-    
     for data in jsonList:
         for datum in data:
             repositories.append(datum['name'])
-            
     return repositories
 
 def getForkedRepositories(clientID, clientSecret):
     '''
-    Returns a list of all the public forked repositories 
-    owned by a User. 
+    Returns a list of all the public forked repositories
+    owned by a User.
 
     Parameters:
-        clientID: String 
+        clientID: String
             - The clientID from registering this application
               on Github.
         clientSecret: String.
@@ -117,17 +114,17 @@ def getForkedRepositories(clientID, clientSecret):
             on Github.
 
     Returns:
-        forkedRepositories: List 
-            - A list containing all forked repository names 
+        forkedRepositories: List
+            - A list containing all forked repository names
               belonging to a user.
     '''
-    
+
     pageNumber = 1
     jsonList = []
     forkedRepositories = []
- 
     while True:
-        req = requests.get('https://api.github.com/users/DrkSephy/repos?page=' + str(pageNumber) + '&' + clientID + '&' + clientSecret)
+        req = requests.get('https://api.github.com/users/DrkSephy/repos?page=' \
+            + str(pageNumber) + '&' + clientID + '&' + clientSecret)
         jsonList.append(json.loads(req.content))
         if len(json.loads(req.content)) < 30:
             break
@@ -147,18 +144,18 @@ def getForkedRepositories(clientID, clientSecret):
 
 def getTopContributedRepositories(repos, clientID, clientSecret):
     '''
-    Returns a list containing the commit totals for all 
-    repositories owned by a user. 
+    Returns a list containing the commit totals for all
+    repositories owned by a user.
 
     Parameters:
-        clientID: String 
+        clientID: String
             - The clientID from registering this application
               on Github.
         clientSecret: String
             - The clientSecret from registering this application
             on Github.
 
-    Returns: 
+    Returns:
         parsedData: Dictionary
             - A dictionary containing the following data:
                 - commits['author']
@@ -170,7 +167,8 @@ def getTopContributedRepositories(repos, clientID, clientSecret):
     '''
     jsonList = []
     for repo in repos:
-        req = requests.get('https://api.github.com/repos/DrkSephy/' + repo + '/stats/contributors' + '?' + clientID + '&' + clientSecret)
+        req = requests.get('https://api.github.com/repos/DrkSephy/' + repo \
+            + '/stats/contributors' + '?' + clientID + '&' + clientSecret)
         jsonList.append(json.loads(req.content))
 
     parsedData = []
@@ -192,40 +190,41 @@ def filterCommits(data):
     '''
     Returns the top 10 committed repositories.
 
-    Parameters: 
+    Parameters:
         data: List
             - A list containing commit counts for all
             of a user's public repositories
 
     Returns:
         maxCommits: List
-            - A list containing the top ten repositories 
+            - A list containing the top ten repositories
             with the maximum number of commits by a user
     '''
 
     maxCommits = []
-    for i in range(1, 10):
-        maxCommitedRepo = max(data, key=lambda x:x['total'])
+    i = 0
+    while i < 10:
+        maxCommitedRepo = max(data, key=lambda x: x['total'])
         maxCommits.append(maxCommitedRepo)
         index = data.index(maxCommitedRepo)
         data.pop(index)
+        i += 1
     return maxCommits
-    
-    
+
 def getStarGazerCount(clientID, clientSecret):
     '''
     Returns a list number of stargazers for each
-    of a user's public repositories.  
+    of a user's public repositories.
 
     Parameters:
-        clientID: String 
+        clientID: String
             - The clientID from registering this application
               on Github.
         clientSecret: String
             - The clientSecret from registering this application
             on Github.
 
-    Returns: 
+    Returns:
         stargazers: Dictionary
             - A dictionary containing the following data:
                 - starData['stargazers_count']
@@ -237,7 +236,8 @@ def getStarGazerCount(clientID, clientSecret):
     jsonList = []
     stargazers = []
     while True:
-        req = requests.get('https://api.github.com/users/DrkSephy/repos?page=' + str(pageNumber) + '&' + clientID + '&' + clientSecret)
+        req = requests.get('https://api.github.com/users/DrkSephy/repos?page=' \
+            + str(pageNumber) + '&' + clientID + '&' + clientSecret)
         jsonList.append(json.loads(req.content))
         if len(json.loads(req.content)) < 30:
             break
@@ -251,29 +251,31 @@ def getStarGazerCount(clientID, clientSecret):
             starData['stargazers_count'] = datum['stargazers_count']
             starData['name'] = datum['name']
             stargazers.append(starData)
-            
+
     return stargazers
 
 def filterStarGazerCount(data):
     '''
     Returns the top 10 stargazed repositories.
 
-    Parameters: 
+    Parameters:
         data: List
             - A list containing stargazer counts for all
             of a user's public repositories
 
     Returns:
         maxStars: List
-            - A list containing the top ten repositories 
+            - A list containing the top ten repositories
             with the maximum number of stargazers
     '''
-    maxStars= []
-    for i in range(1, 10):
-        maxStarGazers = max(data, key=lambda x:x['stargazers_count'])
+    maxStars = []
+    i = 0
+    while i < 10:
+        maxStarGazers = max(data, key=lambda x: x['stargazers_count'])
         maxStars.append(maxStarGazers)
         index = data.index(maxStarGazers)
         data.pop(index)
+        i += 1
     return maxStars
 
 

+ 69 - 3
hackathon_starter/hackathon/scripts/instagram.py

@@ -3,16 +3,24 @@
 instagram.py contains a handful of methods for interacting
 with Instagram data and returning the responses as JSON.
 '''
+
 import requests
 import urllib
 import urllib2
 import json
 import simplejson as json2
+import googlemaps
+from django.conf import settings
+from datetime import datetime
+from time import strftime
 
 authorization_url = 'https://api.instagram.com/oauth/authorize/?client_id='
 access_token_url = 'https://api.instagram.com/oauth/access_token'
 
 class InstagramOauthClient(object):
+	'''
+	Python Client for Instagram API.
+	'''
 
 	access_token = None
 	user_data = None
@@ -27,12 +35,15 @@ class InstagramOauthClient(object):
 				- The client_secret from registering application
 				  on Instagram.
 		'''
+
 		self.client_id 		= client_id
 		self.client_secret 	= client_secret
 
 
 	def get_authorize_url(self):
 		''' 
+		Obtains authorize url link with given client_id.
+
 		Returns:
 			auth_url: String
 				- The authorization url.
@@ -44,6 +55,8 @@ class InstagramOauthClient(object):
 
 	def get_access_token(self, code):
 		''' 
+		Obtains access token.
+
 		Parameters:
 			code: String
 				- The code is retrieved from the authorization url parameter
@@ -63,7 +76,7 @@ class InstagramOauthClient(object):
 		jsonlist = json.load(content)
 		self.access_token = jsonlist['access_token']
 		self.user_data = jsonlist['user']
-		print self.user_data
+		#print self.user_data
 		#print self.access_token
 
 
@@ -96,6 +109,8 @@ class InstagramOauthClient(object):
 
 	def get_user_info(self, access_token):
 		'''
+		Get user information.
+
 		Parameters:
 			access_token: String
 				- The access_token given after granting permission
@@ -113,7 +128,7 @@ class InstagramOauthClient(object):
 		return data
 
 
-	def get_user_media(self, access_token):
+	def get_user_media(self, user_id, access_token):
 		'''
 		Parameters:
 			access_token: String
@@ -125,8 +140,59 @@ class InstagramOauthClient(object):
 				- A dictionary containing user media information.
 		'''
 
-		user_media = 'https://api.instagram.com/v1/users/32833691/media/recent/?access_token='+access_token
+		user_media = 'https://api.instagram.com/v1/users/'+str(user_id)+'/media/recent/?access_token='+access_token
+		#user_media = 'https://api.instagram.com/v1/users/32833691/media/recent/?access_token='+access_token
 		req = requests.get(user_media)
 		content = json2.loads(req.content)
 		data = content['data']
 		return data
+
+	def search_for_location(self, address, access_token):
+		gmaps = googlemaps.Client(key=settings.GOOGLEMAP_API_KEY)
+		#geocoding and address
+		geocode_result = gmaps.geocode(address)
+		
+		if geocode_result:
+			location = geocode_result[0]['geometry']['location']
+			return location
+
+
+	def search_location_ids(self, latitude, longitude, access_token):
+		search_location = 'https://api.instagram.com/v1/locations/search?lat='+str(latitude)+'&lng='+str(longitude)+'&access_token='+access_token+"&distance=5000"
+		req = requests.get(search_location)
+		data = json2.loads(req.content)
+		list_of_ids =[]
+		if data['meta']['code'] != 200:
+			raise Exception("Invalid response %s." % data['meta']['code'])
+		search_ids = data['data']
+		for data in search_ids:
+			for i in data:
+				if i == 'id':
+					list_of_ids.append(data[i])
+		return list_of_ids
+
+	def search_location_media(self, list_location_ids, access_token):
+		media = []
+		for location in list_location_ids:
+			media_by_location = 'https://api.instagram.com/v1/locations/'+location+'/media/recent?access_token='+access_token
+			req = requests.get(media_by_location)
+			content_all = json2.loads(req.content)
+			if content_all['pagination']:
+				temp_media=[]
+				next_url = content_all['pagination']['next_url']
+				req = requests.get(next_url)
+				content = json2.loads(req.content)
+				for i in content['data']:
+					i['created_time'] = datetime.fromtimestamp(int(i['created_time'])).strftime('%Y-%m-%d %H:%M:%S')
+					temp_media.append(i)
+				media += [temp_media]
+			else:
+				for i in content_all['data']:
+					for data in i:
+						if data == 'created_time':
+							i[data]= datetime.fromtimestamp(int(i[data])).strftime('%Y-%m-%d %H:%M:%S')
+				media.append(content_all['data'])
+		return media
+
+
+

+ 120 - 0
hackathon_starter/hackathon/scripts/paypal.py

@@ -0,0 +1,120 @@
+
+'''
+paypal.py contains a handful of methods for interacting
+with Paypal data and returning the responses as JSON.
+'''
+
+import requests
+import simplejson as json2
+import unicodedata
+import urllib
+
+authorization_url = 'https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?client_id='
+access_token_url  = 'https://api.sandbox.paypal.com/v1/oauth2/token'
+
+#password:testing123
+#cafe.mui-buyer@gmail.com
+#https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize?client_id=AcOIP0f8NTl3iv5Etw2nakNrgPmjE65v84a2NQD5mm8-z-dTyhMSNHZuxHbHUaTAxLQIE0u-A2DFEY8M&response_type=code&scope=openid&redirect_uri=http://localhost:8000/hackathon/paypal/
+
+
+class PaypalOauthClient(object):
+	'''
+	Python Client for Paypal API.
+	'''
+
+	access_token = None
+	user_data = None
+	token_type = None
+	refresh_token = None
+
+	def __init__(self, client_id, client_secret):
+		'''
+		Parameters:
+			client_id: String
+				- The client_id from registering application
+				  on Instagram.
+			client_secret: String
+				- The client_secret from registering application
+				  on Instagram.
+		'''
+
+		self.client_id 		= client_id
+		self.client_secret 	= client_secret
+
+
+	def get_authorize_url(self):
+		''' 
+		Obtains authorize url link with given client_id.
+
+		Returns:
+			auth_url: String
+				- The authorization url.
+		'''
+
+		auth_url = authorization_url + self.client_id + '&response_type=code&scope=openid&redirect_uri=http://localhost:8000/hackathon/paypal/'
+		return auth_url
+
+
+	def get_access_token(self, code):
+		''' 
+		Obtains access token from authorization code.
+
+		Parameters:
+			code: String
+				- The code is retrieved from the authorization url parameter
+				  to obtain access_token.
+		'''
+
+		headers = {
+					'Accept': 'application/json',
+					'Accept-Language': 'en_US',
+					'content-type': 'application/x-www-form-urlencoded'
+				  }
+		data = { 'grant_type': 'authorization_code',
+				  'code': code,
+				  'redirect_uri':'http://localhost:8000/hackathon/paypal'}
+
+
+		req = requests.post(access_token_url, data=data, headers=headers, auth=(self.client_id, self.client_secret))
+		
+		if req.status_code != 200:
+			raise Exception("Invalid response %s." %  req.status_code)
+		
+		content = unicodedata.normalize('NFKD', req.text).encode('ascii','ignore')
+		jsonlist = json2.loads(content)
+
+		#print jsonlist
+		self.access_token = jsonlist['access_token']
+		self.token_type = jsonlist['token_type']
+		self.refresh_token = jsonlist['refresh_token']
+
+		return self.refresh_token
+
+
+	def get_refresh_token(self, refresh_token):
+		'''
+		This methods obtain new access token when current access_token expires.
+		'''
+
+		link  = 'https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice'
+
+		headers = {
+					'Accept': 'application/json',
+					'Accept-Language': 'en_US',
+					'content-type': 'application/x-www-form-urlencoded'
+				  }
+		data = { 'grant_type': 'refresh_token',
+				  'refresh_token': refresh_token}
+
+		req = requests.post(link, data=data, headers=headers, auth=(self.client_id, self.client_secret))
+		
+		if req.status_code != 200:
+			raise Exception("Invalid response %s." %  req.status_code)
+		
+		content = unicodedata.normalize('NFKD', req.text).encode('ascii','ignore')
+		jsonlist = json2.loads(content)
+
+		#print jsonlist
+		self.access_token = jsonlist['access_token']
+		self.token_type = jsonlist['token_type']
+

+ 27 - 0
hackathon_starter/hackathon/scripts/quandl.py

@@ -0,0 +1,27 @@
+'''Module containing a handful of methods for
+aggregating data from markets throughout the world'''
+
+import requests
+import json
+
+def fetchData(apikey, url):
+    '''Returns JSON data of the Dow Jones Average.'''
+    parameters = {'rows' : 1, 'auth_token' : apikey}
+    req = requests.get(url, params=parameters)
+    data = json.loads(req.content)
+    parsedData = []
+    stockData = {}
+    for datum in data:
+        if data['code'] == 'COMP':
+    	    stockData['name'] = data['name']
+    	    stockData['description'] = '''The NASDAQ Composite Index measures all 
+    	    NASDAQ domestic and international based common type stocks listed on The NASDAQ Stock Market.'''
+            stockData['data'] = data['data']
+            stockData['code'] = data['code']
+        else:
+            stockData['name'] = data['name']
+            stockData['description'] = data['description']
+            stockData['data'] = data['data']
+            stockData['code'] = data['code']
+    parsedData.append(stockData)
+    return parsedData

+ 55 - 53
hackathon_starter/hackathon/scripts/steam.py

@@ -1,53 +1,55 @@
-# pylint: disable=C0303
-
-import requests
-import json
-
-SteamUN = "Marorin"
-key = '231E98D442E52B87110816C3D5114A1D'
-
-def gamesPulling(steamID,key):
-    # Returns the JSON data from the Steam API based of one's 
-    # Steam ID number and returns a dictionary of gameids and minutes played.
-    steaminfo = {
-        'key': key, 
-        'steamid': steamID,
-        'format':'JSON',
-        'include_appinfo':'1'
-    }
-    r = requests.get('http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/', params=steaminfo)
-    d = json.loads(r.content)
-    return d['response']['games']
- 
-def steamIDPulling(SteamUN,key):
-    #Pulls out and returns the steam id number for use in steam queries.
-    steaminfo = {'key': key,'vanityurl': SteamUN}
-    a = requests.get('http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/', params=steaminfo)
-    k = json.loads(a.content)
-    SteamID = k['response']['steamid']
-    
-    return SteamID
-def steamlibrarypull(steamID, key):
-#Pulls out a CSV of Steam appids.
-    steaminfo = {
-        'key': key,
-        'steamid': steamID,
-        'format':'JSON',
-        'include_appinfo':'1'
-    }
-    r = requests.get('http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/', params=steaminfo)
-    d = json.loads(r.content)
-    response = d['response']['games']
-    games = {}
-    for game in response:
-        getprice = requests.get('http://store.steampowered.com/api/appdetails/?appids=%d&filters=price_overview&cc=us' % game['appid'])
-        if getprice.status_code == 200:
-            rjson = json.loads(getprice.text)
-            # use the appid to fetch the value and convert to decimal
-            # appid is numeric, cast to string to lookup the price
-            try:
-                price = rjson[str(game['appid'])]['data']['price_overview']['initial'] * .01
-            except KeyError:
-                pass
-            games[game['name']] = {'price': price, 'appid': game['appid']}
-    return games
+'''This script contains methods belonging to the Steam web API
+that can collect information based on an user's gaming library.'''
+import requests
+import json
+
+def gamespulling(steamid, apikey):
+    '''Returns the JSON data from the Steam API based of one's
+    Steam ID number and returns a dictionary of
+    gameids and minutes played.'''
+    steaminfo = {
+        'key': apikey,
+        'steamid': steamid,
+        'format':'JSON',
+        'include_appinfo':'1'
+    }
+    apiurl = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/'
+    req = requests.get(apiurl, params=steaminfo)
+    data = json.loads(req.content)
+    return data['response']['games']
+
+def steamidpulling(steamun, apikey):
+    '''Pulls out and returns the steam id number for use in steam queries.'''
+    steaminfo = {'key': apikey, 'vanityurl': steamun}
+    apiurl = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/'
+    req = requests.get(apiurl, params=steaminfo)
+    data = json.loads(req.content)
+    steamid = data['response']['steamid']
+    return steamid
+
+def steamlibrarypull(steamid, apikey):
+    '''Pulls out a CSV of Steam appids.'''
+    steaminfo = {
+        'key': apikey,
+        'steamid': steamid,
+        'format':'JSON',
+        'include_appinfo':'1'
+    }
+    url = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/'
+    req = requests.get(url, params=steaminfo)
+    data = json.loads(req.content)
+    response = data['response']['games']
+    games = {}
+    for game in response:
+        url = 'http://store.steampowered.com/api/appdetails/?appids=%d&filters=price_overview&cc=us'
+        getprice = requests.get(url % game['appid'])
+        if getprice.status_code == 200:
+            rjson = json.loads(getprice.text)
+            # use the appid to fetch the value and convert to decimal
+            # appid is numeric, cast to string to lookup the price
+            try:
+                price = rjson[str(game['appid'])]['data']['price_overview']['initial'] * .01
+            except KeyError:
+                pass
+            games[game['name']] = {'price': price, 'appid': game['appid']}
+    return games

+ 84 - 0
hackathon_starter/hackathon/scripts/twitter.py

@@ -0,0 +1,84 @@
+import urlparse
+import oauth2 as oauth
+import requests
+import base64, random
+
+request_token_url = 'https://api.twitter.com/oauth/request_token'
+access_token_url = 'https://api.twitter.com/oauth/access_token'
+authorize_url = 'https://api.twitter.com/oauth/authorize'
+
+class TwitterOauthClient(object):
+
+	oauth_token = None
+	oauth_token_secret = None
+
+
+	def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
+		self.consumer_key = consumer_key
+		self.consumer_secret = consumer_secret
+		self.access_token = access_token
+		self.access_token_secret = access_token_secret
+		self.consumer = oauth.Consumer(key=self.consumer_key, secret=self.consumer_secret)
+		
+
+	def get_authorize_url(self):
+		'''
+		Obtained oauth_token and oauth_token_secret from request_token_url,
+		returns an authorize url. 
+
+		From the redirect url, we obtain the oauth verifier.
+		'''
+
+		client = oauth.Client(self.consumer)
+		resp, content = client.request(request_token_url, 'GET')
+
+		if int(resp['status']) != 200:
+			raise Exception('Invalid response %s' %resp['status'])
+
+		request_token = dict(urlparse.parse_qsl(content))
+
+		#temporary
+		self.oauth_token = request_token['oauth_token']
+		self.oauth_token_secret  = request_token['oauth_token_secret']
+		print self.oauth_token
+
+		#link to authorize app access twitter data and return to twitter api example page
+		link = authorize_url+"?oauth_token="+self.oauth_token+"&redirect_uri=http%3A%2F%2Flocalhost%3A8000/hackathon/twitter/"
+		return link
+
+	def get_access_token_url(self, oauth_verifier):
+		
+		token = oauth.Token(self.oauth_token, self.oauth_token_secret)
+		token.set_verifier(oauth_verifier)
+
+		client = oauth.Client(self.consumer, token)
+		resp, content = client.request(access_token_url, 'POST')
+		
+		if int(resp['status']) != 200:
+			raise Exception('Invalid response %s' %resp['status'])
+
+		print content
+		access_token = dict(urlparse.parse_qsl(content))
+
+		#permanent
+		self.oauth_token = access_token['oauth_token']
+		self.oauth_token_secret = access_token['oauth_token_secret']
+		self.user_id = access_token['user_id']
+		self.username = access_token['screen_name']
+
+
+	def get_nonce(self):
+		'''
+		Unique token generated for each request.
+		'''
+		n = base64.b64encode(
+			''.join([str(random.randint(0, 9)) for i in range(24)]))
+		return n
+
+	
+		
+
+
+
+
+

+ 6 - 1
hackathon_starter/hackathon/templates/hackathon/api_examples.html

@@ -7,9 +7,14 @@
 	    <div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/githubResume/">Github Example</a></div>
 	    <div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/steam/">Steam Example</a></div>
 	    <div class="col-sm-4"><a href={{tumblr_url}}>Tumblr Example</a></div>
-		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/linkedin/">LinkedIn Example</a></div>
+	    <!--
+			<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/linkedin/">LinkedIn Example</a></div>
+		-->
 		<div class="col-sm-4"><a href="http://127.0.0.1:8000/hackathon/twilio/">Twilio Example</a></div>
 		<div class="col-sm-4"><a href="{{instagram_url}}">Instagram Example</a></div>
+		<div class="col-sm-4"><a href="{{paypal_url}}">Paypal Example</a></div>
+		<div class="col-sm-4"><a href="{{twitter_url}}">Twitter Example</a></div>
+		<div class="col-sm-4"><a href="http://localhost:8000/hackathon/quandlstocks/">Quandl Example</a></div>
 
   	</div>
 

+ 109 - 0
hackathon_starter/hackathon/templates/hackathon/facebook.html

@@ -0,0 +1,109 @@
+<!DOCTYPE html>
+<html>
+<head>
+<title>Facebook Login JavaScript Example</title>
+<meta charset="UTF-8">
+</head>
+<body>
+{% include 'hackathon/base.html' %}
+<script>
+  // This is called with the results from from FB.getLoginStatus().
+  function statusChangeCallback(response) {
+    console.log('statusChangeCallback');
+    console.log(response);
+    // The response object is returned with a status field that lets the
+    // app know the current login status of the person.
+    // for FB.getLoginStatus().
+    if (response.status === 'connected') {
+      // Logged into your app and Facebook.
+      testAPI();
+    } else if (response.status === 'not_authorized') {
+      // The person is logged into Facebook, but not your app.
+      document.getElementById('status').innerHTML = 'Please log ' +
+        'into this app.';
+    } else {
+      // The person is not logged into Facebook, so we're not sure if
+      // they are logged into this app or not.
+      document.getElementById('status').innerHTML = 'Please log ' +
+        'into Facebook.';
+    }
+  }
+
+  // This function is called when someone finishes with the Login
+  // Button.  See the onlogin handler attached to it in the sample
+  // code below.
+  function checkLoginState() {
+    FB.getLoginStatus(function(response) {
+      statusChangeCallback(response);
+    });
+  }
+
+  window.fbAsyncInit = function() {
+  FB.init({
+    appId      : {{yourappid}},
+    cookie     : true, 
+                        
+    xfbml      : true,  // parse social plugins on this page
+    version    : 'v2.2' // use version 2.2
+  });
+
+  FB.getLoginStatus(function(response) {
+    statusChangeCallback(response);
+  });
+
+  };
+
+  // Load the SDK asynchronously
+  (function(d, s, id) {
+    var js, fjs = d.getElementsByTagName(s)[0];
+    if (d.getElementById(id)) return;
+    js = d.createElement(s); js.id = id;
+    js.src = "//connect.facebook.net/en_US/sdk.js";
+    fjs.parentNode.insertBefore(js, fjs);
+  }(document, 'script', 'facebook-jssdk'));
+
+  // Here we run a very simple test of the Graph API after login is
+  // successful.  See statusChangeCallback() for when this call is made.
+  function testAPI() {
+    console.log('Welcome!  Fetching your information.... ');
+    FB.api('/me', function(response) {
+      console.log('Successful login for: ' + response.name);
+      document.getElementById('status').innerHTML =
+        'Thanks for logging in, ' + response.name + '!';
+    });
+  }
+  // Here will be a function that'll create a dialog box to post upon your own wall. 
+  function posttoFeed() {
+    FB.ui({
+     method: 'Feed',
+     name: 'Django-Hackathon-Starter',
+     caption: 'starter dialog box',
+     description: 'This is a wall post brought to you by the Hackathon Starter',
+     message: 'It is alive!'
+    },
+    function(response){
+      if (response && response.post_id){
+        alert('post was published');
+      } else {
+        alert('post was not published');
+      }
+    });
+  }
+</script>
+
+<!--
+  Below we include the Login Button social plugin. This button uses
+  the JavaScript SDK to present a graphical Login button that triggers
+  the FB.login() function when clicked.
+-->
+
+<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
+</fb:login-button>
+
+<input type="button" onclick="posttoFeed()" value="Post to Feed" />
+
+<div id="status">
+</div>
+
+</body>
+</html>

+ 35 - 0
hackathon_starter/hackathon/templates/hackathon/instagram_q.html

@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<html>
+<body>
+	{% include 'hackathon/base.html' %}
+	<h1 class="text-center"> {{ title }}</h1> 
+	<br>
+	<div class="container text-center">
+		<form class="form-inline" method='get' action="/hackathon/instagramMediaByLocation/">
+		  <div class="form-group">
+		    <input type="text" name="address_field" class="form-control" placeholder="address">
+		  </div>
+		  <button type="submit" class="btn btn-default">Search</button>
+		</form>
+	</div>
+
+	{% if geocode_result %}	
+	<div class="col-lg-12">
+		<div class="table-responsive">
+			<h4 class="text-center"> Latitude: {{geocode_result.lat}} </h3>
+			<h4 class="text-center"> Longitude: {{geocode_result.lng}} </h3>
+
+			<p class="text-center"> {{list_id}} </p>
+			<table class="table">
+				{% for list in media %}
+					{% for user in list %}
+						<a href="{{user.link}}" title="{{user.created_time}}"><img src="{{user.images.thumbnail.url}}"></a>
+					{% endfor %}
+				{% endfor %}
+
+			</table>
+		</div>
+	</div>
+	{% endif %}
+
+</html>

+ 7 - 0
hackathon_starter/hackathon/templates/hackathon/paypal.html

@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+<html>
+<body>
+	{% include 'hackathon/base.html' %}
+	<h1 class="text-center"> {{ title }}</h1> 
+	</div>	
+</html>

+ 87 - 0
hackathon_starter/hackathon/templates/hackathon/quandl.html

@@ -0,0 +1,87 @@
+<!DOCTYPE html>
+<html>
+<body>
+	{% include 'hackathon/base.html' %}
+
+    <h1 class="text-center"> Quandl Collection </h1>
+    <h2 class="text-center"> Dow Jones Data </h2>
+	<div class="col-lg-12">
+        <div class="table-responsive">
+            <table class="table table-bordered table-hover table-striped tablesorter">
+                <thead>
+                <tr>
+                <th class="header"> Name <i class="icon-sort"></i></th>
+                <th class="header"> Description <i class="icon-sort"></i></th>
+                <th class="header"> Data <i class="icon-sort"></i></th>
+                <th class="header"> Code <i class="icon-sort"></i></th>  
+                </tr>
+            </thead>
+            <tbody>
+
+            {% for data in everyData.dow %}
+                <tr>
+                    <td>{{ data.name }}</td>
+                    <td>{{ data.description }}</td>
+                    <td>{{ data.data }}</td>
+                    <td>{{ data.code }}</td>
+                </tr>
+            {% endfor %}
+            </tbody>
+            </table>
+        </div>
+    </div>
+
+    <div class="col-lg-12">
+        <div class="table-responsive">
+            <table class="table table-bordered table-hover table-striped tablesorter">
+                <thead>
+                <tr>
+                <th class="header"> Name <i class="icon-sort"></i></th>
+                <th class="header"> Description <i class="icon-sort"></i></th>
+                <th class="header"> Data <i class="icon-sort"></i></th>
+                <th class="header"> Code <i class="icon-sort"></i></th>  
+                </tr>
+            </thead>
+            <tbody>
+
+            {% for data in everyData.snp %}
+                <tr>
+                    <td>{{ data.name }}</td>
+                    <td>{{ data.description }}</td>
+                    <td>{{ data.data }}</td>
+                    <td>{{ data.code }}</td>
+                </tr>
+            {% endfor %}
+            </tbody>
+            </table>
+        </div>
+    </div>
+
+    <div class="col-lg-12">
+        <div class="table-responsive">
+            <table class="table table-bordered table-hover table-striped tablesorter">
+                <thead>
+                <tr>
+                <th class="header"> Name <i class="icon-sort"></i></th>
+                <th class="header"> Description <i class="icon-sort"></i></th>
+                <th class="header"> Data <i class="icon-sort"></i></th>
+                <th class="header"> Code <i class="icon-sort"></i></th>  
+                </tr>
+            </thead>
+            <tbody>
+
+            {% for data in everyData.nasdaq %}
+                <tr>
+                    <td>{{ data.name }}</td>
+                    <td>{{ data.description }}</td>
+                    <td>{{ data.data }}</td>
+                    <td>{{ data.code }}</td>
+                </tr>
+            {% endfor %}
+            </tbody>
+            </table>
+        </div>
+    </div>
+        
+</body>
+</html>

+ 7 - 0
hackathon_starter/hackathon/templates/hackathon/twitter.html

@@ -0,0 +1,7 @@
+<!DOCTYPE html>
+<html>
+<body>
+	{% include 'hackathon/base.html' %}
+	<h1 class="text-center"> {{ title }}</h1> 
+	</div>	
+</html>

+ 70 - 1
hackathon_starter/hackathon/tests.py

@@ -1,3 +1,72 @@
 from django.test import TestCase
 
-# Create your tests here.
+class SteamViewTestCase(TestCase):
+	def testSteam(self):
+		resp = self.client.get('/hackathon/steam/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testSteamDiscountedGames(self):
+		resp = self.client.get('/hackathon/steamDiscountedGames/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testSteamPlaytimeForever(self):
+		resp = self.client.get('/hackathon/steam/')
+		for dict in resp.context:
+			if 'playtime_forever' in dict:
+				self.assertTrue('playtime_forever' in dict)
+
+	def testSteamName(self):
+		resp = self.client.get('/hackathon/steam/')
+		for dict in resp.context:
+			if 'name' in dict:
+				self.assertTrue('name' in dict)
+
+	def testSteamImg(self):
+		resp = self.client.get('/hackathon/steam/')
+		for dict in resp.context:
+			if 'img_logo_url' in dict:
+				self.assertTrue('img_logo_url' in dict)
+
+	def testSteamAppID(self):
+		resp = self.client.get('/hackathon/steam/')
+		for dict in resp.context:
+			if 'appid' in dict:
+				self.assertTrue('appid' in dict)
+
+	def testSteamDiscountedGamesDiscount(self):
+		resp = self.client.get('/hackathon/steamDiscountedGames/')
+		self.assertEqual(resp.context, None)
+
+
+class HackathonViewsTestCase(TestCase):
+	def testIndex(self):
+		resp = self.client.get('/hackathon/api/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testQuandlDowJones(self):
+		resp = self.client.get('/hackathon/quandlDowJones/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testQuandlSnp500(self):
+		resp = self.client.get('/hackathon/quandlSnp500/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testQuandlNasdaq(self):
+		resp = self.client.get('/hackathon/quandlNasdaq/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testGithubUser(self):
+		resp = self.client.get('/hackathon/githubUser/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testGithubTopRepositories(self):
+		resp = self.client.get('/hackathon/githubTopRepositories/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testGithubResume(self):
+		resp = self.client.get('/hackathon/githubResume/')
+		self.assertEqual(resp.status_code, 200)
+
+	def testTwilio(self):
+		resp = self.client.get('/hackathon/twilio/')
+		self.assertEqual(resp.status_code, 200)

+ 1 - 1
hackathon_starter/hackathon/unittests/testgithub.py

@@ -29,7 +29,7 @@ class GithubTests(unittest.TestCase):
 
 		with patch('hackathon.scripts.github.getUserData') as mock_getUserData:
 			# Mock the return value of this method
-			mock_getUserData.return_value = {'public_repos': 51, 'public_gists': 5, 'name': 'David Leonard', 'blog': 'http://drksephy.github.io', 'avatar_url': 'https://avatars.githubusercontent.com/u/1226900?v=3', 'followers': 50, 'following': 7, 'email': 'DrkSephy1025@gmail.com'}
+			mock_getUserData.return_value = {'public_repos': 52, 'public_gists': 5, 'name': 'David Leonard', 'blog': 'http://drksephy.github.io', 'avatar_url': 'https://avatars.githubusercontent.com/u/1226900?v=3', 'followers': 51, 'following': 7, 'email': 'DrkSephy1025@gmail.com'}
 			jsonList.append(mock_getUserData.return_value)
 			for data in jsonList:
 				userData['name'] = mock_getUserData.return_value['name']

+ 11 - 2
hackathon_starter/hackathon/urls.py

@@ -14,12 +14,21 @@ urlpatterns = patterns('',
     url(r'^githubUser/$', views.githubUser, name='githubUser'),
     url(r'^githubTopRepositories/$', views.githubTopRepositories, name='githubTopRepositories'),
     url(r'^tumblr/$', views.tumblr, name='tumblr'),
-    url(r'^linkedin/$', views.linkedin, name='linkedin'),
+    #url(r'^linkedin/$', views.linkedin, name='linkedin'),
     url(r'^snippets/$', views.snippet_list, name='snippets'),
     url(r'^twilio/$', views.twilio, name='twilio'),
     url(r'^instagram/$', views.instagram, name='instagram'),
     url(r'^instagram_login/$', views.instagram_login, name='instagram_login'),
     url(r'^instagramUser/$', views.instagramUser, name='instagramUser'),
+    url(r'^instagramMediaByLocation/$', views.instagramMediaByLocation, name='instagramMediaByLocation'),#
     url(r'^instagramUserMedia/$', views.instagramUserMedia, name='instagramUserMedia'),
+    url(r'^paypal/$', views.paypal, name='paypal'),
+    url(r'^twitter/$', views.twitter, name='twitter'),
     url(r'^tumblr_login/$', views.tumblr_login, name='tumblr_login'),
-)
+    url(r'^twitter_login/$', views.twitter_login, name='twitter_login'),
+    url(r'^facebook/$', views.facebook, name='facebook'),
+    url(r'^quandlSnp500/$', views.quandlSnp500, name='quandlsnp500'),
+    url(r'^quandlNasdaq/$', views.quandlNasdaq, name='quandlnasdaq'),
+    url(r'^quandlDowJones/$', views.quandlDowJones, name='quandldowjones'),
+    url(r'^quandlstocks/$', views.quandlstocks, name='quandlstocks'),
+)

+ 125 - 6
hackathon_starter/hackathon/views.py

@@ -12,12 +12,15 @@ from django.views.decorators.csrf import csrf_exempt
 from django.http import JsonResponse
 
 # Scripts
-from scripts.steam import gamesPulling, steamIDPulling 
+from scripts.steam import gamespulling, steamidpulling 
 from scripts.github import *
 from scripts.tumblr import TumblrOauthClient
 from scripts.twilioapi import *
 from scripts.instagram import InstagramOauthClient
 from scripts.scraper import steamDiscounts
+from scripts.quandl import *
+from scripts.paypal import PaypalOauthClient
+from scripts.twitter import TwitterOauthClient
 
 # Python
 import oauth2 as oauth
@@ -32,6 +35,8 @@ from hackathon.forms import UserForm
 
 getTumblr = TumblrOauthClient(settings.TUMBLR_CONSUMER_KEY, settings.TUMBLR_CONSUMER_SECRET)
 getInstagram = InstagramOauthClient(settings.INSTAGRAM_CLIENT_ID, settings.INSTAGRAM_CLIENT_SECRET)
+getPaypal = PaypalOauthClient(settings.PAYPAL_CLIENT_ID, settings.PAYPAL_CLIENT_SECRET)
+getTwitter = TwitterOauthClient(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET, settings.TWITTER_ACCESS_TOKEN, settings.TWITTER_ACCESS_TOKEN_SECRET)
 
 def index(request):
     context = {'hello': 'world'}
@@ -44,12 +49,14 @@ def index(request):
 
 def api_examples(request):
     instagram_url =getInstagram.get_authorize_url()
+    paypal_url = getPaypal.get_authorize_url()
+    twitter_url = getTwitter.get_authorize_url()
     if not getTumblr.accessed:
         obtain_oauth_verifier = getTumblr.authorize_url()
     else:
         obtain_oauth_verifier = '/hackathon/tumblr'
     #obtain_oauth_verifier = getTumblr.authorize_url()
-    context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url}
+    context = {'title': 'API Examples Page', 'tumblr_url': obtain_oauth_verifier, 'instagram_url':instagram_url, 'paypal_url': paypal_url, 'twitter_url':twitter_url}
     return render(request, 'hackathon/api_examples.html', context)
 
 #################
@@ -60,16 +67,58 @@ def steam(request):
     #Should link to test of Steam API example.
     key = '231E98D442E52B87110816C3D5114A1D'
     SteamUN = "Marorin"
-    steamID = steamIDPulling(SteamUN, key)
-    game = gamesPulling(steamID, key)
+    steamID = steamidpulling(SteamUN, key)
+    game = gamespulling(steamID, key)
     return render(request,'hackathon/steam.html', {"game": game })
 
-
 def steamDiscountedGames(request):
     data = steamDiscounts()
     return JsonResponse({ 'data': data })
 
 #################
+#  FACEBOOK API #
+#################
+
+def facebook(request):
+    '''A sample application that will publish a status update after going into the login process using the Javascript SDK '''
+    yourappid = '364831617044713'
+    return render(request, 'hackathon/facebook.html', { 'yourappid' : yourappid })
+
+#################
+#   QUANDL API  #
+#################
+
+def quandlDowJones(request):
+    '''Returns JSON response about the latest dowjones index.'''
+    APIKEY = 'fANs6ykrCdAxas7zpMz7'
+    dowjonesdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
+    print dowjonesdata
+    return JsonResponse({'data': dowjonesdata})
+
+def quandlSnp500(request):
+    '''Returns JSON response about the latest SNP 500 index.'''
+    APIKEY = 'fANs6ykrCdAxas7zpMz7'
+    snpdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
+    return JsonResponse({'data': snpdata})
+
+def quandlNasdaq(request):
+    '''Returns JSON response about the latest nasdaq index.'''
+    APIKEY = 'fANs6ykrCdAxas7zpMz7'
+    nasdaqdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
+    return JsonResponse({'data': nasdaqdata})
+
+def quandlstocks(request):
+    APIKEY = 'fANs6ykrCdAxas7zpMz7'	
+    everyData = {}
+    dowjonesdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/BCB/UDJIAD1.json?')
+    everyData['dow'] = dowjonesdata
+    snpdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/YAHOO/INDEX_GSPC.json?')
+    everyData['snp'] = snpdata
+    nasdaqdata = fetchData(APIKEY, 'https://www.quandl.com/api/v1/datasets/NASDAQOMX/COMP.json?')
+    everyData['nasdaq'] = nasdaqdata
+    return render(request, 'hackathon/quandl.html', { 'everyData': everyData })
+
+#################
 #   GITHUB API  #
 #################
 
@@ -192,9 +241,75 @@ def instagramUserMedia(request):
     ''' Returns JSON response about a specific Instagram User's Media. '''
     user_id = User.objects.get(username='mk200789').id
     access_token = Profile.objects.get(user=user_id).oauth_secret
-    parsedData = getInstagram.get_user_media(access_token)
+    parsedData = getInstagram.get_user_media(32833691,access_token)
     return JsonResponse({'data': parsedData })
 
+def instagramMediaByLocation(request):
+    if request.method == 'GET':
+        if request.GET.items():
+            if request.user in User.objects.all():
+                address = request.GET.get('address_field')
+                user_id = User.objects.get(username=request.user).id
+                access_token = Profile.objects.get(user=user_id).oauth_secret
+                #lat, lng = getInstagram.search_for_location(address, access_token)
+                geocode_result = getInstagram.search_for_location(address, access_token)
+                if geocode_result:
+                    location_ids =getInstagram.search_location_ids(geocode_result['lat'], geocode_result['lng'], access_token)
+                    media = getInstagram.search_location_media(location_ids, access_token)
+                    title = address
+        else:
+            title, media,location_ids, geocode_result = 'Media by location', '','', ''
+
+
+    context = {'title': title, 'geocode_result':geocode_result, 'media':media, 'list_id':location_ids}
+    return render(request, 'hackathon/instagram_q.html', context)
+
+
+####################
+#    PAYPAL API    #
+####################
+
+def paypal(request):
+    authorization_code = request.GET['code']
+    refresh_token = getPaypal.get_access_token(authorization_code)
+    getPaypal.get_refresh_token(refresh_token)
+    #getPaypal.userinfo()
+    print getPaypal.access_token
+    getPaypal.create_invoice()
+
+    context = {'title':'paypal'}
+    return render(request, 'hackathon/paypal.html', context)
+
+
+####################
+#   TWITTER API    #
+####################
+def twitter(request):
+    oauth_verifier = request.GET['oauth_verifier']
+    getTwitter.get_access_token_url(oauth_verifier)     
+
+
+    if request.user not in User.objects.all():
+        try:  
+            user = User.objects.get(username=getTwitter.username )
+        except User.DoesNotExist:
+            username = getTwitter.username 
+            new_user = User.objects.create_user(username, username+'@example.com', 'password')
+            new_user.save()
+            profile = Profile()
+            profile.user = new_user
+            profile.oauth_token = getTwitter.oauth_token
+            profile.oauth_secret = getTwitter.oauth_token_secret
+            profile.save()
+
+        user = authenticate(username=getTwitter.username, password='password')
+        login(request, user)
+
+    
+
+    context ={'title': 'twitter'}
+    return render(request, 'hackathon/twitter.html', context)
+
 
 ##################
 #  LINKED IN API #
@@ -301,3 +416,7 @@ def instagram_login(request):
 def tumblr_login(request):
     tumblr_url = getTumblr.authorize_url()
     return HttpResponseRedirect(tumblr_url)
+
+def twitter_login(request):
+    twitter_url = getTwitter.get_authorize_url()
+    return HttpResponseRedirect(twitter_url)

+ 8 - 0
hackathon_starter/hackathon_starter/settings.py

@@ -115,4 +115,12 @@ TWITTER_TOKEN = 'F05dgLAzHEOalb4K2xDQ8Umm8'
 TWITTER_SECRET = 'Yy3a74Z7gvyhxRruJsvUtUl8uK8iv6qKkVqbZSijUxK71Z1qTY'
 INSTAGRAM_CLIENT_ID = '77dc10b9e3624e908ce437c0a82da92e'
 INSTAGRAM_CLIENT_SECRET = '8bcf3139857149aaba7acaa61288427f'
+PAYPAL_CLIENT_ID = 'AcOIP0f8NTl3iv5Etw2nakNrgPmjE65v84a2NQD5mm8-z-dTyhMSNHZuxHbHUaTAxLQIE0u-A2DFEY8M'
+PAYPAL_CLIENT_SECRET = 'EOKz-tkbFfRZavSD8T70f961v3NHRVAXXJu-5MU97YqSVKBsUH4NOoy_xQ2Am3EU3lN2m5RQiVb3eI-3'
 
+GOOGLEMAP_API_KEY = 'AIzaSyA7tttML91EGZ32S_FOOoxu-mbxN9Ojds8'
+
+TWITTER_CONSUMER_KEY = 'MS8DNyi5HX9HhJgigL24VEkqA'
+TWITTER_CONSUMER_SECRET = '1QdaLTNyrGIoZUniToou5bqax8mo7yuzIm7o4XjxzMhBE4UPY1'
+TWITTER_ACCESS_TOKEN = '43035062-zulNy9FQtEb2i9DeRGQen62HEDf21hpwWcRVAEOOy'
+TWITTER_ACCESS_TOKEN_SECRET = 'EEssSDgD4JbXzksmWHW1stBVxNtwfj1nq5Pd2Plkm17wj'

+ 0 - 1
ionic/www/templates/instagramUser.html

@@ -14,7 +14,6 @@
 			  <div class="col">Media: {{ data.counts.media }}</div>
     	</ion-item>
   
-
       <img collection-repeat="data in instagramUserMediaData.data"
         ng-src="{{data.images.thumbnail.url}}">
     

+ 1 - 0
requirements.txt

@@ -34,3 +34,4 @@ snowballstemmer==1.2.0
 sphinx-rtd-theme==0.1.7
 twilio==3.8.0
 wsgiref==0.1.2
+googlemaps==2.2