Пример #1
0
def login():
    credentials = firebase.get('/credentials', None)
    if request.method == 'POST':
        temp = -1
        username = request.form['uname']
        password = request.form['pass']
        for i in credentials:
            if username in credentials[i][
                    'EmailId'] and password in credentials[i]['Password']:
                temp += 1
                print("Yes")
                session['logged_in'] = True
                global active
                active = username
                if active == '*****@*****.**':  ##admin
                    applications = firebase.get('/application', None)
                    return render_template('home_admin.html',
                                           u=active,
                                           cutoff=cutoff,
                                           form=applications)
                else:
                    print("logged")
                    return redirect("/")

        if temp == -1:
            return render_template('login.html', msg="Invalid Credentials")
    else:
        return render_template('login.html')
Пример #2
0
def application():
    global active
    cutoff = firebase.get('/Cutoff', None)
    credentials = firebase.get('/credentials', None)
    if active != None:
        for i in credentials:
            if active in credentials[i]['EmailId']:
                idno = i
                break
        applications = firebase.get('/application', None)
        if applications != None:
            for i in applications:
                if i == idno:
                    return render_template('congrats.html')
        if request.method == 'POST':
            username = request.form['studname']
            perc12 = request.form['studPerc']
            branch = request.form.get("branch", None)
            db.child("application").child(idno).set({
                "EmailId": active,
                "Name": username,
                "12thPercentage": perc12,
                "BranchChosen": branch
            })
            return render_template('congrats.html')
        return render_template('application.html',
                               emailId=active,
                               stream=cutoff)
    return render_template('login.html')
Пример #3
0
def getData(studentid, item):  #gets the attributs of users from firebase
    if type(item) is list:  #allows multiple values to be retrieved as a tuple
        outp = []
        for items in item:
            outp.append(firebase.get('/Accounts/%s/%s' % (studentid, items)))
        return tuple(outp)
    else:
        return firebase.get('/Accounts/%s/%s' % (studentid, item))
	def search_by_zip(self):
		self.search_result = []
		self.user = self.manager.get_screen('profile').user
		user_search = self.ids['search_box'].text
		for dispenser in firebase.get('/dispensers'):
			if user_search.isdigit():
				if firebase.get('/dispensers/'+dispenser)['location']==int(user_search):
					self.search_result.append(dispenser)
		self.display_result()
	def search_by_name(self):
		self.search_result = []
		self.user = self.manager.get_screen('profile').user
		user_search = self.ids['search_box'].text
		for dispenser in firebase.get('/dispensers'):
			if user_search in dispenser:
				if firebase.get('/dispensers/'+dispenser)['accessability']=="public" or self.user in firebase.get('/dispensers/'+dispenser)['accessability']:
					self.search_result.append(dispenser)
		self.display_result()
Пример #6
0
def addStud(d_id):
    #print(d_id)
    db.child("application").child(d_id).update({'Status': 'Accepted'})
    applications = firebase.get('/application', None)
    cutoff = firebase.get('/Cutoff', None)
    return render_template('home_admin.html',
                           u=active,
                           cutoff=cutoff,
                           form=applications)
Пример #7
0
def getState(machine,
             item):  #gets the attributes of the machines from firebase
    if type(item) is list:  #allows multiple values to be retrieved as a tuple
        outp = []
        for items in item:
            outp.append(
                firebase.get('/washingmachine/%d/%s' % (machine, items)))
        return tuple(outp)
    else:
        return firebase.get('/washingmachine/%d/%s' % (machine, item))
 def search_by_zip(self):
     self.search_result = []
     self.user = self.manager.get_screen('profile').user
     user_search = self.ids['search_box'].text
     for dispenser in firebase.get('/dispensers'):
         if user_search.isdigit():
             if firebase.get('/dispensers/' +
                             dispenser)['location'] == int(user_search):
                 self.search_result.append(dispenser)
     self.display_result()
 def search_by_name(self):
     self.search_result = []
     self.user = self.manager.get_screen('profile').user
     user_search = self.ids['search_box'].text
     for dispenser in firebase.get('/dispensers'):
         if user_search in dispenser:
             if firebase.get(
                     '/dispensers/' + dispenser
             )['accessability'] == "public" or self.user in firebase.get(
                     '/dispensers/' + dispenser)['accessability']:
                 self.search_result.append(dispenser)
     self.display_result()
	def log_in(self):
		self.ids['status'].text=''
		entered_name = self.ids['username'].text.strip()
		entered_password = self.ids['password'].text
		if entered_name not in firebase.get('/users'):
			self.ids['status'].text = "User doesn't exists!"
		else:
			if entered_password == firebase.get('/users')[entered_name]['password']:
				self.manager.get_screen('profile').user = entered_name
				self.manager.get_screen('profile').display_data()
				self.manager.current = 'profile'
			else:
				self.ids['status'].text = 'Password incorrect!'
