Example #1
0
from firebase import firebase
firebase = firebase.FirebaseApplication('https://<example-app-id>firebaseio.com/', None)

data =  {
          'Name': 'Hawlette Packard',
          'RollNo': '4su15cs023',
          'Percentage': 85.02,
          'Phone': 7451231412
          }
result = firebase.post('/<example-app-id>-<app-number>/Student', data)
print(result)
Example #2
0
''' this code is to detect the red color paste on the thymio and write it in the firebase'''
# some part of the code is from sendtex
import cv2
import numpy as np
from firebase import firebase

url = "https://dw-1d-8f3a9.firebaseio.com/" # URL to Firebase database
token = "PdWOHUtcScXODzmm8b3pSoFY78dxZQXVSpynXx1n" # unique token used for authentication
firebase = firebase.FirebaseApplication(url, token)

cap = cv2.VideoCapture(1) # this output the video capture from the web camera

''' a simple state machine '''
state = 'car_no' # the initial state is there is no_car

while(1): # the camera keeps updating new information
    _, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # this is using opencv to convert the normal BGR 
    
    lower_red = np.array([30,150,50]) # the upper bond of red color get it by trying and error
    upper_red = np.array([255,255,180]) # the lower bond of red color 255 is the biggest and zero is the smallest. (255,255,255) is bright and (0,0,0) is dark
    
    mask = cv2.inRange(hsv, lower_red, upper_red) # if the pixel is the 'red color range'
    res = cv2.bitwise_and(frame,frame, mask= mask) # then we add the mask to the frame
   
    # state machine    
    # if there is no car, the camera continueslly checking whether there is car, if there is the state change to 'car_yes' and upload the inp1 into the firebase for thymio
    if state == 'car_no':
        threshold = len(np.nonzero(res)[0]) # this output how many red pixel there is
        # if there is no red object, the output should from 0 to 5, if there is a red object, the value is above 1000
        # we change the threshold value to 800 here to see whether there is any car
		score += 1
		scoreRange[3] = 1

	if result['temperatura'] > 39:
		score += 3
		scoreRange[0] = 3
	elif result['temperatura'] >= 38:
		score += 1
		scoreRange[0] = 1
	elif result['temperatura'] < 35:
		score += 2
		scoreRange[0] = 2		

	return score

fb = firebase.FirebaseApplication('https://babysanca-4f129.firebaseio.com', None)
place = '/info'
device = '/dev/ttyUSB0'
data = {}

while True:
	while True:
		CPF = getCPF()
		if len(str(CPF)) != 11:
			print("Insira um CPF valido.")
		else:
			break

	data = dataTreatment(CPF, place)
	#getFirebase(place)
Example #4
0
import json
import math
from collections import defaultdict

from flask_restful import Api, Resource
import firebase_admin
from flask import Flask, request, jsonify, redirect, render_template, make_response
from firebase_admin import credentials, firestore, initialize_app
from firebase import firebase

app = Flask(__name__)
api = Api(app)
firebase = firebase.FirebaseApplication(
    "https://login-auth-42458-default-rtdb.firebaseio.com/", None)

# Ignore the config dict its useless
config = {
    "apiKey": "AIzaSyCOyYtjVoddu_v0wuE90AlUO5ZYvIwe1iI",
    "authDomain": "login-auth-42458.firebaseapp.com",
    "projectId": "login-auth-42458",
    "storageBucket": "login-auth-42458.appspot.com",
    "messagingSenderId": "642686191238",
    "appId": "1:642686191238:web:74ba8c7a94671f0d447307",
    "measurementId": "G-9L1VJ04JS7"
}
# ------------------------------

#Initialize trails DB

cred1 = credentials.Certificate('firebase-sdk.json')
app2 = firebase_admin.initialize_app(cred1)
Example #5
0
# -*- coding: utf-8 -*-

from firebase import firebase
import sys
import random
import subprocess
import os.path
import requests

from datetime import datetime
random.seed()

from PyQt4.QtGui import *
from PyQt4.QtCore import *

