def questionBank(): """ Authenticated user will request for question from the question bank. Retrieve the questions and return it as a json to the client. # """ firebase_apikey = os.environ.get("firebase_apiKey") firebase_authDomain = os.environ.get("firebase_authDomain") firebase_databaseURL = os.environ.get("firebase_databaseURL") firebase_storageBucket = os.environ.get("firebase_storageBucket") firebase_appId = os.environ.get("firebase_appId") firebase_storageBucket = os.environ.get("firebase_storageBucket") config = { "apiKey": firebase_apikey, "authDomain": firebase_authDomain, "databaseURL": firebase_databaseURL, "storageBucket": firebase_storageBucket } try: firebase = Firebase(config) db = firebase.database() firebase_result = db.child("question").get() result = {} for data in firebase_result.each(): result[data.key()] = data.val() return json.dumps(result), 200 except Exception as e: print(f"Error: {e}") return "An error has occurred", 400
class StartupScreen(MDScreen): Builder.load_string(kv) def __init__(self, **kw): super().__init__(**kw) from firebase import Firebase self.app = MDApp.get_running_app() self.my_firebase = Firebase() def on_enter(self): from home_screen import HomeScreen from login_screen import LoginScreen home_screen = HomeScreen() login_screen = LoginScreen() self.app.root.add_widget(home_screen) self.app.root.add_widget(login_screen) try: with open("refresh_token.txt", "r") as f: refresh_token = f.read() self.my_firebase.exchange_refresh_token(refresh_token) Clock.schedule_once(lambda dt: self.load_home(), 1) except: Clock.schedule_once(lambda dt: self.load_login(), 1) def load_home(self): self.app.root.current = "home" def load_login(self): self.app.root.current = "login_screen"
def Retrieve(): config = { "apiKey": "AIzaSyDJIZK3ZCPPu3KNK0-1TuPULfbFGUn0aqI", "authDomain": "raspberry-pi-571ec.firebaseapp.com", "databaseURL": "https://raspberry-pi-571ec.firebaseio.com/", "storageBucket": "raspberry-pi-571ec.appspot.com" } firebase = Firebase(config) db = firebase.database() storage = firebase.storage() #new = db.child("Angelica's Inbox").child("New").get() new = db.child("Kris' Inbox").child("New").get() print(new.val()) if (new.val() == '1'): try: storage.child("Kris' Inbox").child("Image").download( "Image.jpg") print("image found") newImg = True return newImg except: print("No image") else: return False
class FirebasePlugin(IPlugin): def __init__(self): try: with open(secrets_filename, "r") as f: data = f.read() except: err = "Error processing {} - make sure to fill in {}!".format(secrets_filename, secrets_filename) with open(secrets_filename, "w") as f: f.write(document) raise Exception(err) try: conf = yaml.load(data) self.firebase_url = conf["firebase_url"] self.secret = conf["secret"] self.data_bucket = conf["data_bucket"] except: raise Exception("Error parsing {}!".format(secrets_filename)) if self.firebase_url is None or self.secret is None: raise Exception("Error parsing {} - not all fields have been filled in!".format(secrets_filename)) auth_payload = {"uid": "1", "auth_data": "foo", "other_auth_data": "bar"} token = create_token(self.secret, auth_payload) self._client = Firebase(self.firebase_url + self.data_bucket, auth_token=token) def process_message(self): message = messages[random.randint(0, len(messages)-1)] self._client.push({'timestamp': int(time.time()), 'message': message})
def login(): config = { "apiKey": "AIzaSyDr3GgNZ7hJhhXb9Grys6xrTRRFsWJlQGA", "authDomain": "mp3wizard-466b5.firebaseapp.com", "databaseURL": "https://mp3wizard-466b5.firebaseio.com", "storageBucket": "mp3wizard-466b5.appspot.com" } firebase = Firebase(config) auth = firebase.auth() w.emailEntry.configure(state="disabled") w.passwordEntry.configure(state="disabled") try: user = auth.sign_in_with_email_and_password(w.emailEntry.get(), w.passwordEntry.get()) validUser = True except HTTPError: print(str(HTTPError.__text_signature__)) w.emailEntry.configure(state="normal") w.passwordEntry.configure(state="normal") w.errorLabel.configure(text="Error when attempting to login") w.errorLabel.configure(foreground='#FF0000') sys.stdout.flush() if validUser: print(user) print(type(user)) destroy_window() uploadBookDash_support.start(user)
def main(): BASE_URL = 'https://amber-fire-5569.firebaseio.com/Traffic/' f = Firebase(BASE_URL) results = f.get() for key in results: pprint(key) pprint(results[key]) payload = results[key] street1 = results[key]['intersection1'] street2 = results[key]['intersection2'] coords = intersection_to_coords(street1, street2) print coords try: payload['Latitude'] = coords['Latitude'] except TypeError: continue payload['Longitude'] = coords['Longitude'] endpoint = Firebase(BASE_URL+key) pprint(payload) endpoint.set(payload)
def publish(temp, humidity): print("Publising to firebase!") firebase = Firebase(config) db=firebase.database() data={"temperature":temp, "humidity":humidity} db.child("dht").push(data) count=len(db.child("dht").get().val()) for x in db.child("dht").get().val(): if(count<=30): break db.child("dht").child(str(x)).remove() count -= 1 setTime()
def _process_pages(self, spider): host = spider.get_origin_host() fire = Firebase('%s/pages/%s' % (self.fire_host, host)) origin_hash = url_hash(host) cursor = self.db.cursor() query = """ SELECT content_item_id , content_node_id , object_type , lint_critical , lint_error , lint_warn , lint_info , lint_results FROM page WHERE request_method = 'GET' AND external = 0 AND object_type IS NOT NULL AND content_item_id IS NOT NULL ORDER BY lint_critical DESC, lint_error DESC, lint_warn DESC LIMIT 20 """ cursor.execute(query) rows = cursor.fetchall() res = {} for row in rows: res[row.pop('content_item_id')] = row fire.update(res)
def get_senadores_metadata_atual(): # Gets attributes from parlamentares and saves into Firebase # --> still needs to put right below 'senadores URL', now it's using FB id there... url = 'http://legis.senado.gov.br/dadosabertos/senador/lista/atual' uh = urllib.urlopen(url) data = uh.read() tree = ET.fromstring(data) senadores_tree = tree.findall('.//IdentificacaoParlamentar') senadores_dict = {} for sen in senadores_tree: codigo = sen.find('CodigoParlamentar').text # creates object with id 'codigo' and all data nested into that senadores_dict[codigo] = {} senadores_dict[codigo]['NomeParlamentar'] = sen.find('NomeParlamentar').text senadores_dict[codigo]['SexoParlamentar'] = sen.find('SexoParlamentar').text senadores_dict[codigo]['FormaTratamento'] = sen.find('FormaTratamento').text senadores_dict[codigo]['UrlPaginaParlamentar'] = sen.find('UrlPaginaParlamentar').text senadores_dict[codigo]['UrlFotoParlamentar'] = sen.find('UrlFotoParlamentar').text senadores_dict[codigo]['EmailParlamentar'] = sen.find('EmailParlamentar').text senadores_dict[codigo]['SiglaPartidoParlamentar'] = sen.find('SiglaPartidoParlamentar').text senadores_dict[codigo]['UfParlamentar'] = sen.find('UfParlamentar').text #firebase.post('/senadores', senadores_dict) # Substituir posteriormente por método genérico para salvar os dados f = Firebase(FBURL + '/senadores') f.put(senadores_dict)
def get_ladder(self): """Parses footywire HTML to get ladder""" ladder_url = "ft_ladder" session = requests.session() response = session.get(self.baseURL + ladder_url, headers=self.headers) soup = BeautifulSoup(response.text) ladder = [] for link in soup.find_all('a'): mylink = link.get('href') if mylink.find('/') == -1: if mylink.find('ft') == -1: mylink = mylink[3:] mylink = mylink.replace('-', ' ') ladder.append((mylink)) if ladder: f = Firebase('https://flickering-fire-9394.firebaseio.com/ladder') response = f.remove() print response for team in ladder: team = multipleReplace(team) print team r = f.push({'team_id': team })
def _init_database(): global user global db global firebase print("Initializing database...") project_id = "fir-test-for-atb-default-rtdb" config = { "apiKey": token_loader.FIREBASE, "authDomain": f"{project_id}.firebaseapp.com", "databaseURL": f"https://{project_id}.firebaseio.com", "storageBucket": f"pro{project_id}jectId.appspot.com" } firebase = Firebase(config) # Get a reference to the auth service auth = firebase.auth() # Log the user in load_dotenv() username = os.getenv('FIREBASE_USERNAME') password = os.getenv('FIREBASE_PASSWORD') user = auth.sign_in_with_email_and_password(username, password) set_next_token_refresh_time() # Get a reference to the database service db = firebase.database()
def broadcast(): sender_id = request.args.get("messenger user id") sender_name = request.args.get("first name") broadcast_item = request.args.get("broadcast_item") users = Firebase('https://bott-a9c49.firebaseio.com/lukkiddd/users/').get() headers = {"Content-Type": "application/json"} data = json.dumps({ "seller_messenger_id": sender_id, "sender": sender_name, "broadcast_item": broadcast_item }) for user_key in users: user_id = Firebase( 'https://bott-a9c49.firebaseio.com/lukkiddd/users/' + user_key + '/messenger_user_id').get() if (user_id != sender_id): if ("https://scontent" in broadcast_item): r = requests.post( "https://api.chatfuel.com/bots/58ccfcdde4b02491f5311c13/users/" + user_id + "/send?chatfuel_token=mELtlMAHYqR0BvgEiMq8zVek3uYUK3OJMbtyrdNPTrQB9ndV0fM7lWTFZbM4MZvD&chatfuel_block_id=59187f88e4b04ca3461dbb0a", headers=headers, data=data) else: r = requests.post( "https://api.chatfuel.com/bots/58ccfcdde4b02491f5311c13/users/" + user_id + "/send?chatfuel_token=mELtlMAHYqR0BvgEiMq8zVek3uYUK3OJMbtyrdNPTrQB9ndV0fM7lWTFZbM4MZvD&chatfuel_block_id=5918735ce4b04ca345f5a19e", headers=headers, data=data)
def __init__(self): config = { "apiKey": "AIzaSyAl0sJD8bl30gnWH9juh6pywzOzsuzSdso", "authDomain": "wear-by-weather.firebaseapp.com", "databaseURL": "https://wear-by-weather.firebaseio.com", "storageBucket": "wear-by-weather.appspot.com", "serviceAccount": "wear-by-weather.json" } self.fir = Firebase(config) self.minus_temperature = [ "1-3", "4-6", "7-9", "10-12", "13-15", "16-18", "19-21", "22-24", "25-27", "28-30" ] self.plus_temperature = ["0-5", "6-11", "12-17", "18-23", "24-30"] self.styles = [ "Casual", "JeanStyle", "SportStyle", "OfficialStyle", "BeachStyle" ] self.skies = [ "Rain", "Snow", "Clouds", "Thunderstorm", "Mist, Fog", "Clear", "Drizzle" ] self.body_weights = [ "1stDegreeObesity", "2ndDegreeObesity", "3rdDegreeObesity", "BodyMassDeficiency", "NormalBodyWeight", "Overweight", "Underweight" ] self.create_paths_minus() self.create_paths_plus()
def runForTerm(term, current_time): last_year = (datetime.datetime.now() - timedelta(days=550)) twitter_counts_to_save = {} while last_year.strftime('%Y-%m-%d') < current_time: print(last_year.strftime('%Y-%m-%d')) while True: try: r = requests.get("https://cdeservice.mybluemix.net:443/api/v1/messages/count?q=" + term + "%20posted%3A" + last_year.strftime('%Y-%m-%d') + "%2C" + last_year.strftime('%Y-%m-%d'), auth=('667dedc9-0e40-4860-abe9-55011697cd3d', 'Pxl3qyvFAH')) parsed_json = json.loads(r.content) if parsed_json == None: last_year = last_year + timedelta(days=1) continue twitter_counts_to_save[last_year.strftime('%Y-%m-%d')] = long(parsed_json['search']['results']) last_year = last_year + timedelta(days=1) break except: print("Download Error") f = Firebase('https://sv2.firebaseio.com/tweets/' + term) while True: try: f.update(twitter_counts_to_save) break except: print ("Upload error...trying again!")
def tracking(): result = json.loads(request.data) tracking_id = result['result']['parameters']['tracking_no'] status = get_tracking_all(tracking_id) if type(status) is list: for s in status: if 'Kerry' in s['name']: status = get_tracking_by_courier(s['link']) break else: status = None if status == None or status == 1: message = { 'speech': u'เค้าขอโทษ เค้าหาไม่เจอเลย รหัสผิดรึเปล่า หรือว่าเป็นเจ้าที่เค้าไม่รู้จัก? ขอโทษน้าา', 'displayText': u'เค้าขอโทษ เค้าหาไม่เจอเลย รหัสผิดรึเปล่า หรือว่าเป็นเจ้าที่เค้าไม่รู้จัก? ขอโทษน้าา' } elif status == 0: message = { 'speech': u'พัสดุอยู่ในสถานะ Pending นะครับ ไว้มาเช็คใหม่น้าา', 'displayText': u'พัสดุอยู่ในสถานะ Pending นะครับ ไว้มาเช็คใหม่น้าา' } else: if status['tag'] == "Delivered": message = { 'speech': u"พัสดุถึง " + status['place'] + u" แล้ว ตอน " + status['date'] + u" | " + status['time'], 'displayText': u"พัสดุถึง " + status['place'] + u" แล้ว ตอน " + status['date'] + u" | " + status['time'] } else: user = Firebase('https://bott-a9c49.firebaseio.com/users/' + fb_id) user.set({choose_track['link'].split('/')[-1]: {'tag': status['tag'],'created_at':str(datetime.datetime.now())}}) message = { 'speech': u'สถานะ: ' + status['tag_th'] + u' ที่ ' + status['place'] + u" ตอน " + status['date'] + u" | " + status['time'], 'displayText': u'สถานะ: ' + status['tag_th'] + u' ที่ ' + status['place'] + u" ตอน " + status['date'] + u" | " + status['time'] } return jsonify(message)
def upload(status): f = Firebase('https://amber-fire-5569.firebaseio.com/tweets') payload = {} payload['body'] = status['text'] payload['geo'] = status['geo'] payload['date'] = status['created_at'] print payload f.push(payload)
def order(): name = request.args.get('first name') food = request.args.get('my_meal') firebase_food = Firebase( 'https://bott-a9c49.firebaseio.com/lukkiddd/hbot/foods') firebase_food.push({"name": name, "food": food}) messages = {"messages": [{"text": u"เรียบร้อย"}]} return jsonify(messages)
def schedule(self, file_path): track = Firebase(FIREBASE_URL + "tracks/") track_data = {} track_data["url"] = file_path.replace(os.path.join(os.getcwd(), "jukebox"), "") track_data["offset"] = self.play_time(file_path) track.post(track_data)
def aboutus(request): firebase = Firebase(config) db = firebase.database() x = db.child("About Us").get() output = { 'value': x, } return render(request, "about-us.html", output)
def plot_line(obj, **kwargs): df = Firebase().get(obj).head( kwargs.get('num_rows') )[[kwargs.get('index')] + kwargs.get('lines')] if not isinstance(obj, pd.DataFrame) else obj.head( kwargs.get('num_rows'))[[kwargs.get('index')] + kwargs.get('lines')] df.index = df[kwargs.get('index')] return df
def __init__(self, auth, structure_id, device_id): self.device_id = device_id self.structure_id = structure_id self.auth = auth self.fb_target_temp = Firebase( "https://developer-api.nest.com/devices/thermostats/" + device_id + "/target_temperature_f", auth_token=auth ) self.fb_away = Firebase("https://developer-api.nest.com/structures/" + structure_id + "/away", auth_token=auth)
def get_votos_senador(codigo): #r = requests.get('https://maisbr.firebaseio.com/senadores/' + codigo + '/votos.json') #senadores_dict = r.json() f = Firebase(FBURL + '/senadores/' + codigo + '/votos') senadores_dict = f.get() return senadores_dict
def firebase_check(self): config = { "apiKey": "AIzaSyAl0sJD8bl30gnWH9juh6pywzOzsuzSdso", "authDomain": "wear-by-weather.firebaseapp.com", "databaseURL": "https://wear-by-weather.firebaseio.com", "storageBucket": "wear-by-weather.appspot.com" } fir = Firebase(config) lis = fir.storage().child("Men/NormalBodyWeight/Casual/1/details")
def fazer_login(email: str, senha: str) -> list: '''Tenta faze login usando o firebase''' firebase = Firebase(config) auth = firebase.auth() try: user = auth.sign_in_with_email_and_password(email, senha) return [user, 200] except: return [404]
def send_data(msg, path): from firebase import Firebase try: fbase = Firebase(path) fbase.push(msg) except Exception as e: print("FireBase: can not send the data to the server:" + str(e)) print("FireBase: not uploading") return "exception"
def createUsersDatabase(): auth_payload = {"uid": "bhptnfQoq1eEytRBbjjGDrv40oC2"} token = create_token("neftLmN0eBpzsRLAasLcer70wt6KqM6OZmoHKgFd", auth_payload) fire = Firebase("https://roofpik-948d0.firebaseio.com/users/data/", auth_token=token) users_all = fire.get() for i in users_all: createUserJSON(i)
def updateOnCloud(): if checkNetwork(): try: firebase = Firebase(config) db = firebase.database() db.update(data) print("Data Pushed") except: print("Firebase Error")
def __init__(self): self.config = { "apiKey": keys['firebase_api_key'], "authDomain": keys['firebase_auth_domain'], "databaseURL": keys['firebase_address'], "storageBucket": keys['firebase_storage_bucket'] } self.firebase = Firebase(self.config) self.conn = self.firebase.database()
def updateProjectFeatures(id): fire = Firebase("https://friendlychat-1d26c.firebaseio.com/protectedResidential/9999/projects/-KLLdC7joRUmOsT11Efp") temp = fire.get() # projects_all = fire.get() # print json.dumps(temp, indent = 4) price_range,size_range = price_size_range({"-KLLdC7joRUmOsT11Efp" : temp}) # print price_range, size_range updated_features = all_features_mapping(getProjectDataDoc(id), getProjectFeaturesDoc(id), price_range, size_range) es.update(index = 'projects', doc_type = 'features', id = id, body = {"doc" : updated_features})
def setting_sale(request): if (request.method == 'POST'): filepath = request.FILES.getlist('imgname') firebase = Firebase(config) storage = firebase.storage() for i in range(len(filepath)): storage.child("setting/Sale Page/sale.jpg").put(filepath[i]) return redirect("/setting.html")
def __init__(self): with open('firebase_config.json', 'r') as file: config = json.loads(file.read()) firebase = Firebase(config) auth = firebase.auth() user = auth.sign_in_with_email_and_password( os.environ['FIREBASE_EMAIL'], os.environ['FIREBASE_PWD']) self.auth_token = user['idToken'] self.db = firebase.database() self._tags = None
def get_dict_nomes_senadores(): # Retorna lista com nomes de todos os senadores salvos no DB f = Firebase(FBURL + '/senadores') dados = f.get() dict_nomes = {} for key, val in dados.iteritems(): dict_nomes[key] = val['NomeParlamentar'] return dict_nomes
def createProjectsDatabase(): fire = Firebase("https://friendlychat-1d26c.firebaseio.com/protectedResidential/9999/projects/-KLLdC7joRUmOsT11Efp/") i = '-KLLdC7joRUmOsT11Efp' temp = fire.get() # projects_all = fire.get() # for i in projects_all: # createProjectDataIndex(i, projects_all[i]) createProjectDataIndex(i, temp ) createProjectFeaturesIndex(i) updateProjectFeatures(i)
def get_votacoes_senador(codigo, params): # Salva votações do senador no banco de dados # !!! Se a matéria foi votada mais de uma vez (em diferentes tramitações), somente um voto é guardado # |_ isso depende de qual for colocado por último no XML (elaborar rotina para ordenar por data!) # @params: JSON com as seguintes opções: # sigla: (opcional) sigla da matéria - retorna apenas as matérias da sigla informada. # numero: (opcional) número da matéria - retorna apenas as matérias do número informado. # ano: (opcional) ano da matéria - retorna apenas as matérias do ano informado # tramitacao: (opcional) (S ou N) - retorna apenas as matérias que estão tramitando (S) ou apenas as que não estão (N). Se não for informado, retorna ambas. if params == {}: params = {'ano':'2016', 'sigla':'PEC'} tree = af.votacoes_senador(codigo, params) votacoes_tree = tree.findall('.//Votacao') # Inicialização com possíveis valores de votação votos_dict = { 'Sim' : {}, 'Nao' : {}, 'PNRV' : {}, 'MIS' : {}, 'LS' : {}, 'LL' : {}, 'Outro' : {} } for vot in votacoes_tree: voto = vot.find('.//DescricaoVoto').text # Testes "frágeis" para adaptar nome das keys, os tipos são somente esses. Primeiro caracter somente para fugir de probs. de codificiação (unicode). Arrumar futuramente! if voto[:1] == 'S' : voto = 'Sim' elif voto[:1] == 'N' : voto = 'Nao' elif voto[:1] == 'M' : voto = 'MIS' elif voto[:1] == 'P' : voto = 'PNRV' elif voto[:2] == 'LS' : voto = 'LS' elif voto[:2] == 'LL' : voto = 'LL' else: voto = 'Outro' cod_materia = vot.find('.//CodigoMateria').text print cod_materia, voto votos_dict[voto][cod_materia] = {} votos_dict[voto][cod_materia]['DescricaoVoto'] = vot.find('.//DescricaoVoto').text votos_dict[voto][cod_materia]['DescricaoVotacao'] = vot.find('.//DescricaoVotacao').text votos_dict[voto][cod_materia]['DescricaoResultado'] = vot.find('.//DescricaoResultado').text votos_dict[voto][cod_materia]['AnoMateria'] = vot.find('.//AnoMateria').text votos_dict[voto][cod_materia]['SiglaSubtipoMateria'] = vot.find('.//SiglaSubtipoMateria').text # Salva no Firebase (teste com atualização 1 a 1) for key, val in votos_dict.iteritems(): for k, v in val.iteritems(): url = '/senadores/' + codigo + '/votos/' + key + '/' + k f = Firebase(FBURL + url) f.patch(votos_dict[key][k])
def add_activity(d): """Add an activity to the stream. """ info = get_auth_info(None, None, admin=True) url = '%s/activities/' % (info['config']['firebase_url'], ) activities = Firebase(url, auth_token=info['auth_token']) response = activities.push(d) if not isinstance(response, dict): # Not on python2.6. response = response() print "Actitity added, FB Response", response
def __init__(self): super(TestApp, self).__init__() self.rfidReader = RFIDReader(handler_function=self.handler) self.firebase = Firebase(config) self.cleanInfoEvent = None self.screen_manager = ScreenManager(transition=NoTransition()) self.home_screen = HomeScreen(name='home') self.viewer_screen = ViewerScreen(name='viewer', firebase=self.firebase) self.screen_manager.add_widget(self.home_screen) self.screen_manager.add_widget(self.viewer_screen)
def get_nest(request): # Virtual DEvice #f=Firebase('https://developer-api.nest.com/devices/thermostats/N96fw5MnBnmwH4ZBZVOgvMwgbVqewXOS',auth_token="c.9tKvASa4R9fG9hx8kFb9QeUMzxo5OalPNFY9YswzKzENRKn51hNdnx6ctVVjQgRUiCbumqTgFZtWnBDtJFzXLFM8QgdlwtRjWtB3rgfDog5juDNHXdpON9XtNyzulgjMJnPYIbgS74bQ8cUc") # ACL Device f = Firebase( 'https://developer-api.nest.com/devices/thermostats/Q3Vcf1OhcRbUfcweDwMdCkNGApfAG1NY', auth_token= "c.Q2DQ3IxfJwtrqg6vMRDjQHx4DBF30BoAwv8kOmV5wSCsTmFPTZR8gLxURcomK3tvWgvJAzpCFNfnZt7b56Va1YkxUaGwpgOXjBpX1gg7vPUj6ayinv8DCGSIzsx5Klz58xRVEtaS1ZBVlTyG" ) rst = f.get() #hum = str(rst.get('humidity')) return HttpResponse(json.dumps(rst))
def _process_overall(self, spider): host = spider.get_origin_host() fire = Firebase('%s/reports/%s/%s' % (self.fire_host, host, datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S'))) origin_hash = url_hash(host) cursor = self.db.cursor() query = """ SELECT COUNT(1) AS pages , AVG(p.response_time) AS avg_response_time , AVG(p.response_time + al.total_response_time) AS avg_total_response_time , AVG(LENGTH(p.body)) AS avg_page_size , AVG(LENGTH(p.body) + al.total_size) AS avg_total_page_size , SUM(p.lint_critical) AS total_lint_critical , SUM(p.lint_error) AS total_lint_error , SUM(p.lint_warn) AS total_lint_warn , SUM(p.lint_info) AS total_lint_info , AVG(al.internal_assets) AS avg_internal_assets , AVG(al.external_assets) AS avg_external_assets , AVG(al.image_assets) AS avg_image_assets , AVG(al.script_assets) AS avg_script_assets , AVG(al.total_size) AS avg_asset_weight FROM page p , (SELECT from_url_hash AS url_hash , SUM(response_time) AS total_response_time , AVG(response_time) AS avg_response_time , SUM(size) AS total_size , AVG(size) AS avg_size , SUM(IF(external=1,0,1)) AS internal_assets , SUM(IF(external=1,1,0)) AS external_assets , SUM(IF(asset_type='image',1,0)) AS image_assets , SUM(IF(asset_type='script',1,0)) AS script_assets , SUM(IF(asset_type='stylesheet',1,0)) AS style_assets FROM links l LEFT JOIN asset a ON l.to_url_hash = a.url_hash GROUP BY l.from_url_hash) al WHERE p.request_method = 'GET' AND p.url_hash = al.url_hash AND p.origin_hash = %s """ cursor.execute(query, [origin_hash]) res = cursor.fetchone() for k, v in res.iteritems(): if isinstance(v, decimal.Decimal): res[k] = float(v) fire.update(res)
def authenticate(): fb = Firebase('https://hack-in.firebaseio.com/users') form = FormLogin() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None and user.verify_pass(form.password.data): login_user(user, form.remember_me.data) rfb = fb.push({'user_id': user.username, 'email': user.email}) return redirect(request.args.get('next') or url_for('main.home')) flash('Invalid username or password.') return render_template('authentication/login.html', form=form, session=session)
def translate(): if not request.json: abort(400) else: req = request.json if not 'chatId' in req or not 'for' in req or not 'message' in req: abort(400) else: try: gs = goslate.Goslate() chatObj = Firebase('https://vivid-inferno-6896.firebaseio.com/' + req['chatId']) language1 = chatObj.child("language1").get() language2 = chatObj.child("language2").get() translatedText = "" if req['for'] == 1: print language1 # translatedText = gs.translate(req['message'], language1) r = requests.post(microsoftAuthUrl, data=payload) resJSON = r.json() accessToken = resJSON["access_token"] translationParams = {"text":req['message'], "from":language2, "to":language1} translationUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?" + urllib.urlencode(translationParams) translationHeader = {'Authorization': "Bearer " + accessToken} r = requests.get(translationUrl, headers=translationHeader) print r.status_code print r.text elif req['for'] == 2: # translatedText = gs.translate(req['message'], language2) print "Stuff" print translatedText # direct_To = firebase.get('https://vivid-inferno-6896.firebaseio.com/123456789/123456789/messages/0/for') # print direct_To # messageList = Firebase('https://vivid-inferno-6896.firebaseio.com/123456789/123456789/messages') # print "Before" + messageList # language1 = Firebase('https://vivid-inferno-6896.firebaseio.com/123456789/123456789/language1').get() # print language1 # language2 = Firebase('https://vivid-inferno-6896.firebaseio.com/123456789/123456789/language2').get() # print language2 # if gs.detect(inputMessage) == language1: #Confirms language of input text # outputMessage = gs.translate(inputMessage,language2); # #Add condition which changes value of "for" field based on last "for" value in previous message dictionary # messageList.post({"text":"outputMessage","for":"1","read":"false"}) # print "After" + messageList except Exception, err: print traceback.format_exc()
def run(self): while True: start_time = time.time() cur_speed = Firebase(FIREBASE_URL + "cur_speed/") bpm = cur_speed.get()['bpm'] dbpm = cur_speed.get()['dbpm'] cur_speed.update({'bpm':bpm+dbpm, 'dbpm':0}) (vo, bg) = self.get_next(); mashup = self.render_next(vo, bg, bpm, dbpm); self.schedule(mashup) time.sleep(max(MIX_DURATION - CROSSFADE_TIME - int(time.time() - start_time), 0))
def get_point_firebase(): points = {} # initiate the connexion to Firebase token = create_token(FIREBASE_SECRET , AUTH_PAYLOAD) firebase_project = FIREBASE_PROJECT + '/' + ROOT_OBJECT + '.json' firebase = Firebase(firebase_project, token) results = firebase.get() if results is not None: for result in results: points[results[result]['id']] = { 'key': result, 'data': results[result] } return points
def store_data(): #db=sqlite3.connect('database.db'); #curs = db.cursor() #curs.execute('CREATE TABLE Shelter(user TEXT, email TEXT, phone TEXT, comment TEXT, duration TEXT );') f = Firebase('https://shelterx2.firebaseio.com/data') t_usr=request.form['usr'] t_email=request.form['email'] t_phone=request.form['phone'] t_description=request.form['description'] t_duration=request.form['duration'] t_country=request.form['country'] t_city=request.form['city'] f.push({'name':t_usr,'email':t_email,'phone':t_phone,'description':t_description,'duration':t_duration, 'country':t_country, 'city':t_city}) #curs.execute('INSERT INTO Shelter (user,email,phone,comment,duration) VALUES (?,?,?,?,?);',(t_usr,t_email,t_phone,t_comment,t_duration)) #db.commit() #db.close() return redirect('/')
class Thermostat: def __init__(self, auth, structure_id, device_id): self.device_id = device_id self.structure_id = structure_id self.auth = auth self.fb_target_temp = Firebase( "https://developer-api.nest.com/devices/thermostats/" + device_id + "/target_temperature_f", auth_token=auth ) self.fb_away = Firebase("https://developer-api.nest.com/structures/" + structure_id + "/away", auth_token=auth) # Method to return the target temp def getTargetTemp(self): return self.fb_target_temp.get() # Method to return the away status def getAwayStatus(self): return self.fb_away.get()
def process(file): f = open(file, 'rU') reader = csv.DictReader(f, fieldnames=fieldnames) i = 0 rows = list(reader) l = len(rows) for row in rows: id = row['CAMIS'] inspect_loc = "https://eat-here-or-there.firebaseio.com/nyc/restaurants/{0}/inspections".format(id) fire_inspection = Firebase(inspect_loc, token) del row['CAMIS'] try: fire_inspection.post(row) except (UnicodeDecodeError, requests.exceptions.ConnectionError) as e: print row i += 1 printProgress(i, l, prefix = 'Progress:', suffix = 'Complete', barLength = 50)
class FirebaseInteraction: def __init__(self): self.tweet_firebase = Firebase('https://vmx.firebaseio.com/tweets') self.report_firebase = Firebase('https://vmx.firebaseio.com/reports') def post_new_tweet(self, tweet_id, title, tweet, location_title, lat, lon, username): if location_title != '': response = self.tweet_firebase.push({'username': username, 'tweet_id': tweet_id, 'title': title, 'text': tweet, 'location': {'title': location_title, 'lat': lat, 'lon': lon}}) else: response = self.tweet_firebase.push({'username': username, 'tweet_id': tweet_id, 'title': title, 'text': tweet}) print response def post_new_report(self, tweet_id, title, tweet, location_title, lat, lon, username): if location_title != '': response = self.report_firebase.push({'username': username, 'tweet_id': tweet_id, 'title': title, 'text': tweet, 'location': {'title': location_title, 'lat': lat, 'lon': lon}}) else: response = self.report_firebase.push({'username': username, 'tweet_id': tweet_id, 'title': title, 'text': tweet}) print response
def main(): """ """ root_reference = Firebase('https://burning-fire-8681.firebaseio.com') this_event_ref = root_reference.child('zE0001') R1_ref = this_event_ref.child('R1') R2_ref = this_event_ref.child('R2') R3_ref = this_event_ref.child('R3') for eun in range(1,11,1): for R_ref in [R1_ref, R2_ref, R3_ref]: eu_ref = R_ref.child("eu_{}".format(get_euns(eun))) eu_ref.put( { "n": random.randint(0,15), "mn": random.randint(0,15), "my": random.randint(0,15), "y": random.randint(0,15) } )
def get_next(self): name_to_id = {} songs = Firebase(FIREBASE_URL + "songs").get() vo_ids = [] bg_ids = [] for song_id in songs: song = songs[song_id] name_to_id[song['song_name'].lower().replace(" ", "")] = song_id if song["file_type"] == "instrumental": bg_ids += [song["id"]] else: vo_ids += [song["id"]] vo_id = vo_ids[int(len(vo_ids) * random.random())] bg_id = bg_ids[int(len(bg_ids) * random.random())] next_song = Firebase(FIREBASE_URL + "next_song/") song_name = next_song.get()['song_name'] if next_song.get()['must_play'] and song_name in name_to_id: if next_song.get()['song_type'] == 'vocal': vo_id = name_to_id[song_name] else: bg_id = name_to_id[song_name] next_song.update({'must_play':0, 'song_name':-1}) vo_clip = self.slice_song(vo_id) bg_clip = self.slice_song(bg_id) return (vo_clip, bg_clip)
def update_groups(): gruposRef = Firebase(FIREBASE_BASE_URL+'groups') gruposRef.delete(); results = json.load(urllib.urlopen(API_BASE_URL+"group/")) for grupo in results['objects']: grupoRef = Firebase(FIREBASE_BASE_URL+'groups/'+str(grupo['id'])) grupoRef.set(grupo)
def __init__(self): try: with open(secrets_filename, "r") as f: data = f.read() except: err = "Error processing {} - make sure to fill in {}!".format(secrets_filename, secrets_filename) with open(secrets_filename, "w") as f: f.write(document) raise Exception(err) try: conf = yaml.load(data) self.firebase_url = conf["firebase_url"] self.secret = conf["secret"] self.data_bucket = conf["data_bucket"] except: raise Exception("Error parsing {}!".format(secrets_filename)) if self.firebase_url is None or self.secret is None: raise Exception("Error parsing {} - not all fields have been filled in!".format(secrets_filename)) auth_payload = {"uid": "1", "auth_data": "foo", "other_auth_data": "bar"} token = create_token(self.secret, auth_payload) self._client = Firebase(self.firebase_url + self.data_bucket, auth_token=token)
def pushFirefox(state): f = Firebase('https://project1.firebaseio.com/state') r = f.set(state)