def render_POST_advanced(self, request, response): """ Method POST to register and update an endpoint. :param request: the request of the POST message. :param response: the response to the POST message. :return: the response to the POST message. """ db = DatabaseManager() if request.uri_path == 'rd': if request.content_type != defines.Content_types[ "application/link-format"]: response.code = defines.Codes.BAD_REQUEST.number return self, response uri_query = request.uri_query if "con=" not in uri_query: uri_query += "&con=coap://" + request.source[0] + ":" + str( request.source[1]) result = db.insert(uri_query, request.payload) if type(result) is int: response.code = result else: response.location_path = result response.code = defines.Codes.CREATED.number else: response.code = db.update(request.uri_path, request.uri_query) return self, response
def initialize_ml( protocole="'2.0.0'", N=50, clas='lda' ): # retourne tous les objets utiles , les range dans 2 listes :ml_fft et ml_cartes db = DatabaseManager("data/enregistrements/", "data/table.db") s = "SELECT * FROM mesures WHERE (categorie = 'calcul mental' OR categorie = 'mouvement imaginé' ) AND protocole = " s += protocole db.load(s) ml = Machine_learning_avec_filtrage(db, 10, 100) ml_fft = 0 print( str(len((db.loadedSignal).keys())) + " signal loaded in the database") ml.treat('fft', 0) print("fft treated") for _ in range(N): ml.train(clas) ml_fft += ml.score() / N print(" fft : " + str(ml_fft)) ml.treat('carte', 0) print("catre treated") ml_carte = 0 for _ in range(N): ml.train(clas) ml_carte += ml.score() / N return (ml_fft, ml_carte)
def fetchDatabases(request): try: userID = request.session['userID'] dm = DatabaseManager() return dm.fetchDatabases(userID, json.loads(request.body)) except KeyError: return redirect(loadLoginPage)
def listDBs(request): try: userID = request.session['userID'] dm = DatabaseManager() return dm.listDBs(request, userID) except KeyError: return redirect(loadLoginPage)
def manage_lifetime(self): """ Every 1800 seconds calls the function to delete the expired resources. """ while not self.rd_stopped.isSet(): db = DatabaseManager() db.delete_expired() self.rd_stopped.wait(timeout=1800)
def render_DELETE_advanced(self, request, response): """ Method DELETE to delete an endpoint registration. :param request: the request of the DELETE message. :param response: the response to the DELETE message. :return: the response to the DELETE message. """ if request.uri_path == 'rd': raise NotImplementedError db = DatabaseManager() response.code = db.delete(request.uri_path) return False, response
def render_DELETE_advanced(self, request, response): """ Method DELETE to delete an endpoint registration. :param request: the request of the DELETE message. :param response: the response to the DELETE message. :return: the response to the DELETE message. """ if request.uri_path == 'rd': raise NotImplementedError db = DatabaseManager() response.code = db.delete(request.uri_path) return False, response
def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.setFixedSize(self.size()) pixmapLeft = QPixmap('compareGirlLeft.jpg') m_pixmapLeft = pixmapLeft.scaled(249, 370, QtCore.Qt.IgnoreAspectRatio) self.searchImageLabel.setPixmap(m_pixmapLeft) pixmapRight = QPixmap('compareGirlRight.jpg') m_pixmapRight = pixmapRight.scaled(249, 370, QtCore.Qt.IgnoreAspectRatio) self.currentImageLabel.setPixmap(m_pixmapRight) self.browseButton.clicked.connect(self.importImage) self.searchButton.clicked.connect(self.searchImage) self.dbMgr = DatabaseManager() self.file_name_list = [] self.known_face_encodings = [] self.known_face_names = [] self.known_face_description = [] for result in self.dbMgr.identityCollection.find({}): self.known_face_encodings.append(result['Encodings']) self.known_face_names.append(result['Name']) self.file_name_list.append(result['FilePath']) self.known_face_description.append(result['Description'])
def __set_up_helpers__(self): self.is_admin = True self.database_manager = DatabaseManager() self.logger = Logger() self.smart_home_activator = SmartHomeActivator() self.gesture_detector = GestureDetector() self.gesture_lexer = GestureLexer() self.gesture_parser = GestureParser() self.gesture_detected = None self.process_manager = ProcessManager() self.valid_webcam = None self.smart_home_activator.set_commands( self.database_manager.get_commands()) self.smart_home_activator.set_log_manager(self.database_manager, self.logger)
async def showBooks_step( self, step_context: WaterfallStepContext) -> DialogTurnResult: iduser = step_context.context.activity.from_property.id genres_user = [] user_with_info = DatabaseManager.find_user_info(iduser) genres_user = user_with_info.categories index = random.randint(0, len(genres_user) - 1) category = genres_user[index] code = cat_and_code[category.name] books = SuggestBooksDialog.call_amazon(code) card = SuggestBooksDialog.create_card(books, category.name) step_context.values["books"] = books dic[iduser] = books await step_context.context.send_activity(card) message_text = "Vuoi aggiungere un libro alla tua wishlist?" prompt_message = MessageFactory.text(message_text, message_text, InputHints.expecting_input) return await step_context.prompt( ConfirmPrompt.__name__, PromptOptions(prompt=prompt_message, retry_prompt=MessageFactory.text( '''Vuoi aggiungere un libro alla tua wishlist? Scrivi yes o no''')))
def submitDatabaseDeletion(request): try: userID = request.session['userID'] result = pluginManager.preSubmitDatabaseDeletion(request) if result != 200: return result dm = DatabaseManager() coreResult = dm.submitDatabaseDeletion(userID, json.loads(request.body)) result = pluginManager.postSubmitDatabaseDeletion(request, coreResult) if result != 200: return result return coreResult except KeyError: return redirect(loadLoginPage)
def createDatabase(request): try: result = pluginManager.preCreateDatabase(request) if result != 200: return result userID = request.session['userID'] dm = DatabaseManager() coreResult = dm.createDatabase(request, userID) result = pluginManager.postCreateDatabase(request, coreResult) if result != 200: return result return coreResult except KeyError: return redirect(loadLoginPage)
def changePassword(request): try: userID = request.session['userID'] result = pluginManager.preChangePassword(request) if result != 200: return result dm = DatabaseManager() coreResult = dm.changePassword(userID, json.loads(request.body)) result = pluginManager.postChangePassword(request, coreResult) if result != 200: return result return coreResult except KeyError: return redirect(loadLoginPage)
async def cancel_step( self, step_context: WaterfallStepContext) -> DialogTurnResult: result = step_context.result user = step_context.values["user"] book_to_remove = step_context.values["book_to_remove"] if result: user.wishlist.remove(book_to_remove) DatabaseManager.remove_wishlist(user.idUser, book_to_remove) step_context.values["user"] = user message_text = "Il libro {} è stato rimosso correttamente.".format( book_to_remove.name) await step_context.context.send_activity( MessageFactory.text(message_text)) return await step_context.next([]) else: await step_context.context.send_activity( MessageFactory.text("Operazione annullata")) return await step_context.end_dialog()
def render_GET_advanced(self, request, response): """ Method GET to search registration parameters. :param request: the request of the GET message. :param response: the response to the GET request. :return: the response to the GET request. """ if (request.accept != defines.Content_types["application/link-format"]) and (request.accept is not None): response.code = defines.Codes.NOT_ACCEPTABLE.number return self, response db = DatabaseManager() result = db.search(request.uri_query, "ep") if type(result) is int: response.code = result else: response.code = defines.Codes.CONTENT.number response.payload = result response.content_type = defines.Content_types["application/link-format"] return self, response
async def login_step(self, step_context: WaterfallStepContext) -> DialogTurnResult: step_context.values["skip"] = False if step_context.result: iduser=step_context.context.activity.from_property.id if not DatabaseManager.user_is_registered(iduser): await step_context.context.send_activity(MessageFactory.text('''Non sei registrato, ti farò selezionare tre categorie di interesse per effettuare la registrazione''')) return await step_context.begin_dialog(self.registration_dialog_id) else: messages = DatabaseManager.search_messages_user(iduser) if len(messages)>0: message_text = "Dal tuo ultimo accesso ci sono novità sui tuoi libri nella wishlist.\n" for message in messages: message_text+=message+"\n" message = MessageFactory.text(message_text, message_text, InputHints.ignoring_input) await step_context.context.send_activity(message) return await step_context.next([]) else: await step_context.context.send_activity("Il login non è andato a buon fine. Riprova.") return await step_context.end_dialog()
def render_GET_advanced(self, request, response): """ Method GET to search resource links. :param request: the request of the GET message. :param response: the response to the GET request. :return: the response to the GET request. """ if (request.accept != defines.Content_types["application/link-format"] ) and (request.accept is not None): response.code = defines.Codes.NOT_ACCEPTABLE.number return self, response db = DatabaseManager() result = db.search(request.uri_query, "res") if type(result) is int: response.code = result else: response.code = defines.Codes.CONTENT.number response.payload = result response.content_type = defines.Content_types[ "application/link-format"] return self, response
def __init__(self): super(Mediator, self).__init__() # Set up the user interface from Designer self.ui = Ui_arsDialog() self.ui.setupUi(self) self.dbManager = DatabaseManager() # Make some local modifications. self.ui.loginButton.clicked.connect(self.handleLogin) self.ui.adminLogoutButton.clicked.connect(self.handleLogout) self.ui.employeeLogoutButton.clicked.connect(self.handleLogout) self.ui.managerLogoutButton.clicked.connect(self.handleLogout) self.ui.addUserMenuButton.clicked.connect(self.showAddUserView) self.ui.searchUserMenuButton.clicked.connect(self.showModifyUserView) self.ui.addButton.clicked.connect(self.handleAddUser) self.ui.backAddButton.clicked.connect(self.handleBackAddButton) self.ui.backModifyButton.clicked.connect(self.handleBackModifyButton) self.ui.searchButton.clicked.connect(self.handleSearchUser) self.ui.deleteButton.clicked.connect(self.handleDeleteUser) self.ui.updateButton.clicked.connect(self.handleUpdateUser) self.searchSuccess = False self.confirmUpdate = False
def render_GET_advanced(self, request, response): """ Method GET to read endpoint links. :param request: the request of the GET message. :param response: the response to the GET request. :return: the response to the GET request. """ if request.uri_path == 'rd': raise NotImplementedError if (request.accept != defines.Content_types["application/link-format"]) and (request.accept is not None): response.code = defines.Codes.NOT_ACCEPTABLE.number return self, response res = "res=" + request.uri_path db = DatabaseManager() result = db.search(res, "res") if type(result) is int: response.code = result else: response.code = defines.Codes.CONTENT.number response.payload = result response.content_type = defines.Content_types["application/link-format"] return self, response
async def register(self, step_context: WaterfallStepContext) -> DialogTurnResult: result = step_context.result selected = step_context.values["selected"] categories = step_context.values["categories"] for i,c in enumerate(categories): if result.lower()==c.name.lower(): selected.append(c) del categories[i] step_context.values["selected"] = selected step_context.values["categories"] = categories break message_text = ("Hai selezionato correttamente la categoria {}".format(result)) message = MessageFactory.text(message_text, message_text, InputHints.ignoring_input) await step_context.context.send_activity(message) iduser=step_context.context.activity.from_property.id DatabaseManager.add_user(iduser, selected) message_text = ("Sei registrato.") message = MessageFactory.text(message_text, message_text, InputHints.ignoring_input) await step_context.context.send_activity(message) return await step_context.end_dialog()
def main(): global server_socket, clients server_socket, clients = None, [] global last_auto_resched try: defs.db_m = DatabaseManager() defs.job_m = defs.db_m.get_jobManager() if not defs.job_m: defs.job_m = JobManager() defs.db_m.register_jobManager(defs.job_m) transaction.commit() last_auto_resched = time() server_socket = listen_on(SERVER_BIND, SERVER_PORT) socket2addr = {} print(WELCOME_MESSAGE) print("Enter 'Help' or 'H' for more details.\n") show_prompt() while True: r, _, _ = select([server_socket, stdin] + clients, [], []) for c in r: if c == server_socket: c, addr = server_socket.accept() socket2addr[c] = addr clients.append(c) elif c == stdin: handle_request(input()) show_prompt() else: handle_client(c, socket2addr[c]) auto_resched() transaction.commit() except Exception as e: ndprint('Error occurred: \n\t' + repr(e)) finally: print("Start closing.") if defs.db_m: defs.db_m.close() if server_socket: server_socket.close() for c in clients: c.close() print("Done closing.")
def render_GET_advanced(self, request, response): """ Method GET to read endpoint links. :param request: the request of the GET message. :param response: the response to the GET request. :return: the response to the GET request. """ if request.uri_path == 'rd': raise NotImplementedError if (request.accept != defines.Content_types["application/link-format"] ) and (request.accept is not None): response.code = defines.Codes.NOT_ACCEPTABLE.number return self, response res = "res=" + request.uri_path db = DatabaseManager() result = db.search(res, "res") if type(result) is int: response.code = result else: response.code = defines.Codes.CONTENT.number response.payload = result response.content_type = defines.Content_types[ "application/link-format"] return self, response
def render_POST_advanced(self, request, response): """ Method POST to register and update an endpoint. :param request: the request of the POST message. :param response: the response to the POST message. :return: the response to the POST message. """ db = DatabaseManager() if request.uri_path == 'rd': if request.content_type != defines.Content_types["application/link-format"]: response.code = defines.Codes.BAD_REQUEST.number return self, response uri_query = request.uri_query if "con=" not in uri_query: uri_query += "&con=coap://" + request.source[0] + ":" + str(request.source[1]) result = db.insert(uri_query, request.payload) if type(result) is int: response.code = result else: response.location_path = result response.code = defines.Codes.CREATED.number else: response.code = db.update(request.uri_path, request.uri_query) return self, response
async def first_step( self, step_context: WaterfallStepContext) -> DialogTurnResult: iduser = step_context.context.activity.from_property.id user = DatabaseManager.find_user_info(iduser) step_context.values["user"] = user dic[iduser] = user.wishlist card, flag = self.create_wishlist_card(user.wishlist) await step_context.context.send_activity(card) if flag: message_text = "Puoi cancellare un libro dalla tua wishlist oppure tornare al menu principale. Cosa desideri fare?" prompt_message = MessageFactory.text(message_text, message_text, InputHints.expecting_input) return await step_context.prompt( TextPrompt.__name__, PromptOptions(prompt=prompt_message)) return await step_context.end_dialog()
def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) # setting up the background oImage = QImage("backgroundMain5.png") sImage = oImage.scaled(self.size(), QtCore.Qt.IgnoreAspectRatio) palette = QPalette() palette.setBrush(10, QBrush(sImage)) self.setPalette(palette) # Connectivity with the dialog boxes self.surveillanceButton.clicked.connect(self.openSurveillanceDialog) self.identifyButton.clicked.connect(self.openIdentifyDialog) self.dbMgr = DatabaseManager()
def saveEncodingInFile(): dbMgr = DatabaseManager() folderName = "Images" faces = {} file_name_list = [] for fileName in os.listdir(folderName): image = face_recognition.load_image_file(os.path.join(folderName, fileName)) image_face_encoding = face_recognition.face_encodings(image)[0] faces[os.path.splitext(fileName)[0]] = image_face_encoding.tolist() file_name_list.append(os.path.join(folderName, fileName)) for key, file_name in zip(faces.keys(), file_name_list): myvalue = { "id": key, "Name": "", "Encodings": faces[key] ,"Description": "", "Miscellaneous": "", "FilePath": file_name } result = list(dbMgr.identityCollection.find(myvalue)) if len(result) == 0: dbMgr.identityCollection.insert_one(myvalue)
async def add_step(self, step_context: WaterfallStepContext) -> DialogTurnResult: title = step_context.result book_to_add = self.find_book(title) iduser = step_context.context.activity.from_property.id if book_to_add is not None: if DatabaseManager.add_book_wishlist(iduser, book_to_add, [book_to_add.genre]): message_text = "Il libro {} è stato aggiunto alla tua wishlist.".format( book_to_add.name) await step_context.context.send_activity( MessageFactory.text(message_text)) else: message_text = "Il libro {} non è stato aggiunto alla tua wishlist.".format( book_to_add.name) await step_context.context.send_activity( MessageFactory.text(message_text)) return await step_context.end_dialog()
async def add_to_wishlist( self, step_context: WaterfallStepContext) -> DialogTurnResult: result = step_context.result iduser = step_context.context.activity.from_property.id book_to_add = BookInfo() books = step_context.values["books"] for book in books: if book.site.lower() == result.lower(): book_to_add = book break for book in books: if book.name is not None: book_to_add.name = book.name break for book in books: if book.author is not None: book_to_add.author = book.author break genres = [] for book in books: if book.genre is not None: genres.append(book.genre) if book_to_add.site is not None: if DatabaseManager.add_book_wishlist(iduser, book_to_add, genres): message_text = ( "Il libro {} è stato aggiunto alla tua wishlist".format( book_to_add.name)) message = MessageFactory.text(message_text, message_text, InputHints.ignoring_input) await step_context.context.send_activity(message) return await step_context.end_dialog() message_text = ( "Si è verificato un errore durante l'aggiunta del libro {} alla tua wishlist" .format(book_to_add.name)) message = MessageFactory.text(message_text, message_text, InputHints.ignoring_input) await step_context.context.send_activity(message) return await step_context.end_dialog()
def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.setFixedSize(self.size()) self.face_detection_widget = FaceDetectionWidget() self.record_video = RecordVideo() # Connect the image data signal and slot together image_data_slot = self.face_detection_widget.facerec_from_webcam self.record_video.image_data.connect(image_data_slot) comboboxChanged = self.comboboxChangedEvent self.face_detection_widget.comboValueChanged.connect(comboboxChanged) self.record_video.start_recording() layout = QtWidgets.QVBoxLayout() layout.addWidget(self.face_detection_widget) self.widget.setLayout(layout) self.comboBox.currentTextChanged.connect(self.updateInfo) self.dbMgr = DatabaseManager()
class Mediator(QDialog): def __init__(self): super(Mediator, self).__init__() # Set up the user interface from Designer self.ui = Ui_arsDialog() self.ui.setupUi(self) self.dbManager = DatabaseManager() # Make some local modifications. self.ui.loginButton.clicked.connect(self.handleLogin) self.ui.adminLogoutButton.clicked.connect(self.handleLogout) self.ui.employeeLogoutButton.clicked.connect(self.handleLogout) self.ui.managerLogoutButton.clicked.connect(self.handleLogout) self.ui.addUserMenuButton.clicked.connect(self.showAddUserView) self.ui.searchUserMenuButton.clicked.connect(self.showModifyUserView) self.ui.addButton.clicked.connect(self.handleAddUser) self.ui.backAddButton.clicked.connect(self.handleBackAddButton) self.ui.backModifyButton.clicked.connect(self.handleBackModifyButton) self.ui.searchButton.clicked.connect(self.handleSearchUser) self.ui.deleteButton.clicked.connect(self.handleDeleteUser) self.ui.updateButton.clicked.connect(self.handleUpdateUser) self.searchSuccess = False self.confirmUpdate = False def showAddUserView(self): self.ui.addNameLineEdit.setText("") self.ui.addPhoneLineEdit.setText("") self.ui.addPasswordLineEdit.setText("") self.ui.confirmPasswordLineEdit.setText("") self.ui.addLoginLineEdit.setText("") self.ui.addUserTypeComboBox.setCurrentText("") self.ui.viewsStackedWidget.setCurrentIndex( self.ui.viewsStackedWidget.indexOf(self.ui.addUserView)) def showModifyUserView(self): self.ui.searchLoginLineEdit.setText("") self.ui.modifyNameLineEdit.setText("") self.ui.modifyPhoneLineEdit.setText("") self.ui.modifyPasswordLineEdit.setText("") self.ui.modifyLoginLineEdit.setText("") self.ui.modifyUserTypeComboBox.clear() self.searchSuccess = False self.confirmUpdate = False self.ui.viewsStackedWidget.setCurrentIndex( self.ui.viewsStackedWidget.indexOf(self.ui.modifyUserView)) def handleBackAddButton(self): self.ui.addUserPromptLabel.setText("Enter all the details to add user") self.ui.viewsStackedWidget.setCurrentIndex(1) def handleBackModifyButton(self): self.ui.modifyUserPromptLabel.setText("Enter the LoginId") self.ui.viewsStackedWidget.setCurrentIndex(1) def handleAddUser(self): name = self.ui.addNameLineEdit.text() phone = self.ui.addPhoneLineEdit.text() ps = self.ui.addPasswordLineEdit.text() loginId = self.ui.addLoginLineEdit.text() cps = self.ui.confirmPasswordLineEdit.text() userType = self.ui.addUserTypeComboBox.currentText() if (cps == ps): user = User(name, phone, loginId, ps, userType) status = self.dbManager.addUser(user) if (status == 1): self.ui.addUserPromptLabel.setText("New User Added!") self.showAddUserView() else: self.ui.addUserPromptLabel.setText( "Error adding user details. Try again.") else: self.ui.addUserPromptLabel.setText( "Password and Confirm Password fields do not match. Try again." ) def handleSearchUser(self): loginId = self.ui.searchLoginLineEdit.text() user = self.dbManager.searchUserByLoginId(loginId) if user == None: self.ui.modifyUserPromptLabel.setText("Not found. Try again.") self.showModifyUserView() else: self.searchSuccess = True self.ui.modifyUserPromptLabel.setText("User details found.") self.ui.modifyNameLineEdit.setText(user.name) self.ui.modifyPhoneLineEdit.setText(user.phone) self.ui.modifyLoginLineEdit.setText(user.loginId) self.ui.modifyPasswordLineEdit.setText(user.password) self.ui.modifyUserTypeComboBox.clear() self.ui.modifyUserTypeComboBox.addItem(user.userType) def handleLogout(self): self.ui.viewsStackedWidget.setCurrentIndex(0) def handleUpdateUser(self): if self.searchSuccess == False: self.ui.modifyUserPromptLabel.setText( "First search for the user. Enter a valid loginId.") self.showModifyUserView() return if self.confirmUpdate == False: self.ui.modifyNameLineEdit.setReadOnly(False) self.ui.modifyPhoneLineEdit.setReadOnly(False) self.ui.modifyLoginLineEdit.setReadOnly(False) self.ui.modifyPasswordLineEdit.setReadOnly(False) self.ui.modifyUserTypeComboBox.clear() self.ui.modifyUserTypeComboBox.addItem("Employee") self.ui.modifyUserTypeComboBox.addItem("Manager") self.ui.modifyUserTypeComboBox.addItem("Admin") self.ui.modifyUserPromptLabel.setText( "Edit the fields below and click Update to confirm Update.") self.confirmUpdate = True else: name = self.ui.modifyNameLineEdit.text() phone = self.ui.modifyPhoneLineEdit.text() ps = self.ui.modifyPasswordLineEdit.text() loginId = self.ui.modifyLoginLineEdit.text() userType = self.ui.modifyUserTypeComboBox.currentText() self.confirmUpdate = False user = User(name, phone, loginId, ps, userType) status = self.dbManager.updateUser(user) if status == 1: self.ui.modifyUserPromptLabel.setText( "Update successful. Enter loginId to search another user") else: self.ui.modifyUserPromptLabel.setText( "Update unsuccessful! Try again") self.showModifyUserView() def handleDeleteUser(self): if self.searchSuccess == True: if self.confirmUpdate == False: loginId = self.ui.searchLoginLineEdit.text() status = self.dbManager.deleteUser(loginId) if status == 1: self.ui.modifyUserPromptLabel.setText( "Delete successful. Enter Login Id to search another user" ) else: self.ui.modifyUserPromptLabel.setText( "Delete unsuccessful. Try Again.") else: self.ui.modifyUserPromptLabel.setText( "Cannot delete in the middle of update operation. Try again. Enter loginId" ) else: self.ui.modifyUserPromptLabel.setText( "First search for the user. Enter valid loginId") self.showModifyUserView() def handleLogin(self): loginId = self.ui.loginLineEdit.text() password = self.ui.passwordLineEdit.text() ps = self.dbManager.getPassword(loginId) print(ps) if ps != None: if password == ps: userType = self.dbManager.getUserType(loginId) self.ui.loginLineEdit.setText("") self.ui.passwordLineEdit.setText("") self.ui.loginPromptLabel.setText( "Please Enter your Login Id and Password to Login") if userType == 'Admin': self.ui.viewsStackedWidget.setCurrentIndex(1) elif userType == 'Employee': self.ui.viewsStackedWidget.setCurrentIndex(4) else: self.ui.viewsStackedWidget.setCurrentIndex(5) else: self.ui.loginPromptLabel.setText( "Incorrect Password. Please try again.") else: self.ui.loginPromptLabel.setText( "Invalid Login Id. Please try again.")
def __init__(self, stdscreen, userpass): self.screen = stdscreen self.username = userpass['user'] self.password = userpass['pass'] self.database_manager = DatabaseManager(self.screen, userpass) self.screen_manager = ScreenManager(self.screen) self.table_manager = TableManager(self.screen, userpass) self.query_manager = queryDB(self.screen, userpass) headeroptions = {'user': self.username} #I ran into an error here when trying to set cursur to invisible #this if/try makes sure that both the version of curses and the #terminal support this functionality if hasattr(curses, 'curs_set'): try: curses.curs_set(0) except: pass importer = impexp(self.screen, userpass) data_items = [ ('Import', self.database_manager.display_all_databases_opt, importer.list_sql_files), ('Export', self.database_manager.display_all_databases_opt, importer.export) ] data = Menu(data_items, self.screen, headeroptions) browse_database_items = [ ('List Databases', self.database_manager.display_all_databases), ('Create', self.database_manager.create_new_database), ('Copy', self.database_manager.display_all_copy_database), ('Drop', self.database_manager.display_all_delete_database) ] browse_database = Menu(browse_database_items, self.screen, headeroptions) browse_table_items = [ ('List Tables', self.database_manager.display_all_databases_opt, self.table_manager.listTables), ('Create', self.database_manager.display_all_databases_opt, self.table_manager.createTable), ('Delete', self.database_manager.display_all_databases_opt, self.table_manager.list_drop_tables) ] browse_table = Menu(browse_table_items, self.screen, headeroptions) query_items = [ ('Enter A Query', self.database_manager.display_all_databases_opt, self.query_manager.do), ('Save A Query', self.query_manager.save), ('View Past Queries', self.database_manager.display_all_databases_opt, self.query_manager.get_history), ('View Saved Queries', self.database_manager.display_all_databases_opt, self.query_manager.get_saved) ] query = Menu(query_items, self.screen, headeroptions) main_menu_items = [('Data Management', data.display), ('Browse Databases', browse_database.display), ('Browse Tables', browse_table.display), ('Query', query.display)] main_menu = Menu(main_menu_items, self.screen, headeroptions) main_menu.display()
class NonVerbalSmartHomeRecognitionSystem: def __init__(self): self.__set_up_helpers__() self.__set_up_gestures__() self.__set_up_commands__() self.__set_up_camera__() self.__set_up_configuration__() self.__set_up_gui__() def main_loop(self): ret, frame = self.cap.read() # Rescaling frame with these numbers to fit it in the GUI debug tab frame = self.rescale_frame(frame, 56, 47) timestamp = datetime.utcnow() # Aggregates gestures into gesture sequences. gesture_sequences = self.gesture_lexer.lex(timestamp, self.minimum_time_increment, self.maximum_time_increment) # Creates a child process to check for predefined patterns of gestures in the list of gesture sequences self.process_manager.add_process(self.gesture_parser.parse_patterns, (gesture_sequences, timestamp)) frame = self.gesture_detector.detect(frame, timestamp, self.open_eye_threshold) self.process_manager.on_done() self.gui_manager.set_debug_frame(cv2.flip(frame, 1)) self.gesture_detected = self.gesture_detector.get_gesture_detected() self.gui_manager.set_gesture_background(self.gesture_detected) new_log_line = self.logger.get_output() if self.gesture_detected != None: self.gui_manager.update_log_text(new_log_line) self.update_commands() def rescale_frame(self, frame, width_frame_percent, height_frame_percent): if self.valid_webcam: width = int(frame.shape[1] * width_frame_percent / 100) height = int(frame.shape[0] * height_frame_percent / 100) dim = (width, height) return cv2.resize(frame, dim, interpolation=cv2.INTER_AREA) else: return frame def set_open_eye_threshold(self, new_ear_value): self.open_eye_threshold = float(new_ear_value) self.database_manager.set_open_eye_threshold(self.open_eye_threshold) def set_minimum_time_increment(self, new_minimum_time_increment): self.minimum_time_increment = int(new_minimum_time_increment) self.database_manager.set_minimum_time_increment( new_minimum_time_increment) def set_maximum_time_increment(self, new_maximum_time_increment): self.maximum_time_increment = int(new_maximum_time_increment) self.database_manager.set_maximum_time_increment( new_maximum_time_increment) def add_command(self, gesture_sequence, command_text, device_name): self.gesture_parser.add_pattern(gesture_sequence) self.database_manager.set_command(gesture_sequence, command_text, device_name) commands = self.database_manager.get_commands() self.smart_home_activator.set_commands(commands) def update_commands(self): for command_map in self.database_manager.get_commands(): self.add_command(command_map['gesture_sequence'], command_map['command_text'], command_map['device_name']) def on_close(self): # Close down OpenCV self.cap.release() cv2.destroyAllWindows() # Close the GUI self.gui_manager.destroy_gui() # Close log file. self.logger.close() def __set_up_helpers__(self): self.is_admin = True self.database_manager = DatabaseManager() self.logger = Logger() self.smart_home_activator = SmartHomeActivator() self.gesture_detector = GestureDetector() self.gesture_lexer = GestureLexer() self.gesture_parser = GestureParser() self.gesture_detected = None self.process_manager = ProcessManager() self.valid_webcam = None self.smart_home_activator.set_commands( self.database_manager.get_commands()) self.smart_home_activator.set_log_manager(self.database_manager, self.logger) def __set_up_gestures__(self): self.gesture_detector.on_gesture(self.gesture_lexer.add) self.gesture_detector.on_gesture(self.database_manager.set_gesture) self.gesture_detector.on_gesture(self.logger.log_gesture) def __set_up_commands__(self): self.gesture_parser.on_gesture_sequence( self.logger.log_gesture_sequence) self.gesture_parser.on_gesture_sequence( lambda gesture_sequence, timestamp, was_recognised: self.database_manager.set_gesture_sequence( gesture_sequence, timestamp, was_recognised)) self.gesture_parser.on_gesture_sequence( lambda gesture_sequence, timestamp, was_recognised: self. smart_home_activator.activate(gesture_sequence, was_recognised)) self.update_commands() def __check_camera_resolution__(self): ret, frame = self.cap.read() try: if ((frame.shape[1]) >= 1280) and ((frame.shape[0]) >= 720): self.valid_webcam = True return True else: self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 600) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 400) self.valid_webcam = False return False except: return False def __set_up_camera__(self): self.cap = cv2.VideoCapture(0) self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) def __set_up_configuration__(self): self.open_eye_threshold = self.database_manager.get_open_eye_threshold( ) self.minimum_time_increment = self.database_manager.get_minimum_time_increment( ) self.maximum_time_increment = self.database_manager.get_maximum_time_increment( ) def __set_up_gui__(self): self.gui_manager = GuiManager(self.cap, self.database_manager, self.is_admin, self.__check_camera_resolution__()) self.__set_up_gui_values__() self.__set_up_gui_watchers__() self.gui_manager.start(self.main_loop, self.on_close) def __set_up_gui_values__(self): self.gui_manager.set_initial_ear(self.open_eye_threshold) self.gui_manager.set_initial_minimum_time_increment( self.minimum_time_increment) self.gui_manager.set_initial_maximum_time_increment( self.maximum_time_increment) def __set_up_gui_watchers__(self): self.gui_manager.on_ear_change(self.set_open_eye_threshold) self.gui_manager.on_minimum_time_increment_change( self.set_minimum_time_increment) self.gui_manager.on_maximum_time_increment_change( self.set_maximum_time_increment) self.gui_manager.on_new_command(self.add_command)
from botbuilder.dialogs import ComponentDialog, DialogContext, DialogTurnResult, PromptValidatorContext, DialogTurnStatus, PromptOptions, TextPrompt, WaterfallDialog, WaterfallStepContext from botbuilder.schema import ActivityTypes, InputHints from botbuilder.core import CardFactory, MessageFactory from .cancel_and_help_dialog import CancelAndHelpDialog from botbuilder.schema._models_py3 import Attachment, CardAction, HeroCard from botbuilder.schema._connector_client_enums import ActionTypes import pyodbc import os import json from botbuilder.dialogs.prompts.choice_prompt import ChoicePrompt from botbuilder.dialogs.choices import Choice from botbuilder.dialogs.choices.list_style import ListStyle from databaseManager import DatabaseManager CATEGORIES=DatabaseManager.find_categories() for cat in CATEGORIES: if cat.name == "Genere sconosciuto": CATEGORIES.remove(cat) class RegistrationDialog(CancelAndHelpDialog): def __init__(self, dialog_id: str = None): super(RegistrationDialog, self).__init__(dialog_id or RegistrationDialog.__name__) self.add_dialog(TextPrompt(TextPrompt.__name__, RegistrationDialog.validate)) self.add_dialog( WaterfallDialog( "WFDialog", [self.select_first, self.select_second, self.select_third,
else: log(ERROR, "The message is not a dictionary object!!".format(message)) # response = "arp response" # This function echoes the message back to the client. if threadedServer is not None: threadedServer.replyMessage(connection, response) else: log(ERROR, "threaded server is none!") if __name__ == '__main__': sDeviceName = socket.gethostname() threadManager = ThreadManager() threadedServer = initializeThreadedServer(receivedMessage, threadManager) databaseManager = DatabaseManager() # databaseManager.insertUser("derp"); # databaseManager.insertUser("a3roy"); # databaseManager.insertUser("shyuan"); # databaseManager.joinGroup("a3roy","group1"); # databaseManager.joinGroup("a3roy","group2"); # databaseManager.joinGroup("a3roy","group3"); # databaseManager.joinGroup("shyuan","group1"); # databaseManager.joinGroup("shyuan","group2"); # databaseManager.joinGroup("shyuan","group3"); # databaseManager.exitGroup("shyuan","group3"); # log(INFO,"group1 {}".format(databaseManager.getUsersInGroup("group1")))