fb = firebase.FirebaseApplication('https://os-lab.firebaseio.com/')


class Example(QWidget):
    def resource_path(self, relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")

        return os.path.join(base_path, relative_path)

    def closeEvent(self, event):
        result = QMessageBox.question(self, "Confirm Exit...",
Example #6
0
from firebase import firebase

url = 'https://chiouapp01-74bde.firebaseio.com'
fb = firebase.FirebaseApplication(url, None)
dict1 = fb.post('/test', {"name": "David"})
print(dict1["name"])  # -KTMkuwiNbE18j9zpzko
Example #7
0
from flask import Flask
from jinja2 import Environment, PackageLoader, select_autoescape
import json
from firebase import firebase

app = Flask(__name__)
firebase = firebase.FirebaseApplication(
    "https://my-project-1511258558859-default-rtdb.europe-west1.firebasedatabase.app/",
    None)

env = Environment(loader=PackageLoader(__name__, 'templates'),
                  autoescape=select_autoescape(['html', 'xml']))


@app.route('/')
def index():
    data = firebase.get("my-project-1511258558859-default-rtdb")
    template = env.get_template('posts.html')
    res = json.loads(data)
    return template.render(data=res)


@app.route('/post/<int:post_id>/')
def user_profile(post_id):
    data = firebase.get("my-project-1511258558859-default-rtdb", post_id)
    template = env.get_template('single.html')
    return template.render(item=json.loads(data))


if __name__ == "__main__":
    app.run(debug=True)
def delete_user(user):
    firebase = fb.FirebaseApplication(database.firebase_link, None)
    delete_result = firebase.delete("/NEW", user)
    return delete_result
Example #9
0
from firebase import firebase
from flask import Flask, request, jsonify, make_response

firebase = firebase.FirebaseApplication(
    'https://loginreact-f8c1d.firebaseio.com')
result = firebase.get('/estado/login', None)
print(result)
Example #10
0
    sql = ''' INSERT INTO Log(CustomerName,MacAdress,InsertDate)
              VALUES(?,?,?) '''
    cur = conn.cursor()
    cur.execute(sql, bl_log_data)

def insert_anon_log(bl_log_data):
    sql = ''' INSERT INTO Log_Anonymus(Mac,InsertedDate)
              VALUES(?,?) '''
    cur = conn.cursor()
    cur.execute(sql, bl_log_data)




#firebase
firebase = firebase.FirebaseApplication(
    'https://beacon-5d432.firebaseio.com/', None)  # database
customers = firebase.get('/', None)  # tum macler
for k, v in customers.iteritems():
    print k, v


#bluetooth
dev_id = 0  # varsayilan bl modulu
try:
	sock = bluez.hci_open_dev(dev_id)
	print "ble thread started"

except:
	print "ERROR BLUETOOTH MODULE NOT FOUND!"
    	sys.exit(1)
def push_to_new(user, url, category):
    firebase = fb.FirebaseApplication(database.firebase_link, None)
    data = {'url': url, 'category': category}
    response = firebase.post("NEW/" + user, data)
    return response
Example #12
0
import pyrebase
from firebase import firebase

firebase = firebase.FirebaseApplication('https://djangoplaces.firebaseio.com/',
                                        None)
data = {'Name': 'Vivek', 'RollNo': 1, 'Percentage': 76.02}
result = firebase.post('/djangoplaces/Places', data)
print(result)
        JSON_FILE_NAME = 'TESTING.json'

        od = collections.OrderedDict(sorted(final_dict_new.items()))

        with open(JSON_FILE_NAME, 'w') as g:
            json.dump(od, g)

        print("DONE!")

        # ## Upload processed data into Firebase

        # In[ ]:

        from firebase import firebase

        firebase = firebase.FirebaseApplication(
            'https://studentplanner-1712e.firebaseio.com', None)
        new_user = '******'.format(idx)

        idx += 1

        destination_path = '/Module/{}/Assessments'.format(
            real_wanted_file_name)

        result = firebase.put(destination_path, new_user, final_dict_new)
        print(result)
        print("REALTIME DATABASE UPDATED!!!")

        # ## Remove audio file from local/Firebase storage

        # In[ ]:
Example #14
0
from tkinter import *
import os
from chat_firebase import Rocket_Chat, receive
from firebase import firebase

clear=lambda:os.system('cls')
Logins = []
import PIL
FIREBASE_URL = "https://rocket-messenger.firebaseio.com/"
fb = firebase.FirebaseApplication(FIREBASE_URL,  None)

from tkinter.colorchooser import *


##  CLASSE CRIAR CHAT  ##


class Chat(Rocket_Chat) :
    def __init__(self, Logins,assunto):
        self.assunto=assunto
        self.Chat = Tk()
        self.Chat.title("Rocket Chat")
        self.Chat.geometry("500x600+40+40")
        self.Chat['bg'] = 'gray'
        user = Rocket_Chat(Logins[0], Logins[1])
        user.post(assunto)
                ## Widgets ##
        self.opcoes = Frame(self.Chat, bg= "light blue")
        self.opcoes.pack(fill=BOTH)
        
        self.input_user = StringVar()
Example #15
0
    StickerSendMessage,
    TemplateSendMessage,

    ButtonsTemplate,
    ConfirmTemplate,
    CarouselTemplate, 
    CarouselColumn,

    PostbackTemplateAction, 
    MessageTemplateAction,
    URITemplateAction,
)

app = Flask(__name__)

firebase = firebase.FirebaseApplication('https://hogu-line-bot.firebaseio.com', None)     

# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
port = os.getenv('PORT', None);

if channel_secret is None:
    print('Specify LINE_CHANNEL_SECRET as environment variable.')
    sys.exit(1)
if channel_access_token is None:
    print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
    sys.exit(1)

line_bot_api = LineBotApi(channel_access_token)
parser = WebhookParser(channel_secret)
Example #16
0
w.writelines([item for item in lines[:-1]])
w.close()

# This finishes writing the remainder of the .json file
mlh_json = open("mlh.json", "a")
mlh_json.write("\t\t}")
mlh_json.write("\n]")
mlh_json.close()

with open('mlh.json') as json_data:
    data = json.load(json_data)

app = Flask(__name__)
CORS(app)

firebase = firebase.FirebaseApplication('https://hackspot12.firebaseio.com',
                                        None)


@app.route('/', methods=['POST', 'GET'])
def index():

    result = firebase.post('/hackathons', data)  #end of argument

    for key, value in result.items():
        print(key, value)

    return value


@app.route('/get/', methods=['POST', 'GET'])
def getHack():
from gtts import gTTS
import serial
import smtplib, ssl
import RPi.GPIO as GPIO
from firebase import firebase
import datetime
from time import sleep
import speech_recognition as sr
import facerecognition
GPIO.setmode(GPIO.BOARD)
Motor1A = 16
Motor1B = 18
#Motor1E = 22
GPIO.setup(Motor1A, GPIO.OUT)
GPIO.setup(Motor1B, GPIO.OUT)
FBConn = firebase.FirebaseApplication(
    'https://home-database-96e2f.firebaseio.com/', None)
time = datetime.datetime.now()
flagr = 0
flags = 0


#function for text to speech
def TextToSpeech(text):
    mytext = text
    myobj = gTTS(text=mytext, lang='en', slow=False)
    myobj.save("text.mp3")
    os.system("mpg321 text.mp3")
    os.system("sudo rm -rf ~/Desktop/project/opencv/facerecg/text.mp3")
    return

Example #18
0
import serial
from firebase import firebase
arduino = serial.Serial('/dev/ttyACM0',9600);
firebase = firebase.FirebaseApplication('https://yes-iot.firebaseio.com')
while(1):
    result = firebase.get('/User1/D1', None)
    arduino.write(result.encode())
Example #19
0
import pandas as pd
import numpy as np
# Load Training data
numbers = []
from firebase import firebase
# firebase = firebase.FirebaseApplication('https://tempdeepblue.firebaseio.com/', None)
firebase = firebase.FirebaseApplication(
    'https://svsfirebaseproject-6cc9f.firebaseio.com/', None)
one = firebase.get('/message', 'Symptom1')
two = firebase.get('/message', 'Symptom2')
three = firebase.get('/message', 'Symptom3')
four = firebase.get('/message', 'Symptom4')
five = firebase.get('/message', 'Symptom5')
n = 2
for i in range(n):

    df = pd.read_csv('data/clean/Training.csv')

    df.head()

    X = df.iloc[:, :-1]
    y = df['prognosis']

    # Train, Test split
    from sklearn.model_selection import train_test_split

    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y,
                                                        test_size=0.3,
                                                        random_state=20)
