Ejemplo n.º 1
0
def return_finaid(income, other):
	eligible = False

	if(income):
		if(isinstance(income, str)):
			income = income.replace("$", "")
			income = income.replace(",", "")
			income = int(income)
		if(income < 24000):
			eligible = True

	if(other):
		if(("SNAP" in other) or ("reduced-lunch" in other) or ("FPL" in other)):
			eligible = True

	colleges = [{}]


	if(eligible):
		client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')

		pages = client.list('schools')

		for page in pages:
			results = page["results"]
			for college in results:
				display = college["value"]
				colleges.append({
					"title":display["title"],
					"amount":"full"})
	return colleges
Ejemplo n.º 2
0
def return_fedaid(income):

	client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')

	searchString = ''

	if(income):
		if(isinstance(income, str)):
			income = income.replace(",", "")
			income = income.replace("$", "")
		searchString += ('income: ["' + str(income) + '" TO "80000"] OR ')

	searchString += ('amount: "$5,730"')

	# list all items that match our search query
	pages = client.search('government', searchString)

	scholarships = []

	for page in pages:
		results = page["results"]
		for scholarship in results:
			display = scholarship["value"]
			scholarships.append({
				"title":display["title"],
				"description":display["description"],
				"link":display["link"],
				"amount":display["amount"]
				})
	return scholarships
Ejemplo n.º 3
0
def zip_est_income(household_size, zip):
	client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')

	# make sure our API key works
	client.ping().raise_for_status()	

	zipcode = client.get('income', zip)

	return zipcode['median']
Ejemplo n.º 4
0
	def put(self):
		client = Client(self.api_key)
		result = client.put(self.collection,
								self.key,
								self.json)
		try:
			result.raise_for_status()
			if result != None:
				response = result.response
				logging.info('Orchestrate response: %s', result.reason)
				if response.reason == 'Created':
					logging.info('Orchestrate Finished Transaction OK')
				else:
					logging.warning('Orchestrate Failed Transaction: %s', result.reason)
		except Exception as e:
			logging.critical('Orchestrate failed with an exception: %s' % (e.message))
			raise
Ejemplo n.º 5
0
def return_scholarships(race, GPA, SAT, gender, income, other):

	client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')

	searchString = ''

	if(race):
		searchString += ('race: "' + str(race) + '" OR')
	if(GPA):
		searchString += ('GPA: ["0.00" TO "' + str(GPA) + '"] OR')
	if(SAT):
		searchString += ('SAT: ["0" TO "' + str(SAT) + '"] OR')
	if(gender):
		searchString += ('gender: "' + str(gender) + '" OR')
	if(income):
		if(isinstance(income, str)):
			income = income.replace(',', '')
			income = income.replace("$", "")
		searchString += ('income: ["' + str(income) + '" TO "100000"] OR')

	if(other):
		for item in other:
			searchString += ('other-classifier: "' + str(item) + '" OR')

	if(searchString):
		searchString = searchString[:-2]

	# list all items that match our search query
	pages = client.search('scholarship', searchString)

	scholarships = []

	for page in pages:
		results = page["results"]
		for scholarship in results:
			display = scholarship["value"]
			scholarships.append({
				"title":display["title"],
				"description":display["description"],
				"link":display["link"],
				"amount":display["amount"]
				})
	return scholarships
Ejemplo n.º 6
0
 def connect(self):
     client = Client(self.USR_KEY)
     client.ping().raise_for_status()
     return client
Ejemplo n.º 7
0
from porc import Client
import utils, time
from agency import Agency

client = Client("your api key")
agency = Agency("rutgers")

relevantTags = ['a', 'b', 'f', 'lx']

relevantRoutes = []
for relevantTag in relevantTags:
    route = agency.getRoute(relevantTag)
    if route != None:
        relevantRoutes.append(route)

while True:
    print("start")
    predictions = []
    for route in relevantRoutes:
        predictions = predictions + route.getPredictions()

    # asynchronously post items
    with client. async () as c:
        futures = [
            c.post('predictions', prediction) for prediction in predictions
        ]
        responses = [future.result() for future in futures]
        [response.raise_for_status() for response in responses]
    print("end")
    time.sleep(10)
# Using .netrc keeps keys and other private data out of repositories.  Read up on .netrc for the details
# Get authentication secrets
secrets = netrc.netrc()