Пример #11
0
def dashboard():
    cutoff = firebase.get('/Cutoff', None)
    applications = firebase.get('/application', None)
    credentials = firebase.get('/credentials', None)
    global active
    if active == '*****@*****.**':  ##admin
        return render_template('home_admin.html',
                               u=active,
                               cutoff=cutoff,
                               form=applications)
    return render_template('student_dashboard.html',
                           u=active,
                           cid=credentials,
                           form=applications)
 def log_in(self):
     self.ids['status'].text = ''
     entered_name = self.ids['username'].text.strip()
     entered_password = self.ids['password'].text
     if entered_name not in firebase.get('/users'):
         self.ids['status'].text = "User doesn't exists!"
     else:
         if entered_password == firebase.get(
                 '/users')[entered_name]['password']:
             self.manager.get_screen('profile').user = entered_name
             self.manager.get_screen('profile').display_data()
             self.manager.current = 'profile'
         else:
             self.ids['status'].text = 'Password incorrect!'
	def display_badges(self):
		badges = firebase.get('/users/'+self.manager.get_screen('profile').user+'/badges')
		badges.remove("None")
		badges_tag={'add': 'add', 'status':'status', 'log':'log', 'buy':'buy', '5':'5', 'join':'join'}
		if len(badges)==0:
			self.ids['badges_display'].add_widget(BoxLayout())
			self.ids['badges_display'].add_widget(Label(text="You don't have any badge yet!", color=(0,0,0,1)))
			self.ids['badges_display'].add_widget(Label(text="Be more active!", color=(0,0,0,1)))
		else:
			i = 0
			image_box=BoxLayout()
			name_box=BoxLayout()
			while i<len(badges):
				if i%3==0:
					self.ids['badges_display'].add_widget(image_box)
					self.ids['badges_display'].add_widget(name_box)
					for j in xrange(0,3):
						self.ids['badges_display'].add_widget(BoxLayout())
					image_box=BoxLayout()
					name_box=BoxLayout()
				image_box.add_widget(Image(source='./assets/badges/'+badges[i]+'.png', size_hint=(1,4)))
				name_box.add_widget(Label(text="[["+badges_tag[badges[i]]+"]]", color=(0,0,0,1)))
				i+=1
			self.ids['badges_display'].add_widget(image_box)
			self.ids['badges_display'].add_widget(name_box)
Пример #14
0
def searchKeyword(word, filt={}):
    sortedList = []
    data = get("notes") + get("lectures")
    for note in data:
        if ("courseLevel" in filt) and (note["courseLevel"] not in filt["courseLevel"]):
            continue

        if ("school" in filt) and (note["school"] not in filt["school"]):
            continue

        keywords = note["keywords"] #returns an array of keywords
        if word in keywords:
            sortedList.append(note)

    sortedList.sort(reverse = True, key= lambda x: x["relevance"])
    return sortedList
 def display_result(self):
     self.ids['search_result'].clear_widgets()
     for i in xrange(0, 3):
         self.ids['search_result'].add_widget(BoxLayout())
     if len(self.search_result) == 0:
         self.ids['search_result'].add_widget(
             Label(text="Cannot find any dispenser!", color=(0, 0, 0, 1)))
     else:
         for dispenser in self.search_result:
             box = BoxLayout()
             box.add_widget(
                 Label(text=dispenser,
                       size_hint=(0.817, 1),
                       color=(0, 0, 0, 1)))
             add_button = Button(id=dispenser, size_hint=(0.083, 1))
             if dispenser in firebase.get(
                     '/users/' +
                     self.manager.get_screen('profile').user)['dispensers']:
                 add_button.background_normal = './assets/buttons/checked.png'
                 add_button.background_down = './assets/buttons/checked.png'
             else:
                 add_button.background_normal = './assets/buttons/add.png'
                 add_button.background_down = './assets/buttons/add.png'
                 add_button.bind(on_press=self.add_the_dispenser)
             box.add_widget(add_button)
             box.add_widget(Label(size_hint=(0.1, 1)))
             self.ids['search_result'].add_widget(box)
 def submit(self):
     new_password = self.ids['new_password'].text
     old_password = self.ids['old_password'].text
     confirm = self.ids['confirm'].text
     password = firebase.get('/users/' +
                             self.manager.get_screen('profile').user +
                             '/password')
     if old_password == password:
         if len(new_password) > 7:
             if new_password == confirm:
                 firebase.put(
                     '/', '/users/' +
                     self.manager.get_screen('profile').user + '/password',
                     new_password)
                 self.ids['new_password'].text = ""
                 self.ids['old_password'].text = ""
                 self.ids['confirm'].text = ""
                 self.ids['status'].text = "Password updated!"
             else:
                 self.ids['status'].text = "New password mismatched!"
         else:
             self.ids['status'].text = "New password too short!"
             print len(new_password)
     else:
         self.ids['status'].text = "Incorrect password!"
 def sign_me_up(self):
     entered_username = self.ids['username'].text.strip()
     entered_email = self.ids['email'].text.strip()
     entered_password = self.ids['password'].text.strip()
     confirm_password = self.ids['password_confirm'].text.strip()
     if " " in entered_username or "	" in entered_username:
         self.ids['status'].text = 'Username invalid! Cannot have spaces'
     elif entered_username in firebase.get('/users'):
         self.ids['status'].text = 'Username Taken!'
     elif self.email_availability(entered_email) == False:
         self.ids['status'].text = 'Email has already been signed up!'
     elif len(entered_password) < 7:
         self.ids['status'].text = "Password too short!"
     elif entered_password != confirm_password:
         self.ids['status'].text = 'Password mismatched!'
     else:
         user = {
             'dispensers': ['None'],
             'email': entered_email,
             'password': entered_password,
             'pic_url': 'http://i.imgur.com/VMtRJHG.jpg',
             'badges': ['None']
         }
         firebase.put('/', '/users/' + entered_username, user)
         self.ids['sign_up'].clear_widgets()
         self.ids['sign_up'].add_widget(Label(text="Sign Up Successful!"))
         self.ids['sign_up'].add_widget(
             Label(text="Start contributing to a better world for cats!"))
         self.ids['sign_up'].add_widget(
             Button(text='Go to your profile',
                    color=(0, 0, 0, 1),
                    background_normal='./assets/buttons/long_button.png',
                    background_down='./assets/buttons/long_button_down.png',
                    on_press=self.transfer_data))