import pandas as pd
import numpy as np
import json
from scipy.stats import poisson
import statsmodels.api as sm
import statsmodels.formula.api as smf
import firebase_admin
from firebase_admin import firestore
from firebase import firebase

firebase = firebase.FirebaseApplication(
    'https://commoncents-190e4.firebaseio.com')

#dataset = pd.read_csv("http://www.football-data.co.uk/mmz4281/1819/E1.csv")
dataset = pd.read_csv("http://www.football-data.co.uk/mmz4281/1819/E0.csv")
#dataset = pd.read_csv('data.csv', index_col=0)
dataset = dataset[['HomeTeam', 'AwayTeam', 'FTHG', 'FTAG']]
dataset = dataset.rename(columns={'FTHG': 'HomeGoals', 'FTAG': 'AwayGoals'})
mean = dataset.mean()
print(mean)

#BPL Teams
Teams = [
    "Man City", "Liverpool", "Tottenham", "Man United", "Arsenal", "Chelsea",
    "Wolves", "Watford", "Everton", "West Ham", "Bournemouth", "Leicester",
    "Crystal Palace", "Brighton", "Burnley", "Newcastle", "Cardiff",
    "Southampton", "Fulham", "Huddersfield"
]
#Teams = ["Norwich", "Sheffield United", "Leeds", "West Brom", "Middlesbrough", "Bristol City",
#         "Derby", "Birmingham", "Nott'm Forest", "Preston", "Hull", "Sheffield Weds",
#        "Aston Villa", "Swansea", "Blackburn", "Brentford", "QPR",
Example #21
0
from tkinter import *
from tkinter import messagebox
import pymysql
from firebase import firebase