# Set the right datacenter for the Orchestrate data
orcHost = 'api.ctl-uc1-a.orchestrate.io'
orcURI = 'https://' + orcHost + '/v0'
# Set Orchestrate Credentials
orcUser, orcAcct, orcKey = secrets.authenticators(orcHost)

if DEBUG == 1:
    sys.stdout.write("Connecting to Orchestrate with key = " + orcKey + "\n")

# Connect to Orchestrate and validate key/connection
oClient = Client(orcKey, orcURI)
oClient.ping().raise_for_status()
# Set the mongo endpoint.
mongoEndpoint = '192.168.0.1'
mongoPort = '27017'
mongoURI = "mongodb://" + mongoEndpoint + ":" + mongoPort

# Set Mongo Credentials
mongoUser, mongoAcct, mongoBasePass = secrets.authenticators(mongoEndpoint)
mongoPass = mongoBasePass.decode('base64').rstrip('\n')

if DEBUG == 1:
    sys.stdout.write("Connecting to " + mongoURI + " with user: "******"\n")
client = MongoClient(mongoURI)
Ejemplo n.º 9
0
from porc import Client
client = Client('f61515c7-8df9-4003-ab45-2f3e259610ff')
import time

if __name__ == '__main__':
    parties = client.list('parties').all()
    for i in range(0, len(parties)):
        print time.ctime(int(parties[i]['reftime'] / 1000))
Ejemplo n.º 10
0
 def connect(self):
     client = Client(self.USR_KEY)
     client.ping().raise_for_status()
     return client
Ejemplo n.º 11
0
from porc import Client
from collections import defaultdict
import time

client = Client('f61515c7-8df9-4003-ab45-2f3e259610ff')


def displayNumUsers():
    numbers = client.list('numbers').all()
    return str(len(numbers))


def mostPopularSong():
    songs = client.list('songs').all()
    max = 0
    songName = ''
    for i in range(0, len(songs)):
        if (songs[i]['value']['playCount'] > max):
            max = songs[i]['value']['playCount']
            songName = songs[i]['path']['key']
            song = songs[i]
    return songName


def displayNumSongs():
    songs = client.list('songs').all()
    return str(len(songs))