Пример #18
0
def register():
    if request.method == 'POST':
        username = request.form['uname']
        password = request.form['pass']  ## DO IT here
        for i in credentials:
            if username in credentials[i]['EmailId']:
                flash('User with this email already exits :/ ')
                return render_template('register.html')
        else:
            lenOfCred = len(credentials)
            userId = "CAMS"
            if lenOfCred <= 9:
                k = "000" + str(lenOfCred)
            elif lenOfCred >= 10 and lenOfCred <= 99:
                k = "00" + str(lenOfCred)
            elif lenOfCred >= 100 and lenOfCred <= 999:
                k = "0" + str(lenOfCred)
            db.child("credentials").child(userId + k).set({
                "EmailId": username,
                "Password": password
            })
            global crendentials
            crendentials = firebase.get('/credentials', None)
            flash('Successfully Registered:) Go ahead and login')
            return render_template('register.html')
    return render_template('register.html')
Пример #19
0
 def refresh(self, value):
     print "REFRESHING"
     self.clr1 = firebase.get('/clr1')
     self.clr2 = firebase.get('/clr2')
     if self.clr1 == 0:
         self.cr1b.disabled = False
         self.cr1b.text = "Book"
     elif self.clr1 == 1:
         self.cr1b.disabled = True
         self.cr1b.text = "Cannot Book \n Room Occupied"
     elif self.clr1 == 2:
         self.cr1b.disabled = True
         self.cr1b.text = "Cannot Book \n Room Already Booked"
     elif self.clr1 == None:
         self.cr1b.disabled = False
         self.clr1 = 0
         self.cr1b.text = "Book"
Пример #20
0
def get_firebase():
	global state
	global vcc
	sleep(1)
	while _on:
		result = firebase.get('/Lamp', None)
		state=result['state']
		vcc = result['vcc']
Пример #21
0
def firebase_get_device_dict(userid):
    url = URL_ROOT + "/devices/%s" % userid
    result = firebase.get(url)
    device_dict = {}
    if isinstance(result, dict):
        for key, value in result.iteritems():
            print key, value
            device_dict[str(key)] = str(value)
            print device_dict
    else:
        print "firebase-get_device_dict: result is not dict:", result
    return device_dict
Пример #22
0
def get_status_all(userid):
    url = URL_ROOT + "/devices/%s" % userid
    print url
    result = firebase.get(url)
    print "result:", result
    if result == None:
        return {}
    else:
        result_removed_uni = ast.literal_eval(json.dumps(result))
        print "result after eval:", result_removed_uni
    #print "yaml:", yaml.safe_load(result)
    return result_removed_uni
Пример #23
0
def firebase_get_device_list(userid):
    url = URL_ROOT + "/devices/%s" % userid
    result = firebase.get(url)
    device_list = []
    if isinstance(result,dict):
        for key, value in result.iteritems():
            print key, value
            device_list.append(str(key))#with remove unicode string
        print device_list
    else:
        print "firebase-get_device_list: result is not dict:",result
    return device_list
Пример #24
0
def get_measurement(m_id):
    """Returns dictionary of measurement attributes for measurement with given unique id m_id

    Returns:
        dict[str:str]: attributes for measurement with given m_id

    Args:
        m_id (str): unique id
    """
    firebase = get_firebase_app()
    attributes = firebase.get(_MEASUREMENTS, m_id)
    return attributes
Пример #25
0
def firebase_get_users_dict(userid):
    url = URL_ROOT + "/users/%s" % userid
    result = firebase.get(url)
    users_dict = {}
    if isinstance(result,dict):
        for key, value in result.iteritems():
            print key, value
            users_dict[str(key)] =str(value)
            print users_dict
    else:
        print "firebase-get_users_dict: result is not dict:",result
    return users_dict
Пример #26
0
def get_status_all(userid):
    url = URL_ROOT + "/devices/%s" % userid
    print url
    result = firebase.get(url)
    print "result:" , result
    if result == None:
        return {}
    else:
        result_removed_uni = ast.literal_eval(json.dumps(result))
        print "result after eval:" , result_removed_uni
    #print "yaml:", yaml.safe_load(result)
    return result_removed_uni
