예제 #1
0
    def __init__(self):

        self.db = DB()
        self.m = Tk()
        self.m.title("quiz")
        self.m.minsize(500, 500)
        self.m.configure(bg='#0a3d62')
        self.login()
        self.m.mainloop()
예제 #2
0
def do_import_rtq(db, password='', newfileonly=False):
    loader = FileLoader()
    db = DB(password=password, db=db)
    db.create_table_deadlink()
    # print 'try loading', sys.argv[1]
    # lines = loader.load(
    # sys.argv[1])
    newdate = str(db.get_last_day('deadlink'))

    if newdate == 'None':
        newfileonly = False
    for file in utils.dir_listfile('result'):
        rawdatestr = utils.stripDateStr(file).group(1)
        datestr = utils.parseDateString(rawdatestr)
        if newfileonly:
            if datestr > newdate:
                lines = loader.load(file, 7)
                print 'staring insert lines from', file, 'datetime is', datestr
                db.inserts_deadlink(lines, date=datestr)
                print 'insert completed'
            else:
                print datestr, 'skiped'
        else:
            lines = loader.load(file, 7)
            print 'staring insert lines from', file, 'datetime is', datestr
            db.inserts_deadlink(lines, date=datestr)
            print 'insert completed'
예제 #3
0
def do_import_rcu(db, password='', newfileonly=False):
    loader = FileLoader()
    db = DB(password=password, db=db)
    db.create_table_deadlink_classify()
    cates = ['aladdin', 'h5', 'lightaap', 'normal', 'siteapp', 'tc']
    newdate = str(db.get_last_day('deadlink'))

    if newdate == 'None':
        newfileonly = False

    def httpcodeNot200(line):
        return line[2] != '200'

    for category in cates:
        for file in utils.dir_listfile(
                'result',
                subdirprefix='result_spider_random_classfiy_url',
                fileSubPrefix='result_spider_10000_' + category):
            datestr = utils.getDateFromStr(file)
            if newfileonly:
                if datestr > newfileonly:
                    lines = loader.load(file, 5)
                    try:
                        filteredlines = [
                            i
                            for i in itertools.ifilter(httpcodeNot200, lines)
                        ]
                    except TypeError, e:
                        print >> sys.stderr, e.args
                        continue
                    print 'deads', len(
                        filteredlines
                    ), 'staring insert lines from', file, 'datetime is', datestr
                    db.inserts_deadlink_classify(filteredlines,
                                                 cls=category,
                                                 date=datestr)
                    print 'insert completed'
                else:
                    print datestr, 'skiped'
            else:
                lines = loader.load(file, 5)
                try:
                    filteredlines = [
                        i for i in itertools.ifilter(httpcodeNot200, lines)
                    ]
                except TypeError, e:
                    print >> sys.stderr, e.args
                    continue
                print 'deads', len(
                    filteredlines
                ), 'staring insert lines from', file, 'datetime is', datestr
                db.inserts_deadlink_classify(filteredlines,
                                             cls=category,
                                             date=datestr)
                print 'insert completed'
예제 #4
0
def do_import_rtq(db, password='', newfileonly=False):
    loader = FileLoader()
    db = DB(password=password, db=db)
    db.create_table_deadlink()
    # print 'try loading', sys.argv[1]
    # lines = loader.load(
    # sys.argv[1])
    newdate = str(db.get_last_day('deadlink'))

    if newdate == 'None':
        newfileonly = False
    for file in utils.dir_listfile('result'):
        rawdatestr = utils.stripDateStr(file).group(1)
        datestr = utils.parseDateString(rawdatestr)
        if newfileonly:
            if datestr > newdate:
                lines = loader.load(file, 7)
                print 'staring insert lines from', file, 'datetime is', datestr
                db.inserts_deadlink(lines, date=datestr)
                print 'insert completed'
            else:
                print datestr, 'skiped'
        else:
            lines = loader.load(file, 7)
            print 'staring insert lines from', file, 'datetime is', datestr
            db.inserts_deadlink(lines, date=datestr)
            print 'insert completed'
예제 #5
0
def admin_process_event(bot, update):
    user = update.message.from_user
    chatid = update.message.chat.id
    userinput = update.message.text.strip()[1:]
    logger.info(userinput)
    print(INFO_STORE['user_token'], userinput)
    DB().admin_manage_events(INFO_STORE['user_token'], userinput)

    button_list = [InlineKeyboardButton(text='OK', callback_data = 'return_admin_panel')]
    menu = build_menu(button_list, n_cols = 1, header_buttons = None, footer_buttons = None)
    replytext = "Okay! Your previous decision has been recorded. Press 'OK' to return to the Admin Panel."

    if userinput[:-5] == 'approveEvent':
        logger.info("Admin has approved event")
        # PROCESS APPROVE WITH DATABASE HERE

    elif userinput[:-5] == 'rejectEvent':
        logger.info("Admin has rejected event")
        # PROCESS REJECT WITH DATABASE HERE
 
    # deletes message sent previously by bot (this is the previous admin panel message)
    bot.delete_message(chat_id=chatid, message_id=INFO_STORE[user.id]["BotMessageID"][-1])

    msgsent = bot.send_message(text = replytext,
                                chat_id = chatid,
                                reply_markup = InlineKeyboardMarkup(menu),
                                parse_mode=ParseMode.HTML)
    
    #appends message sent by bot itself - the very first message: start message
    INFO_STORE[user.id]["BotMessageID"].append(msgsent['message_id'])
    return 
예제 #6
0
def browse_events(bot, update):
    query = update.callback_query
    chatid = query.message.chat.id
    messageid = query.message.message_id
    userinput = html.escape(query.data)
    logger.info(userinput)

    button_list = [InlineKeyboardButton(text='Back', callback_data = 'back')]
    menu = build_menu(button_list, n_cols = 1, header_buttons = None, footer_buttons = None)
    
    # CHECK WITH DATABASE HERE 
    # IF EVENT IS PUBLISHED AND APPROVED, IT WILL BE LISTED HERE

    # published_events_list, published_eventIDs = getPublishedEvents()
    published_events_list = DB().generate_all_approved_events()

    BROWSE_EVENTS_MESSAGE = ''
    for i in range(len(published_events_list)):
        BROWSE_EVENTS_MESSAGE += "\n\n<b>EVENT ID: " + str(published_events_list[i][0]) + "</b>"
        BROWSE_EVENTS_MESSAGE += "\n\n" + str(published_events_list[i][1]) 
        BROWSE_EVENTS_MESSAGE += "\n\n" +"/registerForEvent" + str(published_events_list[i][0])
    
    replytext = einfo + "<b>Sup! List of cool events going on recently</b>:"
    replytext += "\n\n" + BROWSE_EVENTS_MESSAGE
        
    bot.editMessageText(text = replytext,
                        chat_id = chatid,
                        message_id = messageid,
                        reply_markup = InlineKeyboardMarkup(menu),
                        parse_mode=ParseMode.HTML)

    return AFTER_BROWSE_EVENTS
