Exemplo n.º 1
0
def newUser():
    fname = request.form['stu-fname']
    lname = request.form['stu-lname']
    email = request.form['stu-email']
    phone = request.form['stu-phone']
    psw = request.form['stu-psw']
    age = request.form['stu-age']
    skills = request.form['stu-skills']
    try:
        user = firebase.auth().create_user_with_email_and_password(email, psw)
        print("auth success")
    except:
        print('error with create user', email, psw)
        return redirect('')

    uid = user['localId']
    db = firebase.database()
    newData = {
        "fname": fname,
        "lname": lname,
        "email": email,
        "phone": phone,
        "psw": psw,
        "age": age,
        "skills": skills,
        "jobList": None
    }
    print(newData)
    db.child("userdb").child(uid).set(newData)
    print("created")
    if 'user' not in session:
        session['user'] = uid
    return redirect(url_for('user_profile'))
Exemplo n.º 2
0
def newCompany():
    cname = request.form['cmp-cname']
    email = request.form['cmp-email']
    phone = request.form['cmp-phone']
    psw = request.form['cmp-psw']
    industry = request.form['cmp-industry']
    try:
        user = firebase.auth().create_user_with_email_and_password(email, psw)
    except:
        print('error with create user')
        return redirect('')
    uid = user['localId']
    db = firebase.database()
    newData = {
        "cname": cname,
        "email": email,
        "phone": phone,
        "psw": psw,
        "industry": industry,
        "jobList": None
    }
    db.child("companydb").child(uid).set(newData)
    if 'user' not in session:
        session['user'] = uid
    return redirect(url_for('employer_profile'))
Exemplo n.º 3
0
def discardLast():
    """ Discards the last search storing its status """
    last = getCurrentSearch()
    if last:
        new_key_name = datetime.now().strftime("%y%m%d_%H%M%S")
        db.child("searchs/old/" + new_key_name).set(last)
        db.child("searchs/current").delete()
Exemplo n.º 4
0
def main(detect_pots, update_time):

    thermal = ThermalMeasure()
    stove = Stove()
    pot_detector = PotDetector()
    burner_on = BurnerOn()

    while (True):

        for burner in [
                stove.upper_left, stove.lower_left, stove.lower_right,
                stove.upper_right
        ]:
            db.child("burners").child(burner.name).set(vars(burner))

        image_path = capture()

        with open(image_path, mode="rb") as frame:
            if (detect_pots == True):
                pot_detector.update(frame, stove)

        thermal.update(stove)
        burner_on.update(stove)

        if (update_time != None):
            iteration_time = args.update_time
        else:
            iteration_time = ITERATION_TIME

        time.sleep(iteration_time)
Exemplo n.º 5
0
def modificarOferta():
    add_oferta = forms.AgregarOferta(request.form)
    if request.method == 'POST':
        db.child(add_oferta.nombre.data).update(
            {'HOferta': add_oferta.oferta.data})
        return render_template("gestion-oferta.html")
    return render_template("modificar-oferta.html", form=add_oferta)
Exemplo n.º 6
0
def actualizar(id, cantidad):
    #Ingresa los datos del formulario en la variable  data
    cantidad1 = float(db.child(id).child("DCantidad").get().val())
    cantidad2 = float(cantidad)
    nuevacantidad = cantidad1 - cantidad2
    #Inserta en la Base de Datos
    db.child(id).update({"DCantidad": str(nuevacantidad)})
Exemplo n.º 7
0
def salida(id):
    productos = db.get()
    add_product = forms.AgregarProducto(request.form)
    #Ingresa los datos del formulario en la variable  data
    if request.method == 'POST':
        cantidad1 = float(db.child(id).child("DCantidad").get().val())
        cantidad2 = float(add_product.cantidad.data)
        nuevacantidad = cantidad1 - cantidad2
        data = {
            'ANombre': add_product.nombre.data,
            'BCodigo': add_product.codigo.data,
            'CPrecio': add_product.precio.data,
            'DCantidad': str(nuevacantidad),
            'EDia': add_product.dia_vencimiento.data,
            'FMes': add_product.mes_vencimiento.data,
            'GAño': add_product.ano_vencimiento.data,
        }
        #Inserta en la Base de Datos
        db.child(add_product.nombre.data).set(data)
        return redirect(url_for('gestionProductos'))

    return render_template("control-entrada.html",
                           form=add_product,
                           id=id,
                           db=db,
                           data=productos)