Пример #27
0
def firebase_get_device_list(userid):
    url = URL_ROOT + "/devices/%s" % userid
    result = firebase.get(url)
    device_list = []
    if isinstance(result, dict):
        for key, value in result.iteritems():
            print key, value
            device_list.append(str(key))  #with remove unicode string
        print device_list
    else:
        print "firebase-get_device_list: result is not dict:", result
    return device_list
Пример #28
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = firebase.get('/users/' + form.email.data + '.json')
        if user and check_password_hash(user['password'], form.password.data):
            u = load_user(form.email.data)
            login_user(u)
            flash('Successfully logged in.', 'enchilada!')
            return redirect(request.args.get('next') or url_for('index'))
        flash('Invalid email or password.', 'enchilada :(')
        return redirect(url_for('index'))
    flash('Please enter an and password.', 'enchilada')
    return redirect(url_for('index'))
def launch_request():
    session_attributes = {}

    result = firebase.get(url)

    card_title = 'Patient Pulse Rate is '+result['data']
    speech_output = 'Patient Pulse Rate is '+result['data']
    reprompt_text = 'Patient Pulse Rate is '+result['data']
    should_end_session = True
    return build_response(session_attributes,
                          build_speechlet_response(card_title,
                                                   speech_output, reprompt_text,
                                                   should_end_session))
Пример #30
0
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = firebase.get('/users/' + form.teamname.data + '.json')
        if user and check_password_hash(user['password'], form.password.data):
            u = load_user(form.teamname.data)
            login_user(u)
            flash('Successfully logged in.', 'success')
            return redirect(request.args.get('next') or url_for('index'))
        flash('Invalid team name or password.', 'danger')
        return redirect(url_for('index'))
    flash('Please enter a team name and password.', 'danger')
    return redirect(url_for('index'))
	def place_order(self, instance):
		user = self.manager.get_screen('profile').user
		cred_number = self.cred_number.text
		ccv = self.ccv.text
		name = self.the_name.text
		hp = self.hp_no.text
		orders = firebase.get('/orders')
		the_order = {'user': user, 'creditcard': cred_number, 'ccv': ccv, 'name': name, 'phone': hp}
		orders.append(the_order)
		firebase.put('/', '/orders', orders)
		self.ids['order'].clear_widgets()
		self.ids['order'].add_widget(BoxLayout())
		self.ids['order'].add_widget(Label(text="Thanks for purchasing our product!", color=(0,0,0,1)))
		self.ids['order'].add_widget(Label(text="Please find your receipt in your email", color=(0,0,0,1)))
Пример #32
0
def get_time(userID, i):
    """Called when makeReply is getting washInfo, to get information on time remaining"""
    endTimeList = firebase.get('/Accounts/%s/endtime' % (str(userID)))
    currentTime = time()
    #If endtime is not logged returns error
    if endTimeList == None:
        return None
    else:
        iTime = endTimeList[i]
        diff = iTime - currentTime
        if diff > 0:
            return formatTime(diff)
        else:
            return 0
	def submit(self, instance):
		queries = firebase.get('/queries')
		user = self.manager.get_screen('profile').user
		the_time = time.ctime()
		text = self.query.text
		the_query = {'who': user, "time": the_time, "query": text}
		queries.append(the_query)
		firebase.put('/', '/queries', queries)
		self.ids['box'].clear_widgets()
		self.ids['form'].clear_widgets()
		self.ids['form'].add_widget(Button(text='<< Back',color=(0,0,0,1), background_normal='./assets/buttons/long_button.png', background_down='./assets/buttons/long_button_down.png', on_press=self.back))
		self.ids['form'].add_widget(BoxLayout())
		self.ids['form'].add_widget(BoxLayout())
		self.ids['form'].add_widget(Label(text="Thanks! We'll get back to you asap", color=(0,0,0,1)))
Пример #34
0
def get_machineInfo(machineid):
    """Called when makeReply is getting washInfo, to get information on washing machine"""
    #Gets state of washing machine
    status = firebase.get('/washingmachine/%r/state' % (machineid))
    print "Machine %r status: %r" % (machineid, status)  #for reference
    if status > 0:
        statusStr = 'pooling'
    elif status == -1:
        statusStr = 'washing'
    elif status == -2:
        statusStr = '* ready for collection *'
    else:
        statusStr = 'Machine not in use'
    return status, statusStr
	def generate_screen(self):
		dispenser = firebase.get('/dispensers/'+self.dispenser_name)
		if dispenser['fullness'] == 100:
			self.ids['status_img'].source = './assets/percentage/100.png'
		elif dispenser['fullness'] == 75:
			self.ids['status_img'].source = './assets/percentage/75.png'
		elif dispenser['fullness'] == 50:
			self.ids['status_img'].source = './assets/percentage/50.png'
		elif dispenser['fullness'] == 25:
			self.ids['status_img'].source = './assets/percentage/25.png'
		elif dispenser['fullness'] == 0:
			self.ids['status_img'].source = './assets/percentage/0.png'
		self.ids['dispenser_name'].text = self.dispenser_name
		self.ids['last_fill'].text = 'Last filled at: '+dispenser['last_filled']
 def generate_screen(self):
     dispenser = firebase.get('/dispensers/' + self.dispenser_name)
     if dispenser['fullness'] == 100:
         self.ids['status_img'].source = './assets/percentage/100.png'
     elif dispenser['fullness'] == 75:
         self.ids['status_img'].source = './assets/percentage/75.png'
     elif dispenser['fullness'] == 50:
         self.ids['status_img'].source = './assets/percentage/50.png'
     elif dispenser['fullness'] == 25:
         self.ids['status_img'].source = './assets/percentage/25.png'
     elif dispenser['fullness'] == 0:
         self.ids['status_img'].source = './assets/percentage/0.png'
     self.ids['dispenser_name'].text = self.dispenser_name
     self.ids[
         'last_fill'].text = 'Last filled at: ' + dispenser['last_filled']
