def mousePressEvent(self, event): if event.button() == Qt.MiddleButton: self.offset = event.globalPos() - self.frameGeometry().topLeft() ## print(self.offset) elif event.button() == Qt.LeftButton: position = QPoint(event.pos().x(), event.pos().y()) color = QColor.fromRgb(self.local_image.pixel(position)) self.fgcolor = color ## print(color.redF(), color.greenF(), color.blueF(), color.alphaF()) # print values from a QColor if krita: self.updateKritaForeGroundColor(color) self.drawGUI() self.update() # Refresh the drawn colors. elif event.button() == Qt.RightButton: position = QPoint(event.pos().x(), event.pos().y()) color = QColor.fromRgb(self.local_image.pixel(position)) self.bgcolor = color ## print(color.redF(), color.greenF(), color.blueF(), color.alphaF()) # print values from a QColor if krita: self.updateKritaBackGroundColor(color) self.drawGUI() self.update() # Refresh the drawn colors. elif event.buttons() == Qt.XButton1: QApplication.beep() # Do something here... Change a texture/mask/page, call a function, etc.... elif event.buttons() == Qt.XButton2: QApplication.beep()
def zoom(self, facteur): if facteur < 0.0: facteur = -1.0 / facteur else: coordMax = self.scene().carreMosaiQUnivers.tailleDansVue(self) if coordMax * facteur >= VueMosaiQ.INT_MAX: QApplication.beep() return # normalement, en utilisant AnchorUnderMouse, l'instruction 'scale' # seule devrait suffire... mais le résultat obtenu est notablement # imprécis, surtout pour les petit facteurs de zooms ; # pour pallier le manque de précision de AnchorUnderMouse, on # implémente une technique alternative, de plus bas niveau : on prend # les coordonnées courantes du pointeur dans la vue (posVue1), on les # transforme en coordonnées de la scène (posScene), après l'opération # de zoom, on transfome les coordonnées de la scène en coordonnées de # la vue transformée (posVue2) ; comme on veut que le curseur reste # sur la position de la scène, on fait une translation de la vue # selon le vecteur (posVue2 - posVue1) posVue1 = self.mapFromGlobal(QCursor.pos()) posScene = self.mapToScene(posVue1) self.scale(facteur, facteur) posVue2 = self.mapFromScene(posScene) dxVue = posVue2.x() - posVue1.x() dyVue = posVue2.y() - posVue1.y() # self.translate(dxVue,dyVue) # ne fonctionne pas ! self.hScrollBar.setValue(self.hScrollBar.value() + dxVue) self.vScrollBar.setValue(self.vScrollBar.value() + dyVue) self.scene().changed.emit(None)
def __on_load_movies_finished(self): # re-enable gui elements # TODO # self.set_gui_enabled_load_movies(True) self.__main_window.set_loading_panel_visible(False) # play a sound QApplication.beep()
def on_close_tab(self): """Close the current tab.""" index = self.tab_widget.currentIndex() if index < 0: QApplication.beep() return self.tab_widget.removeTab(index) self._update_ui()
def notFound(self): self.lastStart = 0 # We set the cursor to the end if the search was unsuccessful self.fileContentText.moveCursor(QTextCursor.End) # Make system beep QApplication.beep()
def load_movies_end(self): # re-enable gui elements self.set_gui_enabled_load_movies(True) # auto resize table columns self._ui.table_movies.resizeColumnToContents(0) # hide loading panel self._ui.panel_loading.setVisible(False) # play a sound QApplication.beep()
def show_relaxation_image(self): utils.stop_vibration(self.vibration_serial) self.destroy_timers() self.create_timers() print("Relax") QApplication.beep() self.class_image_pixmap.load( self.configurations.feedback_provider.get_image()) self.class_image_view.setPixmap(self.class_image_pixmap) self.next_trial_timer.timeout.connect(self.next_class) self.next_trial_timer.start(self.configurations.relaxation_period * 1000)
def f(): try: fgoFunc.suspendFlag=False fgoFunc.terminateFlag=False fgoFunc.fuse.reset() self.signalFuncBegin.emit() self.applyAll() func(*args,**kwargs) except Exception as e:logger.exception(e) finally: self.signalFuncEnd.emit() QApplication.beep()
def confirm(self): lengthOffeatures = len(self.getFeatures()) label = len(self.getLabel()) if(lengthOffeatures == 0 or label == 0): QApplication.beep() msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Error") msg.setInformativeText('Select at least one feature and select the label!') msg.setWindowTitle("Error") msg.exec_() else: self.accept()
def getScoreAction(self, score): QApplication.beep() value = self.scoreNumber.intValue() newValue = value + score self.scoreNumber.display(newValue) #更新speed if value / levelStep != newValue / levelStep: self.levelNumber.display(newValue / levelStep) self.canvas.speed *= percent
def displayMessage(msgCode): msg = QMessageBox() if msgCode == MSG_SUCCESS: msg.setIcon(QMessageBox.Information) msg.setWindowTitle("Zapis pomyślny") msg.setText("Zapisano wyniki generacji do pliku!") elif msgCode == MSG_INPUT_FILE_ERROR: msg.setIcon(QMessageBox.Critical) msg.setText("Plik zawiera nieprawidłową sekwencję DNA. " "Sprawdź poprawność podanego pliku.") msg.setInformativeText('Dopuszczalne małe/duże litery A,C,G,T oraz białe znaki.') msg.setWindowTitle("Błąd pliku z sekwencją") elif msgCode == MSG_OUTPUT_FILE_ERROR: msg.setIcon(QMessageBox.Critical) msg.setText("Niepoprawne rozszerzenie pliku wyjściowego.") msg.setInformativeText("Plik musi mieć nazwę i być w formacie .csv.") msg.setWindowTitle("Błąd pliku wyjściowego") elif msgCode == MSG_INVALID_PATH: msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Błąd zapisu") msg.setText("Podana ścieżka nie istnieje!") elif msgCode == MSG_ILLEGAL_CHARS: msg.setIcon(QMessageBox.Critical) msg.setWindowTitle("Błąd zapisu") msg.setText("Nazwa pliku nie może zawierać znaków < > : ? * | \"") elif msgCode == MSG_FILE_EXISTS: msg.setIcon(QMessageBox.Question) msg.setWindowTitle("Plik istnieje") msg.setText("Plik o podanej ścieżce i nazwie już istnieje. Nadpisać?") msg.setStandardButtons(msg.Yes | msg.No) buttonY = msg.button(msg.Yes) buttonY.setText("Tak") buttonN = msg.button(msg.No) buttonN.setText("Nie") QApplication.beep() msg.exec_() if msg.clickedButton() == buttonY: return True else: return False QApplication.beep() msg.exec_()
def base_except_hook(exc_type, exc_value, exc_traceback): """ Used to handle all uncaught exceptions. :type exc_type: class :type exc_value: Exception :type exc_traceback: Traceback """ global app global box if issubclass(exc_type, KeyboardInterrupt): app.quit() else: if not box: m1 = 'This is embarrassing ...\n\n' \ 'A critical error has just occurred. ' \ 'Eddy will continue to work, however a reboot is highly recommended.' m2 = 'If the problem persists please <a href="{}">submit a bug report</a>.'.format(BUG_TRACKER) m3 = ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback)) box = QMessageBox() box.setIconPixmap(QPixmap(':/images/eddy-sad')) box.setWindowIcon(QIcon(':/images/eddy')) box.setWindowTitle('Unhandled error!') box.setText(m1) box.setInformativeText(m2) box.setDetailedText(m3) box.setStandardButtons(QMessageBox.Close|QMessageBox.Ok) buttonOk = box.button(QMessageBox.Ok) buttonOk.setText('Close') buttonQuit = box.button(QMessageBox.Close) buttonQuit.setText('Quit {}'.format(APPNAME)) connect(buttonOk.clicked, box.close) connect(buttonQuit.clicked, app.quit) # noinspection PyArgumentList QApplication.beep() box.exec_() box = None
def newTab(self, currentIndex): # File Dialog (uses csv directory) directory = os.path.dirname(os.path.realpath(__file__)) + "\csv" if not os.path.exists(directory): os.makedirs(directory) QApplication.beep() # Path to Selected CSV File path = QFileDialog.getOpenFileName( self, "Open CSV File", directory, "Comma-Separated Values File (*.csv)")[0] if not path: return filename = QUrl.fromLocalFile(path).fileName() # Dialog for user to select features and label progressDialog = ProgressDialog(None, None, 0, 100, self) progressDialog.setWindowTitle("Reading " + filename + "...") progressDialog.setValue(0) progressDialog.show() QApplication.processEvents() selectionFeaturesDialog = SelectionFeaturesDialog(path) progressDialog.setWindowTitle("Done") progressDialog.setValue(100) progressDialog.close() QApplication.processEvents() QApplication.beep() dialogCode = selectionFeaturesDialog.exec_() #If Dialog was cancelled, then avoid opening a new tab if dialogCode == 0: return features = selectionFeaturesDialog.getFeatures() label = selectionFeaturesDialog.getLabel() tabGroupBox = AlgorithmGroupBox(path, features, label) pathToNewCSVIcon = os.path.dirname( os.path.realpath(__file__)) + "\\assets" + "\\csv_icon.png" self.addTab(tabGroupBox, QIcon(pathToNewCSVIcon), filename) self.setCurrentWidget(tabGroupBox)
def moveToPrevious(self): self.read_segmentation_params() save_folder = os.path.join(self.imageFolder, 'result_segmentation') ioSeg.save_segmentation_params( save_folder, [os.path.split(fin)[-1] for fin in self.flist_in], self.chosen_masks, self.down_shapes, self.thinnings, self.smoothings) new_start = np.clip(self.start - self.n_shown_max, 0, self.n_imgs) if self.start == new_start: QApplication.beep() print('No previous images to display!') return self.n_shown = self.start - new_start self.start = new_start self.stop = self.start + self.n_shown # np.clip(self.stop-20,20,self.n_imgs) plt.close(self.overview) self.remake()
def textEntry(self, ch): """Searches for button match from text entry. """ if not ch: return False if ord(ch) == 8: # backspace key self.entryStr = self.entryStr[:-1] elif ord(ch) == 27: # escape key self.entryStr = '' elif ch == '\t': # tab key cmds = [ key for key in self.cmdDict.keys() if key.startswith(self.entryStr.upper()) ] if len(cmds) == 1: button = self.cmdDict[cmds[0]] button.clickEvent() button.tmpDown(300) self.entryStr = '' else: QApplication.beep() elif ch == ':' and not self.entryStr: self.entryStr = ':' # optional command prefix else: newStr = (self.entryStr + ch).upper() if newStr == ':Q': # vim-like shortcut newStr = 'EXIT' button = self.cmdDict.get(newStr.lstrip(':')) if button: button.clickEvent() button.tmpDown(300) self.entryStr = '' else: if [ key for key in self.cmdDict.keys() if key.startswith(newStr.lstrip(':')) ]: self.entryStr += ch else: QApplication.beep() return False self.updateEntryLabel() return True
def closeEvent(self, evt): """Handle window close.""" # confirm the close widget = self.centralWidget() if type(widget) is StartupWidget: # don't allow this if we are analyzing files if widget.analyze_thread: MainWindow.show_info_msg("Please cancel the analysis first.") QApplication.beep() evt.ignore() return else: # check if we should confirm the exit if globals.app_settings.value(CONFIRM_EXIT, True, type=bool): rc = self.ask("Do you want to the close the program?", QMessageBox.Ok | QMessageBox.Cancel, QMessageBox.Cancel) if rc != QMessageBox.Ok: evt.ignore() # save the window settings globals.app_settings.setValue(MAINWINDOW_GEOMETRY, self.saveGeometry())
def stop_recording(self, reference: bool = False): if self.reading_timer is not None: self.reading_timer.deleteLater() self.board.stop_stream() self.recording = False self.recording_reference = False self.recording_progress_dialog.setValue(self.recording_progress_dialog.maximum()) recording_duration_in_samples = self.recording_progress_dialog.maximum() selected_freq = self.frequency_slider.value() if reference: sample_count = min(self.reference_eeg_data.get_channel_data(0).shape[0], recording_duration_in_samples) sample_count -= global_config.SAMPLING_RATE * self.DEFAULT_SAMPLE_PADDING self.index_generator.add_slice(0, self.eeg_sample_count - sample_count, self.eeg_sample_count) else: sample_count = min(self.eeg_data_buffer.get_channel_data(0).shape[0], recording_duration_in_samples) sample_count -= global_config.SAMPLING_RATE * self.DEFAULT_SAMPLE_PADDING self.index_generator.add_slice(selected_freq, self.eeg_sample_count - sample_count, self.eeg_sample_count) if self.root_directory_label.text() != "": self.index_generator.write_to_file(self.root_directory_label.text()) QApplication.beep() start = self.DEFAULT_SAMPLE_PADDING * global_config.SAMPLING_RATE if reference: print(f"reference size: {self.reference_eeg_data.sample_count()}") self.record_btn.setEnabled(True) # self.record_reference_btn.setEnabled(False) self.reference_eeg_data.filter_all_channels( global_config.SAMPLING_RATE, self.DEFAULT_BANDPASS_MIN, self.DEFAULT_BANDPASS_MAX, True ) self.reference_eeg_data = utils.EegData(self.reference_eeg_data.to_row_array()[:, start:]) print("Reference data saved...") else: print("Stopping the recording...") print("Filtering data...") self.eeg_data_buffer.filter_all_channels( global_config.SAMPLING_RATE, self.DEFAULT_BANDPASS_MIN, self.DEFAULT_BANDPASS_MAX, subtract_average=True ) self.eeg_data_buffer = utils.EegData(self.eeg_data_buffer.to_row_array()[:, start:]) print(f"data size: {self.eeg_data_buffer.sample_count()}") reference_c3_extractor = self.reference_eeg_data.feature_extractor( self.DEFAULT_C3_CHANNEL_INDEX, global_config.SAMPLING_RATE ) reference_cz_extractor = self.reference_eeg_data.feature_extractor( self.DEFAULT_CZ_CHANNEL_INDEX, global_config.SAMPLING_RATE ) reference_c4_extractor = self.reference_eeg_data.feature_extractor( self.DEFAULT_C4_CHANNEL_INDEX, global_config.SAMPLING_RATE ) data_c3_extractor = self.eeg_data_buffer.feature_extractor( self.DEFAULT_C3_CHANNEL_INDEX, global_config.SAMPLING_RATE ) data_cz_extractor = self.eeg_data_buffer.feature_extractor( self.DEFAULT_CZ_CHANNEL_INDEX, global_config.SAMPLING_RATE ) data_c4_extractor = self.eeg_data_buffer.feature_extractor( self.DEFAULT_C4_CHANNEL_INDEX, global_config.SAMPLING_RATE ) for i in range(self.c3_amplitude_bar_set.count()): current_freq = int(self.frequencies[i].replace(" Hz", "")) if current_freq == selected_freq: freq_band = utils.FrequencyBand( current_freq - self.DEFAULT_FREQUENCY_PADDING, current_freq + self.DEFAULT_FREQUENCY_PADDING) c3_diff, cz_diff, c4_diff = self.amplitude_diff(freq_band, reference_c3_extractor,reference_cz_extractor, reference_c4_extractor, data_c3_extractor, data_cz_extractor, data_c4_extractor) print(f"C3 diff = {c3_diff}") print(f"Cz diff = {cz_diff}") print(f"C4 diff = {c4_diff}") self.c3_amplitude_bar_set.replace(i, c3_diff) self.cz_amplitude_bar_set.replace(i, cz_diff) self.c4_amplitude_bar_set.replace(i, c4_diff) utils.auto_adjust_axis(self.amplitude_axis, [self.c3_amplitude_bar_set, self.cz_amplitude_bar_set, self.c4_amplitude_bar_set], self.DEFAULT_GRAPH_PADDING)
def beep(): QApplication.beep()
def print_results(self): try: while True: result = self.q.get_nowait() whitelisted_ids = [] whitelist_file = get_setting("whitelist_file_location") # whitelist_file is the empty strign if no file has been specified if whitelist_file: whitelist_file = Path(whitelist_file) with open(whitelist_file) as f: lines = f.readlines() for line in lines: # remove comment if there is one line = line.rsplit("#")[0] # allow whitespace on either end of the id line = line.strip() # allow empty lines anywhere in the file if line == "": continue # TODO: nicer error if the line is an invalid id? try: line = int(line) except ValueError: self.write_to_terminal_signal.emit("<div style='color:#ff5252'>Invalid " f"user id in whitelist file:</div> \"{line}\" is not a valid user id.") continue whitelisted_ids.append(line) ts = datetime.now() # ts = timestamp message = None ischeat = False if isinstance(result, StealResult): if result.earlier_replay.user_id in whitelisted_ids: pass elif result.similarity < get_setting("steal_max_sim"): ischeat = True message = get_setting("message_steal_found").format(ts=ts, sim=result.similarity, r=result, replay1=result.replay1, replay2=result.replay2, earlier_replay_mods_short_name=result.earlier_replay.mods.short_name(), earlier_replay_mods_long_name=result.earlier_replay.mods.long_name(), later_replay_mods_short_name=result.later_replay.mods.short_name(), later_replay_mods_long_name=result.later_replay.mods.long_name()) elif result.similarity < get_setting("steal_max_sim_display"): message = get_setting("message_steal_found_display").format(ts=ts, sim=result.similarity, r=result, replay1=result.replay1, earlier_replay_mods_short_name=result.earlier_replay.mods.short_name(), earlier_replay_mods_long_name=result.earlier_replay.mods.long_name(), later_replay_mods_short_name=result.later_replay.mods.short_name(), later_replay_mods_long_name=result.later_replay.mods.long_name()) if isinstance(result, RelaxResult): if result.replay.user_id in whitelisted_ids: pass elif result.ur < get_setting("relax_max_ur"): ischeat = True message = get_setting("message_relax_found").format(ts=ts, r=result, replay=result.replay, ur=result.ur, mods_short_name=result.replay.mods.short_name(), mods_long_name=result.replay.mods.long_name()) elif result.ur < get_setting("relax_max_ur_display"): message = get_setting("message_relax_found_display").format(ts=ts, r=result, replay=result.replay, ur=result.ur, mods_short_name=result.replay.mods.short_name(), mods_long_name=result.replay.mods.long_name()) if isinstance(result, CorrectionResult): if result.replay.user_id in whitelisted_ids: pass elif len(result.snaps) > 0: ischeat = True snap_message = get_setting("message_correction_snaps") snap_text = "\n".join([snap_message.format(time=snap.time, angle=snap.angle, distance=snap.distance) for snap in result.snaps]) message = get_setting("message_correction_found").format(ts=ts, r=result, replay=result.replay, snaps=snap_text, mods_short_name=result.replay.mods.short_name(), mods_long_name=result.replay.mods.long_name()) if isinstance(result, TimewarpResult): if result.replay.user_id in whitelisted_ids: pass elif result.frametime < get_setting("timewarp_max_frametime"): ischeat = True message = get_setting("message_timewarp_found").format(ts=ts, r=result, replay=result.replay, frametime=result.frametime, mods_short_name=result.replay.mods.short_name(), mods_long_name=result.replay.mods.long_name()) elif result.frametime < get_setting("timewarp_max_frametime_display"): message = get_setting("message_timewarp_found_display").format(ts=ts, r=result, replay=result.replay, frametime=result.frametime, mods_short_name=result.replay.mods.short_name(), mods_long_name=result.replay.mods.long_name()) if message or isinstance(result, AnalysisResult): self.show_no_cheat_found = False if message: self.write(message) if isinstance(result, AnalysisResult): self.add_result_signal.emit(result) else: if ischeat: QApplication.beep() QApplication.alert(self) # add to Results Tab so it can be played back on demand self.add_result_signal.emit(result) except Empty: try: result = self.url_analysis_q.get_nowait() self.add_url_analysis_result_signal.emit(result) except Empty: pass self.print_results_event.set()
def serial_recvThread(self): #print(threading.current_thread().name, "start") while self.recvThreadState: try: data = self.serial.read_all() except Exception as e: self.recvThreadState = False print('Received thread error: ', str(e)) break if data and not self.memStream.closed: if self.rxCount > 1000000: #self.textBrowser.clear() self.on_clear_triggered() # self.rxCount = 0 # self.txCount = 0 # self.streamCursor = 0 # self.memStream.close() # self.textBrowser.clear() # self.InfoRx.setText('RX: {} Bytes'.format(self.rxCount)) # self.InfoTx.setText('TX: {} Bytes'.format(self.txCount)) # self.monitorCnt = 0 # self.lcdNumber.display(self.monitorCnt) # self.memStream = StringIO() self.rxCount += len(data) # self.InfoRx.setText('RX: {} Bytes'.format(self.rxCount)) self.sigRxCnt.emit(self.rxCount) if self.radioButtonRecvASCII.isChecked(): data = data.decode("gbk", "ignore") else: data = ' '.join("%02X" % x for x in data) data = data + ' ' #接收监测 if self.checkBoxMonitor.isChecked(): jsonMonitorEnable = 1 jsonMonitorString = self.lineEditMonitor.text() if len(self.lineEditMonitor.text()): cnt = data.count(self.lineEditMonitor.text()) if cnt > 0: self.monitorCnt += cnt # self.lcdNumber.display(self.monitorCnt) self.sigLcdNum.emit(self.monitorCnt) if self.checkBoxBeep.isChecked(): QApplication.beep() else: jsonMonitorEnable = 0 jsonMonitorString = '' #显示时间 if self.checkBoxTime.isChecked(): jsonTimeEnable = 1 jsonTimestamp = '[' + datetime.now().strftime( '%H:%M:%S.%f')[:-3] + ']' else: jsonTimeEnable = 0 jsonTimestamp = '' #自动换行 if self.checkBoxNewLine.isChecked(): jsonLineEnable = 1 else: jsonLineEnable = 0 jsonRecv = 1 jsonDataLength = len(data) jsonHead = '{"Received":%d, "Length":%d, "TimeEnable":%d, "Timestamp":"%s", "LineEnable":%d, '\ '"MonitorEnable":%d, "Monitor":"%s"}\n'%(jsonRecv, jsonDataLength, jsonTimeEnable, \ jsonTimestamp, jsonLineEnable, jsonMonitorEnable, jsonMonitorString) self.stream_write(jsonHead) self.stream_write(data) self.sigDispaly.emit() continue time.sleep(0.02)
def buttonReleased(self): QApplication.beep()