def get_next(self): name_to_id = {} songs = Firebase(FIREBASE_URL + "songs").get() vo_ids = [] bg_ids = [] for song_id in songs: song = songs[song_id] name_to_id[song['song_name'].lower().replace(" ", "")] = song_id if song["file_type"] == "instrumental": bg_ids += [song["id"]] else: vo_ids += [song["id"]] vo_id = vo_ids[int(len(vo_ids) * random.random())] bg_id = bg_ids[int(len(bg_ids) * random.random())] next_song = Firebase(FIREBASE_URL + "next_song/") song_name = next_song.get()['song_name'] if next_song.get()['must_play'] and song_name in name_to_id: if next_song.get()['song_type'] == 'vocal': vo_id = name_to_id[song_name] else: bg_id = name_to_id[song_name] next_song.update({'must_play':0, 'song_name':-1}) vo_clip = self.slice_song(vo_id) bg_clip = self.slice_song(bg_id) return (vo_clip, bg_clip)
def send_news(): fb = Firebase('https://welse-141512.firebaseio.com/items') old_items = fb.get() if(old_items == None): old_items = scrap() new_items = scrap() new_send = getNew(old_items, new_items) counts = 0 el = [] users_fb = Firebase('https://welse-141512.firebaseio.com/ocz/') users = users_fb.get() for u in users: user = Firebase('https://welse-141512.firebaseio.com/ocz/' + str(u)) user_data = user.get() for type_u in user_data: if(user_data[type_u]['subcribe'] == 1): print new_send[type_u] if len(new_send[type_u]) != 0: el = [] for item in new_send[type_u]: el.append({ "title": item['name'], "subtitle": item['subtitle'], "image_url": item['image'], "buttons": [{ "title": "View", "type": "web_url", "url": item['link'], }, { "type":"element_share" }], "default_action": { "type": "web_url", "url": item['link'] } }) print counts if(counts >= 9 or new_send[type_u][-1]['name'] == item['name']): print "send" send_message(u, 'ใหม่!! ' + str(type_u) + ' ' + str(len(el)) + ' กระทู้ฝอยจัดให้!!') send_generic(u, el) r = random.uniform(0, 1) counts = 0 el = [] break counts += 1 else: r = random.uniform(0, 1) # if r > 0.98: # send_message(u, 'ตลาดเงียบเหงาโคตร แต่ไม่ต้องกลัว ฝอยคอยจับตาดูให้อยู่ตลอด') fb.set(new_items)
def run(self): while True: start_time = time.time() cur_speed = Firebase(FIREBASE_URL + "cur_speed/") bpm = cur_speed.get()['bpm'] dbpm = cur_speed.get()['dbpm'] cur_speed.update({'bpm':bpm+dbpm, 'dbpm':0}) (vo, bg) = self.get_next(); mashup = self.render_next(vo, bg, bpm, dbpm); self.schedule(mashup) time.sleep(max(MIX_DURATION - CROSSFADE_TIME - int(time.time() - start_time), 0))
def main(): BASE_URL = 'https://amber-fire-5569.firebaseio.com/Traffic/' f = Firebase(BASE_URL) results = f.get() for key in results: pprint(key) pprint(results[key]) payload = results[key] street1 = results[key]['intersection1'] street2 = results[key]['intersection2'] coords = intersection_to_coords(street1, street2) print coords try: payload['Latitude'] = coords['Latitude'] except TypeError: continue payload['Longitude'] = coords['Longitude'] endpoint = Firebase(BASE_URL+key) pprint(payload) endpoint.set(payload)
def subscribe_user(): tracking_id = request.args.get('tracking_id') fb_id = request.args.get('fb_id') user = Firebase('https://bott-a9c49.firebaseio.com/users/' + fb_id) tracks = user.get() print tracks found = False found_track = "" if tracks: for track in tracks: print track, tracking_id if track == tracking_id: found = True found_track = track if not found: user.set({tracking_id: {'tag': 'NOT FOUND','subscribe': 'true','created_at':str(datetime.datetime.now())}}) else: track_status = Firebase('https://bott-a9c49.firebaseio.com/users/' + fb_id + '/'+tracking_id).get() user.set({tracking_id: {'tag': track_status['tag'] , 'subscribe': 'true','updated_at':str(datetime.datetime.now()) }}) message = { "messages": [ {"text": u"ได้เลยครับ ถ้ามีอัพเดท ผมจะติดต่อไปทันที"} ] } return jsonify(message)
def get_votos_senador(codigo): #r = requests.get('https://maisbr.firebaseio.com/senadores/' + codigo + '/votos.json') #senadores_dict = r.json() f = Firebase(FBURL + '/senadores/' + codigo + '/votos') senadores_dict = f.get() return senadores_dict
class Thermostat: def __init__(self, auth, structure_id, device_id): self.device_id = device_id self.structure_id = structure_id self.auth = auth self.fb_target_temp = Firebase( "https://developer-api.nest.com/devices/thermostats/" + device_id + "/target_temperature_f", auth_token=auth ) self.fb_away = Firebase("https://developer-api.nest.com/structures/" + structure_id + "/away", auth_token=auth) # Method to return the target temp def getTargetTemp(self): return self.fb_target_temp.get() # Method to return the away status def getAwayStatus(self): return self.fb_away.get()
def updateProjectFeatures(id): fire = Firebase("https://friendlychat-1d26c.firebaseio.com/protectedResidential/9999/projects/-KLLdC7joRUmOsT11Efp") temp = fire.get() # projects_all = fire.get() # print json.dumps(temp, indent = 4) price_range,size_range = price_size_range({"-KLLdC7joRUmOsT11Efp" : temp}) # print price_range, size_range updated_features = all_features_mapping(getProjectDataDoc(id), getProjectFeaturesDoc(id), price_range, size_range) es.update(index = 'projects', doc_type = 'features', id = id, body = {"doc" : updated_features})
def createUsersDatabase(): auth_payload = {"uid": "bhptnfQoq1eEytRBbjjGDrv40oC2"} token = create_token("neftLmN0eBpzsRLAasLcer70wt6KqM6OZmoHKgFd", auth_payload) fire = Firebase("https://roofpik-948d0.firebaseio.com/users/data/", auth_token=token) users_all = fire.get() for i in users_all: createUserJSON(i)
def get_dict_nomes_senadores(): # Retorna lista com nomes de todos os senadores salvos no DB f = Firebase(FBURL + '/senadores') dados = f.get() dict_nomes = {} for key, val in dados.iteritems(): dict_nomes[key] = val['NomeParlamentar'] return dict_nomes
def createProjectsDatabase(): fire = Firebase("https://friendlychat-1d26c.firebaseio.com/protectedResidential/9999/projects/-KLLdC7joRUmOsT11Efp/") i = '-KLLdC7joRUmOsT11Efp' temp = fire.get() # projects_all = fire.get() # for i in projects_all: # createProjectDataIndex(i, projects_all[i]) createProjectDataIndex(i, temp ) createProjectFeaturesIndex(i) updateProjectFeatures(i)
def send_news(): fb = Firebase('https://welse-141512.firebaseio.com/movies') old_items = fb.get() if (old_items == None): old_items = scrap_movie() new_items = scrap_movie() new_send = getNew(old_items, new_items) users_fb = Firebase('https://welse-141512.firebaseio.com/submovies/') users = users_fb.get() for u in users: user = Firebase('https://welse-141512.firebaseio.com/submovies/' + str(u)) user_data = user.get() for m in user_data: el = [] for newMovie in new_send: if m['name'] == newMovie['title']: el.append({ "title": newMovie['title'], "subtitle": str(newMovie['imdb']), "image_url": newMovie['image'], "buttons": [{ "title": u"ดู", "type": "web_url", "url": newMovie['link'], }], "default_action": { "type": "web_url", "url": newMovie['link'] } }) if len(el) == 10 or newMovie['title'] == new_send[-1]['title']: send_generic(sender_id, el) break fb.set(new_items)
def get_nest(request): # Virtual DEvice #f=Firebase('https://developer-api.nest.com/devices/thermostats/N96fw5MnBnmwH4ZBZVOgvMwgbVqewXOS',auth_token="c.9tKvASa4R9fG9hx8kFb9QeUMzxo5OalPNFY9YswzKzENRKn51hNdnx6ctVVjQgRUiCbumqTgFZtWnBDtJFzXLFM8QgdlwtRjWtB3rgfDog5juDNHXdpON9XtNyzulgjMJnPYIbgS74bQ8cUc") # ACL Device f = Firebase( 'https://developer-api.nest.com/devices/thermostats/Q3Vcf1OhcRbUfcweDwMdCkNGApfAG1NY', auth_token= "c.Q2DQ3IxfJwtrqg6vMRDjQHx4DBF30BoAwv8kOmV5wSCsTmFPTZR8gLxURcomK3tvWgvJAzpCFNfnZt7b56Va1YkxUaGwpgOXjBpX1gg7vPUj6ayinv8DCGSIzsx5Klz58xRVEtaS1ZBVlTyG" ) rst = f.get() #hum = str(rst.get('humidity')) return HttpResponse(json.dumps(rst))
def bot_beta_node(): bot_id = request.args.get('bot_id') block_id = request.args.get('block_id') block = Firebase('https://bot-platform-a5a5a.firebaseio.com/bots/bot_' + str(bot_id) + '/blocks/block' + str(block_id)) if(block is not None): nodes = block.get()['nodes'] el = [] for node in nodes: if(len(el) >= 9): break n = Firebase('https://bot-platform-a5a5a.firebaseio.com/bots/bot_' + str(bot_id) + '/blocks/block' + str(block_id) + '/nodes/' + node ).get() el.append({ "title": n['nodeResponse']['response'], "subtitle": n['node_type'], "buttons": [{ "set_attributes": { "node_id": n['node_id'], }, "title": u"เลือก", "type": "show_block", "block_name": "node_text", }] }) message = { "messages": [ { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": el, } } },{ "text": u"เลือก Node ที่จะแก้เลยคร้าบบบ" } ] } else: message = { "messages": [ { "text": u"อืมมมม..." } ] } return jsonify(message)
def bot_beta_block(): bot_id = request.args.get('bot_id') bot = Firebase('https://bot-platform-a5a5a.firebaseio.com/bots/bot_' + str(bot_id)) if(bot is not None): blocks = bot.get()['blocks'] el = [] for block in blocks: if(len(el) >= 9): break b = Firebase('https://bot-platform-a5a5a.firebaseio.com/bots/bot_' + str(bot_id) + '/blocks/' + block).get() el.append({ "title": b['block_name'], "subtitle": "bot_id: " + str(b['bot_id']), "buttons": [{ "set_attributes": { "block_id": b['block_id'], }, "title": u"เลือก", "type": "show_block", "block_name": "node_list", }] }) message = { "messages": [ { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": el, } } },{ "text": u"เลือก Block ที่จะแก้เลยคร้าบบบ" } ] } else: message = { "messages": [ { "text": u"อืมมมม..." } ] } return jsonify(message)
def get_point_firebase(): points = {} # initiate the connexion to Firebase token = create_token(FIREBASE_SECRET , AUTH_PAYLOAD) firebase_project = FIREBASE_PROJECT + '/' + ROOT_OBJECT + '.json' firebase = Firebase(firebase_project, token) results = firebase.get() if results is not None: for result in results: points[results[result]['id']] = { 'key': result, 'data': results[result] } return points
def get_point_firebase(): points = {} # initiate the connexion to Firebase token = create_token(FIREBASE_SECRET, AUTH_PAYLOAD) firebase_project = FIREBASE_PROJECT + '/' + ROOT_OBJECT + '.json' firebase = Firebase(firebase_project, token) results = firebase.get() if results is not None: for result in results: points[results[result]['id']] = { 'key': result, 'data': results[result] } return points
firstIndexPrice = pricesDictionary[date]["close"] return {"totalRevenue":totalRevenue, "firstPrice":firstPrice, "thirtyDayRevenue":thirtyDayRevenue, "firstThirtyDayPrice": firstIndexPrice, "daysRight":daysRight, "daysWrong":daysWrong, "todayDecision": todayDecision} # # client = pubsub.Client.from_service_account_json('/banshee/credentials.json', 'money-maker-1236') # topic = client.topic('hotstocks') # subscription = topic.subscription('hot_shadow_stocks') #should insert while loop around so it continues to pull while there are still items in the queue # get prices and trends snapshot prices = Firebase("https://sv2.firebaseio.com/etf_prices") pricesResults = prices.get() hotpipeline = Firebase("https://sv2.firebaseio.com/hotpipeline") hotpipelineResults = hotpipeline.get() runningProcesses = {} pipeEmpty = False for stock in pricesResults: stockPresent = True for i in range(1,8): #change to 7 days (1,8) if "sage:" + stock + ":" + str(i) not in hotpipelineResults: stockPresent = False if "wizard:" + stock + ":" + str(i) not in hotpipelineResults: stockPresent = False
fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL) fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK) #setup serial for communicating with the Arduino ser = serial.Serial('/dev/ttyACM0', 9600) fire_url = 'https://smart-fridge-76b1c.firebaseio.com' fireserial = Firebase(fire_url + '/Serials') firein = Firebase(fire_url + '/In Fridge') #fireout = Firebase(fire_url+'/Taken Out') fireputin = Firebase(fire_url + '/Functions/PutIn') firetakeout = Firebase(fire_url + '/Functions/TakeOut') #Grab serials and num items in fridge serials = fireserial.get() num_in = len(firein.get()) def put_in(scanned): global num_in num_in += 1 fireputin.patch({scanned: True}) print "Puttin in " + serials[scanned] def take_out(scanned): global num_in num_in -= 1
# # Instantiate a table resource object without actually # # creating a DynamoDB table. Note that the attributes of this table # # are lazy-loaded: a request is not made nor are the attribute # # values populated until the attributes # # on the table resource are accessed or its load() method is called. # table = dynamodb.Table('tweets') query_terms = {} news_terms = {} apiKey = "4469bdfb1ad6870179e7360fe95cc84f839389f1" while True: try: f = Firebase('https://sv2.firebaseIO.com/terms') query_terms = f.get() break except: print("Download Error") while True: try: f = Firebase('https://sv2.firebaseIO.com/news') news_terms = f.get() break except: print("Download Error") for term in query_terms:
class TestApp(App): def __init__(self): super(TestApp, self).__init__() self.rfidReader = RFIDReader(handler_function=self.handler) self.firebase = Firebase(config) self.cleanInfoEvent = None self.screen_manager = ScreenManager(transition=NoTransition()) self.home_screen = HomeScreen(name='home') self.viewer_screen = ViewerScreen(name='viewer', firebase=self.firebase) self.screen_manager.add_widget(self.home_screen) self.screen_manager.add_widget(self.viewer_screen) def build(self): self.rfidReader.start() return self.screen_manager def stop(self): self.rfidReader.stop() def __del__(self): self.rfidReader.stop() def getUserData(self, rfid): try: user_data = self.firebase.get("users/" + rfid).val() return user_data except Exception: raise Exception( "Nessuna connessione ad internet. Contatta la segreteria!") def downloadUserFile(self, rfid, destination_path, filename_path): try: system("mkdir -p %s" % destination_path) system("rm -f %s/*" % destination_path) node = self.firebase.getNode("users/" + rfid + "/scheda.zip") node.download(filename_path) except Exception as e: raise Exception("Impossibile scaricare file dal server. " + str(e)) def extractUserFile(self, rfid, destination_path, filename_path): try: with zipfile.ZipFile(filename_path, "r") as zip_ref: for zip_info in zip_ref.infolist(): if zip_info.filename[-1] == '/': continue zip_info.filename = path.basename(zip_info.filename) zip_ref.extract(zip_info, destination_path) except Exception: raise Exception( "Impossibile estrarre scheda dall'archivio. Contatta la segreteria!" ) def createQRCode(self, rfid, destination_path): try: qr = pyqrcode.create( 'https://firebasestorage.googleapis.com/v0/b/master-fitness.appspot.com/o/users%2F' + rfid + '%2Fscheda.pdf?alt=media') qr.png(destination_path + '/qr_code.png', scale=4) except Exception as e: raise Exception( "Impossibile creare il QR Code. Contatta la segreteria!") def loadViewerScreen(self, rfid, *largs): try: # try to download user data from firebase user_data = self.getUserData(rfid) # if user data is not found, raise exception if not user_data: raise Exception( "Utente non registrato. Chiedi informazioni in segreteria!" ) # ex. filename_path: storage_data/0123456789/scheda_2019-12-28_02-06-09.zip destination_path = 'storage_data/' + rfid filename_path = destination_path + '/' + user_data['file'] # if .zip file doesnt exist download from firebase if not path.isfile(filename_path): self.downloadUserFile(rfid, destination_path, filename_path) if not path.isfile(destination_path + '/scheda_0.jpg'): self.extractUserFile(rfid, destination_path, filename_path) if not path.isfile(destination_path + '/qr_code.png'): self.createQRCode(rfid, destination_path) self.viewer_screen.setUserData(user_data) self.screen_manager.current = 'viewer' except Exception as e: self.showHint(str(e)) def handler(self, rfid): Clock.schedule_once( partial(self.home_screen.setHintMessage, "Carico scheda..."), -1) self.screen_manager.current = 'home' Clock.schedule_once(partial(self.loadViewerScreen, rfid), 0.1) def showHint(self, text, timeout=6): if self.cleanInfoEvent: Clock.unschedule(self.cleanInfoEvent) self.home_screen.setHintMessage(text) self.cleanInfoEvent = Clock.schedule_once( partial(self.home_screen.setHintMessage, ""), timeout)
def get_nome_from_codigo(codigo): # Retorna nome do senador cujo código foi passado no argumento f = Firebase(FBURL + '/senadores/' + codigo + '/NomeParlamentar') return f.get()
import requests from firebase import Firebase import json # Open AccessToken file to load access token for Nest API with open('AccessToken.json') as json_file: data = json.load(json_file) access_token = data['access_token'] email = '*****@*****.**' # create firebase object fb = Firebase('https://developer-api.nest.com/devices', auth_token=access_token) # get devices devices = fb.get() # dump devises into json file with open('devices.json', 'w') as json_out: json.dump(devices, json_out) print devices print "Devices file created!"
def decrease_speed(self): cur_speed = Firebase(FIREBASE_URL + 'cur_speed/') bpm = cur_speed.get()['bpm'] cur_speed.update({'bpm':bpm, 'dbpm':-20})
except: print ("Upload error...trying again!") runningProcesses = {} pipeEmpty = False current_time = "2015-08-14" query_terms = {} twitterData = {} while True: try: f = Firebase('https://sv2.firebaseIO.com/terms') query_terms = f.get() f = Firebase('https://sv2.firebaseIO.com/tweets') twitterData = f.get() break except: print("Download Error") while True: while(len(runningProcesses) < 31 and pipeEmpty == False): term = None while pipeEmpty == False: try: while True: term = query_terms.popitem()[0] if '2014-10-25' not in twitterData[term]:
import os import sys import math from multiprocessing import Process # get prices and trends snapshot pricesResults = {} while True: try: # get prices and trends snapshot prices = Firebase("https://sv2.firebaseio.com/prices") pricesResults = prices.get() print("Got Prices") break except: print("Download Error") #add stocks to pipeline client = pubsub.Client.from_service_account_json('/banshee/credentials.json', 'money-maker-1236') topic = client.topic('stocks') while True: try: with topic.batch() as batch: for stock in pricesResults:
thirtyDayRevenue += dic["revenue"] if firstIndexPrice == 0.0 and date in pricesDictionary and date < lastIndexFirstPrice: lastIndexFirstPrice = date firstIndexPrice = pricesDictionary[date]["close"] return {"totalRevenue":totalRevenue, "firstPrice":firstPrice, "thirtyDayRevenue":thirtyDayRevenue, "firstThirtyDayPrice": firstIndexPrice, "daysRight":daysRight, "daysWrong":daysWrong, "todayDecision": todayDecision} #should insert while loop around so it continues to pull while there are still items in the queue # get prices and trends snapshot prices = Firebase("https://sv2.firebaseio.com/prices") pricesResults = prices.get() algorithmsResults = {} while True: try: algorithms = Firebase("https://sv2.firebaseio.com/google_decision_data_current/aggregation") algorithmsResults["aggregation"] = algorithms.get() break except: print("aggregation issue") while True: try: algorithms = Firebase("https://sv2.firebaseio.com/google_decision_data_current/aggregation_ninety") algorithmsResults["aggregation_ninety"] = algorithms.get() break
def build_firebase_connection(item): firebase = Firebase('https://roofpik-948d0.firebaseio.com/'+str(item)) data = firebase.get() return data
import requests import json from firebase import Firebase import datetime from datetime import timedelta quotes_to_check = {} while True: try: f = Firebase('https://sv2.firebaseio.com/stock_tickers') quotes_to_check = f.get() break except: print("Download Error") print("Got Tickers") #updated to just get current price for stock for quote in quotes_to_check: print("Getting Data for " + quote + "...") while True: try: print("https://chartapi.finance.yahoo.com/instrument/1.0/"+ quotes_to_check[quote] +"/chartdata;type=quote;range=7d/json") r = requests.get("https://chartapi.finance.yahoo.com/instrument/1.0/"+ quotes_to_check[quote] +"/chartdata;type=quote;range=7d/json") # r = requests.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22" + quotes_to_check[quote] + "%22%20and%20startDate%20%3D%20%22" + last_year + "%22%20and%20endDate%20%3D%20%22" + current_time + "%22&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=") # r = requests.get("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22" + quotes_to_check[quote] + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=") validJson = r.content[:-1]
#!/usr/bin/env python from firebase import Firebase import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText import json import logging firebase = Firebase('https://YOURFIREBASE.firebaseio.com/contacts') contact_list = firebase.get() server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() fromaddr = ‘[email protected]' toaddr = ‘[email protected]’ msg = MIMEMultipart() msg['From'] = formatter msg['To'] = toaddr server.login(fromaddr, ‘YOUR_PASSWORD’) for cl in contact_list: contact_name = str(contact_list[cl]['name']) contact_phone = str(contact_list[cl]['phone']) contact_email = str(contact_list[cl]['email']) contact_message = str(contact_list[cl]['message']) contact_type = str(contact_list[cl]['type']) contact_pref = str(contact_list[cl]['contact']) try: contact_view = str(contact_list[cl]['viewed']) except Exception, e:
if date > thirtyDaysAgoString: thirtyDayRevenue += dic["revenue"] if firstIndexPrice == 0.0 and date in pricesDictionary and date < lastIndexFirstPrice: lastIndexFirstPrice = date firstIndexPrice = pricesDictionary[date]["close"] return {"totalRevenue":totalRevenue, "firstPrice":firstPrice, "thirtyDayRevenue":thirtyDayRevenue, "firstThirtyDayPrice": firstIndexPrice, "daysRight":daysRight, "daysWrong":daysWrong, "todayDecision": todayDecision} #should insert while loop around so it continues to pull while there are still items in the queue # get prices and trends snapshot prices = Firebase("https://sv2.firebaseio.com/prices") pricesResults = prices.get() algorithms = Firebase("https://sv2.firebaseio.com/decision_data") algorithmsResults = algorithms.get() single_algorithms = Firebase("https://sv2.firebaseio.com/single_decision_data") single_algorithmsResults = single_algorithms.get() for stock in pricesResults: runStockAlgorithms(stock, pricesResults[stock], algorithmsResults, single_algorithmsResults) runningProcesses = {} pipeEmpty = False # while True: # while(len(runningProcesses) < 15 and pipeEmpty == False): #16 core machines
# Initialize button sensor object using pin 2. button = grove.GroveButton(2) # Initialize touch sensor object using pin 3. touch = ttp223.TTP223(3) # Initialize LCD screen. myLcd = lcd.Jhd1313m1(0, 0x3E, 0x62) # Boolean to recognize if any sensor is activated. sensorPressed = False firebase = Firebase('https://hounds.firebaseio.com/Park/Zones/-TEC' + str(sys.argv[1]) + '/', None) #print "Base" #print firebase result = firebase.get() #print "Result" #print result zone = ParkingZone.ParkingZone(int(sys.argv[1]) + 1, result['capacity'], result['occupied']) # Write into lcd screen. myLcd.clear() myLcd.setCursor(0, 0) myLcd.write("Zone " + str(zone.getZone())) myLcd.setCursor(1, 0) myLcd.write("Free spots: " + str(zone.calculateSpots())) while 1: if not sensorPressed: # Is any sensor activated? if button.value(): # Button zone 1 pressed.
# get prices and trends snapshot pricesResults = {} trendsResults = {} tweetsResults = {} wikipediaResults = {} priceGroupResults = {} while True: try: # get prices and trends snapshot prices = Firebase("https://sv2.firebaseio.com/prices") pricesResults = prices.get() print("Got Prices") trends = Firebase("https://sv2.firebaseio.com/google_trends") trendsResults = trends.get() print("Got Trends") tweets = Firebase("https://sv2.firebaseio.com/tweets") tweetsResults = tweets.get() print("Got Tweets") wikipedia = Firebase("https://sv2.firebaseio.com/wikipedia") wikipediaResults = wikipedia.get() print("Got wikipedia") break except: print("Download Error")
import requests import json from firebase import Firebase import datetime from datetime import timedelta import time query_terms = {} while True: try: f = Firebase('https://sv2.firebaseIO.com/terms_wikipedia') query_terms = f.get() break except: print("Download Error") startDate = datetime.datetime.now() - timedelta(days=3) yesterday = datetime.datetime.now() - timedelta(days=1) today = datetime.datetime.now() + timedelta(days=1) for term in query_terms: print(term) while True: try: r = requests.get("https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/" + term + "/daily/" + startDate.strftime('%Y%m%d') + "00/" + today.strftime('%Y%m%d') + "00") try: json.loads(r.content) except:
from firebase import Firebase import requests f = Firebase('https://burning-fire-8681.firebaseio.com/see-again-choices-R1/Alex') r = f.push( { "user_num": 24, "n": 9, "mn": 5, "my": 7, "y": 12 } ) # ff = Firebase('https://burning-fire-8681.firebaseio.com/see-again-choices-R1/{}'.format(r["name"])) s = f.get() print r # {u'name': u'-Jnbjgqt4tThZmXkyhcS'} # print s # {u'name': u'-Jnbjh7LWmhSyoIGbgyZ'} pprint(s) pprint(s[r["name"]]) # These are the names of the snapshots -- # dictionaries containing Firebase's REST response. print "\n\n\n\n" ff = Firebase("https://burning-fire-8681.firebaseio.com/see-again-choices-R1")
firstIndexPrice = pricesDictionary[date]["close"] return {"totalRevenue":totalRevenue, "firstPrice":firstPrice, "thirtyDayRevenue":thirtyDayRevenue, "firstThirtyDayPrice": firstIndexPrice, "daysRight":daysRight, "daysWrong":daysWrong, "todayDecision": todayDecision} # # client = pubsub.Client.from_service_account_json('/banshee/credentials.json', 'money-maker-1236') # topic = client.topic('hotstocks') # subscription = topic.subscription('hot_shadow_stocks') #should insert while loop around so it continues to pull while there are still items in the queue # get prices and trends snapshot prices = Firebase("https://sv2.firebaseio.com/prices") pricesResults = prices.get() runningProcesses = {} pipeEmpty = False for stock in pricesResults: algorithmsResults = {} print(stock) while True: try: algorithms = Firebase("https://seagle.firebaseio.com/" + stock) algorithmsResults = algorithms.get() break except: print("fetch error") runStockAlgorithms(stock, pricesResults[stock], algorithmsResults )
except: print ("Upload error...trying again!") google_username = "******" google_password = "******" path = "/banshee/" #Currently set for January world_query_terms = {} while True: try: f = Firebase('https://sv2.firebaseIO.com/terms') world_query_terms = f.get() break except: print("Download Error") # connect to Google connector = pyGTrends(google_username, google_password) #WorldWide Trends for query_term in world_query_terms: getReport(query_term, "today 80-d", "world", False) csvfile = open(path + query_term + ".csv", 'r') #computed in advance
import os import sys import math from multiprocessing import Process # get prices and trends snapshot pricesResults = {} while True: try: # get prices and trends snapshot prices = Firebase("https://sv2.firebaseio.com/prices") pricesResults = prices.get() print("Got Prices") break except: print("Download Error") # client = pubsub.Client.from_service_account_json('/banshee/credentials.json', 'money-maker-1236') topic = client.topic('algos') pipelineResults = {} notReady = True itemsNotReady = 0 timesNotReadyWithCount = 0 itemsNeedToReplace = {}
def build_firebase_connection(item): firebase = Firebase('https://roofpik-948d0.firebaseio.com/' + str(item)) data = firebase.get() return data