Пример #37
0
def checkMachines():
    """Called when periodically by main() to check washing machine states"""
    #Repeats for all 3 Washing Machines (wm)
    for i in range(3):
        #Gets state of wm
        wm = firebase.get('/washingmachine/%s/state' % (str(i + 1)))
        #If wash is ready for collection
        if wm == -2:
            #Gets Users assigned to this wm
            users = firebase.get('/washingmachine/%s/studentid' % (str(i + 1)))
            #For all assgined users
            for j in users:
                #Get their chatID and pmState
                ID = firebase.get('/Accounts/%s/chatID' % (str(j)))
                pmState = firebase.get('/Accounts/%s/pmstate' % (str(j)))
                #If pmState does not exist, add it
                if pmState == None:
                    firebase.put('/Accounts/%s/' % (str(j)), "pmstate", 1)
                    pmState = 0
                #change pmState to 0 after 15mins
                elif pmState < 90 and pmState > 0:
                    pmState += 1
                    firebase.put('/Accounts/%s/' % (str(j)), "pmstate",
                                 pmState)
                else:
                    pmState = 0
                    firebase.put('/Accounts/%s/' % (str(j)), "pmstate",
                                 pmState + 1)
                #If chatID exists and pmState = 0, pm the user
                if ID != None and pmState == 0:
                    #Prints message for our reference
                    print "Messenging user: %r" % (ID)
                    #PMs user
                    reply = "Hello! Your laundry in washing machine %r is now ready for collection!" % (
                        i + 1)
                    bot.sendMessage(ID, reply)
Пример #38
0
def firebase_get_users_dict():
    url = URL_ROOT + "/users"
    print "url:", url
    result = firebase.get(url)
    users_dict = {}
    if isinstance(result,dict):
        for key, value in result.iteritems():
            print key, value
            users_dict[str(key)] = ast.literal_eval(json.dumps(value))
            print users_dict
        print "get_users_dict:", users_dict
        return users_dict
    else:
        print "firebase-get_users_dict: result is not dict:",result, bool(result),bool(None)
        return None
Пример #39
0
def firebase_get_users_dict():
    url = URL_ROOT + "/users"
    print "url:", url
    result = firebase.get(url)
    users_dict = {}
    if isinstance(result, dict):
        for key, value in result.iteritems():
            print key, value
            users_dict[str(key)] = ast.literal_eval(json.dumps(value))
            print users_dict
        print "get_users_dict:", users_dict
        return users_dict
    else:
        print "firebase-get_users_dict: result is not dict:", result, bool(
            result), bool(None)
        return None
Пример #40
0
def firebase_get_user_dict(userid):
    url = URL_ROOT + "/users/%s" % userid
    print "url:", url
    result = firebase.get(url)
    users_dict = {}
    if isinstance(result, dict):
        for key, value in result.iteritems():
            print key, value
            users_dict[str(key)] = str(value)
            print users_dict
        print "get_user_dict:", users_dict
        return users_dict
    else:
        print "firebase-get_user_dict: result is not dict:", result, bool(
            result), bool(None)
        return None
Пример #41
0
def changestatus(workstationnumber,value):
    labstatus = firebase.get('/py_lab')
    if labstatus['Work_Station_%s'%workstationnumber]['status'] == value: return firebase.put('/','py_lab/Work_Station_%s'%workstationnumber,labstatus['Work_Station_%s'%workstationnumber])
    else:
        firebase.put('/','py_lab/Work_Station_%s/status'%workstationnumber,'Checking Vacancy\nTimer: ')
        s = watchlist[workstationnumber-1] #workstation1 is sw1, workstation2 is sw2, etc
        if s.status == True: pass
        if s.status == False: s.start()
        while s.getElapsedTime() <= 60.0:
            firebase.put('/','py_lab/Work_Station_%s/timer'%workstationnumber,str(timeformatter(float(s.getElapsedTime()))))
            if s.getElapsedTime() > 60.0:
                s.stop()
                s.reset()
                firebase.put('/','py_lab/Work_Station_%s',{'status':value, 'timer':0})
                break
        pass