firebase = firebase.FirebaseApplication(
    "https://fastgate-d2d06.firebaseio.com/", None)


def exit():
    window.destroy()


def click():
    oname = t1.get()
    mob = t2.get()
    block = t3.get()
    block = block.upper()
    flat_no = t4.get()
    uid = t5.get()

    data = {
        'owner_name': oname,
        'mob': mob,
        'block': block,
        'flat_no': flat_no,
        'uid': uid
    }

    try:
Example #22
0
import tkinter as tk
import time 
from Pedidos import cPedido
from firebase import firebase
firebase = firebase.FirebaseApplication('https://smartserver.firebaseio.com/')



class cInicio:
    def __init__(self):
        self.window=tk.Tk()
        self.window.title ('Inicio') 

    def iniciar(self):
        self.frame = tk.Frame(self.window, width=500, height=500, bd=175)
        self.frame.pack()
        
        self.botaomapa = tk.Button(self.frame,text ='Mapa',height=8 ,width= 20 ,bd=20,padx=20)
        self.botaomapa.pack(side=tk.LEFT)
        self.botaomapa.configure(command = mesa.iniciar)
        
        self.botaocozinha = tk.Button(self.frame,text ='Cozinha',height=8 ,width=20 ,bd=20,padx=20)
        self.botaocozinha.pack(side=tk.RIGHT)
        self.botaocozinha.configure(command = cozinha.iniciar)

        self.window.mainloop()

class cCozinha:
    def __init__(self):
        self.variavel = 1
Example #23
0
from geopy.distance import great_circle
from firebase_admin import credentials
from firebase_admin import db
import datetime