예제 #7
0
def confirm_event_registration(bot, update):
    user = update.message.from_user
    chatid = update.message.chat.id
    userinput = update.message.text.strip()[1:]
    logger.info(userinput)
    ## registerForEvent and user_token
    print(INFO_STORE)
    print(userinput, INFO_STORE['user_token'])
    DB().register_for_event(userinput, INFO_STORE['user_token'])

    replytext = "WOOTS! You have successfully registered for this event! Press /start if you wish to return to the main menu :)"

    if userinput[:-5] == 'registerForEvent':
        logger.info("User will be starting registration for this event.")
        # PROCESS APPROVE WITH DATABASE HERE

    # deletes message sent previously by bot (this is the previous admin panel message)
    bot.delete_message(chat_id=chatid, message_id=INFO_STORE[user.id]["BotMessageID"][-1])

    msgsent = bot.send_message(text = replytext,
                                chat_id = chatid,
                                parse_mode=ParseMode.HTML)
    
    #appends message sent by bot itself - the very first message: start message
    INFO_STORE[user.id]["BotMessageID"].append(msgsent['message_id'])

    return ConversationHandler.END
예제 #8
0
    def __init__(self):

        self.db = DB()
        self.m = Tk()
        self.m.title("quiz")
        self.m.minsize(500, 500)
        self.m.configure(bg='#0a3d62')
        # C=Canvas(self.m, bg="blue", height=250, width=300)
        # filename=PhotoImage(file="C:\\Users\\Designit\\PycharmProjects\\guirough\\trial.png")
        # background_label=Label(self.m, image=filename)
        # background_label.place(x=0, y=0, relwidth=1, relheight=1)
        #
        # C.pack( )
        self.login()
        # self.cl=Button(self.m,text='close',lambda :self.m.close())
        self.m.mainloop()
예제 #9
0
def train(dataset):
    db = DB(join(dbpath,'train.db'))
    tbl_manifest = '%s_man'%dataset
    tbl_rss = '%s_rss'%dataset

    n_feature = int(db.queryone('value',tbl_manifest,'key="n_feature"')[0])
    
    data = []
    cls = []
    for y,entry in db.query(['p_id','entry'], tbl_rss):
        dic = json.loads(entry)
        x = [-100]*n_feature
        for m_id,rss in dic.items():
            x[int(m_id)] = float(rss)
        data.append(x)
        cls.append(y)
    neigh = KNeighborsClassifier(n_neighbors=5)
    neigh.fit(data,cls)
    
    fout = open('model.dat','w')
    pickle.dump(neigh,fout)
    fout.close()