Пример #42
0
def firebase_get_user_list():
    url = URL_ROOT + "/users"
    result = firebase.get(url)
    user_list = []
    if isinstance(result,dict):
        for key, value in result.iteritems():
           # print key, value
            user_dict = {}
            for user_key, user_value in value.iteritems():
               # print "user:"******"userid"]= str(key)
            user_list.append(user_dict)#with remove unicode string
       # print "firebase_get_user_list:", user_list
    else:
        print "firebase-get_user_list: result is not dict:",result
    return user_list
	def generate_screen(self):
		self.dispensers = firebase.get('/users')[self.user]['dispensers']
		self.ids['dispensers_manager'].add_widget(Button(text='<< Back to Profile',color=(0,0,0,1), background_normal='./assets/buttons/long_button.png', background_down='./assets/buttons/long_button_down.png', on_press=self.change_to_profile))
		if len(self.dispensers) == 1:
			self.ids['dispensers_manager'].add_widget(Label(text="You don't have any dispenser!", color=(0,0,0,1)))
			self.ids['dispensers_manager'].add_widget(Label(text="Add Now?", color=(0,0,0,1)))
		else:
			for i in xrange(1, len(self.dispensers)):
				a_dispenser = Button(text=self.dispensers[i], color=(0,0,0,1), background_normal='./assets/buttons/dis_button.png', background_down='./assets/buttons/dis_button_down.png', size_hint=(0.906, 1), on_press=partial(self.go_to_status, i))
				delete_button = Button(size_hint=(0.094, 1), background_normal='./assets/buttons/delete.png', background_down='./assets/buttons/delete.png', on_press=partial(self.delete_dispenser, i))
				box = BoxLayout()
				box.add_widget(a_dispenser)
				box.add_widget(delete_button)
				self.ids['dispensers_manager'].add_widget(box)
			self.ids['dispensers_manager'].add_widget(Label())
		self.ids['dispensers_manager'].add_widget(Button(text="Add New Dispenser",color=(0,0,0,1), background_normal='./assets/buttons/long_button.png', background_down='./assets/buttons/long_button_down.png', on_press=self.change_to_add))
		self.ids['dispensers_manager'].add_widget(Button(text="Buy New Dispenser",color=(0,0,0,1), background_normal='./assets/buttons/long_button.png', background_down='./assets/buttons/long_button_down.png', on_press=self.change_to_buy))
Пример #44
0
def py_lab_data():
    import firebase
    
    py_lab = {}   
    
    url = "https://sizzling-torch-109.firebaseio.com/" 
    token = "4tWC7ZSixm6Xp0HNVzyEWg3urMtxKlTnDLUwZXUq"
    firebase = firebase.FirebaseApplication(url, token)
    
    py_lab_data = firebase.get('/py_lab')
    
    for seat,seat_data in py_lab_data.iteritems():
        pressure_sensor_data = seat_data['Pressure_Mat']
        seatStatus = IndvSeatStatus(pressure_sensor_data)
        py_lab[seat] = seatStatus.getNextState()
            
    return py_lab
Пример #45
0
def firebase_get_user_list():
    url = URL_ROOT + "/users"
    result = firebase.get(url)
    user_list = []
    if isinstance(result, dict):
        for key, value in result.iteritems():
            # print key, value
            user_dict = {}
            for user_key, user_value in value.iteritems():
                # print "user:"******"userid"] = str(key)
            user_list.append(user_dict)  #with remove unicode string
    # print "firebase_get_user_list:", user_list
    else:
        print "firebase-get_user_list: result is not dict:", result
    return user_list
 def generate_screen(self):
     self.dispensers = firebase.get('/users')[self.user]['dispensers']
     self.ids['dispensers_manager'].add_widget(
         Button(text='<< Back to Profile',
                color=(0, 0, 0, 1),
                background_normal='./assets/buttons/long_button.png',
                background_down='./assets/buttons/long_button_down.png',
                on_press=self.change_to_profile))
     if len(self.dispensers) == 1:
         self.ids['dispensers_manager'].add_widget(
             Label(text="You don't have any dispenser!",
                   color=(0, 0, 0, 1)))
         self.ids['dispensers_manager'].add_widget(
             Label(text="Add Now?", color=(0, 0, 0, 1)))
     else:
         for i in xrange(1, len(self.dispensers)):
             a_dispenser = Button(
                 text=self.dispensers[i],
                 color=(0, 0, 0, 1),
                 background_normal='./assets/buttons/dis_button.png',
                 background_down='./assets/buttons/dis_button_down.png',
                 size_hint=(0.906, 1),
                 on_press=partial(self.go_to_status, i))
             delete_button = Button(
                 size_hint=(0.094, 1),
                 background_normal='./assets/buttons/delete.png',
                 background_down='./assets/buttons/delete.png',
                 on_press=partial(self.delete_dispenser, i))
             box = BoxLayout()
             box.add_widget(a_dispenser)
             box.add_widget(delete_button)
             self.ids['dispensers_manager'].add_widget(box)
         self.ids['dispensers_manager'].add_widget(Label())
     self.ids['dispensers_manager'].add_widget(
         Button(text="Add New Dispenser",
                color=(0, 0, 0, 1),
                background_normal='./assets/buttons/long_button.png',
                background_down='./assets/buttons/long_button_down.png',
                on_press=self.change_to_add))
     self.ids['dispensers_manager'].add_widget(
         Button(text="Buy New Dispenser",
                color=(0, 0, 0, 1),
                background_normal='./assets/buttons/long_button.png',
                background_down='./assets/buttons/long_button_down.png',
                on_press=self.change_to_buy))