t = datetime.datetime.now()
t = t.strftime("%a %b %d %H:%M:%S %Y")
send_url = "http://api.ipstack.com/check?access_key=6a554c654da3f5d634ab99a2bedae475"
geo_req = requests.get(send_url)
geo_json = json.loads(geo_req.text)
latitude = geo_json['latitude']
longitude = geo_json['longitude']
city = geo_json['city']

# open database
firebase = firebase.FirebaseApplication('https://close-draw.firebaseio.com', None)

#TODO: Check if time is more than 24 hours


#what to add to each database
data = {
    'Longitude':longitude,
    'Latitude':latitude,
    'Time':t,
    'Picture Location':'PUTGOOGLECLOUDSPACE',
    'Caption':'HEREWITHMYGIRLS',
    'Likes':'Count',
    'Dislikes':0
}
#where to POST IT (CHANGE '/testUser' to something more better)
Example #24
0
#ml
from firebase import firebase
import pandas as pd
import numpy as np
import json
import time
from datetime import timedelta
from sklearn.neighbors import DistanceMetric, BallTree
from sklearn.cluster import DBSCAN
firebase_db = firebase.FirebaseApplication('your-firebase-endpoint',
                                           authentication=None)

# Constants
EARTH_RAD = 6371.0
EPS_CARTESIAN = 0.2 / EARTH_RAD
MINPTS_CARTESIAN = 10
EPS_RAD = 30 / (24 * 60.0) * (2 * np.pi)
MINTPTS_RAD = 10
RADIUS_DEFAULT = 0.5 / EARTH_RAD  # 500m


def invert(x):
    return abs(int(x))


def getBitesDF():
    # Retrieve records from FB
    result = firebase_db.get('/bites/', None)

    # Extract timestamp
    df_timestamp = pd.DataFrame(result.keys(), columns=['timestamp'])
from time import sleep
import datetime
from firebase import firebase
import urllib2, urllib, httplib
import json
import os
from functools import partial
import time;

firebase = firebase.FirebaseApplication('ใส่ URL Firebase ที่นี่', None) # URL Firebase
def update_Status():
    stat = "Good"   # สถานะแสดงอินเทอร์เน็ต
    firebase.put('Network 001','status',{'status':stat})
    print('Update Status')
def sent_Location():
    link = "ใส่ URL Google Location ที่นี่" # Google Location
    firebase.put('Network 001','location',{'link':link})
    print('Sent Location')
def update_timestamp(): 
    ts = time.time()    # อัพเดทค่าเวลา หมายเหตุ ค่าเวลาขึ้นอยู่กับเครื่อง Raspberry pi3 ที่ใช้ปัจจุบัน
    ts = int(ts)*1000
    print(ts)
    firebase.put('Network 001','timestamp',{'now':ts}) #ค่าเวลาที่ส่งขึ้นไปยัง firebase

while True:
    try:
        sent_Location()
        update_timestamp()
        update_Status()
    except:
        print("Error Network, Can't sent data to Firebase.")
Example #26
0
    if attrs:
        recipeData['Course'] = attrs.get('course')
        recipeData['Cuisine'] = attrs.get('cuisine')
    recipeData ['Name'] = data.get('name')

    for nutrition in data['nutritionEstimates']:
        if nutrition['attribute'] == "ENERC_KCAL":
            nutritionData['Calories'] = str(nutrition['value']) + " " + nutrition['unit']['pluralAbbreviation']
        if nutrition['attribute'] == "SUGAR":
            nutritionData['Sugar'] = str(nutrition['value']) + " " + nutrition['unit']['pluralAbbreviation']
        if nutrition['attribute'] == "CHOCDF":
            nutritionData['Carbohydrates'] = str(nutrition['value']) + " " + nutrition['unit']['pluralAbbreviation']
    recipeData['Nutrients'] = nutritionData
    recipeData['allowedDiet'] = 'Ovo vegetarian'
    recipeData['allowedAllergy'] = 'Soy-Free'
    recipeData['sugarLevel'] = 'High'
    #recipeData['allowedIngredient'] = 'pork'
         
    print(recipeData ['Name'])
    
    result = firebase.post('/foodData', recipeData)
    print("RESULT IS:")
    print(result)
    