예제 #10
0
    def __init__(self):
        try:
            # connect to database
            self.db = DB(database="energy_report_consumption")

            # Connecting to the IDA ICE API.
            pid = start()
            test = ida_lib.connect_to_ida(b"5945", pid.encode())
            # connect to ida ice document
            self.building = call_ida_api_function(
                ida_lib.openDocument, b"d:\\ide_mine\\building_work1.idm")
            self.building_name = ida_get_name(self.building)
            self.energy_report = showList.showSingleChild(
                self.building, 'ENERGY-REPORT')
            self.standard_report_list = [
                'Lighting, facility', 'Electric cooling', 'HVAC aux',
                'Fuel heating', 'Domestic hot water', 'Equipment, tenant'
            ]
        except:
            print("Exception in user code:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
예제 #11
0
def do_import_rcu(db, password='', newfileonly=False):
    loader = FileLoader()
    db = DB(password=password, db=db)
    db.create_table_deadlink_classify()
    cates = ['aladdin', 'h5', 'lightaap', 'normal', 'siteapp', 'tc']
    newdate = str(db.get_last_day('deadlink'))

    if newdate == 'None':
        newfileonly = False

    def httpcodeNot200(line):
        return line[2] != '200'
    for category in cates:
        for file in utils.dir_listfile('result',
                                       subdirprefix='result_spider_random_classfiy_url',
                                       fileSubPrefix='result_spider_10000_' + category):
            datestr = utils.getDateFromStr(file)
            if newfileonly:
                if datestr > newfileonly:
                    lines = loader.load(file, 5)
                    try:
                        filteredlines = [i for i in itertools.ifilter(httpcodeNot200, lines)]
                    except TypeError, e:
                        print >> sys.stderr, e.args
                        continue
                    print 'deads', len(filteredlines), 'staring insert lines from', file, 'datetime is', datestr
                    db.inserts_deadlink_classify(filteredlines, cls=category, date=datestr)
                    print 'insert completed'
                else:
                    print datestr, 'skiped'
            else:
                lines = loader.load(file, 5)
                try:
                    filteredlines = [i for i in itertools.ifilter(httpcodeNot200, lines)]
                except TypeError, e:
                    print >> sys.stderr, e.args
                    continue
                print 'deads', len(filteredlines), 'staring insert lines from', file, 'datetime is', datestr
                db.inserts_deadlink_classify(filteredlines, cls=category, date=datestr)
                print 'insert completed'
예제 #12
0
def admin_panel(bot, update):
    query = update.callback_query
    chatid = query.message.chat.id
    messageid = query.message.message_id
    userinput = html.escape(query.data)
    logger.info(userinput)

    button_list = [InlineKeyboardButton(text='Back', callback_data = 'back')]
    menu = build_menu(button_list, n_cols = 1, header_buttons = None, footer_buttons = None)

    # GET EVENTS AND VENUES REQUESTS CALL FROM FUNCTIONS 

    # list_pending_events, list_pending_venues, list_eventIDs, list_venueIDs = getPendingEventsVenues()

    list_events = DB().generate_all_pending_events()

    ADMIN_MENU_MESSAGE = "\n\n" + einfo + "<b>List of Event Publications to be Approved:</b>"
    for i in range(len(list_events)):
        ADMIN_MENU_MESSAGE += "\n\n<b>EVENT ID: " + str(list_events[i][0]) + "</b>"
        ADMIN_MENU_MESSAGE += "\n\n" + str(list_events[i][1]) 
        ADMIN_MENU_MESSAGE += "\n\n" +"/approveEvent" + str(list_events[i][0]) + " | " +  "/rejectEvent" + str(list_events[i][0])


    # ADMIN_MENU_MESSAGE += "\n\n" + einfo + "<b>List of Venue Bookings to be Approved:</b>"
    # for i in range(len(list_pending_venues)):
    #     ADMIN_MENU_MESSAGE += "\n\n<b>VENUE ID: " + str(list_venueIDs[i]) + "</b>"
    #     ADMIN_MENU_MESSAGE += "\n\n" + str(list_pending_venues[i])
    #     ADMIN_MENU_MESSAGE += "\n\n" + "/approveVenue" + list_venueIDs[i] + " | " +  "/rejectVenue" + list_venueIDs[i] 
    
    replytext = "<b>Here is the full list of pending events publication and venue booking requests for you to approve.</b>"
    replytext += ADMIN_MENU_MESSAGE
    
    bot.editMessageText(text = replytext,
                        chat_id = chatid,
                        message_id = messageid,
                        reply_markup = InlineKeyboardMarkup(menu),
                        parse_mode=ParseMode.HTML)
    return AFTER_ADMIN_PANEL
예제 #13
0
#!/usr/bin/env python
from sklearn import svm 
import pickle
import json
from dbhelper import DB
import sys

device = sys.argv[1]

db = DB('train.db')
n_feature = int(db.queryone('value','manifest','key="n_feature"')[0])

data = []
cls = []
for y,entry in db.query(['p_id','entry'], 'rss_'+device):
    dic = json.loads(entry)
    x = [-100]*n_feature
    for m_id, rss in dic.items():
        x[int(m_id)] = float(rss)
    data.append(x)
    cls.append(y)
clf = svm.SVC()
clf.fit(data,cls)

fout = open('model.dat','w')
pickle.dump(clf,fout)
fout.close()


예제 #14
0
def do_test(db, password=''):
    db = DB(password=password, db=db)
    ret = db.get_last_day('classify')
    print 'last day is', ret
예제 #15
0
    def login(token):
        if (not DB().user_login(token)):
            return False

        User.currentUser = User("test", token)
        return DB().user_login(token)
예제 #16
0
 def createEvent(cls, organizerID, name, description):
     return DB().create_event(User.currentUser.token, name, "", "",
                              description)
예제 #17
0
class Report_out():
    def __init__(self):
        try:
            # connect to database
            self.db = DB(database="energy_report_consumption")

            # Connecting to the IDA ICE API.
            pid = start()
            test = ida_lib.connect_to_ida(b"5945", pid.encode())
            # connect to ida ice document
            self.building = call_ida_api_function(
                ida_lib.openDocument, b"d:\\ide_mine\\building_work1.idm")
            self.building_name = ida_get_name(self.building)
            self.energy_report = showList.showSingleChild(
                self.building, 'ENERGY-REPORT')
            self.standard_report_list = [
                'Lighting, facility', 'Electric cooling', 'HVAC aux',
                'Fuel heating', 'Domestic hot water', 'Equipment, tenant'
            ]
        except:
            print("Exception in user code:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)

    def __exit__(self, exc_type, exc_val, exc_tb):
        try:
            self.end = ida_lib.ida_disconnect()
        except:
            print("Exception in user code:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)

    # Insert building information into db, can be extended
    def building_repo(self):
        if self.building_name:
            self.bid = self.db.insertBuil(self.building_name)
        if self.bid:
            print("bid got")
            return True

    # Insert simulation information into db, sid, bid, simulation-option, datetime
    def simulation_repo(self, simulation_option="change some parameter"):
        self.sid = self.db.insertSimu(self.bid, simulation_option)
        if self.sid:
            return True

    # Insert consumption_report into db
    def consumption_report(self):
        try:
            consumption = showList.showSingleChild(self.energy_report,
                                                   'CONSUMPTION')
            value_list = showList.showChildrenListValue(consumption)
            consumption_dict = {}
            check = 1
            consumption_table_name = {
                'Lighting, facility': 'consump_lighting_facility',
                'Electric cooling': 'consump_electric_cooling',
                'HVAC aux': 'consump_hvac',
                'Fuel heating': 'consump_fuel_heating',
                'Domestic hot water': 'consump_domestic_hot_water',
                'Equipment, tenant': 'consump_equipment_tenant'
            }

            # Extract key and values from consumption
            for key, val in value_list.items():
                consumption_dict[key] = re.findall(r"\d+\.?\d*", val)

            for key, val in consumption_dict.items():
                print(key + '==')

            for i in range(len(self.standard_report_list)):
                if self.standard_report_list[i] in consumption_dict:
                    table_name = consumption_table_name.get(
                        self.standard_report_list[i])
                    self.db.insertEle(
                        check, self.sid, self.bid,
                        consumption_dict.get(self.standard_report_list[i]),
                        table_name)
                else:
                    print('Unsuccessfully inserting ' +
                          self.standard_report_list[i] +
                          ' data into energy report- consumption')

        except:
            print("Exception in user code:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)

    def peak_power_report(self):
        try:
            demand = showList.showSingleChild(self.energy_report, 'DEMAND')
            value_list = showList.showChildrenListValue(demand)
            peak_power_dict = {}
            check = 2
            pk_power_table_name = {
                'Lighting, facility': 'pk_power_lighting_facility',
                'Electric cooling': 'pk_power_electric_cooling',
                'HVAC aux': 'pk_power_hvac',
                'Fuel heating': 'pk_power_fuel_heating',
                'Domestic hot water': 'pk_power_domestic_hot_water',
                'Equipment, tenant': 'pk_power_equipment_tenant'
            }
            # Extract key and values from peak power
            for key, val in value_list.items():
                peak_power_dict[key] = re.findall(r"\d+\.?\d*", val)

            for key, val in peak_power_dict.items():
                print(key + '==')

            for i in range(len(self.standard_report_list)):
                if self.standard_report_list[i] in peak_power_dict:
                    table_name = pk_power_table_name.get(
                        self.standard_report_list[i])
                    self.db.insertEle(
                        check, self.sid, self.bid,
                        peak_power_dict.get(self.standard_report_list[i]),
                        table_name)
                else:
                    print('Unsuccessfully inserting ' +
                          self.standard_report_list[i] +
                          'data into energy report- peak power')

        except:
            print("Exception in user code:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
예제 #18
0
from dbhelper import DB
from math import ceil
import random as rand
import bcrypt, cfg, os, shutil, json

try:
    from BytesIO import BytesIO
except ImportError:
    from io import BytesIO

app = Flask(__name__)
app.secret_key = "omgitsosecret"
app.wsgi_app = ProxyFix(app.wsgi_app)
login_manager = LoginManager()
login_manager.init_app(app)
db = DB()

from utils import runHlsThread
runHlsThread()

app.jinja_env.globals['cfg'] = cfg


@app.route("/videos", methods=["GET"])
@login_required
def videos():
    count = db.count("videos")

    n_pages = ceil(count / cfg.V_PAGE_ROWS)
    page = request.args.get('page')
    try:
예제 #19
0
#!/usr/bin/env python
from dbhelper import DB
import json
from os.path import join
import os

rootpath = os.getenv('WLAN_ROOT')
datapath = join(rootpath,'raw_data')
dbpath = join(datapath,'DB')
db = DB(join(dbpath,'train.db'))
dataset = db.queryone('value','meta','key="current"')[0]
tbl_mac = '%s_mac'%dataset
tbl_pt = '%s_pnt'%dataset
tbl_relation = '%s_rel'%dataset
tbl_manifest = '%s_man'%dataset
tbl_rss = '%s_rss'%dataset

map_mac = {}
map_pt = {}
feas_map = {}
mac_dic = dict([(mac,m_id) for mac,m_id in db.query(['mac','m_id'],tbl_mac)])
pid_dic = dict([(p_id,pt) for p_id,pt in db.query(['p_id','pt'],tbl_pt)])
coord_dic = dict([(p_id,(int(x),int(y))) for p_id,x,y in db.query(['p_id','x','y'],tbl_pt)])
n_point = int(db.queryone('value',tbl_manifest,'key="n_point"')[0])
p2p_matrix = [[float('inf')]*n_point for i in range(n_point)]
for i in range(n_point):
    p2p_matrix[i][i] = 0.0
for i,j,dis in db.query(['src_pt','dest_pt','distance'],tbl_relation):
    p2p_matrix[i][j] = p2p_matrix[j][i] = dis

def get_macid(mac):
예제 #20
0
#!/usr/bin/env python
import pickle
from dbhelper import DB
import os
from os.path import join

rootpath = os.getenv('WLAN_ROOT')
datapath = join(rootpath,'raw_data')
dbpath = join(datapath,'DB')
db = DB(join(dbpath,'train.db'))
dataset = db.queryone('value','meta','key="current"')[0]
tbl_manifest = '%s_man'%dataset
n_feature = int(db.queryone('value',tbl_manifest,'key="n_feature"')[0])

fin = open('model.dat')
clf = pickle.load(fin)
fin.close

def predict(dic):
    data = [-100]*n_feature
    for m_id, rss in dic.items():
        data[int(m_id)] = float(rss)
    proba = clf.predict_proba([data]).tolist()[0]
    return proba
예제 #21
0
def do_test(db, password=''):
    db = DB(password=password, db=db)
    ret = db.get_last_day('classify')
    print 'last day is', ret
예제 #22
0
def prepare(dataset):
    split_policy = 'default'
    test_pts = [] #only used when split_policy is 'specify'
    #-------------------------------read data----------------------------
    ratedic = {}
    map_pt = {}
    for txt in os.listdir(join(datapath,dataset,'rss')):
        if not txt in map_pt:
            map_pt[txt] = txt[2:]
        for line in open(join(datapath,dataset,'rss',txt)):
            pt,entry = line.strip().split('\t')
            for item in entry.split(' '):
                mac,rss = item.split('@')
                if not mac in ratedic:
                    ratedic[mac] = 0                
                ratedic[mac] += 1
    mac_lst = [mac for mac,rate in ratedic.items() if rate > 500]
    map_mac = dict([(mac,i) for i,mac in enumerate(mac_lst)])
    map_coord = {}
    for line in open(join(datapath,dataset,'map','coord.txt')):
        pt,xy = line.strip().split('\t')
        x,y = xy.split(' ')
        map_coord[pt] = (x,y)
    relation_lst = []
    for line in open(join(datapath,dataset,'map','relation.txt')):
        src,dest,dist,dir_ = line.strip().split('\t')
        relation_lst.append((map_pt[src],map_pt[dest],dist,dir_))
    #-------------------------------store data----------------------------
    db = DB(join(dbpath,'raw.db'))
    tbl_mac = '%s_mac'%dataset
    tbl_pt = '%s_pnt'%dataset
    tbl_relation = '%s_rel'%dataset
    tbl_manifest = '%s_man'%dataset
    tbl_rss = '%s_rss'%dataset

    # [dataset]_mac : ( m_id | mac )
    db.new_table(tbl_mac, ('m_id integer','mac text'))
    db.insertmany([ (m_id,mac) for mac,m_id in map_mac.items()], tbl_mac)
    # [dataset]_pnt : ( p_id | pt | x | y )
    db.new_table(tbl_pt, ('p_id integer','pt text','x real','y real'))
    db.insertmany([(p_id,pt)+map_coord[pt] for pt,p_id in map_pt.items()], tbl_pt)
    #[dataset]_rel: ( src_pt | dest_pt | distance | directions )
    db.new_table(tbl_relation, ('src_pt integer','dest_pt integer','distance real','directions text'))
    db.insertmany(relation_lst, tbl_relation)
    # [dataset]_manifest : (key, value)
    db.new_table(tbl_manifest, ('key text','value text'))
    db.insert(('n_feature',len(map_mac)), tbl_manifest)
    db.insert(('n_point',len(map_pt)), tbl_manifest)
    
#    for device in os.listdir(join(datapath,dataset)):
    r_id = 0
    db.insert(('dataset',tbl_rss), tbl_manifest)
    #[dataset]_rss: ( r_id | p_id | entry )
    db.new_table(tbl_rss, ('r_id integer','p_id integer','entry text'))
    for txt in os.listdir(join(datapath,dataset,'rss')):
        for line in open(join(datapath,dataset,'rss',txt)):
            r_id += 1
            dic = {}
            pt,entry = line.strip().split('\t')
            for item in entry.split(' '):
                mac,rss = item.split('@')
                if not mac in map_mac:  #filter
                    continue
                dic[map_mac[mac]] = rss
            entry = json.dumps(dic)
            db.insert((r_id, map_pt[pt], entry), tbl_rss)

    db.new_table('meta', ('key text','value text'))
    db.insert(('current',dataset),'meta')

    db.commit()
                
    #-------------------------------split data----------------------------
    db_train = DB(join(dbpath,'train.db'))
    db_test = DB(join(dbpath,'test.db'))
#    for device in db.queryone('value', 'manifest', 'key="device"'):
    db_train.new_table(tbl_rss, ('r_id integer','p_id integer','entry text'))
    db_test.new_table(tbl_rss, ('r_id integer','p_id integer','entry text'))
    if split_policy == None:
        #no test data
        db_train.clone_from(db, tbl_rss)
    elif split_policy == 'default':
        #70% train data & 30% test data
        for record in db.queryall(tbl_rss):
            if random.random() > 0.3:
                db_train.insert(record, tbl_rss)
            else:
                db_test.insert(record, tbl_rss)
    elif split_policy == 'specify':
        #user specify
        for record in db.queryall(tbl_rss):
            if record[1] in test_pts:
                db_test.insert(record, tbl_rss)
            else:
                db_train.insert(record, tbl_rss)
    else:
        #error
        pass
    
    db_train.clone_from(db, tbl_manifest)
    db_train.clone_from(db, tbl_mac)
    db_train.clone_from(db, tbl_pt)
    db_train.clone_from(db, tbl_relation)
    db_train.clone_from(db, 'meta')
    
    db_test.clone_from(db, tbl_manifest)
    db_test.clone_from(db, tbl_mac)
    db_test.clone_from(db, tbl_pt)
    db_test.clone_from(db, tbl_relation)
    db_test.clone_from(db, 'meta')

    
    db_train.commit()
    db_test.commit()
예제 #23
0
 def register(name):
     token = DB().add_user(name)
     User.currentUser = User(name, token)
     return token
예제 #24
0
#!/usr/bin/env python
#import sqlite3
import os
import json
import random
from dbhelper import DB

#-------------------------------store data----------------------------
map_mac = {}
map_pt = {}

db = DB('raw.db')
# map_mac : ( m_id | mac )
db.new_table('map_mac', ('m_id integer','mac text'))        
# map_pt : ( p_id | pt | x | y )
db.new_table('map_pt', ('p_id integer','pt text','x real','y real'))
# manifest : (key, value)
db.new_table('manifest', ('key text','value text'))

m_id = 0
p_id = 0
for device in os.listdir('raw_data/devices'):
    r_id = 0
    db.insert(('device','rss_'+device), 'manifest')
    #rss_device : ( r_id | p_id | entry )
    db.new_table('rss_'+device, ('r_id integer','p_id integer','entry text'))
    for txt in os.listdir('raw_data/devices/'+device):
        for line in open('raw_data/devices/'+device+'/'+txt):
            r_id += 1
            dic = {}
            pt,entry = line.strip().split('\t')
예제 #25
0
class Quiz_gui:
    def __init__(self):

        self.db = DB()
        self.m = Tk()
        self.m.title("quiz")
        self.m.minsize(500, 500)
        self.m.configure(bg='#0a3d62')
        # C=Canvas(self.m, bg="blue", height=250, width=300)
        # filename=PhotoImage(file="C:\\Users\\Designit\\PycharmProjects\\guirough\\trial.png")
        # background_label=Label(self.m, image=filename)
        # background_label.place(x=0, y=0, relwidth=1, relheight=1)
        #
        # C.pack( )
        self.login()
        # self.cl=Button(self.m,text='close',lambda :self.m.close())
        self.m.mainloop()

    def colors(self):
        self.color1 = '#0a3d62'
        self.button_color = '#079992'
        self.button_color1 = '#ffffff'
        self.font1 = 'white'
        self.font2 = 'black'
        # 0a3d62
        # 182C61

    def login(self):
        self.clear()
        self.colors()

        self.label_1 = Label(self.m,
                             text='QUIZ GAME',
                             bg=self.color1,
                             fg='white',
                             font=('Times New Roman', 20))
        self.label_1.pack(pady=(42, 92))

        self.user_Frame = Frame(self.m, bg=self.color1)
        self.user_Frame.pack(pady=(15, 15))
        self.username = Label(self.user_Frame,
                              text='Username',
                              bg=self.color1,
                              fg='white',
                              font=('Arial', 10))
        self.username.grid(sticky='NW')

        self.user_input = Entry(self.user_Frame,
                                width=40,
                                font=('Arial', 8, 'bold'))
        self.user_input.grid(sticky='s')
        self.pswd_Frame = Frame(self.m, bg=self.color1)
        self.pswd_Frame.pack(pady=(0, 25))
        self.password = Label(self.pswd_Frame,
                              text='Password',
                              bg=self.color1,
                              fg='white',
                              font=('Arial', 10)).grid(sticky='NW')
        self.password_input = Entry(self.pswd_Frame,
                                    show='*',
                                    width=40,
                                    font=('Times', 9, 'bold'))
        self.password_input.grid(sticky='s')

        self.frame3 = Frame(self.m, bg=self.color1)
        self.frame3.pack()
        self.loginbutton = Button(self.frame3,
                                  text='Login',
                                  bg=self.button_color,
                                  padx=21,
                                  pady=1,
                                  fg='#ffffff',
                                  font=('Times New Roman', 12),
                                  command=lambda: self.dologin())
        self.loginbutton.pack(padx=(10, 20), side=LEFT)
        self.sign_in_button = Button(self.frame3,
                                     text='Sign in',
                                     bg=self.button_color,
                                     padx=21,
                                     pady=1,
                                     fg='#ffffff',
                                     font=('Times New Roman', 12),
                                     command=lambda: self.registration())
        self.sign_in_button.pack(side=RIGHT, padx=15)

    def dologin(self):
        self.user_name = self.user_input.get()
        print(self.user_name)
        password = self.password_input.get()
        #send this data to database llambda :land check( if user exists or not
        self.data = self.db.checklogin(self.user_name, password)
        if len(self.data) > 0:
            #print the GUI
            self.user_id = self.data[0][0]
            self.homegui()
        else:
            messagebox.showerror("Error", "Incorrect credentials")

    def clear(self):
        for i in self.m.pack_slaves():
            i.destroy()

    def registration(self):
        self.clear()
        self.label_1 = Label(self.m,
                             text='QUIZ GAME',
                             bg=self.color1,
                             fg='white',
                             font=('Arial', 20, 'bold')).pack(pady=(42, 72))

        self.frame2 = Frame(self.m, bg=self.color1, relief='raised')
        self.frame2.pack(pady=(5, 30))

        # email id
        self.email_Frame = Frame(self.frame2, bg=self.color1)
        self.email_Frame.pack(padx=(30, 30), pady=(20, 20))
        self.email = Label(self.email_Frame,
                           text='Email ID',
                           bg=self.color1,
                           fg='white',
                           font=('Arial', 10)).grid(sticky='NW')
        self.email_input = Entry(self.email_Frame,
                                 width=60,
                                 font=('Times', 9, 'bold'))
        self.email_input.grid()
        # username
        self.username_Frame = Frame(self.frame2, bg=self.color1)
        self.username_Frame.pack(padx=(30, 30), pady=(20, 20))
        self.username = Label(self.username_Frame,
                              text='Username',
                              bg=self.color1,
                              fg='white',
                              font=('Arial', 10))
        self.username.grid(sticky='NW')
        self.username_input = Entry(self.username_Frame,
                                    width=60,
                                    font=('Arial', 8, 'bold'))
        self.username_input.grid()

        # first name
        self.First_Name_Frame = Frame(self.frame2, bg=self.color1)
        self.First_Name_Frame.pack(padx=(30, 30), pady=(20, 20))
        self.first_name = Label(self.First_Name_Frame,
                                text='First Name',
                                bg=self.color1,
                                fg='white',
                                font=('Arial', 10))
        self.first_name.grid(sticky='NW')
        self.first_name_input = Entry(self.First_Name_Frame,
                                      width=60,
                                      font=('Arial', 8, 'bold'))
        self.first_name_input.grid(sticky='s')

        #last name
        self.Last_Name_Frame = Frame(self.frame2, bg=self.color1)
        self.Last_Name_Frame.pack(padx=(30, 30), pady=(20, 20))
        self.Last_Name = Label(self.Last_Name_Frame,
                               text='Last Name',
                               bg=self.color1,
                               fg='white',
                               font=('Arial', 10)).grid(sticky='NW')
        self.Last_Name_input = Entry(self.Last_Name_Frame,
                                     width=60,
                                     font=('Times', 9, 'bold'))
        self.Last_Name_input.grid(sticky='s')

        #Age and Gender Frame
        # self.age_gender_frame=Frame(self.m,bg=self.color1)
        # self.age_gender_frame.pack(pady=(10,30))

        #Gender
        self.gender_frame = Frame(self.frame2, bg=self.color1)
        self.gender_frame.pack(padx=(30, 30), pady=(20, 20))
        self.gender = Label(self.gender_frame,
                            text='Gender',
                            bg=self.color1,
                            fg='white',
                            font=('Arial', 10))
        self.gender.grid(sticky='NW')
        self.gender_input = ttk.Combobox(self.gender_frame,
                                         width=57,
                                         values=('Male', 'Female',
                                                 'Transgender'))
        self.gender_input.grid(sticky='s')

        # Age
        self.age_frame = Frame(self.frame2, bg=self.color1)
        self.age_frame.pack(padx=(30, 30), pady=(20, 20))
        self.age = Label(self.age_frame,
                         text='Age',
                         bg=self.color1,
                         fg='white',
                         font=('Arial', 10)).grid(sticky='NW')
        self.age_input = Spinbox(self.age_frame, width=57, from_=8, to=101)
        self.age_input.grid(sticky='s')

        #setting password
        set_pwd = Frame(self.frame2, bg=self.color1)
        set_pwd.pack(pady=(20, 20))
        self.new_password = Label(set_pwd,
                                  text='Password',
                                  bg=self.color1,
                                  fg='white',
                                  font=('Arial', 10)).grid(sticky='NW')
        self.new_password_input = Entry(set_pwd, show='*', width=60)
        self.new_password_input.grid(sticky='s')

        re_set_pwd = Frame(self.frame2, bg=self.color1)
        re_set_pwd.pack(pady=(20, 20))
        self.re_password = Label(re_set_pwd,
                                 text='Re-enter Password',
                                 bg=self.color1,
                                 fg='white',
                                 font=('Arial', 10)).grid(sticky='NW')
        self.re_password_input = Entry(re_set_pwd, show='*', width=60)
        self.re_password_input.grid(sticky='s')
        register = Button(self.frame2,
                          text='Register',
                          bg=self.button_color,
                          fg='white',
                          font=('Times New Roman', 12),
                          command=lambda: self.do_registration())
        register.pack(pady=(25, 20))
        go_back = Button(self.frame2,
                         text='Go back',
                         bg=self.button_color,
                         fg='white',
                         font=('Times New Roman', 12),
                         command=lambda: self.login())
        go_back.pack(pady=(12, 40))

    def do_registration(self):

        email = self.email_input.get()
        username = self.username_input.get()
        fname = self.first_name_input.get()
        lname = self.Last_Name_input.get()
        gender = self.gender_input.get()
        age = self.age_input.get()
        if self.new_password_input.get() == self.re_password_input.get():
            password = self.new_password_input.get()
            response = self.db.performRegistration(email, username, fname,
                                                   lname, gender, age,
                                                   password)
            if (response == 0):
                messagebox.showerror("Error", "User already exists")

            else:
                messagebox.showinfo("Registration Successful",
                                    "Successfully Registered")
                time.sleep(1)
                self.login()
        else:
            messagebox.showerror(' ', 'Password does not match !')

    def display(self):
        print(self.email_input.get())

    def homegui(self):
        self.clear()
        self.colors()

        logout = Button(self.m,
                        text='Log out',
                        bg=self.color1,
                        relief='flat',
                        padx=10,
                        activebackground=self.color1,
                        activeforeground=self.font1,
                        fg=self.font1,
                        font=('Times New Roman', 12),
                        command=lambda: self.login())
        logout.pack(anchor='ne', side=RIGHT)

        editprofile = Button(self.m,
                             text='Edit Profile',
                             bg=self.color1,
                             relief='flat',
                             padx=5,
                             pady=2,
                             activebackground=self.color1,
                             activeforeground=self.font1,
                             fg=self.font1,
                             font=('Times New Roman', 12),
                             command=lambda: self.editprofileGUI())
        editprofile.pack(anchor='nw', side=LEFT)

        self.label_1 = Label(self.m,
                             text='QUIZ GAME',
                             bg=self.color1,
                             fg='white',
                             font=('Times New Roman', 20))
        self.label_1.pack(pady=(42, 92), padx=(0, 12))

        self.frame4 = Frame(self.m, bg=self.color1)
        self.frame4.pack()
        self.quiz_button = Button(self.frame4,
                                  text='Take Quiz',
                                  bd=5,
                                  bg=self.button_color1,
                                  padx=49,
                                  pady=1,
                                  fg=self.font2,
                                  relief='raised',
                                  font=('Times New Roman', 14),
                                  command=lambda: self.topics())
        self.quiz_button.pack(pady=(10, 25))
        self.leaderboard_button = Button(
            self.frame4,
            text='Leaderboard',
            bg=self.button_color1,
            bd=5,
            padx=41,
            pady=1,
            fg=self.font2,
            relief='raised',
            font=('Times New Roman', 14),
            command=lambda: self.show_leaderboard())
        self.leaderboard_button.pack(pady=(25, 35))

    def show_leaderboard(self):
        self.clear()

        logout = Button(self.m,
                        text='Log out',
                        bg=self.color1,
                        relief='flat',
                        padx=10,
                        activebackground=self.color1,
                        activeforeground=self.font1,
                        fg=self.font1,
                        font=('Times New Roman', 12),
                        command=lambda: self.login())
        logout.pack(anchor='ne')

        title = Label(self.m,
                      text='Leaderboard',
                      bg=self.color1,
                      fg='white',
                      font=('Times New Roman', 30))
        title.pack(pady=(20, 25))
        # time.sleep(2)
        # reading name from leaderboard
        lframe = Frame(self.m, bd=5, relief='raised', padx=5)
        lframe.pack(expand=1)
        leadernames = self.db.retrive_leaderboard_names()
        string = "ID" + "  " + "Username" + (
            (23 - len("Username")) * " ") + "score  "
        Label(lframe, text=string,
              font=('Times New Roman', 13)).pack(pady=(0, 5))

        for i in leadernames:
            string = str(i[0]) + ".     " + i[1] + (
                (30 - len(i[1])) * " ") + str(i[2]) + " \n"
            Label(lframe, text=string, font=('Times New Roman', 13)).pack()

        # displaying names on window

        #home button
        home_button = Button(self.m,
                             text='Home',
                             bg=self.color1,
                             fg=self.font1,
                             relief='flat',
                             font=('Times New Roman', 20),
                             command=lambda: self.homegui())
        home_button.pack(pady=(25, 15))

    def topics(self):
        self.clear()
        self.colors()

        logout = Button(self.m,
                        text='Log out',
                        bg=self.color1,
                        relief='flat',
                        padx=10,
                        activebackground=self.color1,
                        activeforeground=self.font1,
                        fg=self.font1,
                        font=('Times New Roman', 12),
                        command=lambda: self.login())
        logout.pack(anchor='ne')

        #title
        self.label_1 = Label(self.m,
                             text='QUIZ GAME',
                             bg=self.color1,
                             fg='white',
                             font=('Times New Roman', 20))
        self.label_1.pack(pady=(16, 92))

        #action button
        self.frame4 = Frame(self.m, bg=self.color1)
        self.frame4.pack()
        self.history = Button(self.frame4,
                              text='History',
                              bd=5,
                              bg=self.button_color1,
                              padx=49,
                              pady=1,
                              fg=self.font2,
                              relief='raised',
                              font=('Times New Roman', 14),
                              command=lambda: self.start_quiz(1))
        self.history.pack(pady=(10, 25))
        self.GK = Button(self.frame4,
                         text='GK',
                         bg=self.button_color1,
                         bd=5,
                         padx=64,
                         pady=1,
                         fg=self.font2,
                         relief='raised',
                         font=('Times New Roman', 14),
                         command=lambda: self.start_quiz(2))
        self.GK.pack(pady=(25, 35))

        #home button

        home_button = Button(self.m,
                             text='Home',
                             bg=self.color1,
                             fg=self.font1,
                             relief='flat',
                             font=('Times New Roman', 20),
                             command=lambda: self.homegui())
        home_button.pack(pady=(25, 15))

    def start_quiz(self, flag):
        self.clear()
        self.response = m(flag)
        self.index, self.r = 0, 0
        self.start()

    #displaying question
    def display_question(self, r):
        # self.frame1=Frame(self.m,bg='#8B008B',width=1500,height=200)
        # self.frame1.pack(expand=False,fill=None)
        # 8B008B

        #question label
        Label(self.m,
              bg='#0a3d62',
              fg='#ffffff',
              text=r.questions,
              font=('Times New Roman', 19)).pack(pady=50)

        self.var = StringVar()
        #options for the question
        b1 = Radiobutton(self.m,
                         bg='#0a3d62',
                         fg='#ffffff',
                         text=r.answers[0],
                         variable=self.var,
                         value=r.answers[0],
                         command=lambda: self.check(r))
        b2 = Radiobutton(self.m,
                         text=r.answers[1],
                         bg='#0a3d62',
                         fg='#ffffff',
                         variable=self.var,
                         value=r.answers[1],
                         command=lambda: self.check(r))
        b3 = Radiobutton(self.m,
                         text=r.answers[2],
                         variable=self.var,
                         bg='#0a3d62',
                         fg='#ffffff',
                         value=r.answers[2],
                         command=lambda: self.check(r))
        b4 = Radiobutton(self.m,
                         text=r.answers[3],
                         variable=self.var,
                         value=r.answers[3],
                         bg='#0a3d62',
                         fg='#ffffff',
                         command=lambda: self.check(r))
        b1.pack(pady=10)
        b2.pack(pady=10)
        b3.pack(pady=10)
        b4.pack(pady=(10, 20))
        Button(self.m,
               text='Quit',
               padx=20,
               relief='raised',
               bd=3,
               font=('Times New Roman', 12),
               command=lambda: self.topics()
               if messagebox.askquestion('.', 'Do you want to quit the Quiz ?')
               == 'yes' else print('hey works')).pack(pady=10)

    #checking whether the answer is correct
    def check(self, r):
        l1 = Label(self.m)
        l1.pack()
        if self.var.get() == r.correct_answer:
            self.r += 1
            l1.configure(text='Right')
            l1.after(800, self.change())
        else:
            l1.configure(text='Wrong')
            l1.after(800, self.change())

    #jumps to next question
    def change(self):
        self.clear()
        self.start()

    #starts the quiz
    def start(self):
        fr1 = Frame(self.m, bg=self.color1)
        #if all questions are attempted then display a message
        if self.index == len(self.response):
            result = 'Your score is ' + str(self.r) + ' out of ' + str(
                len(self.response)
            ) + '\n\n' + 'Thank you for attending the quiz.'
            Label(self.m,
                  text=result,
                  bd=5,
                  pady=15,
                  font=('Times New Roman', 12),
                  relief='groove').pack(pady=(200, 90), ipadx=50)
            fr1.pack(pady=25)
            Button(fr1,
                   text='Home',
                   padx=38,
                   bg=self.button_color1,
                   font=('Times New Roman', 12),
                   command=lambda: self.homegui()).pack(side=LEFT, padx=15)
            Button(fr1,
                   text='Leaderboard',
                   padx=19,
                   bg=self.button_color1,
                   font=('Times New Roman', 12),
                   command=lambda: self.show_leaderboard()).pack(side=RIGHT,
                                                                 padx=15)
            res = self.db.add_score(self.user_name, self.r)

        #show next question if question are remaining
        else:
            self.display_question(self.response[self.index])
            self.index += 1

    def editprofileGUI(self):
        self.clear()

        self.label_1 = Label(self.m,
                             text='QUIZ GAME',
                             bg=self.color1,
                             fg='white',
                             font=('Times New Roman', 20))
        self.label_1.pack(pady=(42, 72))

        self.ageLabel = Label(self.m,
                              text="Set New Age:",
                              bg=self.color1,
                              fg='white')
        self.ageLabel.pack(padx=(10, 210))

        self.ageInput = Entry(self.m, width=45, font=('Arial', 8, 'bold'))
        self.ageInput.pack(pady=(0, 23))

        self.usernameLabel = Label(self.m,
                                   text="Enter New Username:"******"Enter New Password:"******"Confirm Your New Password: "******"Submit",
                              font=('Times New Roman', 12),
                              command=lambda: self.editProfile())
        self.editBtn.pack(pady=15, ipadx=14)
        # home button
        back_button = Button(self.m,
                             text='Home',
                             bg=self.color1,
                             fg=self.font1,
                             relief='flat',
                             font=('Times New Roman', 20),
                             command=lambda: self.homegui())
        back_button.pack(pady=(25, 15))

    def editProfile(self):
        age = self.ageInput.get()
        username = self.usernameInput.get()
        password = self.passwordInput.get()
        response = self.db.editProfile(
            age,
            username,
            password,
            self.user_id,
        )
        if response == 1:
            #destination="C:\\Codes\\Python Codes\\Pycharm\\tinder\\images\\"+self.pathname.split("/")[-1]
            #shutil.copyfile(self.pathname, destination)
            messagebox.showinfo("Success", "Profile updated successfully")
        else:
            messagebox.showerror("Error", "Some error occured")
예제 #26
0
def main():
    updater = Updater(TELEGRAM_TOKEN)
    dispatcher=updater.dispatcher
    dispatcher.add_error_handler(error)

    conv_handler = ConversationHandler(
            entry_points = [CommandHandler('start', start)],

            states = {
                AFTER_START: [CallbackQueryHandler(callback = login, pattern = '^(login)$'),
                            CallbackQueryHandler(callback = register, pattern = '^(register)$')],

                LOGIN: [MessageHandler(Filters.text, login_verify),
                        CallbackQueryHandler(callback = start, pattern = '^(back)$')],

                VERIFY_LOGIN: [CallbackQueryHandler(callback = login, pattern = '^(login_fail)$'),
                                CallbackQueryHandler(callback = dashboard, pattern = '^(login_success)$')],

                FIRST_NAME: [MessageHandler(Filters.text, showtoken),
                            CallbackQueryHandler(callback = register, pattern = '^(register_back)$')],

                # LAST_NAME: [MessageHandler(Filters.text, showtoken),
                #             CallbackQueryHandler(callback = register, pattern = '^(back)$')],

                NEWLOGIN: [CallbackQueryHandler(callback = dashboard, pattern = '^(dashboard)$'),
                            CallbackQueryHandler(callback = showtoken, pattern = '^(back)$')], 

                AFTER_DASHBOARD: [CallbackQueryHandler(callback = mark_attendance, pattern = '^(attendance)$'),
                                CallbackQueryHandler(callback = browse_events, pattern = '^(browse_events)$'),
                                CallbackQueryHandler(callback = manage_events, pattern = '^(manage_events)$'),
                                CallbackQueryHandler(callback = admin_panel, pattern = '^(admin_panel)$'),
                                CallbackQueryHandler(callback = log_out, pattern = '^(log_out)$')],
                
                AFTER_MARK_ATTENDANCE: [CallbackQueryHandler(callback = dashboard, pattern = '^(back)$'),
                                        MessageHandler(Filters.photo, check_QR_code)],

                AFTER_BROWSE_EVENTS: [CallbackQueryHandler(callback = dashboard, pattern = '^(back)$')],

                AFTER_MANAGE_EVENTS: [CallbackQueryHandler(callback = start_edit_event, pattern = '^[0-9]{4}$'),
                                        CallbackQueryHandler(callback = start_create_event, pattern = '^(create_event)$'),
                                        CallbackQueryHandler(callback = dashboard, pattern = '^(back)$')],
                
                AFTER_START_EDIT_EVENT: [CallbackQueryHandler(callback = cancel_date, pattern = '^(canceldate)'),
                                        CallbackQueryHandler(callback = rename_event, pattern = '^(rename_event)$'),
                                        CallbackQueryHandler(callback = edit_event_desc, pattern = '^(edit_desc)$'),
                                        CallbackQueryHandler(callback = book_venue, pattern = '^(book_venue)$'),
                                        CallbackQueryHandler(callback = request_publish_event, pattern = '^(request_publish)$'),
                                        CallbackQueryHandler(callback = manage_events, pattern = '^(back)$')],
                
                CREATE_NEW_EVENT: [MessageHandler(Filters.text, create_event_name),
                                    CallbackQueryHandler(callback = manage_events, pattern = '^(back)$')],

                CREATE_EVENT_DESC: [MessageHandler(Filters.text, final_create_event)],

                FINAL_CREATE_EVENT: [CallbackQueryHandler(callback = manage_events, pattern = '^(back_to_manage_events)$')],

                RENAME_EVENT: [MessageHandler(Filters.text, process_rename_event),
                                CallbackQueryHandler(callback = start_edit_event, pattern = '^[0-9]{4}$')],

                RENAME_EVENT_CONFIRM: [CallbackQueryHandler(callback = start_edit_event, pattern = '^[0-9]{4}$')],

                EDIT_EVENT_DESCRIPTION: [MessageHandler(Filters.text, process_event_description_edit),
                                        CallbackQueryHandler(callback = start_edit_event, pattern = '^[0-9]{4}$')],

                EDIT_EVENT_DESCRIPTION_CONFIRM: [CallbackQueryHandler(callback = start_edit_event, pattern = '^[0-9]{4}$')],

                BOOK_VENUE: [CallbackQueryHandler(callback = start_edit_event, pattern = '^[0-9]{4}$'),
                            CallbackQueryHandler(callback = book_timing, pattern = '^((?![0-9]{4}).)*$')],

                BOOK_TIMING: [CallbackQueryHandler(callback = inline_handler)],

                BOOK_TIMING_FINAL: [CallbackQueryHandler(callback = start_edit_event, pattern = '^[0-9]{4}$')],
                        
                AFTER_ADMIN_PANEL: [CallbackQueryHandler(callback = dashboard, pattern = '^(back)$')]

            },

            fallbacks = [CommandHandler('cancel', cancel)],
            allow_reentry = True
        )
    dispatcher.add_handler(conv_handler)

    list_pending_events, list_pending_venues, list_eventIDs, list_venueIDs = getPendingEventsVenues()
    # create unique command for each approval and rejection of the events and venue bookings:
    for i in range(len(list_eventIDs)):
        approvecommandtext = 'approveEvent' + str(list_eventIDs[i])
        rejectcommandtext = 'rejectEvent' + str(list_eventIDs[i])
        dispatcher.add_handler(CommandHandler(command = approvecommandtext, callback = admin_process_event))
        dispatcher.add_handler(CommandHandler(command = rejectcommandtext, callback = admin_process_event))
    for i in range(len(list_venueIDs)):
        approvecommandtext = 'approveVenue' + str(list_venueIDs[i])
        rejectcommandtext = 'rejectVenue' + str(list_venueIDs[i])
        dispatcher.add_handler(CommandHandler(command = approvecommandtext, callback = admin_process_venue))
        dispatcher.add_handler(CommandHandler(command = rejectcommandtext, callback = admin_process_venue))

    dispatcher.add_handler(CallbackQueryHandler(callback = admin_panel, pattern = '^(return_admin_panel)$'))

    published_events_list = DB().generate_all_approved_events()
    # create unique command for each registration of events:
    for i in range(len(published_events_list)):
        registercommandtext = 'registerForEvent' + str(published_events_list[i][0])
        dispatcher.add_handler(CommandHandler(command = registercommandtext, callback = confirm_event_registration))

    updater.start_polling()
    updater.idle()
예제 #27
0
#!/usr/bin/env python
import pickle
from dbhelper import DB

db = DB('train.db')
n_feature = int(db.queryone('value','manifest','key="n_feature"')[0])

fin = open('model.dat')
clf = pickle.load(fin)
fin.close

def predict(dic):
    data = [-100]*n_feature
    for m_id, rss in dic.items():
        data[int(m_id)] = float(rss)
    proba = clf.predict_proba([data]).tolist()[0]
    print 'proba--', proba
    return proba
예제 #28
0
#!/usr/bin/env python
from dbhelper import DB
import json

map_mac = {}
map_pt = {}
feas_map = {}
db = DB('train.db')
mac_dic = dict([(mac,m_id) for mac,m_id in db.query(['mac','m_id'],'map_mac')])
pid_dic = dict([(p_id,pt) for p_id,pt in db.query(['p_id','pt'],'map_pt')])
coord_dic = dict([(p_id,(int(x),int(y))) for p_id,x,y in db.query(['p_id','x','y'],'map_pt')])
n_point = int(db.queryone('value','manifest','key="n_point"')[0])
p2p_matrix = [[float('inf')]*n_point for i in range(n_point)]
for i in range(n_point):
    p2p_matrix[i][i] = 0.0
for i,j,dis in db.query(['src_pt','dest_pt','distance'],'relation'):
    p2p_matrix[i][j] = p2p_matrix[j][i] = dis

def get_macid(mac):
    return mac_dic[mac]

def get_pointname(pid):
    return pid_dic[pid]

def get_coordinate(pid):
    return coord_dic[pid]

def has_mac(mac):
    return mac in mac_dic

def transform(entry):