Пример #47
0
def syncScreens():
	global CONNECTIONS, prevResp, landscape
	_screens = firebase.firebaseURL(APP_NAME + "/screens")
	resp = firebase.get(_screens)
	if resp is not None:
		CONNECTIONS = len(resp) - 1
		if len(resp) != len(prevResp):
			print "Number of connections: ", CONNECTIONS
			print resp
			if CONNECTIONS >= 1:
				if "innerWidth" in resp[-1].keys():
					landscape = resp[-1]["innerWidth"] > resp[-1]["innerHeight"]
			prevResp = resp
	for idx, screen in enumerate(screens):
		if idx > 0:
			s = firebase.firebaseURL(APP_NAME + "/screens/" + str(idx))
			center, dims, rotation = screen
			firebase.patch(s, {u'center': {u'x':int(center[0]), u'y':int(center[1])}, u'dims': {u'h':int(dims[1]), u'w':int(dims[0])}, u'rotation': int(rotation)})
	def submit(self):
		new_password = self.ids['new_password'].text
		old_password = self.ids['old_password'].text
		confirm = self.ids['confirm'].text
		password = firebase.get('/users/'+self.manager.get_screen('profile').user+'/password')
		if old_password == password:
			if len(new_password) > 7:
				if new_password == confirm:
					firebase.put('/', '/users/'+self.manager.get_screen('profile').user+'/password', new_password)
					self.ids['new_password'].text = ""
					self.ids['old_password'].text = ""
					self.ids['confirm'].text = ""
					self.ids['status'].text = "Password updated!"
				else:
					self.ids['status'].text = "New password mismatched!"
			else:
				self.ids['status'].text = "New password too short!"
				print len(new_password)
		else:
			self.ids['status'].text = "Incorrect password!"
	def display_result(self):
		self.ids['search_result'].clear_widgets()
		for i in xrange(0,3):
			self.ids['search_result'].add_widget(BoxLayout())
		if len(self.search_result)==0:
			self.ids['search_result'].add_widget(Label(text="Cannot find any dispenser!", color=(0,0,0,1)))
		else:	
			for dispenser in self.search_result:
				box = BoxLayout()
				box.add_widget(Label(text=dispenser, size_hint=(0.817, 1), color=(0,0,0,1)))
				add_button=Button(id=dispenser, size_hint=(0.083, 1))
				if dispenser in firebase.get('/users/'+self.manager.get_screen('profile').user)['dispensers']:
					add_button.background_normal='./assets/buttons/checked.png'
					add_button.background_down='./assets/buttons/checked.png'
				else:
					add_button.background_normal='./assets/buttons/add.png'
					add_button.background_down='./assets/buttons/add.png'
					add_button.bind(on_press=self.add_the_dispenser)
				box.add_widget(add_button)
				box.add_widget(Label(size_hint=(0.1, 1)))
				self.ids['search_result'].add_widget(box)
	def sign_me_up(self):
		entered_username = self.ids['username'].text.strip()
		entered_email = self.ids['email'].text.strip()
		entered_password = self.ids['password'].text.strip()
		confirm_password = self.ids['password_confirm'].text.strip()
		if " " in entered_username or "	" in entered_username:
			self.ids['status'].text = 'Username invalid! Cannot have spaces'
		elif entered_username in firebase.get('/users'):
			self.ids['status'].text = 'Username Taken!'
		elif self.email_availability(entered_email) == False:
			self.ids['status'].text = 'Email has already been signed up!'
		elif len(entered_password) < 7:
			self.ids['status'].text = "Password too short!"
		elif entered_password != confirm_password:
			self.ids['status'].text = 'Password mismatched!'
		else:
			user = {'dispensers': ['None'], 'email': entered_email, 'password': entered_password, 'pic_url': 'http://i.imgur.com/VMtRJHG.jpg', 'badges': ['None']}
			firebase.put('/', '/users/'+entered_username, user)
			self.ids['sign_up'].clear_widgets()
			self.ids['sign_up'].add_widget(Label(text="Sign Up Successful!"))
			self.ids['sign_up'].add_widget(Label(text="Start contributing to a better world for cats!"))
			self.ids['sign_up'].add_widget(Button(text='Go to your profile', color=(0,0,0,1), background_normal='./assets/buttons/long_button.png', background_down='./assets/buttons/long_button_down.png', on_press=self.transfer_data))
Пример #51
0
def register():
    form = RegisterForm()
    if request.method == 'POST' and form.validate():
        user_data = {
            'names': [name.strip() for name in form.names.data.split(",")],
            'location': form.location.data,
            'languages': form.languages.data,
            'email': form.email.data,
            # We store a hash of the password instead of the actual password so
            # that if our database is compromised, no one can read the
            # passwords.
            'password': generate_password_hash(form.password.data)
        }
        teamname = form.teamname.data
        ref = '/users/' + teamname + '.json'

        if firebase.get(ref):
            flash('Team name already registered.', 'danger')
            return redirect(url_for('index'))

        firebase.put(ref, user_data)
        return redirect(url_for('index'))
    return render_template('register.html', form=form)