Exemplo n.º 8
0
def tofb():
    df1 = crawling()
    df2 = final_dreams()
    df3 = browser2()
    df4 = data2

    mid = pd.concat([df1, df2, df3, df4])
    mid_df = mid.reset_index(drop=True)
    mid_df['title'] = mid_df['title'].str.strip()
    fin_df = mid_df.drop_duplicates(['title'], keep='first')
    fin = fin_df.reset_index(drop=True)

    postdata = fin.to_dict(orient="index")
    config = {
        "apiKey": "AIzaSyDIo8bt7OrCX6KYaxplvUauQdaehcjUo_0",
        "authDomain": "activity-crawling.firebaseapp.com",
        "databaseURL": "https://activity-crawling-default-rtdb.firebaseio.com",
        "projectId": "activity-crawling",
        "storageBucket": "activity-crawling.appspot.com",
        "messagingSenderId": "608978503357",
        "appId": "1:608978503357:web:374a269b8fa1a64888d9d4"
    }
    firebase = pyrebase.initialize_app(config)
    db = firebase.database()
    db.child().update(postdata)
Exemplo n.º 9
0
def initial_info(firebase, email, salary, total_tax, take_home_monthly,
                 prov_code):

    # replace '.' with dot, so firebase doesnt throw error

    email = email.replace(".", 'dot')

    db = firebase.database()
    data = {
        "Salary": float(salary),
        "Prov_code": prov_code,
        "Total_Tax": float(total_tax),
        "Take_home_income": take_home_monthly,
        "Expenses": {
            "Rent": PrelimInfo.expenses['rent'],
            "Internet": PrelimInfo.expenses['internet'],
            "Phone": PrelimInfo.expenses['phone'],
            "Groceries": PrelimInfo.expenses['groceries'],
            "Commute": PrelimInfo.expenses['commute'],
            "Utility": PrelimInfo.expenses['utility'],
            "Entertainment": PrelimInfo.expenses['entertainment'],
            "Hobbies": PrelimInfo.expenses['hobbies']
        }
    }

    db.child("Users").child(email).child("Financial Profile").set(data)

    return
Exemplo n.º 10
0
def add_santri(key_wali):

     data = request.json

     uid_santri = uuid.uuid4().hex
     data_santri = {
            "id_santri":uid_santri,
            "id_wali":key_wali,
            "no_induk":data["no_induk"],
            'nama_lengkap' : data['nama_lengkap'],
            "jenis_kelamin" : data['jenis_kelamin'],
            "alamat" : data['alamat'],
            "tgl_lahir" : data['tgl_lahir'],
            "url_photo" : data['url_photo'],
            "email" : data['email'],
            "telp" : data['telp'],
            "password" : data['password'],
            "rayon" : data['rayon'],
            "kelas" : data['kelas'],
            "kamar" : data['kamar']
     }

    
     db.child("santri").child(uid_santri).set(data_santri)
     return "Behasil di add"    
Exemplo n.º 11
0
def agregarElemento():
    add_product = forms.AgregarProducto(request.form)
    if request.method == 'POST':
        db.child("Compra").update(
            {add_product.nombre.data: add_product.cantidad.data})
        return render_template("menu-venta.html",
                               form=add_product,
                               db=db.child("Compra").get(),
                               dab=db)
    return render_template("menu-venta.html", form=add_product)
Exemplo n.º 12
0
def member_practice():
    if not flask.request.is_json:
        return flask.abort(400)
    data = flask.request.json

    discord_data = refresh_discord_token_and_get_user_data()
    if not discord_data:
        return forbidden()

    discord_id = discord_data["id"]
    discord_username = discord_data["username"]
    if "avatar" in discord_data:
        discord_avatar = "https://cdn.discordapp.com/avatars/{}/{}".format(
            discord_id, discord_data["avatar"])
    else:
        discord_avatar = None

    player_name = data.get("player", None)
    if not player_name:
        player_name = discord_username

    practice_races = [
        race for race in RACES if race in data.get("practiceRaces", [])
    ]
    timezone = data.get("timezone", None)
    week_time_ranges = {}
    for day in DAYS_OF_THE_WEEK:
        key = "timeRanges" + day
        if key not in data:
            week_time_ranges[key] = []

        week_time_ranges[key] = [{
            **({
                "from": timeRange["from"]
            } if "from" in timeRange else {}),
            **({
                "to": timeRange["to"]
            } if "to" in timeRange else {}),
        } for timeRange in data[key]]

    update = {
        "practiceRaces": practice_races,
        **({
            "timezone": timezone
        } if timezone else {}),
        "player": player_name,
        **({
            "avatar": discord_avatar
        } if discord_avatar else {}),
        **week_time_ranges,
    }
    db = firebase_admin.db.reference()
    db.child("members").child(discord_id).child("practice").update(update)

    return {}
