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 voice(): firebase.put("/", request.form['CallSid'], data={'To': request.form['To'], 'From': request.form['From'], 'StatusCallbackEvent': 'call-created'}) response = twiml.Response() dial = response.dial() dial.conference("SignalWarmTransfer", statusCallbackEvent="start end join leave mute hold", statusCallback="/callback",) return str(response)
def add_user(): if (request.method == "POST"): user_username = request.form['inputUserName'] user_name = request.form['inputFullName'] user_email = request.form['inputEmail'] user_password = request.form['inputPassword'] user_type= request.form['inputType'] user_accountNumber = request.form['inputAccountNumber'] if(user_type == "organization"): user_frequency = "N/A"; user_amount = "-1"; else: user_frequency = request.form['inputFrequency'] user_amount = request.form['inputAmount'] # validate the received values if not (user_username and user_name and user_email and user_password and user_type): # check username uniqueness return render_template('register.html') else: post = {'username':user_username, 'name': user_name, 'password':generate_password_hash(user_password) , 'email':user_email, 'type': user_type, 'accountNumber' : user_accountNumber, 'frequency' : user_frequency, 'amount' : user_amount} firebase.put('/users', user_username, post) session['logged_in'] = True; session['username'] = user_username; session['cust_id'] = user_accountNumber; return redirect(url_for('landing')) # return json.dumps({'status':'OK', 'redirect':url_for('main')}) return "end of func";
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 handle_push(status_string): print 'handle push' timestamp = datetime.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S') r1 = str(randint(100,999)) r2 = str(randint(100,999)) gps_payload = '63 25.' + r1 + 'N 10 23.' + r2 + 'E' firebase.put('/mobile_alarm_payload', 'unit_216', {'status':status_string, 'gps':gps_payload}) print 'payload sent'
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 update_sleep(hours_sleep): avg_hours_sleep = get_sleep() num_users = get_num_users() new_hours_sleep = (hours_sleep + avg_hours_sleep * num_users) / (num_users + 1) firebase.put('/', 'num_users', num_users + 1) firebase.put('/', 'hours_sleep', new_hours_sleep)
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 lock(self): lock = self.getCurrentLock() if lock == None: self.game = firebase.get('/', self.gameID) firebase.put('/'+self.gameID+'/', 'lock', self.player) self.isLocked = True # TODO add consistency check, make sure previous game state is consistent with current return True raise Exception('Could not lock - in use by:' + lock)
def buscar_pedido(self): x = firebase.get(url='/',name='') for i in x.keys(): for j in x[i].keys(): for k in x[i][j]: if k != 'produto': if x[i][j][k][1] == '': self.criar_botao(x[i][j][k][2]+'\n'+i+'\n'+j,i,j,k) firebase.put(url='/'+i+'/'+j+'/'+k,name=1,data='a fazer')
def flush(self): if not self.isLocked: #check local lock raise Exception('Must be locked first') lock = self.getCurrentLock() # check that no one else has inadvertently locked it after us if lock == self.player: firebase.put('/', self.gameID, self.game) firebase.put('/'+self.gameID+'/', 'lock', None) self.isLocked = False else: raise Exception('Not locked to current player - in use by:' + lock)
def __init__(self, gameID, playerName): game = firebase.get('/', gameID) if game == None: game = {} game['Actions'] = [] game['Players'] = [playerName] firebase.put('/', gameID, game) self.game = game self.gameID = gameID self.player = playerName self.isLocked = False
def start(): #servers = ['athena.ecs.csus.edu','atoz.ecs.csus.edu','sp1.ecs.csus.edu','sp2.ecs.csus.edu','hydra.ecs.csus.edu','gaia.ecs.csus.edu'] #servers = ['athena.ecs.csus.edu','atoz.ecs.csus.edu','sp1.ecs.csus.edu','sp2.ecs.csus.edu'] servers = ['athena.ecs.csus.edu'] out_list = [] for server in servers: out_string = pull(server) out_list.append(out_string) firebase.put(out_string) return str(out_list)
def buscar_e_colocar_codigo_FB(self, string, hora, status, n_pedido): for i in codigos.lista_codigos: if i == string: z = codigos.menu_codigos[string] x = z.keys() for e in x: x = e y = z.values() for e in y: y = e pedido_ = [hora, status, x, y] firebase.put(url = 'mesa{0}/cadeira{1}'.format(self.mesa, self.cadeira), name = 'pedido numero {0}'.format(n_pedido), data = pedido_)
def fireput(): #if request.method == "POST": form=FirePut() if request.method == 'POST': print ("i was here") #if form.validate_on_submit(): global count count += 1 putData = {"Name" : form.name.data, "phonenumber" : form.phonenumber.data, "product" : form.product.data,"email":form.email.data} firebase.put("/", "" + str(count), putData) return render_template("file.html", form=form, putData=putData) print (form.name.data) return render_template('users.html',form=form)
def recordQonUser(sessionID, tweetID): tweetIDs = firebase.get('/users', sessionID) print tweetIDs if tweetIDs != None: tweetIDs['TweetID'].append(tweetID) print tweetIDs tweetIDsUP = tweetIDs['TweetID'] result = firebase.put('/users', sessionID, {'TweetID': tweetIDsUP}) print result else: tweetIDsUP.append(tweetID) result = firebase.put('/users', sessionID, {'TweetID': tweetIDs}) print result
def save_phone(): if request.method == 'POST': phone = request.form['phone_number'] user_info = request.form['user'] # user = firebase.get('/users', user_info) firebase.put('/users/%s' %(user_info), 'phone', phone) return redirect(url_for('checkin')) return 'newurl'
def main(): gpio.setup(SW1, gpio.IN) gpio.setup(SW2, gpio.IN) gpio.setup(SW3, gpio.IN) while True: valueSW1 = gpio.read(SW1) valueSW2 = gpio.read(SW2) valueSW3 = gpio.read(SW3) if valueSW1 == 0: firebase.put('/' , "house1", {u'addr': addrSW1, u'id': idSW1, u'visible': "True", u'lat': latSW1, u'lng': lonSW1}) else: pass if valueSW2 == 0: firebase.put('/' , "house2", {u'addr': addrSW2, u'id': idSW2, u'visible': "True", u'lat': latSW2, u'lng': lonSW2}) else: pass if valueSW3 == 0: firebase.put('/' , "house1", {u'addr': addrSW1, u'id': idSW1, u'visible': "False", u'lat': latSW1, u'lng': lonSW1}) firebase.put('/' , "house2", {u'addr': addrSW2, u'id': idSW2, u'visible': "False", u'lat': latSW2, u'lng': lonSW2}) else: pass
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 main(): GPIO.setup(sens1, GPIO.IN) GPIO.setup(sens1off, GPIO.IN) #GPIO.setup(sens2, GPIO.IN) #GPIO.setup(sens2off, GPIO.IN) while True: if GPIO.input(sens1): #pass firebase.put('/' , "house2", {u'addr': addrHouse2, u'id': idHouse2, u'visible': "False", u'lat': latHouse2, u'lng': lonHouse2}) else: #pass firebase.put('/' , "house2", {u'addr': addrHouse2, u'id': idHouse2, u'visible': "True", u'lat': latHouse2, u'lng': lonHouse2})
def do_upload(self, quiz_source_path): """ DESCRIPTION: Upload quiz to online Firebase database USAGE: Command: upload <quiz source path> """ quiz_full_path = quiz_source_path + ".json" quiz_name = os.path.basename(quiz_source_path) quiz_name_to_post = str(quiz_name) #If file exists, upload if os.path.isfile(quiz_full_path) == True: print "File existence confirmed".center(74, "-") #Space for readability print " " # Write the contents to json file with open(quiz_full_path, 'r') as json_file: try: # Use json.load to move contents quiz = json.load(json_file) print "Uploading Quiz {}".format(quiz_name).center(74,"-") for n in tqdm(range(10)): time.sleep(0.5) # Call a put request and save to the firebase database firebase.put("/Quiz/",quiz_name, quiz) print "\nQuiz successfully uploaded!\n".center(74,"-") print " " except: print "Upload failed! Please type upload<quiz_name> to try again.\n".center(74,"-") print "Type help<uploadquiz> for help." else: print "Quiz does not exist at source.".center(74,"-")
def upload_notes(self): """ Gets current data on DB and uploads to FireBase """ rows = self.cursor.execute("SELECT * FROM notes ") objects_list = [] for row in rows: d = collections.OrderedDict() d['id'] = row[0] d['created_at'] = row[1] d['entry'] = row[2] objects_list.append(d) firebase.put('/Notes','note', objects_list)
def to_play(self): print ("at to_play") play_ind = firebase.get(endpoint+index, None) count = 0 for file in os.listdir(self.video_path): if file.endswith('.avi'): count = count + 1 if count == play_ind: print ('toPlay2: ' + file) self.play_video(os.path.join(self.video_path,file)) # set toPlay to false firebase.put('https://hackalexa.firebaseio.com'+endpoint, toPlay, False) break
def zerar_firebase(self): mesa1={} mesa1['cadeira1']={'produto':[1,2,'produto',0]} mesa1['cadeira2']={'produto':[1,2,'produto',0]} mesa1['cadeira3']={'produto':[1,2,'produto',0]} mesa1['cadeira4']={'produto':[1,2,'produto',0]} mesa2={} mesa2['cadeira1']={'produto':[1,2,'produto',0]} mesa2['cadeira2']={'produto':[1,2,'produto',0]} mesa2['cadeira3']={'produto':[1,2,'produto',0]} mesa2['cadeira4']={'produto':[1,2,'produto',0]} mesa2['cadeira5']={'produto':[1,2,'produto',0]} mesa2['cadeira6']={'produto':[1,2,'produto',0]} if mesa.nMesa<7: firebase.put(url='/', name='mesa{0}'.format(mesa.nMesa),data=mesa1) else: firebase.put(url='/', name='mesa{0}'.format(mesa.nMesa),data=mesa2)
def get_scrum_master(): #Get studnet count from firebase n_alunos = int(firebase.get("/alunos","n_alunos")) #Get student at random index in firebase idx = random.randint(1, n_alunos) aluno = firebase.get("/alunos","/alunos{0}".format(idx)) #If student wasn't Scrum Master before, return student and update his/her status if aluno["wasSM"] == "False": scrum_master = aluno["name"] firebase.put("/alunos/alunos{0}".format(idx), name="wasSM", data="True") firebase.put("/alunos", name="n_alunos", data=str(n_alunos-1)) return scrum_master #Else, try again else: get_scrum_master()
def timed_job(): yakker.update_location(locations['tech']) yaks = yakker.get_yaks() print "Found %d yaks" % len(yaks) for yak in yaks: yak.message_id = yak.message_id.replace("R/", "") if firebase.get('/yaks', yak.message_id): break result = firebase.put(url='/yaks', name=yak.message_id, data=yak_to_dict(yak), headers={'print': 'pretty'}) print yak.time, yak.message_id, yak.message print "Sleep 10 seconds..."
def addTweetToDB(hashtag, tweetID): tweetIDs = firebase.get('/', hashtag) print tweetIDs if tweetIDs != None: tweetIDs['TweetID'].append(tweetID) print tweetIDs tweetIDsUP = tweetIDs['TweetID'] found = False for x in range(0,len(tweetIDs)): if tweetID == tweetIDs[x]: found = True if found == False: result = firebase.put('/', hashtag, {'TweetID': tweetIDsUP}) #print result else: tweetIDsUP.append(tweetID) result = firebase.put('/', hashtag, {'TweetID': tweetIDs}) print result
def send_to_firebase(tank, distance): global firebase_log timestamp = int(time.time()) last_sent_timestamp = firebase_log[tank].get('timestamp', 0) last_sent_distance = firebase_log[tank].get('distance', 0) logging.debug([timestamp, tank, distance]) change_in_distance = abs(distance - last_sent_distance) if (last_sent_distance != 0 and change_in_distance > 15): logging.debug('^ rejected'); return if ((timestamp - last_sent_timestamp) >= TIME_INTERVAL_TO_NOTIFY) or (change_in_distance >= DISTANCE_CHANGE_TO_NOTIFY): datetime_str = datetime.datetime.now().isoformat() firebase_log[tank]['timestamp'] = timestamp firebase_log[tank]['distance'] = distance data = {'time': datetime_str, 'timestamp': timestamp, 'distance': distance} firebase.put('/readings/' + tank + '/', timestamp, data)
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 update_sentiment(pos, neg, neu): pos = pos + get_positive() neg = neg + get_negative() neu = neu + get_neutral() firebase.put('/', 'positive', pos) firebase.put('/', 'negative', neg) firebase.put('/', 'neutral', neu)
def postHeavyVehicleFuelEcon(mk, yr, mo, fI): result = firebase.put('/HeavyVehicles/FuelEcon/'+mo+"/"+yr, name="Make",data=mk) result = firebase.put('/HeavyVehicles/FuelEcon/'+mo+"/"+yr, name="Model",data=mo) result = firebase.put('/HeavyVehicles/FuelEcon/'+mo+"/"+yr, name="FuelEcon",data=fI) print(yr+" "+mo+" "+mk+" Truck FuelEcon Data Posted")
def tcpSend(url): print("\nSending tcp url to firebase database") result = firebase.put('/url', name, {"url": "{}".format(url)}) return 'send done.. {}'.format(result)
def postCarFuelEcon(mk, yr, mo, fI): result = firebase.put('/Cars/FuelEcon/'+str(mo)+"/"+str(yr), name="Make",data=mk) result = firebase.put('/Cars/FuelEcon/'+str(mo)+"/"+str(yr), name="Model",data=mo) result = firebase.put('/Cars/FuelEcon/'+str(mo)+"/"+str(yr), name="FuelEcon",data=fI) print(yr+" "+mo+" "+mk+" Car FuelEcon Data Posted ")
def callback(message): attributes = message.attributes event_type = attributes['eventType'] bucket_id = attributes['bucketId'] object_id = attributes['objectId'] if event_type == 'OBJECT_DELETE': print('\n ######################## ' + object_id + ' DELETED FROM STORAGE ########################') # print('\ninside function: receive_messages\n') # print('Received message: {}'.format(message)) # print('MATT Received message: {}'.format(message.data)) if event_type == 'OBJECT_FINALIZE': print('\n ######################## ' + object_id + ' UPLOADED TO STORAGE ########################') data = message.data msg_data = json.loads(data) mediaLink = msg_data["mediaLink"] print('\nreceived file: ', mediaLink) print('bucket_id', bucket_id) print('object_id', object_id) if '.3gp' in object_id or '.aac' in object_id or '.adts' in object_id or '.mp3' in object_id or '.mp4' in object_id: # os.system('rm -f *.mid') # os.system('rm -f *.aac') print('downloading object...') file = ' gs://' + bucket_id + '/' + object_id download = 'gsutil cp ' + file + ' .' os.system(download) # file has been downloaded to vitrual agent # now get metadata of the file # print('getting metadata...') # getmetadata = 'gsutil ls -L ' + file # os.system(getmetadata) # now get hash of the file # gethash = 'gsutil hash -m ' + file # # os.system(gethash) # md5Hash = os.popen(gethash).read()[75:99] # midi_filename = md5Hash + '.mid' # "major-scale.mid" #### HERE IS WHERE ALGORITHM GOES ##### print 'object_id', object_id audioFile = importaudio.processAudio(object_id) # audioFile.printFileName() # audioFile.playaudio() # create midi file audio_filename = object_id[0:19] midi_filename = audio_filename + '.mid' makemidi.create_midi(midi_filename) ####################################### # On completion, remove input audio file from storage... # remove = 'gsutil rm gs://' + bucket_id + '/' + object_id # os.system(remove) print('\nuploading midi...') set_midi_metadata = 'gsutil setmeta -h x-goog-meta-userID:MATTHEW' + \ ' gs://' + bucket_id + '/' + midi_filename upload_midi = 'gsutil cp ' + midi_filename + ' gs://' + bucket_id os.system(upload_midi) # os.system(set_midi_metadata) print('updating database') result = firebase.get(audio_filename, 'mididownload') resultPut = firebase.put(audio_filename, 'midifile', midi_filename) print('result = ', result) print('resultPut = ', resultPut) message.ack() # time.sleep(2) print('\ncleaning out files:') # , midi_filename, ' and ', object_id os.system('rm -f *.mid') # , midi_filename) os.system('rm -f *.aac') # , object_id) os.system('rm -f *.mp4') # , object_id) # time.sleep(7) print('\n\nDONE')
def updateLike(id): checklike = firebase.get('/drawingInfo', id) currentLikes = checklike["Likes"] newLikes = int(currentLikes) + 1 likePush = firebase.put('/drawingInfo' + '/' + id, 'Likes', int(newLikes))
def postCarModel(mk, mo): result = firebase.put('/Cars/Models/'+mo, name="Make" , data=mk) print(mk+" "+mo+" Car model posted")
def postMotorcycleModel(mk, mo): result = firebase.put('/Motorcycles/Models/'+mo, name="Make" , data=mk) print(mk+" "+mo+" Motorcycle model posted")
# Input tensor is the image image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, classes, and num objects detected detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') ''' Finish building tensorflow ''' # This gets the weightOffSet weightOffSet = firebase.get('Pi/loadCell/', None) if weightOffSet == -1: weightOffSet = 0 try: data = firebase.put('Pi/', 'loadCell', weightOffSet) except: print("Error update load cell data") # Initialize frame rate calculation frame_rate_calc = 1 freq = cv2.getTickFrequency() font = cv2.FONT_HERSHEY_SIMPLEX # Initialize Picamera and grab reference to the raw capture camera = PiCamera() camera.resolution = (IM_WIDTH, IM_HEIGHT) camera.framerate = 100 rawCapture = PiRGBArray(camera, size=(IM_WIDTH, IM_HEIGHT)) rawCapture.truncate(0)
def stopListen(): GPIO.cleanup() firebase.put('PowerButton/Machine/', 'power', 0) # Post to firebase? return
caridscrossed = [] # blank list to add car ids that have crossed totalcars = 0 # keeps track of total cars fgbg = cv2.createBackgroundSubtractorMOG2() # create background subtractor # information to start saving a video file ret, frame = cap.read() # import image ratio = .5 # resize ratio image = cv2.resize(frame, (0, 0), None, ratio, ratio) # resize image width2, height2, channels = image.shape video = cv2.VideoWriter('traffic_counter.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), fps, (height2, width2), 1) pev_in = 0 pev_out = 0 firebase.put('/user', 'all', 0) firebase.put('/user', 'in', 0) firebase.put('/user', 'out', 0) while True: ret, frame = cap.read() # import image if ret: # if there is a frame continue with code image = cv2.resize(frame, (0, 0), None, ratio, ratio) # resize image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # converts image to gray fgmask = fgbg.apply(gray) # uses the background subtraction
firsttime = True path_on_cloud = "images/" def get_imgs(): images = os.listdir(img_dir) return images if __name__ == "__main__": images_old = get_imgs() for image in images_old: storage.child(path_on_cloud+image).put(img_dir+image) while True: images_new = get_imgs() if images_old != images_new or firsttime: firsttime = False (x, y) = green_pixels.calc_green_pixels(img_dir) for (x, y) in [("img", image[0]), ("x", x), ("y", y)]: result = firebase.put("/igrow-ac1d6-default-rtdb/growth_mon/"+name, x, y) print("new images received, uploading") for image in images_old: storage.delete(path_on_cloud+image) for image in images_new: storage.child(path_on_cloud+image).put(img_dir+image) images_old = images_new else: print("same old images ", images_old) sleep(5)
if isFire: cv2.putText(image, "Fire detected!", (10, 230), font, 0.5, (0, 0, 255), 1) cv2.imshow("Fire detector", image) key = cv2.waitKey(1) & 0xFF rawCapture.truncate(0) if key == ord("q"): break wasFire = isFire isFire = firecount > threshold if isFire: start = time.time() GPIO.output(11, True) time.sleep(0.001) GPIO.output(11, False) time.sleep(0.001) if start == None: continue LED_alert(start) if wasFire != isFire: firebase.put('fire-state', 'isFire', isFire) cv2.destroyAllWindows() GPIO.cleanup()
rest=0 exer=0 c1=0 c2=0 if(age>=18 and age<=35): while(c1<5): mydata=int(ardData.readline().strip()) if(mydata>=49 and mydata<=82): print(mydata) rest+=mydata c1=c1+1 rest=rest/5 print("RESTING HEART RATE") print(rest) firebase.put('','value',rest) elif(age>=36 and age<=55): while(c1<5): mydata=int(ardData.readline().strip()) if(mydata>=50 and mydata<=84): print(mydata) rest+=mydata c1=c1+1 rest=rest/5 print("RESTING HEART RATE") print(rest) firebase.put('','value',rest) elif(age>=56 and age<=70): while(c1<5): mydata=int(ardData.readline().strip()) if(mydata>=51 and mydata<=82):
result = firebase.get('/dht', None) print(result) #you can also read along the tree further down /dht/humidity result = firebase.get('/dht/humidity', None) print(result) #CHANGING/ADDING/REMOVING DATA #deletes code from the database firebase.delete('/dht', None) #Patches on extra data from our temp and humidity variables at the top of the program, simulated sensor readings result = firebase.patch('/sensor/dht/', { 'First_Vals': temperature, 'Sec_Vals': humidity }) #Patches on extra data, you can also hard code in numbers like below result = firebase.patch('/sensor/dht2/', {'First_Vals': 4, 'Sec_Vals': 2}) #Best to use PATCH instead of PUT or POST as it avoids generating a large random number for the node name #write to the database (PUT means update current values) firebase.put("/dht", "/humidity", "0.00") firebase.put("/dht", "/humidity", "1.00") #POSTS to the database (POST means create an entry, does generate a nasty long node name) data = {"temp": temperature, "humidity": humidity} firebase.post('/dht', data)
def postAtvUtvFuelEcon(mk, yr, mo, fI): result = firebase.put('/Atvs/FuelEcon/'+mo+"/"+yr, name="Make",data=mk) result = firebase.put('/Atvs/FuelEcon/'+mo+"/"+yr, name="Model",data=mo) result = firebase.put('/Atvs/FuelEcon/'+mo+"/"+yr, name="FuelEcon",data=fI) print(yr+" "+mo+" "+mk+" Atv FuelEcon Data Posted "+fI)
ir1 = GPIO.input(11) ir2 = GPIO.input(13) ir3 = GPIO.input(15) ir4 = GPIO.input(31) if c1 < total_slot: print("Conditon1") print(ir1) if ir1 == 0 and f1 == 0: print("Conditon R1") GPIO.output(35, True) countcar = in1 + 1 #lcd_text(slotl,LCD_LINE_1) #lcd_text("Wait...",LCD_LINE_2) carno = "/carparking/" + "car" + str(countcar) firebase.put(carno, 'detect', 'yes') photoupload = firebase.get(carno, '') if (photoupload['photoupload'] == 'yes'): #opencv #lcd_text(slotl,LCD_LINE_1) #lcd_text("Veri",LCD_LINE_2) opencvfunction(carno, countcar) #lcd_text(slotl,LCD_LINE_1) #lcd_text("Done",LCD_LINE_2) q.ChangeDutyCycle(10) time.sleep(0.5) GPIO.output(35, False) GPIO.output(33, True) f1 = 1
def postCarMake(mk): result = firebase.put('/Cars/Makes/', name=mk,data=mk) print(mk+" Car Make Posted")
def echo(client, message): actvt = "" actvt = firebase.get('/stats', 'total_searches') data = {"total_searches": 1} if not actvt: firebase.put('/stats', 'total_searches', data) global pq pq = "" pro = client.send_message(chat_id=message.chat.id, text="Searching...", reply_to_message_id=message.message_id) r_num = message.text num = r_num.replace("+91", "").replace(" ", "") frbseyename = "" frbsefb = "" frbsetrname = "" frbsetrmail = "" if num.isnumeric and len(num) == 5: pq = "\n\n**----••Truecallerprobot says----**\n\nLimit exceeded ,try again tomorrow 🤦🏻♂️----\n\nJoin @ptmlootoffers for get more find" tresponse = "" try: tresponse = truecaller_search(cred.T_AUTH, num) if tresponse: restj = tresponse.json() trslt = json.dumps(restj) tjsonload = json.loads(trslt) if "name" in tjsonload['data'][0]: if tjsonload['data'][0]['internetAddresses']: pq = f"\n\n**----••Truecaller says----**\n\nName : `{tjsonload['data'][0]['name']}`\nCarrier : `{tjsonload['data'][0]['phones'][0]['carrier']}` \nE-mail : {tjsonload['data'][0]['internetAddresses'][0]['id']}" frbsetrname = tjsonload['data'][0]['name'] frbsetrmail = tjsonload['data'][0][ 'internetAddresses'][0]['id'] elif not tjsonload['data'][0]['internetAddresses']: pq = f"\n\n**----••Truecaller says----**\n\nName : `{tjsonload['data'][0]['name']}`\nCarrier : `{tjsonload['data'][0]['phones'][0]['carrier']}`" frbsetrname = tjsonload['data'][0]['name'] else: pq = "\n\n**----••Truecaller says----**\n\nNo results found 🤦🏻♂️" if tresponse.status_code == 429: pq = "\n\n**----••Truecaller says----**\n\nLimit exceeded ,try again tomorrow 🤦🏻♂️" except: pass response = eyecon_search(num) fbres = fb_search(num) fbrslt = fbres.url.replace('https://graph.', '').replace('picture?width=600', '') if response: rslt = response.json() if rslt: temp = json.dumps(rslt).replace('[', '').replace(']', '') jsonload = json.loads(temp) yk = f"\n\n**----••Eyecon says----**\n\nName :`{jsonload['name']}`" frbseyename = jsonload["name"] if "facebook.com" in fbrslt: yk = f"\n\n**----••Eyecon says----**\n\nName : `{jsonload['name']}`\nFacebook : {fbrslt}" frbseyename = jsonload["name"] frbsefb = fbrslt else: yk = "**----••Eyecon says----**\n\nNo results found 🤦🏻♂️" else: yk = "**----••Eyecon says----**\n\nNo results found 🤦🏻♂️" yk += pq pro.edit(text=yk, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Source", callback_data="src")]])) searches() log() if frbseyename and frbsefb and frbsetrname and frbsetrmail: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Facebook": frbsefb, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbseyename and frbsefb and frbsetrname: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Facebook": frbsefb } firebase.put('/Truecallerprobot-log', num, data) elif frbseyename and frbsefb: data = { "Eyecon Name": frbseyename, "Mob": num, "Facebook": frbsefb } firebase.put('/Truecallerprobot-log', num, data) elif frbseyename and frbsetrname and frbsetrmail: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname, "Mail": frbsetrmail } firebase.put('/Truecallerprobot-log', num, data) elif frbseyename and frbsetrname: data = { "Eyecon Name": frbseyename, "Mob": num, "Truecaller name": frbsetrname } firebase.put('/Truecallerprobot-log', num, data) elif frbsetrname and frbsetrmail: data = { "Truecaller name": frbsetrname, "Mob": num, "Mail": frbsetrmail } firebase.put('/knowho-log', num, data) elif frbsetrname: data = {"Truecaller name": frbsetrname} firebase.put('/knowho-log', num, data) else: pro.edit("`Only` **10** `digit numbers allowed` 🤦🏻♂️")
def postMotorcycleMake(mk): result = firebase.put('/Motorcycles/Makes/', name=mk,data=mk) print(mk+" Motorcycle Make Posted")
def updateDislike(id): checkdislike = firebase.get('/drawingInfo', id) currentDislike = checkdislike["Dislikes"] newDislikes = int(currentDislike) + 1 likePush = firebase.put('/drawingInfo' + '/' + id, 'Dislikes', int(newDislikes))
def hello(): pl = request.args.get("turn") data = firebase.get('/game/', '') if (data != None): board = list(data) else: data = { '0': ' ', '1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' ', } firebase.put('/game/', '/', data) print('init') data = firebase.get('/game/', '') board = list(data) print(board) player = 1 if (pl != None): player = int(pl) ########win Flags########## Win = 1 Draw = -1 Running = 0 Stop = 1 ########################### Game = Running Mark = 'X' global Game status = '' if (board[0] == ' ' and board[1] == ' ' and board[2] == ' ' and board[3] == ' ' and board[4] == ' ' and board[5] == ' ' and board[6] == ' ' and board[7] == ' ' and board[8] == ' ' and board[9] == ' '): data = { '0': ' ', '1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' ', } firebase.put('/game/', '/', data) print('init') elif (board[0] != ' ' or board[1] != ' ' or board[2] != ' ' or board[3] != ' ' or board[4] != ' ' or board[5] != ' ' or board[6] != ' ' or board[7] != ' ' or board[8] != ' ' or board[9] != ' '): print('noint') #Horizontal winning condition if (board[1] == board[2] and board[2] == board[3] and board[1] != ' '): Game = Win elif (board[4] == board[5] and board[5] == board[6] and board[4] != ' '): Game = Win elif (board[7] == board[8] and board[8] == board[9] and board[7] != ' '): Game = Win #Vertical Winning Condition elif (board[1] == board[4] and board[4] == board[7] and board[1] != ' '): Game = Win elif (board[2] == board[5] and board[5] == board[8] and board[2] != ' '): Game = Win elif (board[3] == board[6] and board[6] == board[9] and board[3] != ' '): Game = Win #Diagonal Winning Condition elif (board[1] == board[5] and board[5] == board[9] and board[5] != ' '): Game = Win elif (board[3] == board[5] and board[5] == board[7] and board[5] != ' '): Game = Win #Match Tie or Draw Condition elif (board[1] != ' ' and board[2] != ' ' and board[3] != ' ' and board[4] != ' ' and board[5] != ' ' and board[6] != ' ' and board[7] != ' ' and board[8] != ' ' and board[9] != ' '): Game = Draw else: Game = Running if (Game == Running): if (player % 2 != 0): print("Player 1's chance") Mark = 'X' else: print("Player 2's chance") Mark = 'O' # choice = int(input("Enter the position between [1-9] where you want to mark : ")) if (Game == Draw): status = 'draw' elif (Game == Win): if (player % 2 != 0): print("Player 0 Won") status = "Player 0 Won" else: print("Player X Won") status = "Player X Won" print(Game) return render_template('board.html', boardm=board, player=player, status=status)
def opencvfunction(carno, mycar): try: picurl = "car" + str(mycar) + ".jpg" #url=bucket.blob(picurl) #url.download_to_filename(picurl) img = cv2.imread('car1.jpg', cv2.IMREAD_COLOR) #img = cv2.imread('car1.jpg',cv2.IMREAD_COLOR) #mg = cv2.resize(img, (620,480) ) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #convert to grey scale gray = cv2.bilateralFilter(gray, 11, 17, 17) #Blur to reduce noise edged = cv2.Canny(gray, 30, 200) #Perform Edge detection # find contours in the edged image, keep only the largest # ones, and initialize our screen contour cnts = cv2.findContours(edged.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:10] screenCnt = None # loop over our contours for c in cnts: # approximate the contour peri = cv2.arcLength(c, True) approx = cv2.approxPolyDP(c, 0.018 * peri, True) # if our approximated contour has four points, then # we can assume that we have found our screen if len(approx) == 4: screenCnt = approx break if screenCnt is None: detected = 0 else: detected = 1 if detected == 1: cv2.drawContours(img, [screenCnt], -1, (0, 255, 0), 3) # Masking the part other than the number plate mask = np.zeros(gray.shape, np.uint8) new_image = cv2.drawContours( mask, [screenCnt], 0, 255, -1, ) new_image = cv2.bitwise_and(img, img, mask=mask) # Now crop (x, y) = np.where(mask == 255) (topx, topy) = (np.min(x), np.min(y)) (bottomx, bottomy) = (np.max(x), np.max(y)) Cropped = gray[topx:bottomx + 1, topy:bottomy + 1] #Read the number plate text = pytesseract.image_to_string(Cropped, config='--psm 11') firebase.put(carno, 'carno', text) print("Detected Number is:", text) cv2.imshow('image', img) cv2.imshow('Cropped', Cropped) #cv2.waitKey(0) cv2.destroyAllWindows() except: print("hgfh")
except KeyError: # If we got a KeyError we need to create the # dictionary key counter[item] = 1 # Keep overwriting maxItemCount with the latest number, # if it's higher than the existing itemCount if counter[item] > maxItemCount: maxItemCount = counter[item] mostPopularItem = item print(mostPopularItem, maxItemCount) probablity = maxItemCount / n prob = (probablity * 100) result4 = firebase.put('/message', "disease", maximum) result5 = firebase.put("/message", "prob", prob) # diseasese if maximum == 'Fungal infection': tablet = 'Fungal 150 MG Tablet' if maximum == 'Allergy': tablet = 'Cetrizine' if maximum == 'GERD': tablet = 'H-2-receptors blockers' if maximum == 'Chronic cholestasis': tablet = 'corticosteroids' if maximum == 'Drug Reaction': tablet = 'antihistamines' if maximum == 'Peptic ulcer diseae':
"https://sleepyhotelzoo-default-rtdb.firebaseio.com/ ", None ) print("1.Private room") print("2.Package room") print("3.Group room") x = input("Input you TYPE of room you want to update: ") if x == "1": print("########### Private room ###########") room_id = input("Input you ID room you want to UPDATE: ") types = input("input you type for update :") name = input("input you name of room for update :") price = input("input you price for update : ") firebase.put(f"Hotel_room/PrivateROOM/{room_id}", "Price", price) firebase.put(f"Hotel_room/PrivateROOM/{room_id}", "Type of room", types) firebase.put(f"Hotel_room/PrivateROOM/{room_id}", "name_room", name) elif x == "2": print("########### Private room ###########") room_id = input("Input you ID room you want to UPDATE: ") types = input("input you type for update :") name = input("input you name of room for update :") price = input("input you price for update : ") firebase.put(f"Hotel_room/PackageROOM/{room_id}", "Price", price) firebase.put(f"Hotel_room/PackageROOM/{room_id}", "Type of room", types) firebase.put(f"Hotel_room/PackageROOM/{room_id}", "name_room", name) elif x == "3": print("########### Private room ###########") room_id = input("Input you ID room you want to UPDATE: ") types = input("input you type for update :")
#GPIO.setup(mtrBbac, GPIO.OUT) #GPIO.setup(triggerPin, GPIO.OUT) #GPIO.setup(echoPin, GPIO.IN) #buzzer - disabled currently #GPIO.setup(40, GPIO.OUT) #(pin, freq) #servo = GPIO.PWM(motorPin, 50) #servo.start(7.5) firebase = firebase.FirebaseApplication('https://crogobot.firebaseio.com', None) firebase.put('/', 'online' , 'Yes') #Turn on website def editLight(r): if (r == 'up'): print ("MOVING FORWARD") #GPIO.output(forwardPin, GPIO.HIGH) elif (r == 'down'): print ("MOVING BACKWARD") #GPIO.output(backPin, GPIO.HIGH) elif (r == 'right'): print ("TURNING RIGHT") #GPIO.output(rightPin, GPIO.HIGH) elif (r == 'left'): print ("TURNING LEFT") #GPIO.output(leftPin, GPIO.HIGH) elif (r == 'horn'):
from igramscraper.instagram import Instagram from firebase import firebase instagram = Instagram() firebase = firebase.FirebaseApplication( 'https://covidai-1dd78.firebaseio.com/', None) data = firebase.get( '/covidai-1dd78/latest_media/-M3f_ZqzLKNGLoqFP5Mr/-M3gWKCfYoXQpB0gbGJh', '') media_ids = data['medias'] # authentication supported instagram.with_credentials('covid.ai_bengali', 'CoronaCann09') instagram.login() # datas = firebase.post('/covidai-1dd78/latest_media/-M3f_ZqzLKNGLoqFP5Mr/-M3gWKCfYoXQpB0gbGJh', da) media = instagram.get_current_top_medias_by_tag_name('corona') print(media) for m in media: if m.identifier not in media_ids: media_ids.append(m.identifier) comment = instagram.add_comment( m.identifier, 'Follow @covid.ai for the latest coronavirus stats') print(comment) result = firebase.put( '/covidai-1dd78/latest_media/-M3f_ZqzLKNGLoqFP5Mr/-M3gWKCfYoXQpB0gbGJh', 'medias', media_ids) print(result)
for i in lista[b]: if lista[b][i]['quantidade'] < 0: print('{0} : {1}'.format( i, lista[b][i]['quantidade'])) elif escolha == 0: print('Programa encerrado') break else: print('Opção inválida') print('Digite uma opção válida') else: print('Loja não encontrada') elif op == 3: remover = input('Qual o nome da loja? ') if remover in loja: del lista[remover] print('Loja removida') else: print('Loja não cadastrada') elif op == 4: s = [] for i in lista: s.append(i) print(', '.join(s)) a = [lista] firebase.put('/estoques', '0', a)
def update_firebase(count): lat=vehicle.location.global_relative_frame.lat lon=vehicle.location.global_relative_frame.lon firebase.put('/drone1/obj'+str(count),"lat",lat) firebase.put('/drone1/obj'+str(count),"lng",lon) firebase.put('/',"count1",count)
from firebase import firebase firebase = firebase.FirebaseApplication( 'https://striped-harbor-275119.firebaseio.com/', None) data = {'Name': 'Vivek', 'RollNo': 1, 'Percentage': 76.02} result = firebase.put('', '/Potholeinfo/path4', data) print(result)
def upload_data(dataTuple): firebase.put('/automated-gardener-default-rtdb/realtime-plant-value/user1', dataTuple[0], dataTuple[1])