Пример #52
0
rom firebase import firebase
firebase = firebase.FirebaseApplication('https://hivemind.firebaseio.com', authentication=None)
result = firebase.get('/users', None, {'print': 'pretty'})
print result # {'error': 'Permission denied.'}

authentication = firebase.Authentication('THIS_IS_MY_SECRET', '*****@*****.**', extra={'id': 123})
firebase.authentication = authentication
print authentication.extra # {'admin': False, 'debug': False, 'email': '*****@*****.**', 'id': 123, 'provider': 'password'}

user = authentication.get_user()
print user.firebase_auth_token

result = firebase.get('/users', None, {'print': 'pretty'})
print result # {'1': 'John Doe', '2': 'Jane Doe'}
	def email_availability(self, email):
		for user in firebase.get('/users'):
			if email == firebase.get('/users/'+user+'/email'):
				return False
		else:
			return True
"""
Twitter bot that post definitions from the Devil's Dictionary by Ambroce Bierce (1911).

Twitter bot handle: @ghostofambrose
"""

import firebase
import random
import tweepy
import time

# setup firebase and obtain definitions
firebase = firebase.FirebaseApplication('https://yourbot.firebaseio.com', None)
devils_tweets = firebase.get("/tweets", None)

# Set up tweepy configuration
consumer_key = "your_consumer_key"
consumer_secret = "your_consumer_secret"
access_key = "your access_key"
access_secret = "your access_secret"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)


def update_status():  # function that generates a random tweet from the firebase list.
    tweet = devils_tweets.values()[random.randint(0, len(devils_tweets.values())-1)]
    api.update_status(tweet)


while True:  # post random tweet and then sleeps between x and y amount of time.
Пример #55
0
# the Firebase database.
no_commands = True

while no_commands:
    # Check the value of movement_list in the database at an interval of 0.5
    # seconds. Continue checking as long as the movement_list is not in the
    # database (ie. it is None). If movement_list is a valid list, the program
    # exits the while loop and controls the eBot to perform the movements
    # specified in the movement_list in sequential order. Each movement in the
    # list lasts exactly 1 second.

    # Get movement list from Firebase
    movement_list = None

    # Write your code here
    movement_list = firebase.get('/movements')
    if movement_list != None:
        break
    sleep(0.5)

# Write the code to control the eBot here
def f():
    ebot.wheels(1,1)
    sleep(1)
def l():
    ebot.wheels(-1,1)
    sleep(1)
def r():
    ebot.wheels(1,-1)
    sleep(1)
	def display_data(self):
		self.ids['user'].text = self.user
		self.ids['email'].text = firebase.get('/users')[self.user]['email']
		self.ids['pic'].source = firebase.get('/users')[self.user]['pic_url']
Пример #57
0
def load_user(userid):
    r = firebase.get('/users/' + userid + '.json')
    return User(userid, r['names'], r['languages'], r['email'], r['password'])
Пример #58
0
__author__ = 'HanWei'
import RPi.GPIO as GPIO
import firebase

url = "https://flickering-fire-1661.firebaseio.com/"  # URL to Firebase
token = "ZpSWTZaRaODNivf2S3Vil0a50BAPjx1ZhGsVbL2S"
firebase = firebase.FirebaseApplication(url, token)

# Use the BCM GPIO numbers as the numbering scheme
GPIO.setmode(GPIO.BCM)
red = 5
yellow = 16

GPIO.setup(red, GPIO.OUT)
GPIO.setup(yellow, GPIO.OUT)

while True:
    redLED = firebase.get('/ledcontroller/red')
    yellowLED = firebase.get('ledcontroller/yellow')
    if redLED == 'on':
        GPIO.output(red, GPIO.HIGH)
    if yellowLED == 'on':
        GPIO.output(yellow, GPIO.HIGH)
    if redLED == 'off':
        GPIO.output(red, GPIO.LOW)
    if yellowLED == 'off':
        GPIO.output(yellow, GPIO.LOW)
Пример #59
0
 def accessFirebase(self):
     print "Accessing Firebase, please wait a moment..."
     return firebase.get('/py_lab')    
import firebase
url = "https://shinglez.firebaseio.com"
token = "LMM5MC2Q6G1wCDrbrOMraGETVPCj6CSKBpUS2RtQ"
firebase = firebase.FirebaseApplication(url,token)
########################## set up for sensors######################
sensors = {"100": 12, "75": 16, "50": 20, "25":  21}
GPIO.setup([sensors['100'], sensors['75'], sensors['50'], sensors['25']], GPIO.IN)
    
########################## set up for motors#######################
motor = 5
GPIO.setup(motor, GPIO.OUT)
pwm = GPIO.PWM(motor, 50)


food_spoilt = firebase.get('/dispensers/sutd/food_spoilt')
########################## meals time #############################
breakfast = "08:00:59"
lunch = "13:00:59"
dinner = "20:00:59"
fill_time = None
old_percent = 101
new_percent = old_percent

while 'True':
    hundred = GPIO.input(sensors['100'])
    seventy5 = GPIO.input(sensors['75'])
    fifty = GPIO.input(sensors['50'])
    twenty5 = GPIO.input(sensors['25'])
    ####################code for updating info to cloud#########################
    if hundred == 1 and seventy5 == 1 and fifty == 1 and twenty5 == 1: