def __init__(self, args): self.args = args self.context_limit = self.args['context_limit'] self.message_context = [] # create database instance self.db = DB(self.args['files'], self.args['dim'], self.context_limit)
def receive(username, groupID, time, msg): user = UserService.getProfile() user_groupID = user[-1] if user_groupID == groupID: DB.execute( 'INSERT INTO message_group(from_username, group_id, time, message) VALUES (?,?,?,?)', (username, groupID, time, msg))
def infoBroadcast() -> dict: user_info = DB.execute( 'SELECT `user`.username, `user`.firstname, `user`.lastname, `user`.faculty, `user`.year, `user`.group_id, `self`.is_admin, `self`.is_member FROM `user` INNER JOIN `self` ON `user`.username=`self`.username' ).fetchone() role = 'none' if user_info[6] == 1: # isAdmin role = 'admin' elif user_info[7] == 1: role = 'member' info = { 'username': user_info[0], 'role': role, 'firstname': user_info[1], 'lastname': user_info[2], 'faculty': user_info[3], 'year': user_info[4], 'isAdmin': user_info[6], 'isMember': user_info[7], 'groupID': user_info[5], 'group_name': '', 'max_person': 0 } if (user_info[5] != '0'): group_info = DB.execute( 'SELECT * FROM `group` WHERE group_id=? LIMIT 1', (user_info[5], )).fetchone() info['group_name'] = group_info[1] info['max_person'] = group_info[2] return info
def getUser(username=None) -> Union[list, tuple]: users = [] if (username is None): result = DB.execute('SELECT * FROM `user`') users = result.fetchall() else: result = DB.execute( 'SELECT * FROM `user` WHERE username=? LIMIT 1', (username, )) users = result.fetchone() return users
def send(msg): username = UserService.getProfile()[0] timestamp = datetime.utcnow() msgEntity = BroadcastMessageEntity(username, { 'timestamp': str(timestamp), 'message': msg }) setup.net.sendMessageBroadcast(msgEntity) DB.execute( 'INSERT INTO message_broadcast(from_username, time, message) VALUES (?,?,?)', (username, str(timestamp), msg))
def initMe(username: str, firstname, lastname, faculty, year): username = username.replace(':', '') DB.executemultiplesql([( 'REPLACE INTO `user`(username, firstname, lastname, faculty, year) VALUES(?,?,?,?,?)', ( username, firstname, lastname, faculty, year, )), ('REPLACE INTO self(username) VALUES (?)', (username, ))])
def createGroup(groupName, limitPerson): username = UserService.getProfile()[0] DB.executemultiplesql([( 'REPLACE INTO `group`(group_id, group_name, max_person) VALUES (?,?,?)', (username, groupName, limitPerson)), ('UPDATE `user` SET group_id=? WHERE username=?', ( username, username, )), ('UPDATE self SET is_admin=1 WHERE username=?', (username, ))])
def getGroup(groupID: str = None) -> Union[list, tuple]: groups = [] if (groupID is None): result = DB.execute( 'SELECT `group`.group_id, `group`.group_name, `group`.max_person, COUNT(username) FROM `user` LEFT JOIN `group` WHERE `group`.group_id=`user`.group_id AND `group`.group_id != "0"' ) groups = result.fetchall() print(groups) else: result = DB.execute( 'SELECT * FROM `group` WHERE group_id=? LIMIT 1', (groupID, )) groups = result.fetchone() return groups
def send(msg): user = UserService.getProfile() username = user[0] groupID = user[-1] if (groupID != '0'): timestamp = datetime.utcnow() msgEntity = GroupMessageEntity(username, groupID, { 'timestamp': str(timestamp), 'message': msg }) setup.net.sendMessageGroup(msgEntity) DB.execute( 'INSERT INTO message_group(from_username, group_id, time, message) VALUES (?,?,?,?)', (username, groupID, str(timestamp), msg))
def updateGroup(username, newGroupID): username = username.replace(':', '') curr_username = UserService.getProfile()[0] if curr_username == username: DB.executemultiplesql([ ('UPDATE `user` SET group_id=? WHERE username=?', (newGroupID, username)), ('UPDATE `self` SET is_member=1 WHERE username=?', (username, )) ]) else: DB.execute('UPDATE `user` SET group_id=? WHERE username=?', ( newGroupID, username, ))
def browsefile(self): file = QtWidgets.QFileDialog.getOpenFileName(self, 'Выберите файл БД',filter='*.db *.sqlite')[0] db = DB(file,debug=True) print(file) self.db = db self.setActive(True) self.updateCombo()
import json import time brokerIP = '192.168.0.230' test = {"mac": "", "cmd": "switch", "val": "on"} app = Flask(__name__, static_url_path='', template_folder="../smaroomans-client/dist/") app.config['MQTT_BROKER_URL'] = brokerIP app.config['MQTT_BROKER_PORT'] = 1883 app.config['MQTT_REFRESH_TIME'] = 1.0 # refresh time in seconds myDB = DB(app) myDB._initialisation() mqtt = Mqtt(app) sensorManager = SensorManager(myDB, brokerIP, mqtt) statemachine = StateMachine(myDB, sensorManager) statemachineThread = StopableThread( name="statemachineThread", function=statemachine.checkConditions, args={}) statemachineThread.start() roomManager = RoomManager(myDB, sensorManager) cors = CORS(app, resources={r"/api/*": {"origins": "*"}}) @mqtt.on_connect() def handle_connect(client, userdata, flags, rc): sensorManager.on_connect(client, userdata, flags, rc)
def isMember() -> bool: return DB.execute('SELCT * FROM self LIMIT 1').fetchone()[2]
def isAdmin() -> bool: return DB.execute('SELECT * FROM self LIMIT 1').fetchone()[1]
def receive(username, time, msg): DB.execute( 'INSERT INTO message_broadcast(from_username, time, message) VALUES (?,?,?)', (username, time, msg))
class Bot: 'bot class' def __init__(self, args): self.args = args self.context_limit = self.args['context_limit'] self.message_context = [] # create database instance self.db = DB(self.args['files'], self.args['dim'], self.context_limit) def preloadDB(self): # preload vectors self.db.preloadDB(self.args['lang']) def fillContext(self, message_vec): self.message_context.append(message_vec) self.message_context = self.message_context[-self.context_limit:] def answer(self, question): message_vec = self.db.string2contextvec(question, self.args['dim']) # add question to the message context self.fillContext(message_vec) # build question index question_index = self.db.loadQuestionIndex(question) bot_dialog_context = np.divide(np.sum(np.array(self.message_context), axis=0), self.context_limit) # sort question index based on similarity to asked question sortedQI = lalg.getSortedQuestionIndex(bot_dialog_context, question_index) # print(sortedQI) if len(sortedQI) > 0: final_answer = self.db.loadAnswerByIndex(sortedQI[0]) else: final_answer = "hmm.. hmm.." # fetch top 10 Q&A pair for sorted QIndex # fetched_pairs = [] # for i in range(10): # fetched_pairs.append(self.db.dialog_pair[sortedQI[i]].split('\t')) # # create context vectors for each fetched pair # fetched_pairs_context_vec = [] # for pair in fetched_pairs: # sum_ = np.zeros((self.args['dim'],), dtype=float) # count = 0 # for w_question_ in pair: # for w_question in w_question_.split(' '): # try: # tmp = np.array(self.db.context_vectors[w_question], dtype=float) # if w_question is not '': # count = count + 1 # sum_ = np.add(sum_, tmp) # except: # print(w_question) # if count > 0: # sum_ = np.divide(sum_, count) # fetched_pairs_context_vec.append(sum_) # # create context vector for user messages including last one # input_message_context_vec = np.zeros((self.args['dim'],), dtype=float) # count = 0 # for input_m in self.message_context: # for w_question in input_m.split(' '): # try: # tmp = np.array(self.db.context_vectors[w_question], dtype=float) # if w_question is not '': # count = count + 1 # input_message_context_vec = np.add(input_message_context_vec, tmp) # except: # print(w_question) # if count > 0: # input_message_context_vec = np.divide(input_message_context_vec, count) # # sort question pairs based on similarity to user messages context # final_answer_order = lalg.getSortedQuestionIndex(input_message_context_vec, np.array(fetched_pairs_context_vec)) # final_answer = fetched_pairs[final_answer_order[0]][1] # add question to the message context message_vec = self.db.string2contextvec(final_answer, self.args['dim']) self.fillContext(message_vec) return final_answer
def getAll(): result = DB.execute( 'SELECT `user`.firstname, time, message FROM message_broadcast INNER JOIN `user` ON message_broadcast.from_username=`user`.username ORDER BY time ASC' ) return result.fetchall()
def updateProfile(firstname, lastname, faculty, year): username = UserService.getProfile()[0] DB.execute( 'UPDATE `user` SET firstname=?, lastname=?, faculty=?, year=? WHERE username=?', (firstname, lastname, faculty, year, username))
def addUser(username, firstname, lastname, faculty, year, group_id='0'): username = username.replace(':', '') DB.execute( 'REPLACE INTO `user`(username, firstname, lastname, faculty, year, group_id) VALUES (?,?,?,?,?,?)', (username, firstname, lastname, faculty, year, group_id))
GROUP_1 = PARSER.add_argument_group(title='optional parameters') GROUP_1.add_argument('-n', metavar='Name', nargs=1, type=str, \ help='set name of your xml', default=['dir2.xml']) ARGS = PARSER.parse_args() NAME = ARGS.n[0] DIR = ARGS.d[0] try: print('crunching "%s" directory...' % DIR) if(u_file_exists(NAME)): if(not u_user_input(\ r'new xml file already exist, do you wanna proceed? [Y/N] ')): m_quit() START = time() DBS = DB(DIR, s_temporary_db()) DBS.run() XML = DBS.xml_build() XML.write(NAME) del XML if(u_file_exists(NAME)): print('xml generated in %s' % s_ut_crono(START)) else: print('xml not generated') m_quit(False) except KeyboardInterrupt: # Ctrl + C pass except Exception: # remove for develop pass
def removeUser(username): DB.execute('DELETE FROM `user` WHERE username=?', (username, ))
def getAll(): groupID = UserService.getProfile()[-1] result = DB.execute( 'SELECT `user`.firstname, time, message FROM message_group INNER JOIN `user` ON message_group.from_username=`user`.username WHERE message_group.group_id=? ORDER BY time ASC', (groupID, )) return result.fetchall()
def getProfile() -> tuple: username = DB.execute('SELECT * FROM self').fetchone()[0] return UserService.getUser(username)
def addGroup(groupID, groupName, maxPerson=4): groupID = groupID.replace(':', '') DB.execute( 'INSERT INTO `group`(group_id, group_name, max_person) VALUES (?,?,?)', (groupID, groupName, maxPerson))
import socket import asyncio from database.database import DB db = DB('data.db', debug=True) strkdict = { 'username': '******', 'socket': 'TEXT', 'port': 'TEXT', 'adress': 'TEXT' } db.createTable('users', strkdict) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto=0) sock.bind(('', 9090)) sock.listen(10) async def connection(conn, addr): while True: data = conn.recv(1024).decode() if not data: break conn.send(data.upper().encode()) conn.close() while True: conn, addr = sock.accept() print('connected:', addr)
def getMember(groupID): result = DB.execute('SELECT * FROM `user` WHERE group_id=?', (groupID, )) return result.fetchall()
def getAvailableUser() -> list: result = DB.execute( 'SELECT username, firstname, lastname, faculty, year FROM `user` WHERE group_id="0"' ) return result.fetchall()