if __name__ == '__main__':
    print displayNumUsers() + ',' + displayNumSongs() + ',' + mostPopularSong(
Ejemplo n.º 12
0
def index(request):
    #Cargar llave de api para orchestrate del archivo orch.py 
    client = Client(orch.key)
    #Regex para detectar ips validas y evitar que se manipule la informacion recibida
    ValidIp = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
    client_ip = get_ip(request)
    check = False
    country = ""
    city = ""
    if (re.match(ValidIp, client_ip)):
      nm = nmap.PortScanner()
      #client_ip = "186.80.56.1/24"
      #Ejecutar nmap sobre puertos http y script de deteccion de vulnerabilidades
      nm.scan(client_ip, '80,8080,443,64680', arguments='--script=http-vuln-col -Pn -T5')
      #Iterar sobre los resultados del escaneo
      for host in nm.all_hosts():
        client_host = ('\nHost : %s (%s)' % (host, nm[host].hostname()))
        #Consultar datos de la ip frente a geoip
        geoip = lizepy.get_geoip(str(host))
        #Procesamiento de excepciones, en algunos casos geoip no devuelve los datos esperados
        try:
          if geoip.country_code:
            country = geoip.country_code
        except:
          country = ""
        try:
          if geoip.city:
            city = geoip.city
        except:
          city = ""
        for ports in nm[host].all_tcp():
            if nm[host]['tcp'][ports]['state'] == "open":
                try:
                  if (re.search( 'Vulnerabilidad:.+', nm[host]['tcp'][ports]['script']['http-vuln-col'])):
                    vuln = vulnerable(ip_add=host, hostname=nm[host].hostname(), port=ports, date=timezone.now(), result = nm[host]['tcp'][ports]['script']['http-vuln-col'], country = country, city = city)
                    vuln.save()
                    output = nm[host]['tcp'][ports]['script']['http-vuln-col']
                    #Procesar texto recibido de nmap, para ser desplegado al usuario
                    check = re.search( 'Vulnerabilidad:.+', nm[host]['tcp'][ports]['script']['http-vuln-col'])
                    check = check.group()
                    #Parametro json para ser enviado, a orchestrate
                    vuln_json = { "ip": host, "hostname": nm[host].hostname(),  "port": ports, "data": nm[host]['tcp'][ports]['script']['http-vuln-col'], "Country": country, "City": city, "Vulnerable": True, "Date": str(timezone.now())}
                    response = client.post("vulnerables", vuln_json)
                    response.raise_for_status()
                  else:
                    check = False
                except:
                  check = False
        if check == False:
          vuln = vulnerable(ip_add=host, hostname=nm[host].hostname(), port=ports, date=timezone.now(), result = "", vulnerable = False, country = country, city = city)
          vuln.save()
          #Parametro json para ser enviado, a orchestrate
          vuln_json = { "ip": host, "hostname": nm[host].hostname(),  "port": ports, "data": None, "Country": country, "City": city, "Vulnerable": False, "Date": str(timezone.now()) }
          response = client.post("vulnerables", vuln_json)
          response.raise_for_status()
      template = loader.get_template('vulns/index.html') 
      context = {'ip':client_ip, 'host':client_host, 'vulnerable':check}
      return render(request, 'vulns/index.html', context)
    else:
      context = {'ip':"Ip invalida", 'vulnerable':check}
      return render(request, 'vulns/index.html', context)
Ejemplo n.º 13
0
from porc import Client

from porc import Patch

from dejavu.database import Database

client = Client("7e23e64c-f1a8-4072-90c7-6c00c804c0e5")
# tables
FINGERPRINTS_TABLENAME = "fingerprints"
SONGS_TABLENAME = "songs"

# fields
FIELD_FINGERPRINTED = "fingerprinted"
    
class OrchestrateDatabase(Database):
    type = "orchestrate"

    def __init__(self, **options):
            super(OrchestrateDatabase, self).__init__()
            self._options = options
        
    def insert(self, hash, sid, offset):
        """
        Insert a (sha1, song_id, offset) row into database.
        """
       

    def insert_song(self, songname, file_hash):
        """
        Inserts song in the database and returns the ID of the inserted record.
Ejemplo n.º 14
0
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

from porc import Client
import rethinkdb as r

conn = r.connect("localhost", 28015)

host = "https://api.aws-eu-west-1.orchestrate.io/"
client = Client("5d754f98-857a-4aed-8dc6-0e397c8d1816", host)


class ThemisbotPipeline(object):
    def process_item(self, item, spider):
        return item


class CleanUpPipeline(object):
    def process_item(self, item, spider):

        item['content'].remove('Advertisement')

        return item


class OrchestratePipeline(object):
    def process_item(self, item, spider):
Ejemplo n.º 15
0
from flask import Flask, request, abort, jsonify, g
from porc import Client
import datetime
import embedly
import hashlib
import json
import nltk
import os
import requests
import uuid

# embedly
embedly_client = embedly.Embedly(os.environ['EMBEDLY_API_KEY'])

# orchestrate.io - data storage pluse search
client = Client(os.environ['ORCHESTRATE_API_KEY'])

client.ping().raise_for_status()

app = Flask(__name__)

def alchemy_call(service, params):
    ALCHEMY_URL = "http://access.alchemyapi.com/calls/url/"

    params['outputMode'] = 'json'
    params['apikey'] = os.environ['ALCHEMY_API_KEY']
    r = requests.get(ALCHEMY_URL + service, params=params)
    app.logger.debug('json: %s' % r.text)
    return json.loads(r.text)

def alchemy_flow(url):
Ejemplo n.º 16
0
from porc import Client
import csv

client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')

# make sure our API key works
client.ping().raise_for_status()

school_list = []

with open('full-need-schools.csv', 'rt') as csvfile:
	schoolreader = csv.reader(csvfile, delimiter = ',')
	for row in schoolreader:
		school_list = row


for school in school_list:
	response = client.put('schools', school, {
	  "title": school,
	  "amount":"full",
	  "income":"$24,000",
	  "other-classifier":["SNAP","reduced-lunch","FPL"]
	})
	# make sure the request succeeded
	response.raise_for_status()
# # prints the item's key
# print response.key
# # prints the item version's ref
# print response.ref
Ejemplo n.º 17
0
from flask import Flask, request
from porc import Client

import braintree

braintree.Configuration.configure(braintree.Environment.Sandbox,
                                  merchant_id="MERCHANT_ID",
                                  public_key="PUBLIC_KEY",
                                  private_key="PRIVATE_KEY")

API_KEY = 'API_KEY'
client = Client(API_KEY)

app = Flask(__name__)


@app.route('/price', methods=['GET', 'POST'])
def price():
    store = request.args.get('store')
    upc_code = request.args.get('upc')
    result = 'No Product In Database'
    response = client.get('stores', store)
    if (upc_code in response['upc']):
        result = str(response['upc'][upc_code]['price'])
    return result


@app.route('/name', methods=['GET', 'POST'])
def name():
    store = request.args.get('store')
    upc_code = request.args.get('upc')
Ejemplo n.º 18
0
from porc import Client

client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')

# make sure our API key works
client.ping().raise_for_status()	

zipcode = client.get('income', 97229)

print(zipcode['median'])
Ejemplo n.º 19
0
	def get(self):
		client = Client(self.api_key)
		return client.get(self.collection, self.key)
Ejemplo n.º 20
0
from porc import Client
client = Client('f61515c7-8df9-4003-ab45-2f3e259610ff')
import time

if __name__ =='__main__':
    parties = client.list('parties').all()
    for i in range(0, len(parties)):
        print time.ctime(int(parties[i]['reftime']/ 1000))
Ejemplo n.º 21
0
#!/usr/bin/env python
from flask import Flask, redirect, url_for, render_template, jsonify
from porc import Client
from humanize import intword
from secrets import ORCHESTRATE_KEY
import random
app = Flask(__name__)
app.config["SERVER_NAME"] = "chopmotto.ml"
orche = Client(ORCHESTRATE_KEY, "https://api.aws-eu-west-1.orchestrate.io/")
orche.ping().raise_for_status()

tops = [""]
bots = [""]

with open("top.txt") as f:
    for line in f:
        if len(line.strip()) > 0:
            tops.append(line.strip())
print("%i tops loaded" % (len(tops)-1))

with open("bottom.txt") as f:
    for line in f:
        if len(line.strip()) > 0:
            if not line.strip().endswith("."):
                line = line.strip() + "."
            bots.append(line)
print("%i bottoms loaded" % (len(bots)-1))

@app.route("/api/<int:t>/<int:b>")
@app.route("/api/r/<int:b>")
@app.route("/api/<int:t>/r")
Ejemplo n.º 22
0
from porc import Client
import csv

client = Client('e6e56d2e-b91e-4dc2-aac7-ec6028c378e2')

# make sure our API key works
client.ping().raise_for_status()

income = []

with open('income.csv', 'rt') as csvfile:
	incomereader = csv.reader(csvfile, delimiter = ',')
	for row in incomereader:
		income.append({
			"ZIP":row[0],
			"median":row[1],
			"mean":row[2],
			})
		
for zipcode in income:
	response = client.put('income', zipcode["ZIP"], {
	  "ZIP": zipcode["ZIP"],
	  "median": zipcode["median"],
	  "mean": zipcode["mean"]
	})
	# make sure the request succeeded
	response.raise_for_status()
Ejemplo n.º 23
0
import random
from threading import Timer
from datetime import datetime

# Sevabot & Orchestratre
from sevabot.bot.stateful import StatefulSkypeHandler
from sevabot.utils import ensure_unicode, get_chat_id
from porc import Client

# Load settings
import settings

# Init logger
logger = logging.getLogger('Duarte')
# Init orchestrate.io
client = Client(settings.API_KEY, settings.API_URL)

# Set to debug only during dev
logger.debug('[Duarte] Loading class')


class Duarte(StatefulSkypeHandler):
    """
    Duarte
    Handle Duarte's bans
    """

    def __init__(self):
        """
        Use `init` method to initialize a handler.
        """
Ejemplo n.º 24
0
"""
Roadmap's main flask app.


"""

import os
from porc import Client
from flask import Flask
from flask.ext.appconfig import AppConfig


def create_app(configfile=None):
    app = Flask(__name__)
    AppConfig(app, configfile)
    return app


app = create_app()

# mail = Mail(app)
# db = SQLAlchemy(app)

client = Client(app.config['ORCHESTRATE_KEY'])
client.ping().raise_for_status()

import roadmap.views

if __name__ == '__main__':
    app.run()