Exemplo n.º 13
0
def Get_rating(xp1content):
    users = db.child("players").child(xp1content).get()
    xmu = db.child("players").child(xp1content).child('mu').get()
    xsigma = db.child("players").child(xp1content).child('sigma').get()
    x = users.val()
    sigma = xsigma.val()
    mu = xmu.val()

    d,y = float(mu),float(sigma)
    r1 = Rating(d,y)
    return r1
Exemplo n.º 14
0
def basic():
    if request.method == 'POST':
        if request.form['submit'] == 'add':

            name = request.form['name']
            todo = db.child("Events Table").get()
            to = todo.val()
            return render_template('index.html', t=to.values())
        elif request.form['submit'] == 'delete':
            db.child("todo").remove()
        return render_template('index.html')
    return render_template('index.html')
Exemplo n.º 15
0
def update_customer(db, name):
    #finds the customer and returns parent and child in tuple
    customer = find_customer(db, name)
    changing = True
    while changing == True:
        change = str.replace(input("What would you like to change?: "), " ",
                             "_")
        avalue = input("To what value?")
        db.child("Customer").child(customer[0]).update({change: avalue})

        if input("Anymore changes on this Customer(y/n)? ") == "Y":
            changing = True
        else:
            changing = False
Exemplo n.º 16
0
def getlen():
    try:
        global posts_len
        company = db.child(news_names).get()
        posts_len = len(company)
        if posts_len >= 200:
            db.child(news_names).delete()
            posts_len = 0
            os.remove(save_news)
            f = open(save_news, "w")
            f.close()
    except Exception as er:
        errlog(er, "글 수 가져오기 에러")
        pass
Exemplo n.º 17
0
def edit(id):
    if request.method == "POST":

        title = request.form["title"]
        content = request.form["content"]

        post = {"title": title, "content": content, "author": session["email"]}

        #update the post
        db.child("Posts").child(id).update(post)
        return redirect("/post/" + id)

    orderedDict = db.child("Posts").order_by_key().equal_to(id).limit_to_first(
        1).get()
    return render_template("edit.html", data=orderedDict)
Exemplo n.º 18
0
def home():

    if request.method == 'POST':
        email = request.form['signInEmail']
        password = request.form['signInPassword']

        global client
        global NICK

        users = db.child("users").get()
        if users.val() != "none":
            for user in users.each():
                userList.append(user.val())

            for user in userList:
                newUser = user.get("username")
                newUserMail = user.get("email")

                if newUserMail == email:
                    NICK = newUser
            client = Client(NICK)
            print(NICK)

        try:
            auth.sign_in_with_email_and_password(email, password)
            # user_id = auth.get_account_info(user['idToken'])
            # session['usr'] = user_id
            # print(session['usr'])
            return render_template("chat.html")
        except:
            unseccessful = "please check your e-mail or password"
            return render_template("index.html", unmessage=unseccessful)

    return render_template("index.html")
Exemplo n.º 19
0
def add_user_to_db(firebase, email, name):

    # replace '.' with dot, so firebase doesnt throw error
    replace = "dot"
    #email = replace.join(email.rsplit('.', 1))

    email = email.replace(".", 'dot')

    db = firebase.database()
    data = {"Name": name, "Phone": '123-456-7890'}

    # add User to the data base under 'Users'
    db.child("Users").child(email).set(data)

    #print("Returning from ")

    return
Exemplo n.º 20
0
def index():
    allposts = db.child("Posts").get()
    #print(allposts.val(), file=sys.stderr)
    if allposts.val() == None:
        #print(posts, file=sys.stderr)
        return render_template("index.html")
    else:
        return render_template("index.html", posts=allposts)
Exemplo n.º 21
0
def validarcodigo(x):
    producto = db.get()
    for item in producto:
        if (db.child(item.key()).child("BCodigo").get()).val() == x:
            x = x + 1
            print(x)
            return validarcodigo(x)

    return x
Exemplo n.º 22
0
def agregarProducto():
    #Guarda los datos ingresados en el formulario
    add_product = forms.AgregarProducto(request.form)

    #Ingresa los datos del formulario en la variable  data
    if request.method == 'POST':
        data = {
            'ANombre': add_product.nombre.data,
            'BCodigo': validarcodigo(add_product.codigo.data),
            'CPrecio': add_product.precio.data,
            'DCantidad': add_product.cantidad.data,
            'EDia': add_product.dia_vencimiento.data,
            'FMes': add_product.mes_vencimiento.data,
            'GAño': add_product.ano_vencimiento.data,
        }
        #Inserta en la Base de Datos
        db.child(add_product.nombre.data).set(data)
        return render_template("agregar-producto.html", form=add_product)
    return render_template("agregar-producto.html", form=add_product)
Exemplo n.º 23
0
def connect_firebase_pyrebase():
    # add a way to encrypt those, I'm a starter myself and don't know how
    username = "******"
    password = "******"

    firebase = pyrebase.initialize_app(configfb)
    auth = firebase.auth()

    user = auth.sign_in_with_email_and_password(username, password)

    #user['idToken']
    # At pyrebase's git the author said the token expires every 1 hour, so it's needed to refresh it
    user = auth.refresh(user['refreshToken'])

    #set database
    db = firebase.database()
    values = db.child('SensorDataSet').get()
    data = pd.DataFrame(values.val())
    #print (dataX[0:6].T)
    npdata = np.array(data.values).T

    print(npdata.shape)
    print(npdata[0:5, :])

    # new_dataX = []
    # for i in range(0, npdataX.shape[0] , timestep_size):
    #     if i+timestep_size < npdataX.shape[0]-1 :
    #         new_dataX.append(npdataX[i:i+timestep_size, :].flatten())
    # new_dataX = np.array(new_dataX)

    # # dataNum = new_dataX.shape[0]
    # # new_dataY = npdataY[0:dataNum,:]

    # dataNum = npdataY.shape[0]
    # new_dataY = npdataY
    # new_dataX = new_dataX[0:dataNum,:]
    # print (new_dataX.shape)
    # print (new_dataY.shape)

    # raw_data = np.hstack((new_dataY, new_dataX))
    # print (raw_data.shape)
    # print (raw_data[0:5,:])

    # trainNum = int(dataNum*train_p)
    # trainX = new_dataX[0:trainNum,:]
    # trainY = new_dataY[0:trainNum,:]
    # testX = new_dataX[trainNum:dataNum,:]
    # testY = new_dataY[trainNum:dataNum,:]

    # print (trainX.shape)
    # print (trainY.shape)
    # print (testX.shape)
    # print (testY.shape)

    return npdata
Exemplo n.º 24
0
def create():

    if request.method == "POST":
        #get the request data
        title = request.form["title"]
        content = request.form["content"]

        post = {"title": title, "content": content, "author": session["email"]}

        try:
            #print(title, content, file=sys.stderr)

            #push the post object to the database
            db.child("Posts").push(post)
            return redirect("/")
        except:
            return render_template("create.html",
                                   message="Something wrong happened")

    return render_template("create.html")
Exemplo n.º 25
0
def add_customer(db, fname, lname, address, city, state, zip_code,
                 phone_number, status):
    # Get last customer name

    last_cust = db.child("Customer").order_by_key().limit_to_last(1).get()
    last_key = last_cust.keys()
    s = "%s" % last_key
    new_index = "customer" + str(int(s.split("customer")[1].split("'")[0]) + 1)
    #Adds a new customer
    db.child("Customer").update({
        new_index: {
            "First_Name": fname,
            "Last_Name": lname,
            "Street_Address": address,
            "City": city,
            "State": state,
            "Zip_Code": zip_code,
            "Phone_Number": phone_number,
            "Status": status,
        }
    })
Exemplo n.º 26
0
def update_firebase():
    print(ser.readline())
    ser.flushInput()
    lines = ser.readline().strip()
    values = lines.decode('ascii').split(',')
    if len(values) == 5:
        water_level, humidity, temperature, lux, water_temp = [
            float(s) for s in values
        ]
        print(ser)
        data = {
            "humidity": humidity,
            "temperature": temperature,
            "water level": water_level,
            "lux": lux,
            "water temp": water_temp
        }
        db.child("sensor").update(data)
    settings = db.child("settings").get()
    for setting in settings.each():
        ser.write(json.dumps(settings.val()).encode())
Exemplo n.º 27
0
def signup():
    if request.method == 'POST':
        email = request.form['signUpEmail']
        password = request.form['signUpPassword']
        username = request.form['signUpUsername']

        global client
        global NICK
        users = db.child("users").get()
        if users.val() != "none":
            for user in users.each():
                userList.append(user.val())

            unseccessful = "Username has already taken"
            forgot_message = "E-mail has already taken"

            for user in userList:
                newUser = user.get("username")
                newUserMail = user.get("email")

                if newUserMail == email:
                    return render_template("signup.html",
                                           forgot_message=forgot_message)
                if newUser == username:
                    return render_template("signup.html",
                                           unmessage=unseccessful)

            NICK = username
            client = Client(NICK)
            print(NICK)
        db.child("users").push({"email": email, "username": username})
        try:
            auth.create_user_with_email_and_password(email, password)
        except:
            unseccessful = "Make sure you enter it completely"
            if username == "" or email == "" or password == "":
                return render_template("signup.html", unmessage=unseccessful)

        return render_template("chat.html")
    return render_template("signup.html")
Exemplo n.º 28
0
def getJourney(profil):

    weight = 0
    if (profil == "Strong"):
        weight = 2000
    elif (profil == "Skinny"):
        weight = 500
    elif (profil == "Medium"):
        weight = 1000

    req = flask.request.json
    orders = []
    for current in ORDERS.val().items():
        orders.append(current)

    # get best order list
    order_list = defineBestCombinaison(orders, weight)

    # get ordered products of current orders
    products_keys = getProducts(order_list)

    products_content = []
    for current in products_keys:
        products_content.append(
            dict(db.child('products').child(current).get(0).val()))
    sorted(products_content, key=itemgetter('place'))
    journeys_tmp = db.child('journeys').get()
    count_id = 0
    for i in journeys_tmp.val().items():
        count_id = count_id + 1
    # create and push journey
    journey = {
        "orders": [item[0] for item in order_list],
        "ordered_products": products_content,
        "done": 0,
        "id": count_id + 1
    }
    db.child('journeys').push(journey)
    print(journey)
    return jsonify(journey)
Exemplo n.º 29
0
def editar(id):
    productos = db.get()
    add_product = forms.AgregarProducto(request.form)
    #Ingresa los datos del formulario en la variable  data
    if request.method == 'POST':
        data = {
            'ANombre': add_product.nombre.data,
            'BCodigo': validarcodigo(add_product.codigo.data),
            'CPrecio': add_product.precio.data,
            'DCantidad': add_product.cantidad.data,
            'EDia': add_product.dia_vencimiento.data,
            'FMes': add_product.mes_vencimiento.data,
            'GAño': add_product.ano_vencimiento.data,
        }
        #Inserta en la Base de Datos
        db.child(add_product.nombre.data).set(data)
        return redirect(url_for('gestionProductos'))

    return render_template("editar-producto.html",
                           form=add_product,
                           id=id,
                           db=db,
                           data=productos)
Exemplo n.º 30
0
def newListing():
    title = request.form['jl-title']
    totalHours = request.form['jl-totalHours']
    wage = request.form['jl-wage']
    startDate = request.form['jl-startDate']
    shift = request.form['jl-shifts']
    description = request.form['jl-description']
    companyId = session['user']

    db = firebase.database()
    newData = {
        "companyId": companyId,
        "title": title,
        "wage": wage,
        "totalHours": totalHours,
        "startDate": startDate,
        "shift": shift,
        "description": description,
        "taken": 0
    }
    newId = db.child("jobsdb").push(newData)
    db.child("companydb").child(companyId).child('jobList').push(newId)
    return redirect(url_for('employer_profile'))