firebase = firebase.FirebaseApplication('https://zenhealth-215f6.firebaseio.com/', authentication=None)


getRecipeData()

Example #27
0
from firebase import firebase

max_id = ''

#target hashtag explore page
# base_url = "https://www.instagram.com/explore/tags/travel/?__a=1"
base_url = "https://www.instagram.com/explore/tags/travel/?__a=1&max_id=QVFBNm5wYVhGWXNQRjljZGxJaWNoRHpyUUd4S3ZwYkJaMGRvdWk0dG1sc3g3Mm9UV004NTFyenNOVWl6T2phTWxVQUgxdmpXZVdRb0lFYmZtVk85bUY2QQ=="
#header for scraping
headers = {
    "user-agent":
    "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36 Edg/87.0.664.57",
    "cookie": "sessionid = 45781691217%3Ao2vnqwsRftb4Dx%3A9"
}

#setup firebase
firebase = firebase.FirebaseApplication(
    'https://ig-scraper-d10a3-default-rtdb.firebaseio.com', None)

#target list of keywords
Target = [
    '#adventurous', '#backpacking', '#budget', '#chillout', '#cruise',
    '#culturevulture', '#exotic', '#foodie', '#golocal', '#nature',
    '#luxurious', '#photography', '#rail', '#train', '#roadtrip', '#romantic',
    '#shopaholic', '#spontaneous', '#sporty', '#thrilling', '#vegan',
    '#youngwildandfree', '#ars', '#nightlife', '#biking', '#cycling',
    '#cafehopping', '#camping', '#extremesports', '#festivals', '#flying',
    '#gliding', '#hiking', '#historical', '#hotspring', '#museums',
    '#galleries', '#outdooradventure', '#scubadiving', '#shopping',
    '#sightseeing', '#snorkelling', '#snowsports', '#skiing', '#snowboarding',
    '#spa', '#themeparks', '#winetasting', '#zoo', '#aquariums', '#sunshine',
    '#beach', '#sports', '#motorcycling', '#DIY', '#chillout'
]
Example #28
0
 def __init__(self, searchData):
     self.baseURL = 'https://contentsquaresearch.firebaseio.com/'
     self.searchData = searchData
     self.instance = firebase.FirebaseApplication(self.baseURL, None)
Example #29
0
from firebase import firebase

firebase=firebase.FirebaseApplication('https://ep01-acf3b.firebaseio.com/', None)

lojas=firebase.get('/Lojas', None)

if lojas == None:
    lojas={}

opcoes = ["\nControle do estoque", "0 - Voltar ao controle de lojas",\
        "1 - Adicionar item", "2 - Remover item",\
        "3 - Alterar item (Quantidade ou Valor)", "4 - Imprimir estoque",\
        "5 - Imprimir saldo total do estoque"]


controle_de_lojas = ["\nControle de loja", "0 - Sair", "1 - Adicionar loja", \
                    "2 - Editar estoque da loja", "3 - Remover loja", "4 - Imprimir lojas cadastradas"]

for i in controle_de_lojas:
    print(i)
opcao = input("O que deseja fazer? ")


while opcao != "0":       
        
        
    if opcao == "1":
        loja = input("Escreva o nome da loja: ")
        if loja in lojas:
            print("Loja já cadastrada.")
            for i in controle_de_lojas:
Example #30
0
def tempToDeg(temp):
	if temp in range(0,20): return "40"
	if temp in range(20,40): return "80"
	if temp in range(40,60): return "120"
	return "160"






myDevice='d001'



firebase = firebase.FirebaseApplication('https://regadera-c338c.firebaseio.com/', None)


ser = serial.Serial(
    port='\\\\.\\COM4',
    baudrate=9600,
    timeout=3
)
if ser.isOpen():
    ser.close()
ser.open()
ser.isOpen()


#constantly check if a user activates the shower
while(True):