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 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 clear(): from firebase import firebase firebase = firebase.FirebaseApplication( 'https://ihubems-3dcee.firebaseio.com/', None) #result = firebase.post('/phonebook',data) firebase.delete('/', 'phonebook') return render_template("employ.html")
def putInFirebase(phrase, response): phrase = phrase.strip() if getResp(phrase) == None: a = eval(getResp("trips")) if response in a and phrase == "trips": return 0 if len(response) > 1: if response[0] == "'": response = "[" + response + "]" else: response = "['" + response + "']" else: response = "[]" firebase.post(phrase, response) return 1 else: a = eval(getResp("trips")) if response in a and phrase == "trips": return 0 print "1" a = eval(getResp(phrase)) r = eval(getResp(phrase)) for item in r: print "Item: " + item + "Res: " + response if item == response: return len(a) print "2" a.append(response) print "3" firebase.delete(phrase, None) print "4" firebase.post(phrase, str(a)) print "5" return len(a)
def search(client_lat, client_lon, max_distance): drawings = firebase.get("/drawingInfo", None) good_drawings = [] for key, val in drawings.items(): val["_id"] = key # just to make it easier to send to Evan lat = val["Latitude"] lon = val["Longitude"] coordUser = (client_lat, client_lon) coordDB = (lat, lon) distance = great_circle(coordUser, coordDB) if distance <= max_distance: good_drawings.append(val) ## Above will return a good drawing ##BELOW WILL REMOVE ALL PAST 24 HOUR DRAWING remove = firebase.get('/drawingInfo', None) for key, val in remove.items(): print('DB TIME: ' + val["Time"]) oldTime = datetime.datetime.strptime(val["Time"], "%a %b %d %H:%M:%S %Y") newTime = datetime.datetime.now() lapTime = newTime - oldTime if (lapTime.total_seconds() > (86400)): firebase.delete('/drawingInfo', key) print("Deleted database" + key) ##ONCE FINISHED IT WILL RETURN GOOD PHOTOS within distance return good_drawings
def search(client_lat, client_lon, max_distance): remove = firebase.get('/drawingInfo', None) for key, val in remove.items(): print('DB TIME: ' + val["Time"]) oldTime = datetime.datetime.strptime(val["Time"], "%a %b %d %H:%M:%S %Y") newTime = datetime.datetime.now() lapTime = newTime - oldTime if (lapTime.total_seconds() > (86400)): firebase.delete('/drawingInfo', key) drawings = firebase.get("/drawingInfo", None) good_drawings = [] for key, val in drawings.items(): val["_id"] = key # just to make it easier to send to Evan lat = val["Latitude"] lon = val["Longitude"] coordUser = (client_lat, client_lon) coordDB = (lat, lon) print(coordUser, coordDB) distance = great_circle(coordUser, coordDB) if distance.miles <= max_distance: val["Distance"] = int(distance.feet) good_drawings.append(val) return good_drawings
def delete_transation(user_id, transaction_id): firebase.delete('/' + user_id + '/transactions/', transaction_id) return "{ \"success\" : true }", 200, { 'Content-Type': 'application/json; charset=utf-8' }
def reset_firebase(settings): # Nuke existing Firebase data and push default values to database try: r = firebase.put('/','settings', settings, params=fb_params) # r = firebase.delete('/','temp-history', params=fb_params) r = firebase.delete('/','PID', params=fb_params) r = firebase.delete('/','cook', params=fb_params) r = firebase.delete('/','timers', params=fb_params) r = firebase.delete('/','programs', params=fb_params) except Exception: SmokeLog.common.error('Failed to initialize database!') SmokeLog.common.error(traceback.format_exc()) sys.exit(1) else: SmokeLog.common.notice('Successfully initialized database.') pid_defaults = {'Time': time.time()*1000, 'u': 0, 'P':0, 'I': 0, 'D': 0, 'PID': 0, 'Error': 0, 'Derv': 0, 'Inter': 0} try: r = firebase.post_async('/PID', pid_defaults, params=fb_params) except Exception: SmokeLog.common.error('Failed to push default values for /PID!') SmokeLog.common.error(traceback.format_exc()) sys.exit(1) else: timers['LastSettingsPush'] = time.time() SmokeLog.common.info('Successfully pushed default values for /PID.')
def updateDB(): firebase.delete('',None) for key in payload: print key data = {"Name":payload[key]['Name'], 'Grade':payload[key]['Grade'],'CheckIn':payload[key]['CheckIn']} sent = json.dumps(data) firebase.put('','Student/'+key,data)
def delete_group(_id): if "username" in session: password = request.form["password"] user = get_user("username", session["username"]) if user["password"] == password: group = get_group("_id", _id) for i in group["members"].split(): usr = get_user("_id", int(i)) groups = usr["groups"].replace(str(_id) + " ", "") firebase.put("/users/" + str(usr["_id"]), "groups", groups) for i in group["posts"].split(): post = get_post("_id", int(i)) usr = get_user("_id", post["user_id"]) posts = usr["posts"] - 1 firebase.put("/users/" + str(usr["_id"]), "posts", posts) users = all_users() for user in users: if _id in user["liked_items"].split(): liked_items = user["liked_items"].replace(f"{_id} ", "") firebase.put("/users/" + user["_id"], "liked_items", liked_items) if _id in user["saved_items"].split(): saved_items = user["saved_items"].replace(f"{_id} ", "") firebase.put("/users/" + user["_id"], "saved_items", saved_items) if _id in user["commented_items"].split(): commented_items = user["commented_items"].replace(f"{_id} ", "") firebase.put("/users/" + user["_id"], "commented_items", commented_items) firebase.put("/users/" + user["_id"], "comments", comments) firebase.delete("/posts", post["_id"]) firebase.delete("/groups", group["_id"]) return redirect(url_for("index")) else: flash("Incorrect password.") return redirect(f"/{_id}-group") flash(login_message) return redirect(url_for("login"))
def _firebase_get_or_retrieve(fburl, q, retrievefn, retrieveparams, retrieve=True): obj = firebase.get(fburl, q) if obj: print "(Firebase cached) Found %s %s" % (fburl, q) if "cachedAt" in obj: del obj["cachedAt"] return obj if not retrieve: return None try: obj = retrievefn(*retrieveparams) if not obj: print "No result to store" return obj["cachedAt"] = FIREBASE_SERVER_TIMESTAMP firebase.delete(fburl, q) firebase.put_async(fburl, q, obj) del obj["cachedAt"] return obj except Exception, e: print "Exception on %s %s, SKIPPING." % (fburl, q), type(e), e
def deleteForm(fid): firebase.delete('/formularios', fid) if fid != "": return jsonify({"message": "Deleted"}) return jsonify({"message": "No Form Found"})
def on_delete(self, req, resp): #One of the challengers has declined, or deleted the challenge #need to remove this challenge for both challengers #The challenge ID is the otherchallengerID which explain the path to delete if req.get_param('param') == 'task': logging.info('Deleting one task') result = firebase.delete( '/users/' + req.get_param('userID') + '/tasklist', req.get_param('taskID')) resource = 'deleted' resp.body = json.dumps(resource) resp.status = falcon.HTTP_200 elif req.get_param('param') == 'challenge': logging.info('Deleting a challenge for User 1 and User 2') result = firebase.delete( '/users/' + req.get_param('otherUserID') + '/challenge/', req.get_param('userID')) result = firebase.delete( '/users/' + req.get_param('userID') + '/challenge/', req.get_param('otherUserID')) resource2 = 'deleted' resp.body = json.dumps(resource2) resp.status = falcon.HTTP_200 elif req.get_param('param') == 'question': logging.info('Deleting a question from the followed list') result = firebase.delete( '/users/' + req.get_param('userID') + '/followedQuestion/', req.get_param('questionID')) resource3 = 'deleted' resp.body = json.dumps(resource3) resp.status = falcon.HTTP_200
def mean_std_all_columns(df): """ function to create and store forecast from mean std model """ data = df.copy() rooms = data['R'].unique() #delete the existing prediction firebase.delete('/', 'Model 02') #get the prediction data = mean_std_model(data) #initialize an empty dictionary dict_mean_std = {} for column in rooms: #get bounds df_ = get_bounds(data, column) #post process the prediction df_ = mean_std_postprocessing(df_) #post the forecast into firebase realtime db path = 'Model 02/' post_data(df_, column, path) df_.set_index(['time'], inplace=True) #add forecast to the dictionary dict_mean_std[column] = df_.copy() return dict_mean_std
def delete(_id): if "username" in session: post = get_post("_id", _id) user = get_user("username", session["username"]) posts= user["posts"] - 1 firebase.put("/users/" + user["_id"], "posts", posts) users = all_users() li_users = list(users) for user in li_users: user = users[user] if _id in user["liked_items"].split(): liked_items = user["liked_items"].replace(f"{_id} ", "") firebase.put("/users/" + user["_id"], "liked_items", liked_items) if _id in user["saved_items"].split(): saved_items = user["saved_items"].replace(f"{_id} ", "") firebase.put("/users/" + user["_id"], "saved_items", saved_items) if _id in user["commented_items"].split(): commented_items = user["commented_items"].replace(f"{_id} ", "") firebase.put("/users/" + user["_id"], "commented_items", commented_items) if post["group"]: group = get_group("_id", post["group"]) posts = group["posts"].replace(_id + " ", "") firebase.put("/groups/" + group["_id"], "posts", posts) firebase.delete("/posts", post["_id"]) return redirect(url_for("index")) flash(login_message) return redirect(url_for("login"))
def serialAT(): print('serial') Receive_serial.write('1') send = Receive_serial.readline() print(send) send = send.replace('\r\n', '') firebase.delete('/tasks/umidade', None) send = firebase.post('/tasks/umidade', send) data = Receive_serial.write('2') send = Receive_serial.readline() print(send) send = send.replace('\r\n', '') firebase.delete('/tasks/acidez', None) send = firebase.post('/tasks/acidez', send) Receive_serial.write('3') send = Receive_serial.readline() print(send) send = send.replace('\r\n', '') firebase.delete('/tasks/temp', None) send = firebase.post('/tasks/temp', send) data = Receive_serial.write('4') send = Receive_serial.readline() print(send) send = send.replace('\r\n', '') firebase.delete('/tasks/pluv', None) send = firebase.post('/tasks/pluv', send) if GPIO.RISING: firebase.delete('/tasks/bateria', None) send = firebase.post('/tasks/bateria', 'Bateia fraca')
def putInFirebase(phrase,response): phrase = phrase.lower() phrase = phrase.strip() if getResp(phrase) == None: response = "['"+response+"']" firebase.post(phrase,response) keys = eval(getResp("Keys")) keys.append(phrase) firebase.delete("Keys",None) firebase.post("Keys",str(keys)) incrementN() return 1 else: print "1" a = eval(getResp(phrase)) r = eval(getResp(phrase)) for item in r: print "Item: "+item + "Res: "+response if item == response: return len(a) print "2" a.append(response) print "3" firebase.delete(phrase,None) print "4" firebase.post(phrase,str(a)) print "5" incrementN() return len(a)
def ResetFirebase(Parameters): try: r = firebase.put('/', 'Parameters', Parameters, params=Params) r = firebase.delete('/', 'Temps', params=Params) r = firebase.delete('/', 'Controls', params=Params) r = firebase.delete('/', 'Program', params=Params) except: logger.info('Error initializing Firebase') #Post control state D = { 'time': time.time() * 1000, 'u': 0, 'P': 0, 'I': 0, 'D': 0, 'PID': 0, 'Error': 0, 'Derv': 0, 'Inter': 0 } try: r = firebase.post_async('/Controls', D, params=Params, callback=PostCallback) except: logger.info('Error writing Controls to Firebase')
def putInFirebasePython(phrase, response): phrase = phrase.lower() phrase = phrase.strip() if getResp(phrase) == None: response = "['" + response + "']" firebase.post(phrase, response) keys = eval(getResp("PythonKeys")) keys.append(phrase) firebase.delete("PythonKeys", None) firebase.post("PythonKeys", str(keys)) incrementN() return 1 else: print "1" a = eval(getResp(phrase)) r = eval(getResp(phrase)) for item in r: print "Item: " + item + "Res: " + response if item == response: return len(a) print "2" a.append(response) print "3" firebase.delete(phrase, None) print "4" firebase.post(phrase, str(a)) print "5" incrementN() return len(a)
def update_db(): while True: global data mutex.acquire(0) try: print "Thread 2:", data if data: temp, lux = data.split() temp = float(temp) lux = float(lux) print 'temp:', temp print 'lux:', lux location = '/rooms/room-1' record = {'temperature': temp, 'luminosity': lux} try: response = firebase.get(location, None) if response: key, value = response.popitem() firebase.delete(location, key) result = firebase.post(location, record) print result except Exception as e: print e time.sleep(fixed_interval) finally: mutex.release()
def mine(): # blockchain.resolve_conflicts() last_block = blockchain.last_block last_proof = last_block['proof'] proof = blockchain.proof_of_work(last_proof) # User recieve reward for finding PoW blockchain.new_transaction( sender="0", reciever=blockchain.public_key, amount=1, ) previous_hash = blockchain.hash(last_block) pending_transactions_firebase = firebase.get("/pending_transactions", None) for transaction_id in pending_transactions_firebase: transaction = firebase.get("/pending_transactions", transaction_id) blockchain.current_transactions.append(transaction) block = blockchain.new_block(proof, previous_hash) firebase.delete('/pending_transactions', None) response = { 'message': 'New block forged', 'index': block['index'], 'transactions': block['transactions'], 'proof': block['proof'], 'previous_hash': block['previous_hash'], } return jsonify(response), 201
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 delete_all(): if "username" in session: usr = get_user("username", session["username"]) if usr["password"] == request.form["password"]: usr["posts"] = 0 posts = get_post("username", session["username"]) ids = [] for post in posts: ids.append(str(post["_id"])) users = all_users() for user in users: for _id in ids: if _id in users[user]["liked_items"].split(): liked_items = users[user]["liked_items"].replace(f"{_id} ", "") firebase.put("/users/" + user, "liked_items", liked_items) if _id in users[user]["saved_items"].split(): saved_items = users[user]["saved_items"].replace(f"{_id} ", "") firebase.put("/users/" + user, "saved_items", saved_items) if _id in users[user]["commented_items"].split(): commented_items = users[user]["commented_items"].replace(f"{_id} ", "") firebase.put("/users/" + user, "commented_items", commented_items) for post in posts: if post["group"]: group = get_group("_id", post["group"]) posts = group["posts"].replace(post["_id"], " ") firebase.put("/groups/" + str(group["_id"]), "posts", posts) for post in posts: firebase.delete("/posts", post["_id"]) return redirect(url_for("settings")) else: return redirect(url_for("delete_all_password")) return render_template("error.html", user=get_user("username", session["username"])) flash(login_message) return redirect(url_for("login"))
def postdata(name, data): #time.sleep(1) try: firebase.delete('/' + base + '/' + name, None) firebase.post('/' + base + '/' + name, data) except: pass
def exit(plate): from firebase import firebase from datetime import datetime now = datetime.now() current_time = now.strftime("%m/%d/%y %H:%M:%S") curr = datetime.strptime(current_time, "%m/%d/%y %H:%M:%S") # maine entry time uuthaya ya pe firebase = firebase.FirebaseApplication( 'https://anpr-265503.firebaseio.com/', None) # plate = "MH03BE8760" # idhar baadmae current plate okok entry_time = datetime.strptime( firebase.get('/Cars/' + plate, 'Entry Time'), "%m/%d/%y %H:%M:%S") # calculating paise diffTime = str(curr - entry_time) if len(diffTime) < 8: diffTime = "0" + diffTime # if else agar unpaid hai toh aage continue nako. print(diffTime) hr = int(diffTime[0:1]) * 60 min = int(diffTime[3:5]) cost = (hr + min) * 100 # update saare tables firebase.put('/Cars/' + plate, "Exit Time", current_time) firebase.put('/Cars/' + plate, "Cost", cost) firebase.put('/Cars/' + plate, "Parking_time", diffTime) firebase.put('/Cars/' + plate, "Status", "Unpaid") Uid = firebase.get('/Cars', plate + "/uid") data = firebase.get('/Cars', plate) print("entry: - ", entry_time) firebase.put('user-posts', Uid + "/History/" + plate + " " + str(entry_time), data) firebase.delete( "user-posts/" + Uid + "/Recent/" + plate + " " + str(entry_time), None)
def scrape_data_from_url(): print("clearing previous news...") firebase.delete('/news', None) print("scraping....") for url in url_lists: get_link(url) print("completed") print("waiting for next iteration")
def on_delete(self, req, resp): logging.info('Deleting the resource') #data must only contains the ID of the task data = json.loads(req.get_param("data")) firebase.delete('/tasks/taskName', data) resource = {'result': 'deleted'} resp.body = json.dumps(resource) resp.status = falcon.HTTP_200
def addVidHelp(link): links = eval(getResp("helpVids")) if link in links: return "Already in List" links.append(link) firebase.delete('helpVids',None) firebase.post("helpVids",str(links)) return "Added"
def addToRand(phrase): arr = eval(getResp('randomR')) if phrase not in arr: arr.append(phrase) firebase.delete('randomR', None) firebase.post('randomR', str(arr)) return 'green' return 'red'
def deleteEvent(username, event): result = firebase.get("/events", event) if result != None: #This is for security. if result['manager'] == username: firebase.delete("/events", event) return redirect(url_for('serveManagerHome', username=username))
def addToRand(phrase): arr = eval(getResp('randomR')) if phrase not in arr: arr.append(phrase) firebase.delete('randomR',None) firebase.post('randomR',str(arr)) return 'green' return 'red'
def test_upload(self): databaseFb.db_upload('/test', "test", '') os.system("sudo pon fona") time.sleep(3) result = firebase.get('/test', None) self.assertTrue("test" in result) firebase.delete('/test', '') os.system("sudo poff fona") time.sleep(1)
def nettoyage_bdd(mes_job_bdd, tab_id): count = 0 for i in range(len(mes_job_bdd) - 1): if mes_job_bdd[i] in mes_job_bdd[i + 1:len(mes_job_bdd) - 1]: print(str(count)) count += 1 firebase.delete('/salaire-data/job', tab_id[i]) print('nbr doublon = ' + str(count))
def fire(self, data, send): if data == 1: firebase.delete('/tasks/umidadeM', None) send = firebase.post('/tasks/umidadeM', send) elif data == 2: firebase.delete('/tasks/acidezM', None) send = firebase.post('/tasks/acidezM', send) else: print("Sensor invalido")
def removeComic(email,comic): print "Logging In" users = eval(getResp("Users")) b = eval(getResp("Comics")) for i in range(0,len(users)): if users[i] == email: if comic in b[i]: b[i].remove(comic) firebase.delete('Comics',None) firebase.post("Comics",str(b))
def putInFirebase(phrase,response): phrase = phrase.strip() if getResp(phrase) == None: firebase.post(phrase,response) keys = eval(getResp("Keys")) keys.append(phrase) firebase.delete("Keys",None) firebase.post("Keys",str(keys)) incrementN() return 1 else: print "Already In system" return 0
def ResetFirebase(Parameters): try: r = firebase.put('/', 'Parameters', Parameters, params=Params) r = firebase.delete('/', 'Temps', params=Params) r = firebase.delete('/', 'Controls', params=Params) r = firebase.delete('/', 'Program', params=Params) except: logger.info('Error initializing Firebase') #Post control state D = {'time': time.time() * 1000, 'u': 0, 'P': 0, 'I': 0, 'D': 0, 'PID': 0, 'Error': 0, 'Derv': 0, 'Inter': 0} try: r = firebase.post_async('/Controls', D, params=Params, callback=PostCallback) except: logger.info('Error ResetFirebase() writing Controls to Firebase')
def addUser(userName,password): userName = userName.strip() if getResp(userName) == None: firstArray = [userName,password,0,[]] firebase.post(userName,str(firstArray)) users = eval(getResp("Users")) users.append(userName) firebase.delete("Users",None) firebase.post("Users",str(users)) incrementN() return 1 else: print "Already In system" return 0
def completeLess(lessonName,email): try: users = eval(getResp("Users")) userData = eval(getResp("UserData")) for i in range(0,len(users)): if users[i] == email: if lessonName in userData[i][0]: return "You already completed this lesson!" userData[i][0].append(lessonName) firebase.delete("UserData",None) firebase.post("UserData",str(userData)) return "You have been awarded 10 points!" except: return "An Error Has Occured :("
def incrementN(): a = firebase.get("NumOfPhrases",None) print a keys = [] count = 0 for key in a: """ print "key: %s , value: %s" % (key, a[key]) """ keys.append(key) count = count +1 i = int(a[keys[count-1]]) i = i+1 firebase.delete('NumOfPhrases',None) firebase.post("NumOfPhrases",str(i))
def WriteProgram(Program): try: r = firebase.delete('/','Program', params=Params) for P in Program: r = firebase.post('/Program', P, params=Params) except: logger.info('Error writing Program to Firebase')
def editUserData(name,nick,summary,pic,email,contact): try: users = eval(getResp("Users")) userData = eval(getResp("UserData")) for i in range(0,len(users)): if users[i] == email: print userData print "Change" userData[i][1]=[str(name),str(nick),str(summary),str(pic),str(contact)] print userData firebase.delete("UserData",None) firebase.post("UserData",str(userData)) return except: return
def update_times(ident, time): result = firebase.get('/line', None, connection=None, params={'print': 'pretty', 'auth': token, 'orderBy': '"ident"', 'equalTo': str('"' + ident + '"')}) key = result.keys()[0] data = result[key] total_time = time - parse(data['timestamp']) new_entry = {'ident': ident, 'timeIn': data['timestamp'], 'timeOut': time, 'total': str(total_time)} firebase.post('/data', new_entry, connection=None, params={'print': 'pretty', 'auth': token}) firebase.delete('/line', key, connection=None, params={'print': 'pretty', 'auth': token}) return str(total_time)
def process(responses): if responses != None and type(responses) == type({}) and len(responses) > 0: print "============================" for key in responses.keys(): data = responses[key] text = data["message"]["text"] chat_id = data["message"]["chat"]["id"] print text print chat_id out = console.process(text) payload = { "chat_id": chat_id, "text": json.dumps(out) } res = requests.post(nlpbot_demo_url, data=payload) print res.text firebase.delete('/messages', key)
def removeRobotPostEvents(firebase_url, robot_name): import threading from firebase import firebase print 'fetching events from the database ... ' stop_event= threading.Event() thread = threading.Thread(target = threaded_function, args = [stop_event]) thread.start() firebase = firebase.FirebaseApplication(firebase_url, None) events = firebase.get('/events', None) robot_event_list_key = [] if events == None: stop_event.set() print "There is no events in the database." print "\n" print "\n" print "\n" return for key in events: if events[key]['authorName'] == robot_name: robot_event_list_key.append(key) stop_event.set() print "robot had posted", len(robot_event_list_key), "events" print "How many events you want to delete today?" num = input("Number: ") print "Are you sure you want to delete " + str(num) + " events?" yes_or_no = raw_input("Y/N: ") if yes_or_no == "Y": for i in range(min(num, len(robot_event_list_key))): firebase.delete('/events', robot_event_list_key[i]) print 'deleted', i, 'events' print "DONE" print "\n" print "\n" print "\n"
def addUser(email,passW): users = eval(getResp("Users")) users.append(email) firebase.delete('Users',None) firebase.post("Users",str(users)) b = eval(getResp("passwords")) b.append(passW) firebase.delete('passwords',None) firebase.post("passwords",str(b)) comics = eval(getResp("Comics")) comics.append([]) firebase.delete('Comics',None) firebase.post("Comics",str(comics))
def addUser(email,passW): users = eval(getResp("Users")) users.append(email) firebase.delete('Users',None) firebase.post("Users",str(users)) b = eval(getResp("passwords")) b.append(passW) firebase.delete('passwords',None) userData = eval(getResp("UserData")) userData.append([[],[str(email),"Nick Name",'This is my summary, I love to code!',"http://www.priorlakeassociation.org/wp-content/uploads/2011/06/blank-profile.png","show"]]) firebase.delete("UserData",None) firebase.post("UserData",str(userData)) firebase.post("passwords",str(b))
def deleteA(email): try: users = eval(getResp("Users")) userData = eval(getResp("UserData")) b = eval(getResp("passwords")) for i in range(0,len(users)): if users[i] == email: del users[i] del userData[i] del b[i] firebase.delete("UserData",None) firebase.delete('Users',None) firebase.post("Users",str(users)) firebase.post("UserData",str(userData)) firebase.delete('passwords',None) firebase.post("passwords",str(b)) return "Account Deleted" except: return "Error Occured"
Now = datetime.utcnow() # get the last time we ran the update orders response = firebase.get('/api_calls/ebay', 'update_orders') NumberOfDays = 0 if response: print 'Last time we updated orders was %s' % response response = datetime.strptime(response, "%Y-%m-%dT%H:%M:%S.%fZ") time_since_last_run = Now - response NumberOfDays = time_since_last_run.days # if response is None, that means we haven't run this script before else: NumberOfDays = 30 # clear fees in case they exist firebase.delete('/', 'orders') try: if NumberOfDays > 0: responses = GetOrders(NumberOfDays=NumberOfDays, IncludeFinalValueFee=True ) for i, response in enumerate(responses): response = response.dict() print 'PageNumber: %s' % (i + 1) print json.dumps(response, sort_keys=True, indent=5) if 'OrderArray' in response and 'Order' in response['OrderArray']: for order in response['OrderArray']['Order']: firebase.put('/orders', order['OrderID'], order)
"/usr/bin/ssh %s -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -l web 'kill `cat /home/web/.app_pid`; sleep 3; kill -9 `cat /home/web/.app_pid`; '" % net, shell=True, ) print po.wait() po = subprocess.Popen( "/usr/bin/ssh %s -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -l web 'screen -m -d /usr/bin/ruby /home/web/web/app.rb; echo `pidof SCREEN` > /home/web/.app_pid'" % net, shell=True, ) print po.wait() elif p["type"] == "php": print "LOL PHP U NEED NO RELOAD" else: print ("Unsupported type!") return False if __name__ == "__main__": firebase = firebase.FirebaseApplication("https://dep10y.firebaseio.com", authentication=None) while True: deploys = firebase.get("/files", name=None, params=None) if deploys: for i in deploys: val = deploys[i] print (i, val) firebase.delete("/files", i) thread = Thread(target=doDeploy, args=(i, val)) thread.start() time.sleep(3)
if data['COMMAND'] in messages: print('Translates to IR message:') print(messages[data['COMMAND']]) #send command to transmitter os.system(path + 'AC_control.py ' + data['COMMAND']) #update most recent command sent #this gives feedback that message was recieved firebase.put('IR','past_IR_ctr',result) else: print('Not a valid command') else: print('Error: non string input') #delete command firebase.delete('IR','IR_ctr') else: print('No command found') else: print('No data found') #log temperature os.system(path + 'LogTemp.py ')
firebase.put("/device/" + DEVICE_ID + "/packet/" + st, "moisture", moisture_reading) # , firebase.put("/device/" + DEVICE_ID + "/packet/" + st, "temperature", temperature_reading) if int(float(state)) > 1: firebase.put("/device/" + DEVICE_ID + "/packet/" + st, "valve_state", "OPEN") else: firebase.put("/device/" + DEVICE_ID + "/packet/" + st, "valve_state", "CLOSED") print "=================================" print st print "MOISTURE: " + moisture_reading print "TEMP: " + temperature_reading print "CURR_STATE: " + state ser.flushInput() ser.flushOutput() result = firebase.get("/device/" + DEVICE_ID + "/command/", None) if result: for key, value in result.items(): rxCom = value["command"] rxArg = value["argument"] if str(rxArg) == "0": rxArg = "00" print rxCom Generator.GenerateByteArray(FunctionMap[rxCom], rxArg) Generator.SendFrame(ser) status = xbee.wait_read_frame() firebase.delete("/device/" + DEVICE_ID + "/command/", key) except KeyboardInterrupt: break
def callend(): sleep(1.5) firebase.delete("/", request.form['CallSid']) return '200'
def download_book(bookname, chapter_count, start_chapter=1): from firebase import firebase firebase = firebase.FirebaseApplication('https://project-6084703088352496772.firebaseio.com', None) result = firebase.delete('/en', None) book_json = [] # load book chapters for ch in range(chapter_count): chnum = ch + start_chapter book_json = get_chapter(bookname, chnum) book_parts = [] for verse in book_json: book_parts.append(verse['text']) bookstr = ' '.join(book_parts) bookstr = fixtxt(bookstr) doc = nlp(bookstr) words = [] for sent in doc.sents: prev_prev_word = None prev_word = None for word in sent: words.append(unicode(word)) #print word verse_positions = [] token_first = 0 token_last = 0 tokens = [] for verse in book_json: token_first = len(tokens) token = '' for char in fixtxt(verse['text']): if char.isalnum(): token += char else: if token: tokens.append(token) token = '' if not char.isspace(): tokens.append(char) token_last = len(tokens) verse_id = 'en/net/%s/%s/%s' % (slugify(verse['bookname']), verse['chapter'], verse['verse']) verse_name = '%s %s:%s' % (verse['bookname'], verse['chapter'], verse['verse']) span = doc[token_first : token_last] vdict = { 'id': verse_id, 'span': span, 'name': verse_name, 'num': verse['verse'], #'pretitle': verse['title'] } if verse.has_key('title'): vdict['pretitle'] = verse['title'] verse_positions.append(vdict) chapdict = { 'name': '%s %s' % (bookname, chnum), 'verses': [] } for v in verse_positions: vdict = { 'n': v['num'], 't': [] } chapdict['verses'].append(vdict) tokens = vdict['t'] index = 0 for word in v['span']: token = { 't': unicode(word) # word text } if word.is_punct: token['p'] = word.is_punct # is punctuation if not word.is_punct: if unicode(word) != word.lemma_: token['l'] = word.lemma_ # lemma root word if word.is_title: token['h'] = word.is_title # is title / heading token['s'] = word.pos_ # part of speech token['d'] = word.dep_ # dep #token['g'] = word.tag_, # tag #token['tw'] = word.text_with_ws, # text with whitespace if word.whitespace_ == ' ': token['w'] = word.whitespace_ # whitespace tokens.append(token) if word.dep_ not in NODEP and word.pos_ not in NOPOS: #add_phrase(word.lemma_, v) verse_id = str(chnum) + ':' + str(v['num']) lemma = spacyfix(word.lemma_) if lemma: if SEARCH_DICT.has_key(lemma): w = SEARCH_DICT[lemma] w['count'] += 1 curbook = w['refs'][bookname] curbook['count'] += 1 if curbook.has_key(verse_id): curbook[verse_id].append(index) else: curbook[verse_id] = [index] else: SEARCH_DICT[lemma] = { 'count': 1, 'text': word.lemma_, 'refs': { bookname: { 'count': 1, verse_id: [index] } } } index += 1 ''' /search/[word]/ # { count: 23, text: 'word', refs: { matthew: { count: 3, '1:23': [ 4, 8, 9 ] {token index} } } } ''' chapid = '/en/net/%s' % slugify(bookname) #print 'Saving %s ...' % chapid result = firebase.put(chapid, chnum, chapdict)#, {'print': 'pretty'}, {'X_FANCY_HEADER': 'VERY FANCY'}) #print json.dumps(SEARCH_DICT, separators=(',', ':')) #searchdict = {} #for s in SEARCH_LIST: # key = slugify(s['text']) # if key: # searchdict[key] = s #save_file('firebase/public/data/search/search_terms.json', json.dumps(searchdict)) print 'Saving %d search terms ...' % len(SEARCH_DICT)
# set final score based on date set_score(quanta_temp[i]) except: print 'Quanta scraper has failed, site architecture may have changed, please reevaluate scraper code' # Concatenate all scraped results into one big list all_arts = plusmath_temp + maa_temp + nyt_temp + wired_temp + phys_temp + sciAm_temp + forbes_temp + quartz_temp + mathless_tmp + nsf_temp + quanta_temp # uniquify the articles all_arts =list({v['blurb']:v for v in all_arts}.values()) # Import itemgetter to construct lambada function for sorter from operator import itemgetter # Sort the list of articles by descending date all_arts=sorted(all_arts, key=itemgetter('date'), reverse=True) # Sort the list by descending score (see above) #all_arts=sorted(all_arts, key=itemgetter('score'), reverse=True) # Connect to firebase, wipe it, and start fresh with the new sorted list of articles firebase = firebase.FirebaseApplication('https://sweltering-heat-2148.firebaseio.com/', None) firebase.delete('/articles', '') # if you want all articles for i in range(len(all_arts)): # if you want first 25 articles #for i in range(0,25): # if all_arts[i]['date'] > datetime.combine(date.today()-relativedelta(days=60), datetime.min.time()): result = firebase.post('/articles', {"blurb": all_arts[i]['blurb'], "url": all_arts[i]['url'], "title": all_arts[i]['title'], "date": all_arts[i]['date']})
#!/usr/bin/python3 from firebase import firebase firebase = firebase.FirebaseApplication('https://chaalfirebase.firebaseio.com') #result = firebase.delete('/users','fourth') #result = firebase.delete('/users','-KDolAgp0g3IwXxDdqhw') result = firebase.delete('/users',None) print(result)
return count = reddit.get_comment_count(js) print str(url) + " has " + str(count) return count def email(person): sg = sendgrid.SendGridClient('DaxEarl', send_grid_password) message = sendgrid.Mail() message.add_to(person["email"]) message.set_subject('Your Reddit Ama Is Ready!') message.set_html('Body') message.set_text('Your ama is availibe at available at ') message.set_from('easyAMA<*****@*****.**>') status, msg = sg.send(message) print status,msg print "sent "+person["email"] +" an email" while True: result = firebase.get('/', None) for x in range(10): for k in result: person = result[k] if person["trigger"]=="count": if get_count_url(person["thread"])>person["min"]: print "Emailing "+str(person["email"]) email(person) print "Removing "+str(person["email"]) firebase.delete('/',k) print "Deleted!" time.sleep(20)