def make_firebase_entries(user_name): user_payments = json.loads(get_user_payments(user_name)) # print(json.dumps(user_payments)) present = time.strftime('%Y-%m-%d'); perDayMoney = get_per_day_money(user_name); print(perDayMoney) for eachPurchase in user_payments: fb_purchaseID = firebase.get('users/'+user_name+'/donationHistory/' + present, eachPurchase["_id"]) if (fb_purchaseID == None): merchant_for_payment = get_merchant_by_id(eachPurchase["merchant_id"]) amount = eachPurchase['amount'] date = eachPurchase['purchase_date'] pruchaseID = eachPurchase['_id'] existingTotal = firebase.get('/users/'+user_name+'/donationHistory/'+date, 'Total'); if(existingTotal==None): existingTotal = 0.0 if(math.ceil(amount) - amount) <= 0.3: extra_amount = float("{0:.2f}".format(math.ceil(amount)-amount)) customJSON = {'original': amount, 'extra':extra_amount, 'date':date, 'merchant':merchant_for_payment} newTotal = existingTotal+extra_amount newTotal = float("{0:.2f}".format(newTotal)) if(newTotal < perDayMoney): resp = firebase.put('/users/'+user_name+'/donationHistory/'+date, pruchaseID, customJSON); firebase.delete('/users/'+user_name+'/donationHistory/'+date, 'Total') resp2 = firebase.put('/users/'+user_name+'/donationHistory/'+date, 'Total', newTotal);
def foodLog(): global userId logs = firebase.get('/DayFoodLog', None) for day in logs: dayInfo = firebase.get('/DayFoodLog/'+day, None) if dayInfo["UserID"] == userId: print("Date: " + dayInfo["date"] + " Intake: " + dayInfo['CaloricIntake'])
def add(): id = id_generator() route = "/" + id result = firebase.get(route, None) while result != None: id = id_generator() route = "/" + id result = firebase.get(route, None) item = request.form["item"] animal = request.form["animal"] depth = request.form["depth"] recovered = request.form["isRecovered"] material = request.form["material"] lat = request.form["lat"] lon = request.form["lon"] photo = request.form["photo"] print lon print photo route = "/" + id firebase.put(route, "Item", item) firebase.put(route, "Animals", animal) firebase.put(route, "Depth", depth) firebase.put(route, "Recovered", recovered) firebase.put(route, "Material", material) firebase.put(route, "Lat", lat) firebase.put(route, "Lon", lon) firebase.put(route, "Photo", photo) return redirect('/thankyou');
def save_statuses(): while True: timestamp = int(time.time() * 1000) for machine_id, machine in scrape_machines().iteritems(): last = firebase.get(url="/machines/%s/statuses" % machine_id, name=None) # params={"limitToLast": 1} last_array = sorted(last.values(), key=lambda x: x[0]) if last else [] last_timestamp, last_status = last_array[-1] if last else ("", "") status = machine.pop('status') if status == "Out of service": continue if last_status != status: firebase.put(url='/machines/%s/statuses' % machine_id, name=timestamp, data=(timestamp, status), headers={'print': 'pretty'}) firebase.put(url='/machines/%s' % machine_id, name='timestamp', data=timestamp, headers={'print': 'pretty'}) firebase.put(url='/machines/%s' % machine_id, name='status', data=status, headers={'print': 'pretty'}) print machine_id, t.red(last_status), "=>", t.green(status) if status == "Avail": all_avails = [tm for tm,st in last_array[:-1] if st == "Avail" and tm < timestamp] if last else None last_avail_timestamp = all_avails[-1] if all_avails else None last_avail_timestamp_index = last_array.index([last_avail_timestamp, "Avail"]) if last_avail_timestamp else None timestamp_after_last_avail = last_array[last_avail_timestamp_index + 1][0] if last_avail_timestamp_index else None if timestamp_after_last_avail: prev_num_runs = firebase.get(url='/machines/%s' % machine_id, name='num_runs', headers={'print': 'pretty'}) or 0 firebase.put(url='/machines/%s' % machine_id, name='num_runs', data=prev_num_runs+1, headers={'print': 'pretty'}) firebase.post(url='/machines/%s/runs' % machine_id, data=(timestamp_after_last_avail, timestamp), headers={'print': 'pretty'}) print machine_id, "Run Complete:", timestamp_after_last_avail, timestamp print "\nSleeping 10 seconds ...\n"
def putToFirebase(date, soundSensor, vibrationSensor, moveSensor, lightSensor, soundThreshold, vibrationThreshold, moveThreshold, lightThreshold, status, push, pull, number = "+79601825839"): field = \ { "date" : date, "sensor" : { "sound" : soundSensor, "vibration" : vibrationSensor, "move" : moveSensor, "light" : lightSensor }, "threshold" : { "sound" : soundThreshold, "vibration" : vibrationThreshold, "move" : moveThreshold, "light" : lightThreshold }, "status" : status, "number" : number, "notification" : { "pull" : 0, "push" : 0 } } prevDate = firebase.get('','last/date') prevField = firebase.get('','last') firebase.put('',prevDate,prevField) firebase.put('','last',field)
def getFirebaseAsDict(): firebase_url = 'https://cflo-sbd.firebaseio.com' from firebase import firebase firebase = firebase.FirebaseApplication(firebase_url, None) result = firebase.get('/transactions_master', None) result2 = firebase.get('/transactions_compare', None) return [result, result2]
def setDictionary(): dict = {} #print "getting top stories from hacker-news" result = firebase.get('/v0/topstories', None) # result = result[:200] for itemid in result: try: data = firebase.get('/v0/item/' + str(itemid), None) if (data['type'] == 'story'): # get tags url = data['url'] (to_insert, tags) = selectTags(itemid) # store to temp db r.db("tagger_db").table("id2html").insert({"id": itemid, "tag_string": to_insert}).run(connection) if len(tags) > 1: title = data['title'] score = str(data['score']) usr = data['by'] comments = str(data['descendants']) myString = "<tr class='athing'><td align=\"right\" valign=\"top\" class=\"title\"><span class=\"rank\"> </span></td><td><center><a id=\"up_10287983\"><div class=\"votearrow\" title=\"upvote\"></div></a></center></td><td class=\"title\"><span class=\"deadmark\"></span><a href=\"" + url + "\">" + title + "</a>" + to_insert + "</td><td><center><a id=\"up_10287983\"><div class=\"votearrow\" title=\"upvote\"></div></a></center></td></tr><tr><td colspan=\"2\"></td><td class=\"subtext\"><span class=\"score\">" + score + " points</span> by <a>" + usr + "</a> | <a>" + comments +" comments</a></td></tr><tr class=\"spacer\" style=\"height:5px\"></tr>" print "tags: ", tags[0], tags[1] add(tags[0], myString, dict) add(tags[1], myString, dict) except KeyError: pass # r.db("test").table("tag_dict").delete().run(connection) r.db("tagger_db").table("tag2html").insert(dict).run(connection)
def slot (self): self.current_slot = self.comboBox.currentText() self.current_name = firebase.get("/users", "{0}".format(self.current_slot)) self.lineEdit.setText(self.current_name["nome"]) self.lineEdit_2.setText(self.current_name["idade"]) self.lineEdit_7.setText(self.current_name["email"]) self.lineEdit_10.setText(self.current_name["telefone"]) self.lineEdit_6.setText(self.current_name["facebook"]) self.lineEdit_8.setText(self.current_name["snapchat"]) self.lineEdit_9.setText(self.current_name["instagram"]) self.lineEdit_11.setText(self.current_name["adicional"]) self.lineEdit_4.setText(self.current_name["curso"]) self.lineEdit_3.setText(self.current_name["aniversario"]) self.frase = 0 dicientidades = firebase.get("/users/{0}".format(self.current_slot), "/entidade") listadeentidades = [] for v in dicientidades.values(): listadeentidades.append(v) if len(listadeentidades) == 1 : self.lineEdit_5.setText("{0}".format(listadeentidades[0])) elif len(listadeentidades) == 2 : self.lineEdit_5.setText("{0} e {1}".format(listadeentidades[0], listadeentidades[1])) elif len(listadeentidades) == 3: self.lineEdit_5.setText("{0}, {1} e {2}".format(listadeentidades[0], listadeentidades[1], listadeentidades[2])) else: self.lineEdit_5.setText("Nenhuma")
def viewLifts(): global userId lifts = firebase.get('/Lifts', None) for lift in lifts: liftInfo = firebase.get('/Lifts/'+lift, None) if liftInfo["UserID"] == userId: print("Date: " + liftInfo["date"] + " Lift: " + liftInfo['name'] + " Sets: " + liftInfo['sets'] + " Weight: " + liftInfo['weight'])
def demo(): if('logged_in' in session): if(session['logged_in'] == False): return redirect(url_for('login')) else: merchants = firebase.get('/merchants', None) print(merchants) accountID = firebase.get('users/' + session['username'], "accountNumber"); return render_template('demo.html', accountID=accountID, orgBalance=get_balance(capitalOrgID), currBalance=get_balance(accountID), merchants=merchants) return redirect(url_for('login'))
def try_decode(bit_string, roundId): if bit_string in morse_code_lookup.keys(): data = firebase.get('/morse', roundId) s = morse_code_lookup[bit_string] data['input'] = data['input'].encode("utf-8") data['input'] += s firebase.patch('/morse/' + roundId, {'input':data['input']}) data = firebase.get('/morse', roundId) sys.stdout.write(morse_code_lookup[bit_string]) sys.stdout.flush()
def get_per_day_money(user_name): userAmount = float(firebase.get('users/'+user_name, 'amount')) userFrequency = firebase.get('users/'+user_name, 'frequency') if(userFrequency.lower() == 'Monthly'.lower()): timePeriod = 30 elif (userFrequency.lower() == 'Biweekly'.lower()): timePeriod = 14 else: timePeriod = 7 return (userAmount/timePeriod)
def landing(): if('logged_in' in session): if(session['logged_in'] == False): return redirect(url_for('login')) else: freq = firebase.get('users/'+session['username'],'frequency') fullName = firebase.get('users/'+session['username'],'name') amount = firebase.get('users/'+session['username'],'amount') return render_template('landing.html', name=fullName, freq=freq, amount=amount) return redirect(url_for('login'))
def init(firebase): global users global data users = firebase.get("/users", None) data = firebase.get("/data", None) if users is None: users = {} if data is None: data = {} print "Initialization done"
def getItems(items, startID=None, count=None): if items is None and startID is None and count is None: return currentlyDownloading(True) global getItemsCount global itemIDs items = str(items) if count is None: getItemsCount = 30 else: getItemsCount = count if startID is None: itemIDs = firebase.get('/v0/'+items, None) if len(itemIDs) < getItemsCount: getItemsCount = len(itemIDs) else: allIDs = firebase.get('/v0/'+items, None) startIDFound = False for i in allIDs: if i == startID: startIDFound = True continue if startIDFound is False: continue itemIDs.append(i) if len(itemIDs) >= getItemsCount: break if len(itemIDs) == 0: resetDownloader() currentlyDownloading(False) return if len(itemIDs) < getItemsCount: getItemsCount = len(itemIDs) itemID = None i = 0 for itemID in itemIDs: itemID = str(itemID) item = firebase.get_async('/v0/item/'+itemID, None, callback=cbNewItem) i += 1 if i >= getItemsCount: break
def pushPull(): while True: if getPushFromFirebase() == 1: startThreads() if getPullFromFirebase() == 1: thresholds.sound = (firebase.get('','last/threshold/sound')) thresholds.vibration = (firebase.get('','last/threshold/vibration')) thresholds.motion = (firebase.get('','last/threshold/move')) thresholds.light = (firebase.get('','last/threshold/light')) phone.number = (firebase.get('','last/number')) startThreads() time.sleep(15)
def trash_in(): last_person = firebase.get("/last_in", None) next_person_ind = (last_person + 1) % 7 next_person = firebase.get("/users/%s" % next_person_ind, None) name = next_person["name"] phone = next_person["phone"] print "Sending text to %s" % name r = firebase.put("/", "last_in", next_person_ind) message = client.messages.create( body="Time to bring the trash back in, %s!" % name.title(), to="+%s" % phone, from_="+15134492254" )
def main(): url = 'http://data.ntpc.gov.tw/od/data/api/28AB4122-60E1-4065-98E5-ABCCB69AACA6?$format=json' response = requests.get(url) response.encoding = 'UTF-8' items = response.json() # STG firebase.delete(stgTable, None) print('count = ' + str(len(items))) for item in items: addr = item['location'] g = geocoder.google(addr) if g.ok: data = {'lineid': item['lineid'], 'car': item['car'], 'address': addr, 'time': item['time'], 'lat': g.lat, 'lng': g.lng} result = firebase.post(stgTable, data) else: print(g.json) time.sleep(0.5) # Copy to PROD print('Copy to PROD') firebase.delete('/PROD', None) stgResults = firebase.get(stgTable, None) firebase.patch('/PROD', stgResults) print('Done')
def removeAllPostEvents(firebase_url): print 'fetching events from the database ... ' from firebase import firebase firebase = firebase.FirebaseApplication(firebase_url, None) events = firebase.get('/events', None) if events == None: print "There is no events in the database." print "\n" print "\n" print "\n" return print "found", len(events), "events" print "Do you want to remove them all?" num = len(events) print "Are you sure you want to delete all " + str(num) + " events?" yes_or_no = raw_input("Y/N: ") if yes_or_no == "Y": for i in range(num): firebase.delete('/events', events.keys()[i]) print 'deleted', i, 'events' print "DONE" print "\n" print "\n" print "\n"
def calcolaAttesa(numeroServito, ultimoNumeroPrenotato): codaPersone = ultimoNumeroPrenotato - numeroServito jsonRispostaFirebaseTempistiche = firebase.get('TempiAttesa', None) mediaPaziente = jsonRispostaFirebaseTempistiche['mediaPaziente'] tempoAttesa = mediaPaziente * codaPersone print('Hai ', codaPersone, ' persone davanti a te.') print('Il tempo stimato di attesa è di ', tempoAttesa)
def getFromAppleWatch(beacon,user): userPostStr = '/' + beacon + '/' + user result = firebase.get(userPostStr,None) #a=(json.dump(result)) a = result print(a) timeList = [] hrList = [] #print(a.itervalues().next()) for value in a.iteritems(): second=(value[1]) time = str(second.keys()) lenTime = len(time) time = time[3:lenTime-2] time = int(time) timeList.append(time) hr = str(second.values()) hrLen = len(hr) hr = hr[3:hrLen-2] hr = int(hr) hrList.append(hr) elapsedTime = max(timeList) - min(timeList) avghr = np.average(hrList) maxhr = max(hrList) print(elapsedTime) print(maxhr) print(avghr)
def createUser(robot_data, firebase_url): from firebase import firebase firebase = firebase.FirebaseApplication(firebase_url, None) users = firebase.get('/users', None) username_has_been_created = False if users is not None and len(users) > 0: for user in users.values(): if user['username'] == robot_data['username']: username_has_been_created = True break # create a robot user if has not been created yet. if username_has_been_created == False: print "creating robot user:", robot_data['username'] usr_data = { 'age': robot_data['age'], 'gender': robot_data['gender'], 'interest': robot_data['interest'], 'myAttendanceNumber': robot_data['myAttendanceNumber'], 'myPostsNumber': robot_data['myPostsNumber'], 'nickname': robot_data['nickname'], 'password': robot_data['password'], 'username': robot_data['username'], 'usrProfileImage': robot_data['usrProfileImage'], 'whatsup': robot_data['whatsup'] } post_user = firebase.post('/users', usr_data) print post_user return robot_data
def display(): item_choice = request.form["item"] animal_choice = request.form["animal"] depth_choice = request.form["depth"] recovered_choice = request.form["isRecovered"] material_choice = request.form["material"] return_list = [] results = firebase.get('/', None) count = 1 for id in results.keys(): if (filter_recovered(recovered_choice, results[id]["Recovered"]) and filter_material(material_choice, results[id]["Material"]) and filter_animal(animal_choice, results[id]["Animals"]) and results[id]["Item"] == item_choice and filter_depth(depth_choice, results[id]["Depth"])): local_list = [] local_list.append(count) local_list.append(results[id]["Item"]) local_list.append(results[id]["Animals"]) local_list.append(results[id]["Recovered"]) local_list.append(results[id]["Depth"]) local_list.append(results[id]["Lat"]) local_list.append(results[id]["Lon"]) local_list.append(results[id]["Photo"]) return_list.append(local_list) count = count + 1 print len(return_list) if len(return_list) == 0: return render_template("display_entriesFail.html") else: return render_template("display_entries.html", return_list=return_list)
def assign_state_first_chat(chat_id): """ Assign values to the user's current_state and first_chat status. This function should reach out to Firebase and assign current_state and first_chat, basically this is the first step in the long chain of if else statements, different logic based on these two variables. """ current_state = None first_chat = None try: firebase_dict = firebase.get('/users/' + str(chat_id), None) for k, v in firebase_dict.iteritems(): if k == "state": current_state = v elif k == "first_chat": first_chat = v print "THIS IS THE CURRENT STATE" print current_state print "THIS IS THE FIRST_CHAT STATUS" print first_chat except Exception as e: print "FAILURE TO ASSIGN STATE" print current_state print first_chat print str(e) return (current_state, first_chat)
def create_img_payload(chat_id): """ Generate the database entry that will be sent to our MongoDB backend. This function directly communicates with our MongoDB backend so that we can store the photos and statuses for each user. """ firebase_dict = firebase.get('/users/' + str(chat_id), None) for k, v in firebase_dict.iteritems(): key = k value = v if key == "file_id": file_id = value elif key == "weight": weight = value elif key == "feeling": feeling = value elif key == "memo": memo = value elif key == "tags": tags = value payload = { 'file_id': file_id, 'weight': weight, 'feeling': feeling, 'memo': memo, 'tags': tags} return payload
def get_time(): result = firebase.get('/data', None, connection=None, params={'print': 'pretty', 'auth': token, 'orderBy': '"timeOut"', 'limitToLast': '1'}) total_time = result[list(result.keys())[0]]['total'] return total_time
def add_user_to_database(username, data): """ username = the user name of the person data = a dict of all the explicit tweets """ if does_user_exist(username): existing_data = firebase.get('Users/' + username, None) data = merge_two_dicts(data, existing_data) firebase.put('/Users', name=username, data=data)
def fireput(): form = FirePut() global count count += 1 putData = {'Title':form.title.data, 'Year':form.year.data, 'Rating':form.rating.data) firebase.put('/films','film' + str(count),putData) result = firebase.get('/films','film' + str(count)) return '<h3>' + str(result) + '</h3>'
def textoComboBox(self): self.nome_dos_usuarios = [] self.dicionario = firebase.get("/users", None) for usuario in self.dicionario.values(): self.nome_dos_usuarios.append(usuario) print(self.nome_dos_usuarios) return self.nome_dos_usuarios
def firebase1(): result = firebase.get('/articles', None) # print result r = requests.get(r'http://www.reddit.com/user/spilcm/comments/.json') print r print r.text print r.status_code return result
def updateCurrentUser(userId): # Update the local variable storing the user id currentUser = userId # Get the user information from database return firebase.get("/users", userId)
print("temperature is", temp) ##### print("Now let's upload that to Firebase") #Patches on extra data from our temp and humidity variables at the top of the program, simulated sensor readings result = firebase.patch('/sensor/dht/', { 'Temperature': temp, 'Humidity': humid }) sleep(2) print("Give it a moment to upload...") sleep(2) print("Okay Done") print("Now seeing if we can read from the database...") print("The last uploaded temperature was:") result = firebase.get('/sensor/dht/Temperature', None) print(result) print("The last uploaded humidity was:") result = firebase.get('/sensor/dht/Humidity', None) print(result) sleep(3) print("program done") sleep(1000)
from firebase import firebase import sys str = 'TEST/' str2 = '1' int = 1234 int2 = 1 i = 11 firebase = firebase.FirebaseApplication( 'https://professor-shi.firebaseio.com/', None) result = firebase.patch('/USER/' + str, {'num': 2}) result = firebase.get('/USER/' + str, 'Y') result2 = firebase.get('/USER/' + str, 'M') result3 = firebase.get('/USER/' + str, 'D') result4 = firebase.get('/USER/' + str, 'num') result5 = firebase.get('/USER/' + str, 'H') result6 = firebase.get('/USER/' + str, 'Min') print(result) print(result2) print(result3) print(result4) print(result5) print(result6)
from firebase import firebase import time # the generated root for your project FIREBASE_ROOT = 'https://ms-iot.firebaseio.com' # init Firebase Database instance firebase = firebase.FirebaseApplication(FIREBASE_ROOT, None) while True: # execute a GET request on the node result = firebase.get('/sensor', None) # log the result print result # wait 1 second between two consecutive requests time.sleep(1)
def getUser(): rq_id = request.query.id result = firebase.get('/users', rq_id) return result
def get_data(id): return list(firebase.get(str(id),'').values())[-1]
import cv2 import numpy as np from pyzbar import pyzbar from firebase import firebase cap = cv2.VideoCapture(0) img=cv2.imread("big-number.png") firebase = firebase.FirebaseApplication('https://empedded-system-vise-project.firebaseio.com/') result = firebase.get('/users', None) print(result) b = 0 while True: _, frame=cap.read() dobject=pyzbar.decode(frame) cv2.imshow("frame", frame) for barcode in dobject: (x, y, w, h) = barcode.rect cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) barcodeData = barcode.data.decode("utf-8") barcodeType = barcode.type # draw the barcode data and barcode type on the image
def check_database(short_code): return firebase.get(('/shortcodes/' + short_code), None)
def checker(doorCode): firstname="" lastname="" from firebase import firebase #start print("the door code you input is..."+doorCode) firebase = firebase.FirebaseApplication("https://pineappleverification.firebaseio.com/",None) NumOfDoors =firebase.get('/DoorCount/node/cnt','') #firstly i need this program to check if the user has access to the door and is authorised to access the door DoorCount=NumOfDoors dc=int(DoorCount) print(dc) checker=False placeName="" authlevel="" while dc > 0 and checker == False : doorResult=firebase.get('/Doors/'+str(dc),'') doorjson=json.dumps(doorResult, sort_keys=True, indent=4) x=json.loads(doorjson) if x is not None: print(x) print(x["Status"]) if x["DoorName"] == DoorName: if x["Status"]=="active": checker=True placeName=x["placeName"] authlevel=x["AuthLevel"] print("doorFound") else: print("door not active") dc=dc-1 if checker ==True: NumOfAccessRecords =firebase.get('/AccessRequestsCount/node/cnt','') x3=NumOfAccessRecords print(x3) x5= int(x3) doorAccIsFound=False userAuthCode="" while x5>0 and doorAccIsFound == False: doorAccResult=firebase.get('/AccessRequests/'+str(x5),'') doorAccjson=json.dumps(doorAccResult, sort_keys=True, indent=4) doorJson=json.loads(doorAccjson) try: print(doorJson["DoorCode"]) doojint=doorJson["DoorCode"] dji=int(doojint) print (doorCode) if int(doorCode) == dji: doorAccIsFound=True userAuthCode=doorJson["AuthCode"] print("doorCode found") except: print("error") x5=x5-1 if doorAccIsFound==True: NumOfUsers =firebase.get('/UserCount/node/cnt','') x2=NumOfUsers numofu=int(x2) userAccess=False while numofu >0 and userAccess==False: doorUserResult=firebase.get('/Users/'+str(numofu),'') doorUserjson=json.dumps(doorUserResult, sort_keys=True, indent=4) userJson=json.loads(doorUserjson) try: print(userJson["PlaceName"]) print(userJson["AuthLevel"]) print(userJson["AuthCode"]) print(userJson["Status"]) #check auth code then status then auth level and then place name if int(userAuthCode)==int(userJson["AuthCode"]): if userJson["Status"]=="active": if int(userJson["AuthLevel"])==int(authlevel): print("up to here ") if userJson["PlaceName"]== placeName: #this user has access to the db print("access granted") userAccess=True firstname=userJson["FirstName"] lastname=userJson["LastName"] except: print('null') numofu=numofu-1 #i need to firstly check if the door access request exists and is valid #then i need to check if the users account has access to the door GPIO.cleanup() GPIO.setmode(GPIO.BCM) GPIO.setup(6,GPIO.OUT) GPIO.setup(12,GPIO.OUT) print(checker) print(doorAccIsFound) print(userAccess) if checker == True and doorAccIsFound ==True and userAccess==True: #show green led try: NumOfLog =firebase.get('/LogCount/node/cnt','') x3=NumOfLog numofl=int(x3) numofl=numofl+1 print(numofl) data1={ 'cnt':numofl } TodaysDate = date.today() result1=firebase.put('/LogCount','node',data1) data2={ 'DateAndTime':TodaysDate, 'DoorName':DoorName, 'FirstName':firstname, 'LastName':lastname, 'LogDesc':'door opened', 'PlaceName':placeName, } result1=firebase.put('/Logs',str(numofl),data2) except: print("error") print("acess granted") display.lcd_clear() display.lcd_display_string("access granted", 1) GPIO.output(6,1) time.sleep(1) GPIO.output(6,0) openDoor() time.sleep(1) else: display.lcd_clear() display.lcd_display_string("access denied", 1) print("access denied") GPIO.output(12,1) time.sleep(1) GPIO.output(12,0) time.sleep(1) #show red led GPIO.cleanup() time.sleep(1)
from firebase import firebase firebase = firebase.FirebaseApplication('https://aljohri-nuyak.firebaseio.com', None) yaks = firebase.get("/yaks", None) texts = [yak['message'] for message_id, yak in yaks.iteritems()] import random import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD N_CLUSTERS = 3 k_means = KMeans(n_clusters=N_CLUSTERS, init='k-means++', max_iter=100, n_init=1, verbose=True) # vectorizer = TfidfVectorizer(tokenizer=LemmaTokenizer(), max_df=0.5, min_df=0.1) vectorizer = TfidfVectorizer(stop_words='english') # max_df=0.1, min_df=0.1 lsa = TruncatedSVD(2) vectors = vectorizer.fit_transform(texts) X = lsa.fit_transform(vectors) km = k_means.fit(X) k_means_labels = k_means.labels_ k_means_cluster_centers = k_means.cluster_centers_ k_means_labels_unique = np.unique(k_means_labels)
movieRatings = userRecord[userId] movieRatings.append([movieId, rating]) userRecord[userId] = movieRatings userRatings = movieRecord[movieId] userRatings.append([userId, rating]) movieRecord[movieId] = userRatings f.close() userLocations = {} movieLocations = {} for user in users: #userLocations[user] = np.random.normal(loc=lam,scale=sigma,size=(dim,1)) #userLocations[user] = np.random.random(size=(dim,1)) result = firebase.get('/user_location/' + user, None) if result != None: tmp = '' for key in result.keys(): tmp = result[key] scores = [] for t in tmp.split(','): scores.append(float(t)) userLocations[user] = np.array(scores).reshape((dim, 1)) else: userLocations[user] = np.random.random(size=(dim, 1)) print 'no location found, generate a new one' for movie in movies: result = firebase.get('/movie_location/' + movie, None) tmp = ''
from firebase import firebase firebase = firebase.FirebaseApplication('https://villiagesimulator.firebaseio.com', None) #문서 : http://ozgur.github.io/python-firebase/ #첫번째 루틴 villiage1, villiage2 값 같이 받아옴 초깃값 다 0으로 설정 초깃값 바꿀 수 있음 # 전체 값 받아보기 vil1 = firebase.get('/villiage1', None) # 일부 특정 키 에 해당 되는 값 받아오기 #vil1 = firebase.get('/villiage1', 'BuyCost') vil2 = firebase.get('/villiage2', None) print(vil1) print(vil2) # TODO #해당 키에 되는거 값 Update , Post는 하지 마세요 update_vil1 = firebase.patch('/villiage1', {'BuyCost' : 6123}) update_vil2 = firebase.patch('/villiage2', {'NumPeople' : 5, 'Production' : 2}) print(update_vil1) print(update_vil2)
from firebase import firebase url = "https://digital-world-cohort-4.firebaseio.com/" # URL to Firebase database token = "3ZPgzzzMpnbUUIRxf1kyiNsD5T5Zy9FF9UqgBL5a" # unique token used for authentication # Create a firebase object by specifying the URL of the database and its secret token. # The firebase object has functions put and get, that allows user to put data onto # the database and also retrieve data from the database. firebase = firebase.FirebaseApplication(url, token) print("Reading from my database.") print(firebase.get('/age')) # get the value from node age print(firebase.get('/name')) # get the value from node name print( firebase.get('/facts_about_me')) # get the value from node facts_about_me firebase.put('/', 'lazy', True) # put the value True into node lazy firebase.put('/', 'pie', 3.14) # put the value 3.14 into node pie firebase.put('/', 'love_digitalworld', True) firebase.put('/', 'pie', 3.14)
from firebase import firebase import time url = 'https://laundry-pool.firebaseio.com/' # URL to Firebase database token = 'TVEKlcgHcA5QTWOrESZI8aocvLTwUX58BTjhHN1v' # unique token used for authentication # Create a firebase object by specifying the URL of the database and its secret token. # The firebase object has functions put and get, that allows user to put data onto # the database and also retrieve data from the database. firebase = firebase.FirebaseApplication(url, token) print "Reading from my database." print firebase.get('/Name') # get the value from the node age class account(object): def __init__(self, name, contact, balance=0): self.name = name self.info = { "contact": contact, "machineid": None, "time": None, "weight": None } self.balance = balance def withdraw(self, value): if value > self.balance: self.insufficientFunds() return False else:
from firebase import firebase firebase = firebase.FirebaseApplication('https://pyocr-464c8.firebaseio.com/') SECRET_KEY = 'gi2m28GsAeA2FPEdYJpAN4MAeM1qAUMZMlboifeQ' speed = firebase.get("vehicle", "speed") id = firebase.get("vehicle", "id") print(speed) print(id) if (speed >= 3): f = open("file.txt", "a") f.write() f.close()
def get_all_cred(): result = firebase.get('YOUR DATABASE', '') return result
print(start) print(last) path = shortest_path(graph, start, last) length = len(path) firebase = firebase.FirebaseApplication(firebaseURL, None) firebase.put('/', 'step', 0) firebase.put('/', 'step0', -1) firebase.put('/', 'step1', -1) firebase.put('/', 'step2', -1) firebase.put('/', 'step3', -1) firebase.put('/', 'step4', -1) firebase.put('/', 'step5', -2) if (length >= 1): firebase.put('/', 'step0', path[0]) if (length >= 2): firebase.put('/', 'step1', path[1]) if (length >= 3): firebase.put('/', 'step2', path[2]) if (length >= 4): firebase.put('/', 'step3', path[3]) if (length >= 5): firebase.put('/', 'step4', path[4]) if (length >= 6): firebase.put('/', 'step5', path[5]) output = firebase.get('/', None) print(output)
firebase = firebase.FirebaseApplication(url, token) robot = ThymioReal() # create an eBot object no_movements = True while no_movements: # Check the value of movement_list in the database at an interval of 0.5 # seconds. Continue checking as long as the movement_list is not in the # database (ie. it is None). If movement_list is a valid list, the program # exits the while loop and controls the eBot to perform the movements # specified in the movement_list in sequential order. Each movement in the # list lasts exactly 1 second. # Write your code here if firebase.get('/movement_list') != None: if len(firebase.get('/movement_list')) > 0: no_movements = False robot.sleep(0.5) # Write the code to control the eBot here # 'up' movement => robot.wheels(100, 100) # 'left' movement => robot.wheels(-100, 100) # 'right' movement => robot.wheels(100, -100) movement_list = firebase.get('/movement_list') firebase.put('/', 'movement_list', None) for move in movement_list: if move.lower() == "up":
def signal_handler(sig, frame): os.popen('tmux kill-session -t SmartSoundSystem') sys.exit(0) #connecting to the firebase firebase = firebase.FirebaseApplication("https://smart-sound-system.firebaseio.com/", None) #open spotify os.popen('tmux new-session -s SmartSoundSystem -d -n spotify tizonia --spotify-playlist "New"') signal.signal(signal.SIGINT, signal_handler) on = 1 volume = 100 balance = 'left' while 1: result = firebase.get('/Instructions', '') if result != None: #processing all available Instructions for key, inst in result.items(): #for each command firebase.delete('/Instructions', key) print(inst) if inst == 'ONOFF': if on == 1: os.popen('tmux kill-session -t SmartSoundSystem') on=0 else: os.popen('tmux new-session -s SmartSoundSystem -d -n spotify tizonia --spotify-playlist "New"') on=1 elif inst == 'NEXT': #send n os.popen('tmux send-keys -t spotify "n^M"')
from kivy.app import App from kivy.uix.boxlayout import BoxLayout from firebase import firebase firebase = firebase.FirebaseApplication('https://xyzq-3712f.firebaseio.com', None) result = firebase.get('/s', None) print(result) temperature = 77 humidity = 10 import time class SigninWindow(BoxLayout): def __init__(self, **kwargs): #super().__init__(**kwargs) super(SigninWindow, self).__init__(**kwargs) def validate_user(self): date1 = self.ids.date_field1 time1 = self.ids.time_field1 med1 = self.ids.med_field1 date2 = self.ids.date_field2 time2 = self.ids.time_field2 med2 = self.ids.med_field2 date3 = self.ids.date_field3 time3 = self.ids.time_field3 med3 = self.ids.med_field3 info = self.ids.info
def read_from_fb(): result = firebase.get('/python-sample-ed7f7/', '') print "reading data to database" print(result) return jsonify(result)
from scipy import stats from firebase import firebase from datetime import datetime from threading import Timer import time url = "https://iot-dw-1d-2017.firebaseio.com/" # URL to Firebase database token = "0lYSxo2k1Jrr3i3rxhyb3IFy3kTKEAsXP39n3mpV" # unique token used for authentication # Create a firebase object by specifying the URL of the database and its secret token. # The firebase object has functions put and get, that allows user to put data onto # the database and also retrieve data from the database. firebase = firebase.FirebaseApplication(url, token) print "Reading from my database." infrared = firebase.get('/Infrared') # get the value from the node age methane = firebase.get('/Methane') ultrasound = firebase.get('Ultrasound') if infrared == '': infrared = 0 if methane == '': methane = 0 if ultrasound == '': ultrasound = 0 class LinearRegression(linear_model.LinearRegression): """ LinearRegression class after sklearn's, but calculate t-statistics and p-values for model coefficients (betas). Additional attributes available after .fit()
# Draw a label with a name below the face cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) # Display the resulting image cv2.imshow('Video', frame) # Save Woorksheet as present month # book.save(str(month)+'.xlsx') # Integrate with firebase if (firebase.get('/Harsh', 'IIT2018049') == 'False'): if face_names[0] == 'Harsh': result = firebase.patch('/Harsh', {'IIT2018049': 'True'}) elif (firebase.get('/Mrigyen', 'IIT2018033') == 'False'): if face_names[0] == 'Mrigyen': result = firebase.patch('/Mrigyen', {'IIT2018033': 'True'}) elif (firebase.get('/Soumyadeep', 'IIT2018001') == 'False'): if face_names[0] == 'Soumyadeep': result = firebase.patch('/Soumyadeep', {'IIT2018001': 'True'}) elif (firebase.get('/Shreyansh', 'IIT2018073') == 'False'): if face_names[0] == 'Shreyansh': result = firebase.patch('/Shreyansh', {'IIT2018073': 'True'}) elif (firebase.get('/Bindu', 'IIT2018105') == 'False'): if face_names[0] == 'Bindu': result = firebase.patch('/Bindu', {'IIT2018105': 'True'})
print rcv time.sleep(0.4) port.write('AT+CMGF=1'+'\r') # Select Message format as Text mode rcv = port.read(10) print rcv time.sleep(0.4) port.write('AT+CNMI=2,1,0,0,0'+'\r') # New SMS Message Indications rcv = port.read(10) print rcv time.sleep(0.4) gsm_init() balance1 = firebase.get('/balance1',None) reading1 = firebase.get('/reading1',None) def firebse_update(): global balance1, reading1 #balance3, reading1, reading2, reading3 firebase.put('','balance1',balance1) firebase.put('','reading1',reading1) firebase.put('','balance2',balance1+100) firebase.put('','reading2',reading1+20) firebase.put('','balance3',balance1+200) firebase.put('','reading3',reading1+40) def port_read(): global gsm gsm= port.readline()
from flask import Flask, request, render_template, jsonify from firebase import firebase firebase = firebase.FirebaseApplication("https://fundflow-team3.firebaseio.com/", None) result = firebase.get("/fundflow-team3/Users", '') def user_info(): return result def get_user_list(): user_list = [] for key in result: user_list.append(key["username"]) return user_list def get_email_list(): email_list = [] for key in result: email_list.append(key["email"]) return email_list # Can change the route name @app.route('/backend/create_account', methods=['GET', 'POST']) def create_account(): # Assuming the method is post # This gets the data sent over from an ajax call (if that's what's being used) data = request.get_json() user_list = get_user_list()
import json from pyfcm import FCMNotification from firebase import firebase firebase = firebase.FirebaseApplication('https://healthhacks2017-ec6bf.firebaseio.com/', None) result = firebase.get('/Clinic', None) #print (json.dumps(result, indent=2)) _, d = result.items()[-1] room_num, values = d.items()[-1] if values["temperature"] < 97.4 or values["temperature"] > 99.6: print("Temperature: " + str(values["temperature"])) push_service = FCMNotification(api_key="AAAA_RINJFk:APA91bF4wqCoC-rvQ01XXedftgncrjw2RaqbQL9iWIwBhNr948KjQ02flNn5Gud49eOfnuGgQcNR2rH6XnhD1EllE-GpWnT-7DicLVoq2b0xynCFZwVBE0m7IP0I4ItaBlntZL70kUsI") registration_id = "crWV01AoxHk:APA91bGftkZ70ZPZqaL7yK_lkYMWPHGhSPrZOc9kwvlMSDUk7f4BQ4UV4gRTE7o2fhdaTafgQ745RdcGZpx_djC7GDq9M6MHgQg_Hhx6op4Bq5Ar5wtooblrgj2h6AuZ15xw5GNXacfn" message_title = "Patient in CRITICAL CONDITION" message_body = "Patient 1 has an EXTREME Temperature" rest = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) if values["SpO2"] > 0.94: print("SpO2: " + str(values["SpO2"])) push_service = FCMNotification(api_key="AAAA_RINJFk:APA91bF4wqCoC-rvQ01XXedftgncrjw2RaqbQL9iWIwBhNr948KjQ02flNn5Gud49eOfnuGgQcNR2rH6XnhD1EllE-GpWnT-7DicLVoq2b0xynCFZwVBE0m7IP0I4ItaBlntZL70kUsI") registration_id = "crWV01AoxHk:APA91bGftkZ70ZPZqaL7yK_lkYMWPHGhSPrZOc9kwvlMSDUk7f4BQ4UV4gRTE7o2fhdaTafgQ745RdcGZpx_djC7GDq9M6MHgQg_Hhx6op4Bq5Ar5wtooblrgj2h6AuZ15xw5GNXacfn" message_title = "Patient 1 in CRITICAL CONDITION" message_body = "Patient 1 has high SpO2 levels" rest1 = push_service.notify_single_device(registration_id=registration_id, message_title=message_title, message_body=message_body) if 0 == values["age"] and 120 > values["HR"] < 160 or 50 <values["systolic BP"]>70: print("SpO2: " + str(values["SpO2"])) push_service = FCMNotification(api_key="AAAA_RINJFk:APA91bF4wqCoC-rvQ01XXedftgncrjw2RaqbQL9iWIwBhNr948KjQ02flNn5Gud49eOfnuGgQcNR2rH6XnhD1EllE-GpWnT-7DicLVoq2b0xynCFZwVBE0m7IP0I4ItaBlntZL70kUsI") registration_id = "crWV01AoxHk:APA91bGftkZ70ZPZqaL7yK_lkYMWPHGhSPrZOc9kwvlMSDUk7f4BQ4UV4gRTE7o2fhdaTafgQ745RdcGZpx_djC7GDq9M6MHgQg_Hhx6op4Bq5Ar5wtooblrgj2h6AuZ15xw5GNXacfn" message_title = "Patient 1 in CRITICAL CONDITION"
from firebase import firebase import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) GPIO.setup(19, GPIO.OUT) GPIO.setup(20, GPIO.OUT) GPIO.setwarnings(False) firebase = firebase.FirebaseApplication( 'https://automation-47434.firebaseio.com/') while (1): light1 = firebase.get('/Switch1', None) print(light1) light2 = firebase.get('/Switch2', None) print(light2) light3 = firebase.get('/Switch3', None) print(light3) if (light1 == "0"): GPIO.output(18, GPIO.LOW) else: GPIO.output(18, GPIO.HIGH) if (light2 == "0"):
df_PICP = pd.DataFrame() df_MPIW = pd.DataFrame() df_NPIW = pd.DataFrame() df_CWC = pd.DataFrame() df_avg_pinball = pd.DataFrame() model = 2 spike_price = 1 for method in list_method: print(method) list_PICP, list_MPIW, list_NPIW, list_CWC, list_avg_pinball = [], [], [], [], [] for task in list_task: if spike_price == 1: result = firebase.get( '/GEFcom2014_spike/{}/results/model-{}'.format(task, model), '{}'.format(method)) else: result = firebase.get( '/GEFcom2014/{}/results/model-{}'.format(task, model), '{}'.format(method)) list_PICP.append(result['PICP']) list_MPIW.append(result['MPIW']) list_NPIW.append(result['NPIW']) list_CWC.append(result['CWC']) list_avg_pinball.append(result['avg_pinball']) df_PICP['{}'.format(method)] = list_PICP df_MPIW['{}'.format(method)] = list_MPIW df_NPIW['{}'.format(method)] = list_NPIW df_CWC['{}'.format(method)] = list_CWC
def last_val(last_date): result = firebase.get('/Sensor/{}'.format(last_date), '') print(result) return result[-1]
def last_date(): result = firebase.get('/Sensor', '') for i in result: last_date = i return last_date