class Dashboard(QtGui.QMainWindow): def __init__(self): super(Dashboard, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.show()
class appWin(QMainWindow): def __init__(self): super(appWin, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.config() def config(self): self.ui.btn_segway_gazebo_rviz.clicked.connect(self.btn) self.ui.btn_topics.clicked.connect(self.btn) self.ui.btn_topics.setEnabled(False) self.genericThread = GenericThread(command_run, delay=0.3) def btn(self, sender): if (self.sender().objectName() == 'btn_segway_gazebo_rviz'): cmd = 'gazebo' self.genericThread = GenericThread(command_run, cmd, delay=0.3) self.genericThread.start() self.ui.btn_topics.setEnabled(True) elif (self.sender().objectName() == 'btn_topics'): cmd = 'topics' self.genericThread = GenericThread(command_run, cmd, delay=0.3) self.genericThread.start() print(cmd)
class DoubanPic(QtGui.QMainWindow): def __init__(self, parent=None): super(DoubanPic, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.douban = DoubanBackend(self) self.ui.btn_download.clicked.connect(self.get_pic) self.ui.ipt_address.returnPressed.connect(self.get_pic) def get_pic(self): origin_url = unicode(self.ui.ipt_address.text()) url = self.douban.check_url(origin_url) if not url: logging_entry.info("Not a valid origin_link") self.init() return logging_entry.info("Ready to analysis album info.") album_link = self.douban.get_album_link(url) if not album_link: logging_entry.info("Not a valid album_link") self.init() return self.msg(u"开始获取图片地址") photo_links = self.douban.get_photo_links(album_link) self.msg(u"生成txt下载文件") filename = self.douban.generate_txt(photo_links) self.msg(u"下载文件已生成,{}.txt 和 {}_large.txt".format(filename, filename)) def init(self): self.ui.ipt_address.setText("") self.ui.ipt_address.setFocus() def msg(self, message): self.ui.status_bar.showMessage(message)
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.monWidget = MonitorWidget(self.ui.widgetMonitor) self.roiWidget = RoiWidget(self.ui.widgetROI)
def __init__(self): # Boilerplate PySide6 app constructors super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) # SINGLE tab self.ui.roll_btn.pressed.connect(self.clear_roll_output) # Clears previous result when pressed self.ui.roll_btn.released.connect(self.roll_btn) # Initiates single roll when released self.ui.atk_btn_1.clicked.connect(self.atk_btn_1) # Dice button connections... self.ui.atk_btn_2.clicked.connect(self.atk_btn_2) self.ui.atk_btn_3.clicked.connect(self.atk_btn_3) self.ui.def_btn_1.clicked.connect(self.def_btn_1) self.ui.def_btn_2.clicked.connect(self.def_btn_2) self.atk_list = [] # SINGLE dice container (atk) self.def_list = [] # SINGLE dice container (def) # ONSLAUGHT tab self.ui.onslaught_btn.pressed.connect(self.clear_onslaught_output) # Clears previous result when pressed self.ui.onslaught_btn.released.connect(self.onslaught_btn) # Initiates onslaught roll when released self.ui.atk_army_total.valueChanged.connect(self.atk_available_armies) # Updates current atk army total self.ui.def_army_total.valueChanged.connect(self.def_available_armies) # Updates current def army total self.onslaught_atk_dice = [] # ONSLAUGHT dice container (atk) self.onslaught_def_dice = [] # ONSLAUGHT dice container (def) self.atk_total_armies = 0 # Current atk army total self.def_total_armies = 0 # Current def army total self.atk_army_losses = 0 # Post-ONSLAUGHT atk losses self.def_army_losses = 0 # Post-ONSLAUGHT def losses
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle("Quiz It!") self.ui.tableWidget.setColumnCount(4) self.ui.tableWidget.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.headers = ["Lock", "Question", "Answer", "Category", "No.", "ID"] self.ui.tableWidget.setColumnCount(len(self.headers)) self.ui.tableWidget.hideColumn( self.ui.tableWidget.columnCount() - 1) # hide last column, as this is where its id is stored self.ui.comboBox.addItems(questions_dao.get_categories()) self.set_headers() self.ui.pushButton.clicked.connect(self.refresh_button) self.ui.saveButton.clicked.connect(self.save_button) self.ui.openButton.clicked.connect(self.open_button)
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('Watlow EZ-Zone PM3 Temperature Control') # Icon from: https://icons8.com/icons/set/temperature self.setWindowIcon(QIcon(':icon.ico')) # Tab and Widget Setup self.controlTabWidget = ControlTabWidget() self.configTabWidget = ConfigTabWidget() self.ui.tabWidget.insertTab(0, self.controlTabWidget, 'Control') self.ui.tabWidget.insertTab(1, self.configTabWidget, 'Config') #self.ui.tabWidget.insertTab(1, self.massSpecWidget, 'Mass Spec Plot') self.configTabWidget.fnameEmitted.connect( self.controlTabWidget.parseConfigFile) self.controlTabWidget.statusEmitted.connect(self._displayStatus) self.configTabWidget.tabIndexEmitted.connect(self._changeTab) self.configTabWidget.manualAddEmitted.connect( self.controlTabWidget.handleManualAdd) def _displayStatus(self, message): self.ui.statusbar.showMessage(message, 10000) def _changeTab(self, index): self.ui.tabWidget.setCurrentIndex(index)
def __init__(self, client): QMainWindow.__init__(self) # setup ui self.setAttribute(Qt.WA_TranslucentBackground) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.bt_send.clicked.connect(self.bt_send_message) self.ui.textEdit_message.installEventFilter(self) self.ui.textEdit_message.setFocus() # declare elements necessary for message list object self.client = client self.brush = QBrush() self.model = QtGui.QStandardItemModel() # setup connection info self.HOST = '127.0.0.1' self.PORT = 60453 self.ENCODE_FORMAT = "utf-8" self.nick = 'nick' # create object of Receiver class, connect to messageSignal and run it in separate thread self.receiver = Receiver(self.client) self.receiver.messageSignal.connect(self.new_message) self.thread1 = threading.Thread(target=self.receiver.run) self.thread1.start()
def __init__(self, parent=None): super(DoubanPic, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.douban = DoubanBackend(self) self.ui.btn_download.clicked.connect(self.get_pic) self.ui.ipt_address.returnPressed.connect(self.get_pic)
class MainQT5(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.action_New_View.triggered.connect(self.new_view) self.ui.action_Tile.triggered.connect(self.tile) self.ui.action_Settings.triggered.connect(self.settings) self.new_view().showMaximized() #self.plot() self.loadSettings() def plot(self): widget = PlotWidget() self.ui.mdiArea.addSubWindow(widget); widget.show() return widget def settings(self): widget = SettingsWidget() self.ui.mdiArea.addSubWindow(widget); widget.show() return widget def new_view(self): widget = ImageWidget() self.ui.mdiArea.addSubWindow(widget); widget.show() return widget def tile(self): if self.ui.mdiArea.currentSubWindow().isMaximized(): self.ui.mdiArea.currentSubWindow().showNormal() position = QtCore.QPoint(0, 0) for window in self.ui.mdiArea.subWindowList(): rect = QtCore.QRect(0, 0, self.ui.mdiArea.width(), self.ui.mdiArea.height() / len(self.ui.mdiArea.subWindowList())) window.setGeometry(rect) window.move(position) position.setY(position.y() + window.height()) def loadSettings(self): if not os.path.exists(Configuration.configuration_file): return dictionary = None with open(Configuration.configuration_file, 'rb') as f: dictionary = pickle.load(f) for name, value in dictionary.items(): setattr(Configuration, name, value)
def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Connessione segnali ad eventi self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.VisualizzaProg)
def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.currentItemsSB = [] # Used to store variables to be displayed in status bar at the bottom right self.verbose = True # Initialization. Used in the thread generated in application self.fs = 10; self.N = 50; self.dt = 1.0/self.fs self.sample_time = self.N*self.dt self.data = [] self.R01 = 10000 self.R02 = 10000 self.R1 = 10000 self.R2 = 10000 self.K1 = 3950 self.K2 = 3950 self.delay = 0 self.calibrateButton = QPushButton() # self.calibrateButton.setMinimumSize(QSize(0, 0)) # self.calibrateButton.setMaximumSize(QSize(88, 21)) self.calibrateButton.setObjectName("calibrateButton") self.ui.gridLayout.addWidget(self.calibrateButton, 4, 0, 1, 2) self.calibrateButton.setText("Calibrate!") self.setStyleSheet(qdarkstyle.load_stylesheet()) self.getLogo() self.getFonts() self.initalConnections() # self.initialGraphSettings() self.arduinoStatusLed() # self.initialTimer() # self.initialState() # self.ui.graphWidgetOutput.setLabel('left',"<span style=\"color:white;font-size:16px\">Speed (m/s)</span>") # self.ui.graphWidgetOutput.setLabel('bottom',"<span style=\"color:white;font-size:16px\">Time (s)</span>") # self.ui.graphWidgetOutput.setTitle("Speed", color="w", size="12pt") # self.ui.graphWidgetInput.setLabel('left',"<span style=\"color:white;font-size:16px\">°C</span>") # self.ui.graphWidgetInput.setLabel('bottom',"<span style=\"color:white;font-size:16px\">Time (s)</span>") # self.ui.graphWidgetInput.setTitle("Temperature", color="w", size="12pt") # # self.currentValueSB(self.course) # self.course = "Sound" self.list_ports() self.COM = str(self.com_ports[0]) self.ui.com_port.addItems(self.com_ports) self.ui.com_port.setCurrentIndex(self.com_ports.index(self.COM)) atexit.register(self.closeSerial)
def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.selected_project = "" self.projects = db.getProjects() if self.projects: self.populateProjectList(self.projects) else: pass
def __init__(self, parent=None): self.__isDrag = False self.__startPos = QtCore.QPoint(0, 0) #UI初期化処理 super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.menubar.addMenu('File') #ディレクトリ関連の処理 self.ui.listView.clicked.connect(self.nextDir)
class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.progress) def progress(self): item = QtGui.QListWidgetItem(self.ui.listWidget) item_widget = progress.Ui_("It works") item.setSizeHint(item_widget.sizeHint()) self.ui.listWidget.addItem(item) self.ui.listWidget.setItemWidget(item,item_widget)
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filename = '' self.threshold = 0 self.h_file = h5py.File QtCore.QObject.connect(self.ui.pushButton_browse, QtCore.SIGNAL("clicked()"), self.browse) QtCore.QObject.connect(self.ui.pushButton_start, QtCore.SIGNAL("clicked()"), self.start) QtCore.QObject.connect(self.ui.pushButton_auto_threshold, QtCore.SIGNAL("clicked()"), self.auto_threshold) QtCore.QObject.connect(self.ui.comboBox_test_num, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.test_change) self.setWindowIcon(QtGui.QIcon('horsey.ico'))
class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.selected_project = "" self.projects = db.getProjects() if self.projects: self.populateProjectList(self.projects) else: pass def populateProjectList(self, projects): for project_id, project_info in projects.items(): item = QtWidgets.QListWidgetItem(project_info['project_name']) item.setTextAlignment(QtCore.Qt.AlignHCenter) self.ui.project_list_widget.addItem(item) def createProject(self): self.hide() self.create_project_window = CreateProjectWindow() self.create_project_window.show() def itemSelected(self, item): print(item.text()) self.selected_project = item.text() def openSelectedProject(self): project = { proj_id: proj_info for proj_id, proj_info in self.projects.items() if self.selected_project in proj_info.values() } #print(project) if project: self.hide() self.project_window = ProjectWindow(project) self.project_window.show() def openCodeEditor(self): self.code_editor_window = CodeEditorWindow() self.code_editor_window.show() def logout(self): global CURRENT_USERNAME self.hide() self.login_window = LoginWindow() CURRENT_USERNAME = "" self.login_window.show()
def __init__(self): QtGui.QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton_8.clicked.connect(self.conectar) self.ui.pushButton_7.clicked.connect(self.crearMaquina) self.ui.pushButton_6.clicked.connect(self.apagarMaquina) self.ui.pushButton_5.clicked.connect(self.iniciarMaquina) self.ui.pushButton_4.clicked.connect(self.pausarMaquina) self.ui.pushButton_3.clicked.connect(self.reanudarMaquina) self.ui.pushButton_2.clicked.connect(self.reiniciarMaquina) self.ui.pushButton_9.clicked.connect(self.borrarMaquina) self.ui.pushButton.clicked.connect(self.mostrarMaquinas) self.listView = QtGui.QListView() self.listWidget = QtGui.QListWidget()
def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.action_New_View.triggered.connect(self.new_view) self.ui.action_Tile.triggered.connect(self.tile) self.ui.action_Settings.triggered.connect(self.settings) self.new_view().showMaximized() #self.plot() self.loadSettings()
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.available_layout_elements = [] self.init_ui() self.template = LayoutTemplate(self.ui) self.config = Config() if c.CONFIG_USER_LAST_TEMPLATE_FILE in self.config.user_config: template_file = self.config.user_config[ c.CONFIG_USER_LAST_TEMPLATE_FILE] if os.path.exists(template_file): self.current_file = template_file self.template.load_template(template_file) self.change_title() self.show()
def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.current_directory = str(pathlib.Path(__file__).parent.absolute()) self.set_image_attribute() # set clicked self.ui.btnPlay.clicked.connect(self.playAzan) self.ui.btnStop.clicked.connect(self.stopAzan) # self.ui.btnHide.clicked.connect(self.openSetting) self.ui.btnHide.clicked.connect(self.hide) self.ui.btnExit.clicked.connect(self.exit) self.ui.btnSave.clicked.connect(self.do_save) self.ui.btnSetting.clicked.connect(self.show_frame_setting) self.ui.btnTimeTable.clicked.connect(self.show_time_table) # init form setting self.ui.frameSetting.setVisible(False) # get username of this login user self.myusername = pwd.getpwuid(os.getuid()).pw_name # get time self.init_times() # init thread self.docalc = threading.Thread( target=self.do_calculate, name="Azan Calculating") # init icon self.setting_file = self.current_directory + '/setting.txt' self.icopath = self.current_directory + '/icon/masjid.xpm' self.setWindowIcon(QIcon(self.icopath)) self.default_azan = self.current_directory + '/audio/azan.mp3' # open setting self.openSetting() # show times self.showTimes() # show tray on start self.show_tray()
class MyApp(QtGui.QMainWindow, Ui_MainWindow): p = AutoStart.AutoStart() a = p.ShowAll() def __init__(self): QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Connessione segnali ad eventi self.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), self.VisualizzaProg) def VisualizzaProg(self): for i in range(0, len(self.a)): self.ui.lista.addTopLevelItem(QtGui.QTreeWidgetItem([self.a[i].Name])) self.ui.lista.topLevelItem(i).setIcon(0, QtGui.QIcon.fromTheme(self.a[i].Icon))
class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.monWidget = MonitorWidget(self.ui.widgetMonitor) self.roiWidget = RoiWidget(self.ui.widgetROI) # 프로그램을 닫으려 할때 def closeEvent(self, event): reply = QtGui.QMessageBox.warning(self, u'프로그램 종료', u"진행중인 모든 데이터 송·수신을 중지합니다.\n" u"프로그램을 종료하시겠습니까?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() elif reply == QtGui.QMessageBox.No: event.ignore()
def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.listSearch.setVisible(False) self.ui.scrollResult.setVisible(False) self.connect(self.ui.actionAbout , QtCore.SIGNAL('triggered()') , self.actionAbout_triggered ) self.connect(self.ui.actionQuit , QtCore.SIGNAL('triggered()') , QtCore.SLOT('close()') ) self.connect(self.ui.editSearch , QtCore.SIGNAL('textChanged(QString)') , self.editSearch_textChanged ) self.connect(self.ui.buttonSearch , QtCore.SIGNAL('clicked()') , self.buttonSearch_clicked ) self.connect(self.ui.editSearch , QtCore.SIGNAL('returnPressed()') , self.buttonSearch_clicked ) self.connect(self.ui.listSearch , QtCore.SIGNAL('itemActivated(QListWidgetItem *)') , self.listSearch_itemActivated ) self.connect(self.ui.buttonPlayA , QtCore.SIGNAL('clicked()') , self.buttonPlayA_clicked ) self.connect(self.ui.buttonPlayB , QtCore.SIGNAL('clicked()') , self.buttonPlayB_clicked ) self.connect(self.ui.buttonCueA , QtCore.SIGNAL('clicked()') , self.buttonCueA_clicked ) self.connect(self.ui.buttonCueB , QtCore.SIGNAL('clicked()') , self.buttonCueB_clicked ) self.connect(self.ui.listA , QtCore.SIGNAL('itemActivated(QListWidgetItem *)') , self.listA_itemActivated ) self.connect(self.ui.listB , QtCore.SIGNAL('itemActivated(QListWidgetItem *)') , self.listB_itemActivated ) for i in range(0, SEARCHRESULTS): self.resultWidgets.append( WidgetResult(self.ui.scrollResultContents, self.ui.listA, self.ui.listB) ) self.resultWidgets[i].setGeometry(QtCore.QRect(0, i * self.resultWidgets[i].height(), self.resultWidgets[i].width(), self.resultWidgets[i].height())); self.resultWidgets[i].setObjectName( "result" + str(i) )
def __init__(self): QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.serial = serial.Serial() baudrate_list = ["9600", "115200"] for item in baudrate_list: self.combobox_seial_baudrate.addItem(item) self.button_fresh.clicked.connect(self.fresh_port) self.action_fresh.setShortcut("F5") self.action_fresh.triggered.connect(self.fresh_port) self.fresh_port() self.button_open_close.clicked.connect(self.on_click_button_open_close) self.alive = threading.Event() self.recive_process = my_thread(self.recive_process_callback) self.recive_process.signal_trigger.connect(self.on_updata_text_output) self.send_process = my_thread(self.send_process_callback)
def __init__(self, frequency, parent=None): super(MyMainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) wd = os.path.dirname(os.path.abspath(__file__)) self.tick_pixmaps = {True: QtGui.QPixmap(os.path.join(wd, 'pics', 'blinkenlicht_on.png')), False: QtGui.QPixmap(os.path.join(wd, 'pics', 'blinkenlicht_off.png'))} self.speaker_pixmaps = {True: QtGui.QIcon(QtGui.QPixmap(os.path.join(wd, 'pics', 'speaker_on.png'))), False: QtGui.QIcon(QtGui.QPixmap(os.path.join(wd, 'pics', 'speaker_off.png')))} self.tick_soundFile=QFile() self.tick_soundFile.setFileName(os.path.join(wd, 'sounds', 'tick.raw')) self.tick_soundFile.open(QIODevice.ReadOnly) self.play_sound = True self.format = QAudioFormat() self.format.setChannels(1) self.format.setFrequency(44050) self.format.setSampleSize(16) self.format.setCodec("audio/pcm") self.format.setByteOrder(QAudioFormat.LittleEndian) self.format.setSampleType(QAudioFormat.SignedInt) self.audio_output = QAudioOutput(self.format) self.ui.ping_icon.setPixmap(self.tick_pixmaps[False]) self.ui.speaker_button.setIcon(self.speaker_pixmaps[self.play_sound]) self.blink_timer = QTimer() self.blink_timer.setSingleShot(True) self.blink_timer.timeout.connect(self.clear_blink) self.timer = QTimer() self.frequency = frequency self.last_played = 0 self.count = 0 self.ui.f_spin.setValue(self.frequency) self.set_speed() self.timer.timeout.connect(self.play_tick) self.play_ctrl = {True: 'Stop', False: 'Start'} self.ui.play_button.setText(self.play_ctrl[False]) self.ui.statusBar.showMessage('{count:04d} - Dev.: {delta:.3f} ms'.format(delta=0, count=self.count))
def __init__(self): super(Appwin, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setMinimumWidth(resolution.width() / 3.0) self.setMinimumHeight(resolution.height() / 1.5) self.config = util.import_yaml( os.path.join(os.getcwd(), 'config', 'config.yml')) root = self.config['dataset']['path'] print(util.check_VOC(root)) self.data, self.category_index = util.Read_VOC(self.config) # print(self.data) self.config_update() self.ui.tableView.clicked.connect(self.table_clicked) self.threadpool = QThreadPool() print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount()) self.ui.btn_filter.clicked.connect(self.btn_filter) self.ui.btn_gen_text.clicked.connect(self.btn_gen_text) self.ui.btn_create_dataloader_torch.clicked.connect( self.btn_torch_data_loader)
class MainWindow(QMainWindow): #Ui_MainWindow生成のための初期化処理 def mousePressEvent(self, event): self.__isDrag = True self.__startPos = event.pos() super(MainWindow, self).mousePressEvent(event) def mouseReleaseEvent(self, event): self.__isDrag = False super(MainWindow, self).mouseReleaseEvent(event) def mouseMoveEvent(self, event): if self.__isDrag: self.move(self.mapToParent(event.pos() - self.__startPos)) super(MainWindow, self).mouseMoveEvent(event) def nextDir(self, item): model_old = item.model() model_new = QFileSystemModel() path_new = model_old.filePath(item) model_new.setRootPath(path_new) self.ui.listView.setModel(model_new) self.ui.listView.setRootIndex(model_new.index(path_new)) def __init__(self, parent=None): self.__isDrag = False self.__startPos = QtCore.QPoint(0, 0) #UI初期化処理 super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.menubar.addMenu('File') #ディレクトリ関連の処理 self.ui.listView.clicked.connect(self.nextDir)
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filename = '' self.directory = '' self.h_file = h5py.File self.chan_dict = {} self.ui.progressBar_data.setMaximum(75) QtCore.QObject.connect(self.ui.pushButton_browse_open, QtCore.SIGNAL("clicked()"), self.browse) QtCore.QObject.connect(self.ui.pushButton_browse_save, QtCore.SIGNAL("clicked()"), self.browse2) QtCore.QObject.connect(self.ui.pushButton_start, QtCore.SIGNAL("clicked()"), self.start) QtCore.QObject.connect(self.ui.pushButton_auto_threshold, QtCore.SIGNAL("clicked()"), self.auto_threshold) QtCore.QObject.connect(self.ui.comboBox_test_num, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.test_change) QtCore.QObject.connect(self.ui.comboBox_threshold, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.chan_change) QtCore.QObject.connect(self.ui.doubleSpinBox_threshold, QtCore.SIGNAL("valueChanged(double)"), self.thresh_change)
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.set_listeners() self.shift_selector = 0 #determina que turno se ejecutara a continuacion. self.shift_worked01 = 0 #Cantidad de turnos trabajados por maquina 1 self.shift_worked02 = 0 #Cantidad de turnos trabajados por maquina 2 self.TruckLoad = 0 #Carga sobrante entre turnos. self.proLoad = 0 #Carga al principio del turno self.Package01 = 0 #Cantidad de paquetes hechos por la primera maquina self.Package02 = 0 #Cantidad de paquetes hechos por la segunda maquina self.Packages = 0 #Cantidad de paquetes por turno. self.Time_Off01 = 0 #Cantidad de tiempo que la maquina permanece sin uso self.Time_Off02 = 0 #Cantidad de tiempo que la maquina permanece sin uso self.Time_On01 = 0 #Cantidad de tiempo que la maquina se encuentra ocupada self.Time_On02 = 0 #Cantidad de tiempo que la maquina se encuentra ocupada self.totalTime01 = 0 self.totalTime02 = 0
def __init__(self): super(AppWindow,self).__init__() self.ui= Ui_MainWindow() self.ui.setupUi(self) self.UI_config()
class AppWindow(QMainWindow): def __init__(self): super(AppWindow,self).__init__() self.ui= Ui_MainWindow() self.ui.setupUi(self) self.UI_config() def UI_config(self): self.ui.btn_train.clicked.connect(self.train) self.ui.btn_dataset_gen.clicked.connect(self.dataset_generation) self.ui.btn_model_gen.clicked.connect(self.model_generation) self.ui.btn_model_arch.clicked.connect(self.model_archi_btn) self.ui.btn_plot_imgs.clicked.connect(self.plot_btn) self.ui.tableWidget.cellClicked.connect(self.showCell) self.ui.btn_3d_plot.clicked.connect(self.btn_plot_3d) # self.ui.in_cmbox_3dPlot.setItemText(0,'tesrt') # self.ui.in_cmbox_3dPlot.currentText() # self.ui.bt # self.ui.tra self.ui.btn_train_allmodels.clicked.connect(self.btn_train_all_models) # this is a place holder for the data set cofiguration --> img_H, img_W, num of train and val set ... self.modelList =OrderedDict() # it holds the generated model by the program self.config={} self.config_update() # Gui tools such as display the logs and fill the table self.tools=gui_tools.utils(self) # state of the program # while it is training you can not change the model parameters self.ui_state='idle' self.ui.tableWidget.setColumnCount(1) # self.ui.tableWidget.setColumnWidth(1, 250) # self.ui.tableWidget.setColumnWidth(2, 250) # self.ui.tableWidget.setColumnWidth(3, 250) # self.ui.tableWidget.setRowCount(1) self.ui.tableWidget.setColumnWidth(0, 300) def btn_plot_3d(self) : loss_file = os.path.join(os.getcwd(), self.module_dir_name, 'All_Results.losses') self.tools.plot_3d_(loss_file) def btn_train_all_models(self): for model in self.modelList.items(): print(model[0]) model_name=model[0] self.model=self.tools.load_object(self.modelList[model_name]['model_address']) self.model_name=self.modelList[model_name]['name'] self.model_txt_file=self.modelList[model_name]['text_log'] print("**--**" * 30) print(self.model) if (self.ui.chkbox_stop_training.isChecked()): break self.train() self.model = self.tools.save_object(object=self.model,path=self.model_txt_file) print((self.modelList)) loss_file=os.path.join(os.getcwd(),self.module_dir_name,'All_Results.losses') params={'models_inputs':self.config['models_inputs'], 'models_outputs':self.config['models_outputs'], 'models_kernels':self.config['models_kernels'], 'models_num_classes':self.config['models_num_classes']} self.modelList.update({'params' : params}) self.tools.save_object(path=loss_file,object=self.modelList) # print(self.modelList) # self.tools.plot_3d_(loss_file) # del (self.modelList) # print((self.modelList)) # print('----') def config_update(self): self.config.update({'img_H': int(self.ui.in_img_H.text())}) self.config.update({'img_W': int(self.ui.in_img_W.text())}) self.config.update({'dataset_train_size': int(self.ui.in_train_dataset.text())}) self.config.update({'dataset_val_size': int(self.ui.in_val_dataset.text())}) self.config.update({'dataset_obj_shape_triangle': self.ui.in_shape_triangle.isChecked()}) self.config.update({'dataset_obj_shape_circle': self.ui.in_shape_circle.isChecked()}) self.config.update({'dataset_obj_shape_mesh': self.ui.in_shape_mesh.isChecked()}) self.config.update({'dataset_obj_shape_square': bool(self.ui.in_shape_squre.isChecked())}) self.config.update({'dataset_obj_shape_plus': self.ui.in_shape_plus.isChecked()}) self.config.update({'train_Epoch_number': int(self.ui.in_train_epoch_num.text())}) self.config.update({'dataset_batch_size': int(self.ui.in_batch_size.text())}) self.config.update({'model_counter': 0}) self.ui.btn_train.setDisabled(not (hasattr(self,'image_datasets') and hasattr(self,'model'))) self.ui.btn_plot_imgs.setDisabled(not hasattr(self,'image_datasets')) self.ui.in_models_layers.setEnabled(False) self.module_dir_name = self.ui.in_model_save_dir.text() #It generates event when you click on the tabel cells and give you row and column number def showCell(self,row,col): if(self.ui_state=='idle'): model_name=self.ui.tableWidget.item(row,col).text() # self.model=self.modelList[model_name]['model'] # selected_name=self.ui.tableWidget.item(row,0).text() print(row, col, self.ui.tableWidget.item(row, col).text()) self.model=self.tools.load_object(self.modelList[model_name]['model_address']) self.model_name=self.modelList[model_name]['name'] self.model_txt_file=self.modelList[model_name]['text_log'] print(self.modelList[model_name]['trained']) print("**--**" * 30) print(self.model) self.config_update() if(self.modelList[model_name]['trained']): joy_plot_.plot1(self.modelList[model_name]['loss']) def train(self): self.config_update() training(self) print(len(self.image_datasets['train'])) self.config_update() self.tools.fill_out_table(self.modelList) self.tools.fill_out_table_2(self.modelList) # print(self.modelList) def dataset_generation(self): self.config_update() Dataset_create(self) self.config_update() def model_generation(self): self.config_update() self.ui_state = 'model_generation' Model_create(self) self.ui_state = 'idle' self.config_update() def model_archi_btn(self): self.modelList={} # self.modelList = model_architecture(self) self.tools.fill_out_table(self.modelList) self.tools.fill_out_table_2(self.modelList) self.config_update() # self.ui.tableWidget_2.setColumnCount(len(self.config['models_kernels'])) # self.ui.tableWidget_2.setRowCount (len(self.config['models_outputs'])) # print(len(self.config['models_kernels'])) # print(len(self.config['models_outputs'])) def plot_btn(self): self.tools.plotting(self) self.tools.logging(str(list(self.image_datasets['train'])[0][0].numpy().shape),'red') # self.tools.check_dir('test/123',create_dir=True) def closeEvent(self, event): pass
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.pushButton.clicked.connect(self.progress)
class Window(QMainWindow): def __init__(self, *args, **kwargs): super(Window, self).__init__(*args, **kwargs) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.currentItemsSB = [] # Used to store variables to be displayed in status bar at the bottom right self.verbose = True # Initialization. Used in the thread generated in application self.fs = 10; self.N = 50; self.dt = 1.0/self.fs self.sample_time = self.N*self.dt self.data = [] self.R01 = 10000 self.R02 = 10000 self.R1 = 10000 self.R2 = 10000 self.K1 = 3950 self.K2 = 3950 self.delay = 0 self.calibrateButton = QPushButton() # self.calibrateButton.setMinimumSize(QSize(0, 0)) # self.calibrateButton.setMaximumSize(QSize(88, 21)) self.calibrateButton.setObjectName("calibrateButton") self.ui.gridLayout.addWidget(self.calibrateButton, 4, 0, 1, 2) self.calibrateButton.setText("Calibrate!") self.setStyleSheet(qdarkstyle.load_stylesheet()) self.getLogo() self.getFonts() self.initalConnections() # self.initialGraphSettings() self.arduinoStatusLed() # self.initialTimer() # self.initialState() # self.ui.graphWidgetOutput.setLabel('left',"<span style=\"color:white;font-size:16px\">Speed (m/s)</span>") # self.ui.graphWidgetOutput.setLabel('bottom',"<span style=\"color:white;font-size:16px\">Time (s)</span>") # self.ui.graphWidgetOutput.setTitle("Speed", color="w", size="12pt") # self.ui.graphWidgetInput.setLabel('left',"<span style=\"color:white;font-size:16px\">°C</span>") # self.ui.graphWidgetInput.setLabel('bottom',"<span style=\"color:white;font-size:16px\">Time (s)</span>") # self.ui.graphWidgetInput.setTitle("Temperature", color="w", size="12pt") # # self.currentValueSB(self.course) # self.course = "Sound" self.list_ports() self.COM = str(self.com_ports[0]) self.ui.com_port.addItems(self.com_ports) self.ui.com_port.setCurrentIndex(self.com_ports.index(self.COM)) atexit.register(self.closeSerial) def getLogo(self): script_dir = os.path.dirname(__file__) logo_rel_path = r"logo\CUAtHomeLogo-Horz.png" logo_abs_file_path = os.path.join(script_dir, logo_rel_path) self.ui.imageLabel.setPixmap(QPixmap(logo_abs_file_path).scaled(200, 130, Qt.KeepAspectRatio, Qt.FastTransformation)) def getFonts(self): script_dir = os.path.dirname(__file__) font_rel_path = r"fonts\Roboto" font_abs_file_path = os.path.join(script_dir, font_rel_path) for f in os.listdir(font_abs_file_path): if f.endswith("ttf"): QFontDatabase.addApplicationFont(os.path.join(font_abs_file_path,f)) #print(QFontDatabase().families()) def arduinoStatusLed(self): self._led = QLed(self, onColour=QLed.Red, shape=QLed.Circle) self._led.clickable = False self._led.value = True self._led.setMinimumSize(QSize(15, 15)) self._led.setMaximumSize(QSize(15, 15)) self.statusLabel = QLabel("Teensy Status:") self.statusLabel.setFont(QFont("Roboto", 12)) self.statusBar().addWidget(self.statusLabel) #self.statusBar().reformat() self.statusBar().addWidget(self._led) def initalConnections(self): """ 6 Main Buttons (for now) """ self.ui.serialOpenButton.clicked.connect(self.serialOpenPushed) self.ui.settingsButton.clicked.connect(self.settingsPushed) self.ui.recordbutton.clicked.connect(self.recordbuttonPushed) self.ui.sendbutton.clicked.connect(self.sendbuttonPushed) self.ui.plotbutton.clicked.connect(self.plotbuttonPushed) self.ui.savebutton.clicked.connect(self.savebuttonPushed) self.calibrateButton.clicked.connect(self.calibratebuttonPushed) # self.ui.clearbutton.clicked.connect(self.clearbuttonPushed) # self.ui.settings.clicked.connect(self.settingsMenu) def serialOpenPushed(self): self.COM = str(self.ui.com_port.currentText()) self.ser = serial.Serial(port=self.COM) sleep(2) self.ser.flush() print("Serial opened successfully!") if self.ser.is_open: self._led.onColour = QLed.Green self.ui.serialOpenButton.clicked.disconnect(self.serialOpenPushed) # self.ui.serialCloseButton.clicked.connect(self.serialClosePushed) # self.ui.startbutton.clicked.connect(self.recordbuttonPushed) # Set N and fs on Teensy write_string = f"S0,N{self.N},%".encode('utf-8') self.ser.write(write_string) write_string = f"S1,T{self.fs},%".encode('utf-8') self.ser.write(write_string) write_string = f"S2,T{self.delay},%".encode('utf-8') self.ser.write(write_string) def closeSerial(self): if self.ser.is_open: self.ser.close() print("Serial closed.") def recordbuttonPushed(self): print('Recording...',end='',flush=True) self.ser.write(b'R1,%') sleep(self.sample_time+self.delay) print('Done.') def sendbuttonPushed(self): print('Sending Data...',end='',flush=True) # Initialize data list self.raw_data=[] # Continue reading the data until '#' is found while(1): self.ser.write(b'R0%') # Request a data point from arduino line = [] # initialize as empty array, line buffer string_buff='' # intiailze as empty string while(1): # Read char by char until '\0' found if(self.ser.in_waiting > 0): # if data in buffer read line.append(self.ser.read(1).decode()) # Read 1 character and decode from bytes to characters if '\0' in line: break # if '\0' found break out of line loop # print(''.join(line)) # See line received self.raw_data.append(''.join(line)) # Append line read (joined as one single string) to data block if '#' in line: # if '#' found break out of reading loop break print('Done.') self.decipher_raw_data() def decipher_raw_data(self): # Get first letter of each segment separated by commas # Give the pandas dataframe column names col_name = [i[0] for i in self.raw_data[0].split(',')[:-1]] # Initialize data buffers buff=[] for row in self.raw_data: # Get all but first character in each segment separated by commas # Get all the numbers in the data into a 2d list new_data = row.split(',')[:-1] # print(new_data) buff.append([float(j[1:]) for j in new_data]) # print(col_name) self.data = pd.DataFrame(buff, columns=col_name) self.data = self.data.drop(columns=['C']) # # Conversion to temperature: R_therm = 10k*exp(K*(1/T-1/T0) # # and ADC = R/(R+10k)*(2^12-1) # T0 = 25+273.15 # K # K = 3950 # K # self.data['Temp'] = 1.0/(1.0/T0+np.log(self.data['C']/((2**12-1)-self.data['C']))/K)-273.15 # oC # def initialGraphSettings(self): # self.ui.graphWidgetOutput.showGrid(x=True, y=True, alpha=None) # self.ui.graphWidgetInput.showGrid(x=True, y=True, alpha=None) # self.ui.graphWidgetOutput.setBackground((0, 0, 0)) # self.ui.graphWidgetInput.setBackground((0, 0, 0)) def plotbuttonPushed(self): # self.ui.graphWidgetOutput.clear() # self.ui.graphWidgetInput.clear() # self.legendOutput.clear() # self.legendInput.clear() self.time = self.data['T'].to_numpy() self.A = self.data['A'].to_numpy() self.B = self.data['B'].to_numpy() T0 = 25+273.15 # K # K = 3950 # K self.A = 1.0/(1.0/T0+np.log(self.R1/self.R01*self.A/((2**12-1)-self.A))/self.K1)-273.15 # oC self.B = 1.0/(1.0/T0+np.log(self.R2/self.R02*self.B/((2**12-1)-self.B))/self.K2)-273.15 # oC self.fig = plt.figure() ax = self.fig.add_subplot(111) ax.plot(self.time, self.A) self.update_line, = ax.plot(self.time,self.B) self.fig.canvas.draw() self.fig.canvas.flush_events() plt.show() def savebuttonPushed(self): print('Saving...',end='',flush=True) self.now = datetime.datetime.now() self.nrow = 1 self.result_file = Workbook() self.dl = self.result_file.worksheets[0] self.writerow(self.dl,['Data Logged From Teensy '+ self.now.strftime("%Y-%m-%d %H-%M")]) self.writerow(self.dl,['Time (s)','Thermistor 1', 'Thermistor 2']) for row in self.data.to_numpy(): self.writerow(self.dl,row) self.result_file.save(directory+'\\data\\Experiment Data '+ self.now.strftime("%Y-%m-%d %H-%M") +'.xlsx') print('Done.') def calibratebuttonPushed(self): self.A = self.data['A'].to_numpy() self.B = self.data['B'].to_numpy() A_mean = np.mean(self.A) B_mean = np.mean(self.B) T0 = 25+273.15 # K K = 3950 # K # self.R01 = self.R1*A_mean/((2**12-1)-A_mean)/np.exp(K*(1/273.15-1/T0)) # self.R02 = self.R2*B_mean/((2**12-1)-B_mean)/np.exp(K*(1/273.15-1/T0)) self.K1 = np.log(self.R1*A_mean/((2**12-1)-A_mean)/self.R01)/(1/273.15-1/T0) self.K2 = np.log(self.R2*B_mean/((2**12-1)-B_mean)/self.R02)/(1/273.15-1/T0) print(self.K1,self.K2) print('Calibrated!') def writerow(self,ws,output=[]): for dd, data in enumerate(output): ws.cell(row = self.nrow,column = dd+1).value = data self.nrow = self.nrow+1 def settingsPushed(self): self.settingsDialog = QDialog() self.settingsDialog.setStyleSheet(qdarkstyle.load_stylesheet()) self.settingsDialog.setWindowTitle("Settings") layout = QVBoxLayout(self.settingsDialog) # com_widget = QComboBox(self.settingsDialog) # self.list_ports() # com_widget.addItems(self.com_ports) # com_widget.setCurrentIndex(self.com_ports.index(self.COM)) # layout.addWidget(com_widget) fs_layout = QHBoxLayout() fs_label = QLabel() fs_label.setText("Sampling Rate (fs)") fs_widget = QLineEdit(self.settingsDialog) fs_widget.setText(str(self.fs)) fs_layout.addWidget(fs_label) fs_layout.addWidget(fs_widget) layout.addLayout(fs_layout) N_layout = QHBoxLayout() N_label = QLabel() N_label.setText("Number of Samples (N)") N_widget = QLineEdit(self.settingsDialog) N_widget.setText(str(self.N)) N_layout.addWidget(N_label) N_layout.addWidget(N_widget) layout.addLayout(N_layout) delay_layout = QHBoxLayout() delay_label = QLabel() delay_label.setText("Record Delay (s)") delay_widget = QLineEdit(self.settingsDialog) delay_widget.setText(str(self.delay)) delay_layout.addWidget(delay_label) delay_layout.addWidget(delay_widget) layout.addLayout(delay_layout) R1_layout = QHBoxLayout() R1_label = QLabel() R1_label.setText("Resistor 1 (Ohm)") R1_widget = QLineEdit(self.settingsDialog) R1_widget.setText(str(self.R1)) R1_layout.addWidget(R1_label) R1_layout.addWidget(R1_widget) layout.addLayout(R1_layout) R2_layout = QHBoxLayout() R2_label = QLabel() R2_label.setText("Resistor 2 (Ohm)") R2_widget = QLineEdit(self.settingsDialog) R2_widget.setText(str(self.R2)) R2_layout.addWidget(R2_label) R2_layout.addWidget(R2_widget) layout.addLayout(R2_layout) buttonBox = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.settingsDialog.accept) buttonBox.rejected.connect(self.settingsDialog.reject) layout.addWidget(buttonBox) self.settingsDialog.setLayout(layout) if self.settingsDialog.exec_() == QDialog.Accepted: self.fs = int(fs_widget.text()) self.N = int(N_widget.text()) self.dt = 1.0/self.fs self.sample_time = self.N*self.dt # if self.fs > 1000: # print('WARNING: sample rate for the Accelerometer must not exceed 1000 Hz.') self.delay = int(delay_widget.text()) self.R1 = int(R1_widget.text()) self.R2 = int(R2_widget.text()) write_string = f"S0,N{self.N},%".encode('utf-8') self.ser.write(write_string) write_string = f"S1,T{self.fs},%".encode('utf-8') self.ser.write(write_string) write_string = f"S2,T{self.delay},%".encode('utf-8') self.ser.write(write_string) print('Settings saved.') else: print('Settings NOT saved.') # print(f"Current fs is {self.fs}.") # self.fs = int(input('Specify Sampling Rate (fs): ')); # print(f"Current N is {self.N}.") # self.N = int(input('Specify Number of Samples (N): ')); # self.dt = 1.0/self.fs; # self.sample_time = self.N*self.dt # write_string = f"S0,N{self.N},%".encode('utf-8') # self.ser.write(write_string) # write_string = f"S1,T{self.fs},%".encode('utf-8') # self.ser.write(write_string) # print ('Settings saved.') def list_ports(self): self.com_ports = [ p.device for p in serial.tools.list_ports.comports() if 'Arduino' or 'tty' in p.description ] if not self.com_ports: raise IOError("No COM ports found. Replug in USB cable and try again.") self.com_ports.sort(key=lambda s: (s[:-2], int(s[-2:])) if s[-2] in '0123456789' else (s[:-1], int(s[-1:])))
def __init__(self): # Store the username of logged in user self.currentLoggedIn = "" # Used to build table from sql data self.tableData = [] self.rows = 0 self.columns = 0 self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.main_win) # Start by showing the log in screen self.ui.stackedWidget.setCurrentWidget(self.ui.loginPage) # NAVIGATION BUTTONS: # Log in when we press log in button self.ui.loginButton.clicked.connect(self.tryLoggin) # Log out when we press log out button self.ui.logoutButton.clicked.connect(self.logOut) self.ui.logoutButton_2.clicked.connect(self.logOut) # Buttons that navigate to dashboard self.ui.dashboardButton.clicked.connect(self.navigateDashboard) self.ui.dashboardButton_2.clicked.connect(self.navigateDashboard) self.ui.backButton.clicked.connect(self.navigateDashboard) self.ui.createBugBack.clicked.connect(self.navigateDashboard) self.ui.returnFromUserToDashboard.clicked.connect( self.navigateDashboard) self.ui.returnToDashboard.clicked.connect(self.navigateViewBugs) # Buttons that navigate to viewBugsPage self.ui.viewBugsButton.clicked.connect(self.navigateViewBugs) self.ui.viewBugsButton_2.clicked.connect(self.navigateViewBugs) # Buttons that navigate to createBug page self.ui.createBugButton.clicked.connect(self.navigateCreateBugs) self.ui.createBugButton_2.clicked.connect(self.navigateCreateBugs) self.ui.addBugButton.clicked.connect(self.navigateCreateBugs) # Buttons that navigate to editBugStatus page self.ui.editBugStatus.clicked.connect(self.navigateEditStatusPage) # Buttons that navigate to User page self.ui.userButton.clicked.connect(self.navigateUserPage) self.ui.userButton_2.clicked.connect(self.navigateUserPage) # ACTION BUTTONS: # Buttons that loads data from sql database (uncompleted or completed bugs) self.ui.loadTableButton.clicked.connect(self.loadUncomplete) self.ui.loadCompleteTable.clicked.connect(self.loadComplete) # Buttons that submits/creates new bug self.ui.createBugSubmit.clicked.connect(self.addBugToDB) self.ui.createBugSubmit.clicked.connect(self.navigateDashboard) # Buttons that marks bug as complete self.ui.markBugAsComplete.clicked.connect(self.bugCompleted) self.ui.markBugAsComplete.clicked.connect(self.navigateViewBugs) self.ui.markBugAsComplete.clicked.connect(self.loadUncomplete) # Buttons that deletes bug from database self.ui.deleteBugFromDatabase.clicked.connect(self.bugDelete) self.ui.deleteBugFromDatabase.clicked.connect(self.navigateViewBugs) self.ui.deleteBugFromDatabase.clicked.connect(self.loadUncomplete) # Buttons that adds new user to database self.ui.submitNewUser.clicked.connect(self.addUserToDb) self.ui.submitNewUser.clicked.connect(self.navigateDashboard) # Buttons that removes user from database self.ui.deleteUserButton.clicked.connect(self.removeUserFromDb) self.ui.deleteUserButton.clicked.connect(self.navigateDashboard)
class MainWindow: def __init__(self): # Store the username of logged in user self.currentLoggedIn = "" # Used to build table from sql data self.tableData = [] self.rows = 0 self.columns = 0 self.main_win = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(self.main_win) # Start by showing the log in screen self.ui.stackedWidget.setCurrentWidget(self.ui.loginPage) # NAVIGATION BUTTONS: # Log in when we press log in button self.ui.loginButton.clicked.connect(self.tryLoggin) # Log out when we press log out button self.ui.logoutButton.clicked.connect(self.logOut) self.ui.logoutButton_2.clicked.connect(self.logOut) # Buttons that navigate to dashboard self.ui.dashboardButton.clicked.connect(self.navigateDashboard) self.ui.dashboardButton_2.clicked.connect(self.navigateDashboard) self.ui.backButton.clicked.connect(self.navigateDashboard) self.ui.createBugBack.clicked.connect(self.navigateDashboard) self.ui.returnFromUserToDashboard.clicked.connect( self.navigateDashboard) self.ui.returnToDashboard.clicked.connect(self.navigateViewBugs) # Buttons that navigate to viewBugsPage self.ui.viewBugsButton.clicked.connect(self.navigateViewBugs) self.ui.viewBugsButton_2.clicked.connect(self.navigateViewBugs) # Buttons that navigate to createBug page self.ui.createBugButton.clicked.connect(self.navigateCreateBugs) self.ui.createBugButton_2.clicked.connect(self.navigateCreateBugs) self.ui.addBugButton.clicked.connect(self.navigateCreateBugs) # Buttons that navigate to editBugStatus page self.ui.editBugStatus.clicked.connect(self.navigateEditStatusPage) # Buttons that navigate to User page self.ui.userButton.clicked.connect(self.navigateUserPage) self.ui.userButton_2.clicked.connect(self.navigateUserPage) # ACTION BUTTONS: # Buttons that loads data from sql database (uncompleted or completed bugs) self.ui.loadTableButton.clicked.connect(self.loadUncomplete) self.ui.loadCompleteTable.clicked.connect(self.loadComplete) # Buttons that submits/creates new bug self.ui.createBugSubmit.clicked.connect(self.addBugToDB) self.ui.createBugSubmit.clicked.connect(self.navigateDashboard) # Buttons that marks bug as complete self.ui.markBugAsComplete.clicked.connect(self.bugCompleted) self.ui.markBugAsComplete.clicked.connect(self.navigateViewBugs) self.ui.markBugAsComplete.clicked.connect(self.loadUncomplete) # Buttons that deletes bug from database self.ui.deleteBugFromDatabase.clicked.connect(self.bugDelete) self.ui.deleteBugFromDatabase.clicked.connect(self.navigateViewBugs) self.ui.deleteBugFromDatabase.clicked.connect(self.loadUncomplete) # Buttons that adds new user to database self.ui.submitNewUser.clicked.connect(self.addUserToDb) self.ui.submitNewUser.clicked.connect(self.navigateDashboard) # Buttons that removes user from database self.ui.deleteUserButton.clicked.connect(self.removeUserFromDb) self.ui.deleteUserButton.clicked.connect(self.navigateDashboard) def show(self): self.main_win.show() def tryLoggin(self): # Get input for login username = self.ui.userNameInput.text() password = self.ui.passwordInput.text() # Set the username of the currently logged in self.currentLoggedIn = username # Either login provided correct credentials, or display error if(checkValidLogin(username, password)): # Clear password from line edit self.ui.passwordInput.clear() self.ui.stackedWidget.setCurrentWidget(self.ui.welcomePage) else: # Clear password from line edit self.ui.passwordInput.clear() self.wrongCredentials() def wrongCredentials(self): # Simple popup message box to alert user when wrong login credentials is given msg = QMessageBox() msg.setWindowTitle("Error!") msg.setText("Wrong Username and Password combination") x = msg.exec_() def notAccess(self): # Simple popup message box to alert that user does not have access to certain parts of the app msg = QMessageBox() msg.setWindowTitle("Access denied!") msg.setText("You do not have correct privileges") x = msg.exec_() # Navigate to log in screen when we press logout def logOut(self): # Simply navigate to the loginPage after setting currentLoggedIn to an empty string self.currentLoggedIn = "" self.ui.stackedWidget.setCurrentWidget(self.ui.loginPage) def navigateDashboard(self): # First we update the dashboard bug counters self.ui.highCount.setText( "<html><head/><body><p align=\"center\"><span style=\" font-size:48pt;\">{highCount}</span></p></body></html>".format(highCount=getHigh())) self.ui.medCount.setText( "<html><head/><body><p align=\"center\"><span style=\" font-size:48pt;\">{medCount}</span></p></body></html>".format(medCount=getMed())) self.ui.lowCount.setText( "<html><head/><body><p align=\"center\"><span style=\" font-size:48pt;\">{lowCount}</span></p></body></html>".format(lowCount=getLow())) self.ui.completeCount.setText( "<html><head/><body><p align=\"center\"><span style=\" font-size:48pt;\">{completeCount}</span></p></body></html>".format(completeCount=getComplete())) # No restrictions when navigating to the dashboard self.ui.stackedWidget.setCurrentWidget(self.ui.dashBoardPage) def navigateViewBugs(self): self.ui.stackedWidget.setCurrentWidget(self.ui.viewBugsPage) def navigateCreateBugs(self): # Check if user has role admin or moderator if(adminCheck(self.currentLoggedIn) or moderatorCheck(self.currentLoggedIn)): # Navigate to page is user has correct roles self.ui.stackedWidget.setCurrentWidget(self.ui.createBugsPage) else: # Display error message if user does not have access self.notAccess() def navigateUserPage(self): # Check if user has role admin if(adminCheck(self.currentLoggedIn)): # Navigate to user page if user is admin self.ui.stackedWidget.setCurrentWidget(self.ui.userPage) else: # Display error message if user does not have access self.notAccess() def navigateEditStatusPage(self): # Check if user has role admin or moderator if(adminCheck(self.currentLoggedIn) or moderatorCheck(self.currentLoggedIn)): # Navigate to edit status page self.ui.stackedWidget.setCurrentWidget(self.ui.editBugStatusPage) else: # Display error message if user does not have access self.notAccess() def loadUncomplete(self): # Retrieve data from sql query and get columns and rows length self.tableData = getUncompleteData() self.rows = len(self.tableData) self.columns = len(self.tableData[0]) # Clear table incase it hase been filled with data earlier self.ui.bugTable.clear() # Set the row and column count of the table to display self.ui.bugTable.setRowCount = self.rows self.ui.bugTable.setColumnCOunt = self.columns # Add correct labels to each of the columns and hide the vertical labels self.ui.bugTable.setHorizontalHeaderLabels( "BugId;Title;Application;Version;Details;Steps;Priority;AssignedTo;CreatedBy;DayCreated".split(";")) # Resize rows so all information can be viewed for i in range(100): self.ui.bugTable.setRowHeight(i, 100) # Insert data in table for row in range(self.rows): for column in range(self.columns): # Check if value datatime, if True convert to string if isinstance(self.tableData[row][column], datetime.date): self.ui.bugTable.setItem(row, column, QTableWidgetItem( (self.tableData[row][column].strftime('%d/%m/%Y')))) else: self.ui.bugTable.setItem( row, column, QTableWidgetItem(str(self.tableData[row][column]))) def loadComplete(self): # Retrieve data from sql query and get columns and rows length self.tableData = getCompleteData() self.rows = len(self.tableData) self.columns = len(self.tableData[0]) # Clear table incase it hase been filled with data earlier self.ui.bugTable.clear() # Set the row and column count of the table to display self.ui.bugTable.setRowCount = self.rows self.ui.bugTable.setColumnCOunt = self.columns # Add correct labels to each of the columns self.ui.bugTable.setHorizontalHeaderLabels( "BugId;Title;Application;Version;Details;Steps;Priority;AssignedTo;CreatedBy;DayCreated".split(";")) # Resize rows so all information can be viewed for i in range(100): self.ui.bugTable.setRowHeight(i, 100) # Insert data in table for row in range(self.rows): for column in range(self.columns): # Check if value datatime, if True convert to string if isinstance(self.tableData[row][column], datetime.date): self.ui.bugTable.setItem(row, column, QTableWidgetItem( (self.tableData[row][column].strftime('%d/%m/%Y')))) else: self.ui.bugTable.setItem( row, column, QTableWidgetItem(str(self.tableData[row][column]))) def bugCompleted(self): bugId = int(self.ui.editStatusBugId.text()) self.ui.editStatusBugId.clear() setBugComplete(bugId) def bugDelete(self): bugId = int(self.ui.editStatusBugId.text()) self.ui.editStatusBugId.clear() deleteBug(bugId) def addBugToDB(self): # Get all the input fields title = self.ui.inputBugTitle.text() appName = self.ui.inputAppName.text() version = self.ui.inputVersion.text() creator = self.ui.inputCreatedBy.text() assigned = self.ui.inputAssignedTo.text() details = self.ui.inputDetails.text() priority = int(self.ui.inputPriority.value()) steps = self.ui.inputSteps.toPlainText() # Add bug to database addBug(title, appName, version, creator, assigned, details, priority, steps) # Clear inputs self.ui.inputBugTitle.clear() self.ui.inputAppName.clear() self.ui.inputVersion.clear() self.ui.inputCreatedBy.clear() self.ui.inputAssignedTo.clear() self.ui.inputDetails.clear() self.ui.inputSteps.clear() def addUserToDb(self): # Get the different inputs name = self.ui.addNameInput.text() username = self.ui.addUsernameInput.text() password = self.ui.addPasswordInput.text() iD = self.ui.addIDInput.text() email = self.ui.addEmailInput.text() if(email == ""): email = "Not Specified" role = "" # Get role selected if(self.ui.radioAdmin.isChecked()): role = "admin" elif(self.ui.radioModerator.isChecked()): role = "moderator" else: role = "user" # For debugging purposes # print("Added new user with this info\nName: {}\nUsername: {}\nPassword: {}\nID: {}\nEmail: {}\nRole: {}".format( # name, username, password, iD, email, role)) # Add user to database with login information addNewUser(name, username, password, iD, email, role) self.ui.addNameInput.clear() self.ui.addUsernameInput.clear() self.ui.addPasswordInput.clear() self.ui.addIDInput.clear() self.ui.addEmailInput.clear() def removeUserFromDb(self): iD = self.ui.deleteUserId.text() # For debuggin purposes # print("Deleted user with employee id {} from database".format(iD)) # Pass iD to database functions that removes employee with employee id = iD removeUser(iD)
class MainWindow(QtWidgets.QMainWindow): ui = Ui_MainWindow() FILEDATA = FileData() about_page = None action_dialog = None app_version = app.build_settings['version'] main_icon = app.get_resource('icon.png') def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setWindowTitle("File to Dir") self.ui.setupUi(self, CustomLabel) self.setIcons() self.set_menu_toolbar_button_action() self.reset_all() def setIcons(self): icon = QtGui.QIcon(app.get_resource('reset.png')) self.ui.actionReset.setIcon(icon) self.ui.actionReset_1.setIcon(icon) icon = QtGui.QIcon(app.get_resource('exit.png')) self.ui.actionExit.setIcon(icon) self.ui.actionExit_1.setIcon(icon) icon = QtGui.QIcon(app.get_resource('plus.png')) self.ui.actionAdd.setIcon(icon) self.ui.actionAdd_1.setIcon(icon) icon = QtGui.QIcon(app.get_resource('clear.png')) self.ui.actionClear.setIcon(icon) self.ui.actionClear_1.setIcon(icon) self.ui.actionAdd_Multiple_Folder.setIcon(QtGui.QIcon(app.get_resource('add.png'))) self.ui.actionAbout_the_Author.setIcon(QtGui.QIcon(self.main_icon)) def set_menu_toolbar_button_action(self): # menu self.ui.actionAbout_the_Author.triggered.connect(self.see_about) self.ui.actionExit_1.triggered.connect(lambda: sys.exit(0)) self.ui.actionAdd_1.triggered.connect(self.select_folder) self.ui.actionAdd_Multiple_Folder.triggered.connect(lambda: self.select_folder(multiple=True)) self.ui.actionClear.triggered.connect(self.clear_all_folders) self.ui.actionReset.triggered.connect(self.reset_all) # toolbar self.ui.actionAdd.triggered.connect(self.select_folder) self.ui.actionClear.triggered.connect(self.clear_all_folders) self.ui.actionReset.triggered.connect(self.reset_all) self.ui.actionExit.triggered.connect(sys.exit) # button self.ui.output_bt.clicked.connect(self.select_output_folder) self.ui.bt_go.clicked.connect(self.start_action_dialog) def select_folder(self, multiple=False, drag=False, folders=None): if multiple: file_dialog = QtWidgets.QFileDialog(directory=self.last_selected_dir) file_dialog.setFileMode(QtWidgets.QFileDialog.DirectoryOnly) file_dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog, True) file_dialog.setWindowTitle("Select Folders") file_dialog.setWindowIcon(QtGui.QIcon(self.main_icon)) f_tree_view = file_dialog.findChild(QtWidgets.QTreeView) if f_tree_view: f_tree_view.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection) if not file_dialog.exec(): return folders = file_dialog.selectedFiles() elif drag: folders = [f for f in folders if is_valid_dir(f)] else: folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Directory", directory=self.last_selected_dir)) if folder == '': return folder = str(Path(folder)) self.last_selected_dir = join(*folder.split('\\')[:len(folder.split('\\'))-1]) folders = [folder] self.FILEDATA.select_dirs(folders) self.ui.txt_stat.setText(self.FILEDATA.get_status_txt()) def clear_all_folders(self): self.FILEDATA.reset() self.ui.txt_stat.setText(self.FILEDATA.get_status_txt()) def select_output_folder(self): folder = str(QtWidgets.QFileDialog.getExistingDirectory(self, "Select Output Directory", directory=self.last_selected_out_dir)) if folder != '': folder = str(Path(folder)) self.last_selected_out_dir = join(*folder.split('\\')[:len(folder.split('\\'))-1]) self.ui.input_2.setText(folder) def reset_all(self): self.last_selected_dir = 'C:' self.last_selected_out_dir = 'C:' self.ui.side_input_2.setChecked(False) self.ui.side_input_3.setChecked(False) self.ui.side_input_4.setText('') self.ui.side_input_5.setText('') self.ui.side_input_6.setText('') self.ui.side_input_7.setText('') self.ui.side_input_8.setChecked(False) self.ui.side_input_9.setChecked(False) self.ui.side_input_10.setText('') self.ui.side_input_11.setText('') self.ui.side_input_12.setText('') self.ui.side_input_13.setText('') self.ui.input_1.setCurrentIndex(0) self.ui.input_2.setText('') self.clear_all_folders() def see_about(self): if self.about_page is None: self.about_page = QtWidgets.QWidget() self.about_page.ui = Ui_AboutPage() self.about_page.ui.setupUi(self.about_page) self.about_page.ui.version.setText(f'v{self.app_version}') self.about_page.ui.icon.setPixmap(QtGui.QPixmap(self.main_icon)) self.about_page.ui.name.setText("File To Dir") self.about_page.destroy() self.about_page.show() def go_for_work(self): self.action_dialog.ui.pushButton_start.setEnabled(False) self.action_dialog.ui.pushButton_cancel.setEnabled(False) self.action_dialog.ui.pushButton_finish.setEnabled(False) self.action_dialog.ui.stackedWidget.setCurrentIndex(0) self.action_dialog.ui.progressBar.setMaximum(get_file_count(self.action_dialog.data_folders) or 1) self.thread = actionThread(self.action_dialog.data_action, self.action_dialog.data_folders, self.action_dialog.data_data, self.action_dialog.data_des) self.thread.finished.connect(self.on_action_finish) self.thread.updateSignal.connect(self.on_action_update) self.thread.startActionSignal.connect(self.on_action_update_2) self.thread.start() def start_action_dialog(self): i1 = self.ui.input_1.currentIndex() i2 = self.ui.input_2.text() include_subfolder = self.ui.side_input_1.isChecked() if i2.strip() == '': return QtWidgets.QMessageBox.warning(self, "Warning", f"<p style=\"font-size: 10pt;\"><b>Error Found.</b> Please, give Output Directory.</p>") i2 = Path(i2) if not (i2.exists() and i2.is_dir()): return QtWidgets.QMessageBox.warning(self, "Warning", f"<p style=\"font-size: 10pt;\"><b>Error Found.</b> Output Directory not exist.</p>") i2 = str(i2) folders = self.FILEDATA.get_all_folders(include_subfolder) data = { 's2': self.ui.side_input_2.isChecked(), 's3': self.ui.side_input_3.isChecked(), 's4': self.ui.side_input_4.text(), 's5': self.ui.side_input_5.text(), 's6': self.ui.side_input_6.text(), 's7': self.ui.side_input_7.text(), 's8': self.ui.side_input_8.isChecked(), 's9': self.ui.side_input_9.isChecked(), 's10': self.ui.side_input_10.text(), 's11': self.ui.side_input_11.text(), 's12': self.ui.side_input_12.text(), 's13': self.ui.side_input_13.text(), } if self.action_dialog == None: self.action_dialog = QtWidgets.QWidget() self.action_dialog.setWindowTitle("Action") self.action_dialog.ui = Ui_ActionDialog() self.action_dialog.ui.setupUi(self.action_dialog) self.action_dialog.setFixedHeight(223) self.action_dialog.setFixedWidth(515) self.action_dialog.ui.progressBar.setMinimum(0) self.action_dialog.ui.pushButton_start.clicked.connect(self.go_for_work) self.action_dialog.ui.pushButton_cancel.clicked.connect(self.action_dialog.close) self.action_dialog.ui.pushButton_finish.clicked.connect(self.action_dialog.close) self.action_dialog.ui.pushButton_start.setEnabled(True) self.action_dialog.ui.pushButton_cancel.setEnabled(True) self.action_dialog.ui.pushButton_finish.setEnabled(False) self.action_dialog.ui.label_desDir.setText(get_prefferd_text(i2)) action = 'Copying :' action_ = 'Copied' if i1 == 1: action = 'Moving :' action_ = 'Moved' self.action_dialog.ui.label_action_going.setText(action) self.action_dialog.ui.label_action.setText(action_) self.action_dialog.ui.stackedWidget.setCurrentIndex(1) self.action_dialog.ui.label_statBar.setText("""<html><body><p align="center"><span style="font-size:18pt;">Click 'Start' to go</span></p></body></html>""") self.action_dialog.ui.label_done.setText("0") self.action_dialog.ui.label_failed.setText("0") self.action_dialog.ui.label_notAllowed.setText("0") self.action_dialog.ui.label_ignored.setText("0") self.action_dialog.ui.progressBar.setValue(0) self.action_dialog.data_data = data self.action_dialog.data_folders = folders self.action_dialog.data_action = i1 self.action_dialog.data_des = i2 self.action_dialog.action_done = 0 self.action_dialog.destroy() self.action_dialog.show() def on_action_update(self, done, fail, not_allowed, ignored): self.action_dialog.ui.label_done.setText(str(done)) self.action_dialog.ui.label_failed.setText(str(fail)) self.action_dialog.ui.label_notAllowed.setText(str(not_allowed)) self.action_dialog.ui.label_ignored.setText(str(ignored)) self.action_dialog.action_done += 1 self.action_dialog.ui.progressBar.setValue(self.action_dialog.action_done) def on_action_finish(self): self.action_dialog.ui.pushButton_start.setEnabled(False) self.action_dialog.ui.pushButton_cancel.setEnabled(False) self.action_dialog.ui.pushButton_finish.setEnabled(True) self.action_dialog.ui.progressBar.setMaximum(100) self.action_dialog.ui.progressBar.setValue(100) self.action_dialog.ui.stackedWidget.setCurrentIndex(1) self.action_dialog.ui.label_statBar.setText("""<html><body><p align="center"><span style="font-size:18pt;">Finished</span></p></body></html>""") def on_action_update_2(self, folder, file): self.action_dialog.ui.label_fromDir.setText(get_prefferd_text(folder)) self.action_dialog.ui.label_file.setText(get_prefferd_text(file))
class MainWindow(QtGui.QMainWindow): def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.set_listeners() self.shift_selector = 0 #determina que turno se ejecutara a continuacion. self.shift_worked01 = 0 #Cantidad de turnos trabajados por maquina 1 self.shift_worked02 = 0 #Cantidad de turnos trabajados por maquina 2 self.TruckLoad = 0 #Carga sobrante entre turnos. self.proLoad = 0 #Carga al principio del turno self.Package01 = 0 #Cantidad de paquetes hechos por la primera maquina self.Package02 = 0 #Cantidad de paquetes hechos por la segunda maquina self.Packages = 0 #Cantidad de paquetes por turno. self.Time_Off01 = 0 #Cantidad de tiempo que la maquina permanece sin uso self.Time_Off02 = 0 #Cantidad de tiempo que la maquina permanece sin uso self.Time_On01 = 0 #Cantidad de tiempo que la maquina se encuentra ocupada self.Time_On02 = 0 #Cantidad de tiempo que la maquina se encuentra ocupada self.totalTime01 = 0 self.totalTime02 = 0 def about(self): """ Ventana con los integrantes del grupo """ message = u'Simulador realizado para el ramo de Investigación Operativa II \n\ \nIntegrantes: \n- Nicolas Aravena\n- Hernan Casanova\n- Arturo Reyes\n\ \nProfesor responsable: \n - Miguelina Vega Rosales\n' self.ui.about = QtGui.QMessageBox.information(self, 'Acerca de Simulador', message) def set_listeners(self): """ Se inicializan los listeners """ self.ui.aboutUs.triggered.connect(self.about) self.ui.simulate.clicked.connect(self.simulate) def CreaCarga(self, TruckLoad): """ Creamos los camiones que llegan ese turno """ Time = 0 #Inicializamos la variable en 0 Trucks_shift = 0 while Time < 480: #agregamos mas camiones al turno hasta que se completen los 480 minutos rand = random.expovariate(0.05) Time += rand #agregamos una cantidad de tiempo al azar a los minutos para simular la llegada de un camion Trucks_shift += 1 #agregamos un contador al contador de camiones #print "rand carga", rand Trucks_shift = math.ceil(Trucks_shift) Trucks_shift += self.TruckLoad #agregamos los camiones sobrantes del turno anterior a los camiones para este turno return Trucks_shift def Machine01(self, carga): """ Proceso de la maquina 1 equivalente a 1 turno """ time = 480 self.totalTime01 += time while time > 0 and carga > 0:#Maquina opera mientras dure el turno o duren las cargas de los camiones, lo que se acabe primero rand = random.normalvariate(12,5) if rand < 0: rand *= (-1) time -= rand #print "rand mq1", rand carga -= 1 self.Package01 += 1 if time > 0: #Si el turno se termina por falta de cargas se suma el tiempo sobrante al tiempo desocupado self.Time_Off01 += time self.Time_On01 += (480 - time) else: self.Time_On01 += 480 self.shift_worked01 += 1 return carga def Machine02(self, carga): """ Proceso de la maquina 2 equivalente a 1 turno """ time = 480 self.totalTime02 += time while time > 0 and carga > 0:#Maquina opera mientras dure el turno o duren las cargas de los camiones, lo que se acabe primero rand = random.uniform(12,15) if rand < 0: rand *= (-1) time -= rand carga -= 2 self.Package02 += 1 #print "rand MQ2", rand if time > 0: #Si el turno se termina por falta de cargas se suma el tiempo sobrante al tiempo desocupado self.Time_Off02 += time self.Time_On02 += (480 - time) else: self.Time_On02 += 480 self.shift_worked02 += 1 return carga def simulate(self): """ Simulacion realizada por el usuario """ self.resetValues() shift_count = self.ui.shifts.value() #En esta variable se guarda la cantidad de turnos a contar for i in range(0,shift_count): # el proceso funciona hasta pasar por todos los turnos introducidos if self.shift_selector == 0: #Turno de la primera maquina self.shift_selector = 1 self.proLoad = self.CreaCarga(self.TruckLoad) self.TruckLoad = self.Machine01(self.proLoad) elif self.shift_selector == 1: #Turno de la segunda maquina self.shift_selector = 2 self.proLoad = self.CreaCarga(self.TruckLoad) self.TruckLoad = self.Machine02(self.proLoad) elif self.shift_selector == 2: #Turno de descanso, no se hace nada, no llegan camiones. self.shift_selector = 0 self.Packages = self.Package01 + self.Package02 if shift_count > 1: message = u'Paquetes totales creados: {0}\ \nPaquetes creados máquina 1: {1}\ \nPaquetes creados máquina 2: {2}\ \n----------------------\ \nTiempo promedio trabajado máquina 1: {3} minutos\ \nTiempo promedio trabajado máquina 2: {4} minutos\ \n----------------------\ \nTiempo promedio desocupado máquina 1: {5} minutos\ \nTiempo promedio desocupado máquina 2: {6} minutos\ \n----------------------\ \nPorcentaje tiempo desocupado promedio máquina 1: {7}%\ \nPorcentaje tiempo desocupado promedio máquina 2: {8}%\ '.format( self.Packages, #total paquetes self.Package01, #paquetes mq 1 self.Package02, #paquetes mq 2 round(self.Time_On01/self.shift_worked01,3), round(self.Time_On02/self.shift_worked02,3), round(self.Time_Off01/self.shift_worked01,3), #tiempo mq 1 round(self.Time_Off02/self.shift_worked02,3), #tiempo mq 2 round(self.Time_Off01*100/self.totalTime01,3), #porcentaje mq1 round(self.Time_Off02*100/self.totalTime02,3), #porcentaje mq2 ) else: message = u'Paquetes totales creados: {0}\ \nPaquetes creados maquina 1: {1}\ \nPaquetes creados maquina 2: {2}\ \n----------------------\ \nTiempo promedio trabajado máquina 1: {5} minutos\ \nTiempo promedio trabajado máquina 2: 0 minutos\ \n----------------------\ \nTiempo promedio desocupado máquina 1: {3} minutos\ \nTiempo promedio desocupado máquina 2: 0 minutos\ \n----------------------\ \nPorcentaje tiempo desocupado promedio máquina 1: {4}%\ \nPorcentaje tiempo desocupado promedio máquina 2: 0%\ '.format( self.Packages, #total paquetes self.Package01, #paquetes mq 1 self.Package02, #paquetes mq 2 round(self.Time_Off01/self.shift_worked01,3), #tiempo mq 1 round(self.Time_Off01*100/self.totalTime01,3), #porcentaje mq1 round(self.Time_On01/self.shift_worked01,3), ) self.ui.results.setText(message) def resetValues(self): """ Se reinician los valores para una nueva simulación """ self.shift_selector = 0 self.shift_worked01 = 0 self.shift_worked02 = 0 self.TruckLoad = 0 self.proLoad = 0 self.Package01 = 0 self.Package02 = 0 self.Packages = 0 self.Time_Off01 = 0 self.Time_Off02 = 0 self.Time_On01 = 0 self.Time_On02 = 0 self.totalTimeOff01 = 0 self.totalTimeOff02 = 0 self.totalTimeOn01 = 0 self.totalTimeOn02 = 0 self.totalTime01 = 0 self.totalTime02 = 0
class MainQT5(QtWidgets.QMainWindow): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.action_New_View.triggered.connect(self.new_view) self.ui.action_Tile.triggered.connect(self.tile) self.ui.action_Settings.triggered.connect(self.settings) self.new_view().showMaximized() #self.plot() self.loadSettings() def plot(self): widget = PlotWidget() self.ui.mdiArea.addSubWindow(widget) widget.show() return widget def settings(self): widget = SettingsWidget() self.ui.mdiArea.addSubWindow(widget) widget.show() return widget def new_view(self): widget = ImageWidget() self.ui.mdiArea.addSubWindow(widget) widget.show() return widget def tile(self): if self.ui.mdiArea.currentSubWindow().isMaximized(): self.ui.mdiArea.currentSubWindow().showNormal() position = QtCore.QPoint(0, 0) for window in self.ui.mdiArea.subWindowList(): rect = QtCore.QRect( 0, 0, self.ui.mdiArea.width(), self.ui.mdiArea.height() / len(self.ui.mdiArea.subWindowList())) window.setGeometry(rect) window.move(position) position.setY(position.y() + window.height()) def loadSettings(self): if not os.path.exists(Configuration.configuration_file): return dictionary = None with open(Configuration.configuration_file, 'rb') as f: dictionary = pickle.load(f) for name, value in dictionary.items(): setattr(Configuration, name, value)
class MainWindow(QtGui.QMainWindow): playingA = False playingB = False resultWidgets = [] def __init__(self, parent = None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.listSearch.setVisible(False) self.ui.scrollResult.setVisible(False) self.connect(self.ui.actionAbout , QtCore.SIGNAL('triggered()') , self.actionAbout_triggered ) self.connect(self.ui.actionQuit , QtCore.SIGNAL('triggered()') , QtCore.SLOT('close()') ) self.connect(self.ui.editSearch , QtCore.SIGNAL('textChanged(QString)') , self.editSearch_textChanged ) self.connect(self.ui.buttonSearch , QtCore.SIGNAL('clicked()') , self.buttonSearch_clicked ) self.connect(self.ui.editSearch , QtCore.SIGNAL('returnPressed()') , self.buttonSearch_clicked ) self.connect(self.ui.listSearch , QtCore.SIGNAL('itemActivated(QListWidgetItem *)') , self.listSearch_itemActivated ) self.connect(self.ui.buttonPlayA , QtCore.SIGNAL('clicked()') , self.buttonPlayA_clicked ) self.connect(self.ui.buttonPlayB , QtCore.SIGNAL('clicked()') , self.buttonPlayB_clicked ) self.connect(self.ui.buttonCueA , QtCore.SIGNAL('clicked()') , self.buttonCueA_clicked ) self.connect(self.ui.buttonCueB , QtCore.SIGNAL('clicked()') , self.buttonCueB_clicked ) self.connect(self.ui.listA , QtCore.SIGNAL('itemActivated(QListWidgetItem *)') , self.listA_itemActivated ) self.connect(self.ui.listB , QtCore.SIGNAL('itemActivated(QListWidgetItem *)') , self.listB_itemActivated ) for i in range(0, SEARCHRESULTS): self.resultWidgets.append( WidgetResult(self.ui.scrollResultContents, self.ui.listA, self.ui.listB) ) self.resultWidgets[i].setGeometry(QtCore.QRect(0, i * self.resultWidgets[i].height(), self.resultWidgets[i].width(), self.resultWidgets[i].height())); self.resultWidgets[i].setObjectName( "result" + str(i) ) def actionAbout_triggered(self): box = QtGui.QMessageBox() box.setStandardButtons(QtGui.QMessageBox.Ok) box.setIconPixmap( QtGui.QPixmap( ':/images/cliptor.png' ) ) box.setText( u'Cliptor\n\nCopyright (c) 2009\n\nPavol Rusnák' ) box.setWindowTitle('About Cliptor') box.exec_() def listSearch_itemActivated(self, i): self.ui.editSearch.setText(i.text()) self.buttonSearch_clicked() def editSearch_textChanged(self, s): self.ui.scrollResult.setVisible(False) self.ui.listSearch.clear() for i in Utils.getSuggestions(s): self.ui.listSearch.addItem(i) self.ui.listSearch.setVisible( s != '' and self.ui.listSearch.count() > 0 ) def buttonSearch_clicked(self): s = self.ui.editSearch.text() if s == "": return self.ui.listSearch.setVisible(False) self.ui.listSearch.clear() vids = Utils.getVideos(s) for i in range(0, SEARCHRESULTS): if i < len(vids): self.resultWidgets[i].setData(vids[i]) else: self.resultWidgets[i].setData(None) self.ui.scrollResultContents.setGeometry(QtCore.QRect(0,0,self.resultWidgets[0].width(),self.resultWidgets[0].height()*len(vids))) self.ui.scrollResult.setVisible(True) def buttonPlayA_clicked(self): self.playingA = not self.playingA self.ui.buttonPlayA.setIcon( Utils.getIcon(self.playingA and 'pause' or 'play') ) def buttonPlayB_clicked(self): self.playingB = not self.playingB self.ui.buttonPlayB.setIcon( Utils.getIcon(self.playingB and 'pause' or 'play') ) def buttonCueA_clicked(self): self.ui.buttonCueA.setIcon( Utils.getIcon('cue-go') ) def buttonCueB_clicked(self): self.ui.buttonCueB.setIcon( Utils.getIcon('cue-go') ) def listA_itemActivated(self, i): vid = i.data(QtCore.Qt.UserRole).toString() streams = i.data(QtCore.Qt.UserRole+1).toPyObject() for q in QUALITY: if streams.has_key(q): Utils.downloadStream( vid, q, streams[q] ) return def listB_itemActivated(self, i): vid = i.data(QtCore.Qt.UserRole).toString() streams = i.data(QtCore.Qt.UserRole+1).toPyObject() for q in QUALITY: if streams.has_key(q): Utils.downloadStream( vid, q, streams[q] ) return
class MainForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filename = '' self.directory = '' self.h_file = h5py.File self.chan_dict = {} self.ui.progressBar_data.setMaximum(75) QtCore.QObject.connect(self.ui.pushButton_browse_open, QtCore.SIGNAL("clicked()"), self.browse) QtCore.QObject.connect(self.ui.pushButton_browse_save, QtCore.SIGNAL("clicked()"), self.browse2) QtCore.QObject.connect(self.ui.pushButton_start, QtCore.SIGNAL("clicked()"), self.start) QtCore.QObject.connect(self.ui.pushButton_auto_threshold, QtCore.SIGNAL("clicked()"), self.auto_threshold) QtCore.QObject.connect(self.ui.comboBox_test_num, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.test_change) QtCore.QObject.connect(self.ui.comboBox_threshold, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.chan_change) QtCore.QObject.connect(self.ui.doubleSpinBox_threshold, QtCore.SIGNAL("valueChanged(double)"), self.thresh_change) def browse(self): self.ui.comboBox_test_num.clear() QtGui.QFileDialog(self) self.filename = QtGui.QFileDialog.getOpenFileName() # Make sure proper separators are being used self.filename = self.filename.replace('/', os.sep).replace('\\', os.sep) self.ui.lineEdit_file_name.setText(self.filename) # If the filename is not blank, attempt to extract test numbers and place them into the combobox if self.filename != '': if '.hdf5' in self.filename: try: self.h_file = h5py.File(unicode(self.filename), 'r') except IOError: self.ui.textEdit.append('Error: I/O Error\n') return tests = {} for key in self.h_file.keys(): if 'segment' in key: for test in self.h_file[key].keys(): tests[test] = int(test.replace('test_', '')) sorted_tests = sorted(tests.items(), key=operator.itemgetter(1)) temp = [] for test in sorted_tests: temp.append(test[0]) self.ui.comboBox_test_num.addItems(temp) else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return else: self.ui.textEdit.append('Error: Must select a file to open.\n') return if self.ui.lineEdit_output_directory.text() == '': temp = copy.copy(self.filename) filename_split = self.filename.split(os.sep) output = temp.replace(filename_split[-1], '') # Make sure proper separators are being used output = output.replace('/', os.sep).replace('\\', os.sep) self.ui.lineEdit_output_directory.setText(output) def browse2(self): QtGui.QFileDialog(self) self.directory = QtGui.QFileDialog.getExistingDirectory() self.ui.lineEdit_output_directory.setText(self.directory) def test_change(self): filename = self.filename = self.ui.lineEdit_file_name.text() # Validate filename if filename != '': if '.hdf5' in filename: try: h_file = h5py.File(unicode(self.filename), 'r') target_test = self.ui.comboBox_test_num.currentText() except IOError: self.ui.textEdit.append('Error: I/O Error\n') return else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return else: self.ui.textEdit.append('Error: Must select a file to open.\n') return target_seg = None # Find target segment for segment in h_file.keys(): for test in h_file[segment].keys(): if target_test == test: target_seg = segment target_test = test if target_seg is None: return # Add Comments try: comment = h_file[target_seg].attrs['comment'] self.ui.lineEdit_comments.setText(comment) except: self.ui.lineEdit_comments.clear() self.ui.textEdit.append("Error: Can't open attribute (Can't locate attribute: 'comment')\n") for key in h_file.keys(): if 'segment' in key: for test in h_file[key].keys(): if test == self.ui.comboBox_test_num.currentText(): # Build site string if len(h_file[key][test].value.shape) > 3: # no_chan = False # traces = h_file[key][test].value.shape[0] # repetitions = h_file[key][test].value.shape[1] channels = h_file[key][test].value.shape[2] # samples = h_file[key][test].value.shape[3] else: # no_chan = True # traces = h_file[key][test].value.shape[0] # repetitions = h_file[key][test].value.shape[1] channels = 1 # samples = h_file[key][test].value.shape[2] self.ui.comboBox_threshold.clear() for chan in islice(count(1), channels): self.ui.comboBox_threshold.addItem('channel_' + str(chan)) h_file.close() def chan_change(self): if str(self.ui.comboBox_threshold.currentText()) in self.chan_dict: self.ui.doubleSpinBox_threshold.setValue(self.chan_dict[str(self.ui.comboBox_threshold.currentText())]) else: self.ui.doubleSpinBox_threshold.setValue(0) def thresh_change(self): self.chan_dict[str(self.ui.comboBox_threshold.currentText())] = self.ui.doubleSpinBox_threshold.value() def auto_threshold(self): threshFraction = 0.7 filename = self.ui.lineEdit_file_name.text() # Validate filename if filename != '': if '.hdf5' in filename: try: h_file = h5py.File(unicode(self.filename), 'r') target_test = self.ui.comboBox_test_num.currentText() except IOError: self.ui.textEdit.append('Error: I/O Error\n') return else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return else: self.ui.textEdit.append('Error: Must select a file to open.\n') return # Find target segment for segment in h_file.keys(): for test in h_file[segment].keys(): if target_test == test: target_seg = segment target_test = test trace_data = h_file[target_seg][target_test].value if len(trace_data.shape) == 4: # Compute threshold from average maximum of traces max_trace = [] tchan = int(self.ui.comboBox_threshold.currentText().replace('channel_', '')) for n in range(len(trace_data[1, :, tchan - 1, 0])): max_trace.append(np.max(np.abs(trace_data[1, n, tchan - 1, :]))) average_max = np.array(max_trace).mean() thresh = threshFraction * average_max else: # Compute threshold from average maximum of traces max_trace = [] for n in range(len(trace_data[1, :, 0])): max_trace.append(np.max(np.abs(trace_data[1, n, :]))) average_max = np.array(max_trace).mean() thresh = threshFraction * average_max self.ui.doubleSpinBox_threshold.setValue(thresh) def auto_threshold2(self, test, channel): threshFraction = 0.7 filename = self.ui.lineEdit_file_name.text() # Validate filename if filename != '': if '.hdf5' in filename: try: h_file = h5py.File(unicode(self.filename), 'r') target_test = test except IOError: self.ui.textEdit.append('Error: I/O Error\n') return else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return else: self.ui.textEdit.append('Error: Must select a file to open.\n') return # Find target segment for segment in h_file.keys(): for test in h_file[segment].keys(): if target_test == test: target_seg = segment target_test = test trace_data = h_file[target_seg][target_test].value if len(trace_data.shape) == 4: # Compute threshold from average maximum of traces max_trace = [] tchan = channel for n in range(len(trace_data[1, :, tchan - 1, 0])): max_trace.append(np.max(np.abs(trace_data[1, n, tchan - 1, :]))) average_max = np.array(max_trace).mean() thresh = threshFraction * average_max else: # Compute threshold from average maximum of traces max_trace = [] for n in range(len(trace_data[1, :, 0])): max_trace.append(np.max(np.abs(trace_data[1, n, :]))) average_max = np.array(max_trace).mean() thresh = threshFraction * average_max return thresh def convert(self): filename = self.ui.lineEdit_file_name.text() if filename != '': h_file = h5py.File(unicode(self.filename), 'r') # Check for extraction parameters if '.hdf5' in filename: pass else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return meta_progress = 0 data_progress = 0 temp_filename = get_file_name(self.ui.lineEdit_file_name.text().replace('.hdf5', '')) test_name = self.ui.comboBox_test_num.currentText() datafile = temp_filename + '_' + test_name + '.stad' stam = open(self.ui.lineEdit_output_directory.text() + os.path.sep + temp_filename + '_' + test_name + '.stam', 'w') stad = open(self.ui.lineEdit_output_directory.text() + os.path.sep + temp_filename + '_' + test_name + '.stad', 'w') stam.write('# Data filepath\n') stam.write('datafile=' + datafile + ';\n') stam.write('#\n') stam.write('# Site metadata\n') meta_progress += 5 self.ui.progressBar_meta.setValue(meta_progress) site_count = 0 trace_count = 0 category_count = 0 site_string = '' category_string = '' trace_string = '' for key in h_file.keys(): if 'segment' in key: fs = h_file[key].attrs['samplerate_ad'] for test in h_file[key].keys(): if test == test_name: # Build site string if len(h_file[key][test].value.shape) > 3: no_chan = False traces = h_file[key][test].value.shape[0] repetitions = h_file[key][test].value.shape[1] channels = h_file[key][test].value.shape[2] samples = h_file[key][test].value.shape[3] else: no_chan = True traces = h_file[key][test].value.shape[0] repetitions = h_file[key][test].value.shape[1] channels = 1 samples = h_file[key][test].value.shape[2] # The number of stimuli each trace contains stimuli_count = {} channel_progress = 75 / float(channels) for channel in islice(count(1), channels): self.ui.textEdit.append('Channel: ' + str(channel)) # Execute only once to create category metadata if channel == 1: for trace in islice(count(1), traces): stimuli_types = {} stimuli = json.loads(h_file[key][test].attrs['stim']) stimulus = stimuli[trace - 1] for components in stimulus['components']: # Build category string category_count += 1 if trace in stimuli_count: stimuli_count[trace] += 1 else: stimuli_count[trace] = 1 if components['stim_type'] == 'Vocalization': # Get only the filename and then remove the extension stim = os.path.splitext(components['filename'].split('/')[-1])[0] else: if components['stim_type'] in stimuli_types: stimuli_types[components['stim_type']] += 1 else: stimuli_types[components['stim_type']] = 1 stim = components['stim_type'] + '_' + str(stimuli_types[components['stim_type']]) category_string += 'category=' + str(category_count) + '; ' category_string += 'label=' category_string += 'trace_' + str(trace) + ' ' + stim category_string += ';\n' meta_progress += 15 / float(traces) self.ui.progressBar_meta.setValue(meta_progress) cat_count = 0 trace_progress = channel_progress / float(len(stimuli_count.keys())) for trace in stimuli_count.keys(): self.ui.textEdit.append('Channel: ' + str(channel) + ' Trace: ' + str(trace)) stimuli = json.loads(h_file[key][test].attrs['stim']) stimulus = stimuli[trace - 1] if stimuli_count[trace] < 2: cat_count += 1 for rep in islice(count(1), repetitions): self.ui.textEdit.append('Channel: ' + str(channel) + ' Trace: ' + str(trace) + ' Rep: ' + str(rep)) trace_count += 1 # Trace Metadata trace_string += 'trace=' + str(trace_count) + '; ' trace_string += 'catid=' + str(cat_count) + '; ' trace_string += 'trialid=' + str(rep) + '; ' trace_string += 'siteid=' + str(channel) + '; ' trace_string += 'start_time=' + '0' + '; ' trace_string += 'end_time=' + str(samples / h_file[key].attrs['samplerate_ad']) + '; ' trace_string += '\n' if no_chan: raw_trace = h_file[key][test].value[trace - 1, rep - 1, :] else: raw_trace = h_file[key][test].value[trace - 1, rep - 1, channel - 1, :] # Add to Data File try: spike_times = get_spike_times(raw_trace, self.chan_dict['channel_' + str(channel)], fs) except: temp_thresh = self.auto_threshold2(test, channel) spike_times = get_spike_times(raw_trace, temp_thresh, fs) self.chan_dict['channel_' + str(channel)] = temp_thresh msg = QtGui.QMessageBox() msg.setWindowTitle("Warning!") msg.setWindowIcon(QtGui.QIcon('horsey.ico')) msg.setIcon(QtGui.QMessageBox.Warning) msg.setText("No threshold selected for " + str(test) + ", channel_" + str(channel) + ".\nEstimating threshold at: " + str(temp_thresh) + " V") msg.exec_() for sample in spike_times: stad.write(str(sample)) stad.write(' ') stad.write('\n') meta_progress += trace_progress / float(repetitions) data_progress += trace_progress / float(repetitions) self.ui.progressBar_meta.setValue(meta_progress) self.ui.progressBar_data.setValue(data_progress) QtGui.qApp.processEvents() else: stim_progress = trace_progress / stimuli_count[trace] for stim in islice(count(1), stimuli_count[trace]): self.ui.textEdit.append('Channel: ' + str(channel) + ' Trace: ' + str(trace) + ' Stim: ' + str(stim)) add_time = self.ui.doubleSpinBox_add_stim_time.value() cat_count += 1 for rep in islice(count(1), repetitions): self.ui.textEdit.append('Channel: ' + str(channel) + ' Trace: ' + str(trace) + ' Stim: ' + str(stim) + ' Rep: ' + str(rep)) trace_count += 1 # Trace Metadata trace_string += 'trace=' + str(trace_count) + '; ' trace_string += 'catid=' + str(cat_count) + '; ' trace_string += 'trialid=' + str(rep) + '; ' trace_string += 'siteid=' + str(channel) + '; ' trace_string += 'start_time=' + '0' + '; ' if stimulus['components'][stim-1]['stim_type'] != 'silence': trace_string += 'end_time=' + str(stimulus['components'][stim-1]['duration'] + add_time) + '; ' elif stimulus['components'][stim-1]['stim_type'] == 'silence' and stim > 1: trace_string += 'end_time=' + str(stimulus['components'][stim - 1]['duration'] - add_time) + '; ' else: trace_string += 'end_time=' + str(stimulus['components'][stim - 1]['duration']) + '; ' trace_string += '\n' # h_file[key][test].value[trace, rep, chan, :] if no_chan: raw_trace = h_file[key][test].value[trace - 1, rep - 1, :] else: raw_trace = h_file[key][test].value[trace - 1, rep - 1, channel - 1, :] sample_start = stimulus['components'][stim-1]['start_s'] * h_file[key].attrs['samplerate_ad'] if stimulus['components'][stim-1]['stim_type'] != 'silence': sample_duration = (stimulus['components'][stim - 1]['duration'] + add_time) * h_file[key].attrs['samplerate_ad'] elif stimulus['components'][stim - 1]['stim_type'] == 'silence' and stim > 1: sample_duration = (stimulus['components'][stim - 1]['duration'] - add_time) * h_file[key].attrs['samplerate_ad'] else: sample_duration = stimulus['components'][stim-1]['duration'] * h_file[key].attrs['samplerate_ad'] sample_end = sample_start + sample_duration stimuli_trace = raw_trace[:sample_end][sample_start:] # Add to Data File spike_times = get_spike_times(stimuli_trace, self.chan_dict['channel_' + str(channel)], fs) for sample in spike_times: stad.write(str(sample)) stad.write(' ') stad.write('\n') meta_progress += stim_progress / float(repetitions) data_progress += stim_progress / float(repetitions) self.ui.progressBar_meta.setValue(meta_progress) self.ui.progressBar_data.setValue(data_progress) QtGui.qApp.processEvents() # Build site string # time_scale is 1 due to Sparkle storing time in seconds for channel in islice(count(1), channels): site_count += 1 site_string += 'site=' + str(site_count) + '; ' site_string += 'label=' + test if channels > 1: site_string += ' chan_' + str(channel) + '; ' else: site_string += '; ' if h_file[key][test].attrs['mode'] == 'continuous': site_string += 'recording_tag=continuous; ' elif h_file[key][test].attrs['mode'] == 'finite': site_string += 'recording_tag=episodic; ' else: # TODO Error pass site_string += 'time_scale=1; ' # TODO Calculate Time Resolution site_string += 'time_resolution=0.001;\n' site_string += 'si_unit=volts; si_prefix=1.0;\n' meta_progress += 5 / float(channels) self.ui.progressBar_meta.setValue(meta_progress) stam.write(site_string) stam.write('#\n') stam.write('# Category metadata\n') if self.ui.doubleSpinBox_add_stim_time.value() != 0: stam.write('# stimulus window: + ' + str(self.ui.doubleSpinBox_add_stim_time.value()) + ' s\n') stam.write(category_string) stam.write('#\n') stam.write('# Trace metadata\n') if self.ui.doubleSpinBox_add_stim_time.value() != 0: stam.write('# Stim + \n') stam.write(trace_string) stam.close() stad.close() self.ui.textEdit.append('\nComplete') def start(self): self.ui.progressBar_meta.reset() self.ui.progressBar_data.reset() self.convert()
def __init__(self): super().__init__() self.ui = Ui_MainWindow(self) self.homeTab = HomeTabUI(self.ui.tab1) self.registration = RegistrationUI(self.ui.tab2) self.profile = ProfileUI(self.ui.tab3) self.connection = create_connection("localhost", "root", "", "ofwtmc_db") select_members = "SELECT id, mem_name, mem_address, contact_no FROM members" self.members_data = execute_read_query(self.connection, select_members) self.getMembersData() self.right = self.ui.tabWidget.tabBar().RightSide self.save_registration_tab = self.ui.tabWidget.widget( 1) # save it for later self.save_profile_tab = self.ui.tabWidget.widget( 2) # save Member Profile Tab for later self.removeRegistrationTab() self.removeMemberProfileTab() # Create actionsDict actionsDict = { self.ui.menuHome: "Home", self.ui.actionNew: "New", self.ui.actionSave: "Save", self.ui.actionCut: "Cut", self.ui.actionCopy: "Copy", self.ui.actionPaste: "Paste", self.ui.actionPreview: "Preview" } self.childrenData = [] self.id = self.profile.inputId self.date = self.registration.dateInput self.id_picture = self.registration.filenameText self.ofw_name = self.registration.ofwNameInput self.ofw_address = self.registration.ofwAddressInput self.b_name = self.registration.beneficiaryNameInput self.b_address = self.registration.beneficiaryAddresInput self.pob = self.registration.placeOfBirthInput self.province_add = self.registration.provincialAddressInput self.religion = self.registration.religionInput self.contact_no = self.registration.contactInput self.email = self.registration.emailAddInput self.age = self.registration.ageInput self.status = self.registration.civilStatusInput self.citizenship = self.registration.citizenshipInput self.tin = self.registration.tinInput self.sss = self.registration.sssInput self.hw_name = self.registration.hwNameInput self.hw_pob = self.registration.hwPlaceOfBirthInput self.hw_occupation = self.registration.hwOccupationInput self.hw_dob = self.registration.hwDateOfBirthInput self.hw_age = self.registration.hwAgeInput self.emp_name = self.registration.empNameInput self.emp_position = self.registration.empPositionInput self.emp_address = self.registration.empAddressInput self.emp_date = self.registration.empDateInput self.emp_cn = self.registration.empContactInput self.emp_email = self.registration.empEmailInput self.incase_name = self.registration.incaseNameInput self.incase_contact = self.registration.incaseContactInput self.incase_address = self.registration.incaseContactInput self.dob = self.registration.dateOfBirthInput self.op_dr_name = self.registration.opOrDriverInput self.sex = self.getSRBtn() self.ch1_name, self.ch1_address, self.ch1_age = self.getChildData(0) self.ch2_name, self.ch2_address, self.ch2_age = self.getChildData(1) self.ch3_name, self.ch3_address, self.ch3_age = self.getChildData(2) #self.registration_inputs = {self.date, self.id_picture, self.ofw_address, self.b_name, # self.b_address, self.pob, self.province_add, self.religion, # self.contact_no, self.email, self.age, self.status, # self.hw_name, self.hw_pob, self.hw_dob, self.hw_age, self.hw_occupation, # self.emp_name, self.emp_position, self.emp_address,self.emp_date, self.emp_cn, # self.emp_email, self.incase_name, self.incase_address, self.incase_contact, # self.op_dr_name, self.id_picture} # Iterate on actionsDict.items then call updateClick for action, actionName in actionsDict.items(): self.updateClick(action, actionName) # Call the openFileNameDialog when fileSelectBtn is clicked self.registration.fileSelectBtn.clicked.connect( self.openFileNameDialog) # Call the uploadBtnClicked when uploadBtn is clicked self.registration.uploadBtn.clicked.connect(self.uploadBtnClicked) self.registration.submitBtn.clicked.connect(self.submitPopup) self.registration.msgBox.buttonClicked.connect(self.saveFileDialog) self.registration.comboBox.activated.connect(self.comboPressed) self.registration.chAddBtn.clicked.connect(self.addChildren) self.profile.showBtn.clicked.connect(self.LoadData) self.homeTab.register_btn.clicked.connect(self.showRegistration) self.homeTab.member_profiles_btn.clicked.connect( self.showMemberProfile) self.homeTab.listwidget.itemClicked.connect(self.LoadData) self.homeTab.search_input.textChanged.connect(self.inputChecker) self.homeTab.comboBox.currentTextChanged.connect(self.getMembersData)
class MyForm(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.filename = '' self.threshold = 0 self.h_file = h5py.File QtCore.QObject.connect(self.ui.pushButton_browse, QtCore.SIGNAL("clicked()"), self.browse) QtCore.QObject.connect(self.ui.pushButton_start, QtCore.SIGNAL("clicked()"), self.start) QtCore.QObject.connect(self.ui.pushButton_auto_threshold, QtCore.SIGNAL("clicked()"), self.auto_threshold) QtCore.QObject.connect(self.ui.comboBox_test_num, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.test_change) self.setWindowIcon(QtGui.QIcon('horsey.ico')) def browse(self): self.ui.comboBox_test_num.clear() QtGui.QFileDialog(self) self.filename = QtGui.QFileDialog.getOpenFileName() self.ui.lineEdit_file_name.setText(self.filename) # If the filename is not blank, attempt to extract test numbers and place them into the combobox if self.filename != '': if '.hdf5' in self.filename: try: self.h_file = h5py.File(unicode(self.filename), 'r') except IOError: self.ui.textEdit.append('Error: I/O Error\n') return tests = {} for key in self.h_file.keys(): if 'segment' in key: for test in self.h_file[key].keys(): tests[test] = int(test.replace('test_', '')) sorted_tests = sorted(tests.items(), key=operator.itemgetter(1)) temp = [] for test in sorted_tests: temp.append(test[0]) self.ui.comboBox_test_num.addItems(temp) else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return else: self.ui.textEdit.append('Error: Must select a file to open.\n') return def test_change(self): filename = self.filename = self.ui.lineEdit_file_name.text() self.ui.comboBox_channel.clear() # Validate filename if filename != '': if '.hdf5' in filename: try: h_file = h5py.File(unicode(self.filename), 'r') target_test = self.ui.comboBox_test_num.currentText() except IOError: self.ui.textEdit.append('Error: I/O Error\n') return else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return else: self.ui.textEdit.append('Error: Must select a file to open.\n') return target_seg = None # Find target segment for segment in h_file.keys(): for test in h_file[segment].keys(): if target_test == test: target_seg = segment target_test = test if target_seg is None: return # If there are more than three attributes in value (test, trace, rep, channel) temp = h_file[target_seg][target_test].value.shape if len(temp) > 3: channels = temp[2] else: channels = 1 if channels == 1: self.ui.comboBox_channel.addItem('channel_1') else: temp = [] for i in range(channels): temp.append('channel_' + str(i + 1)) self.ui.comboBox_channel.addItems(temp) # Add Comments try: comment = h_file[target_seg].attrs['comment'] self.ui.lineEdit_comments.setEnabled(True) self.ui.lineEdit_comments.setText(comment) except: self.ui.lineEdit_comments.clear() self.ui.textEdit.append("Error: Can't open attribute (Can't locate attribute: 'comment')\n") if self.ui.lineEdit_comments.text() == '': self.ui.lineEdit_comments.setDisabled(True) h_file.close() def auto_threshold(self): threshFraction = 0.7 filename = self.filename = self.ui.lineEdit_file_name.text() # Validate filename if filename != '': if '.hdf5' in filename: try: h_file = h5py.File(unicode(self.filename), 'r') target_test = self.ui.comboBox_test_num.currentText() except IOError: self.ui.textEdit.append('Error: I/O Error\n') return else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return else: self.ui.textEdit.append('Error: Must select a file to open.\n') return # Find target segment for segment in h_file.keys(): for test in h_file[segment].keys(): if target_test == test: target_seg = segment target_test = test trace_data = h_file[target_seg][target_test].value if len(trace_data.shape) == 4: trace_data = trace_data.squeeze() # Compute threshold from average maximum of traces max_trace = [] for n in range(len(trace_data[1, :, 0])): max_trace.append(np.max(np.abs(trace_data[1, n, :]))) average_max = np.array(max_trace).mean() thresh = threshFraction * average_max self.ui.doubleSpinBox_threshold.setValue(thresh) def extract(self): filename = self.filename = self.ui.lineEdit_file_name.text() if filename != '': h_file = h5py.File(unicode(self.filename), 'r') # Check for extraction parameters if '.hdf5' in self.filename: pass else: self.ui.textEdit.append('Error: Must select a .hdf5 file.\n') return if not self.ui.checkBox_calibration.isChecked() and not self.ui.checkBox_stim.isChecked() and \ not self.ui.checkBox_spikes.isChecked() and not self.ui.checkBox_raw.isChecked(): self.ui.textEdit.append('Error: Must select at least one type of export.\n') return if self.ui.doubleSpinBox_threshold.value() == 0: self.ui.textEdit.append('Warning: Threshold has a value of 0\n') # Display parameters self.ui.textEdit.append('File: ' + self.filename) self.ui.textEdit.append('Threshold: ' + str(self.ui.doubleSpinBox_threshold.value()) + ' V') self.ui.textEdit.append('Test: ' + self.ui.comboBox_test_num.currentText()) threshold = self.ui.doubleSpinBox_threshold.value() extract_test = self.ui.comboBox_test_num.currentText() if self.ui.radioButton_normal.isChecked(): self.ui.textEdit.append('Type: Normal') thresh_type = 'normal' elif self.ui.radioButton_inverse.isChecked(): self.ui.textEdit.append('Type: Inverse') thresh_type = 'inverse' else: self.ui.textEdit.append('Type: Error') thresh_type = 'error' if self.ui.checkBox_calibration.isChecked(): self.ui.textEdit.append('Export: Calibration') export_calibration = True else: export_calibration = False if self.ui.checkBox_stim.isChecked(): self.ui.textEdit.append('Export: Stimulus') export_stimulus = True else: export_stimulus = False if self.ui.checkBox_spikes.isChecked(): self.ui.textEdit.append('Export: Spike Times') export_spikes = True else: export_spikes = False if self.ui.checkBox_raw.isChecked(): self.ui.textEdit.append('Export: Raw Data') export_raw = True else: export_raw = False self.ui.textEdit.append('') if export_calibration: for key in h_file.keys(): # If key is a calibration if 'calibration' in key: # print 'Cal:', key temp_filename = filename.replace('.hdf5', '_') + key + '.csv' try: cal_file = open(temp_filename, 'wb') except IOError, e: self.ui.textEdit.append('Unable to open ' + get_file_name(temp_filename)) self.ui.textEdit.append('Error ' + str(e.errno) + ': ' + e.strerror + '\n') cal_writer = csv.writer(cal_file) cal_writer.writerow([key]) for dataSet in h_file[key].keys(): # print ' ', dataSet cal_writer.writerow(['', dataSet]) for attr in h_file[key][dataSet].attrs.items(): # print ' ', ' ', attr[0], ' ', attr[1] cal_writer.writerow(['', '', attr[0]]) cal_writer.writerow(['', '', '', attr[1]]) cal_file.close() self.ui.textEdit.append(key + ' Complete') # Print all of the samples np.set_printoptions(threshold='nan') # -------------------------------------------------------------------------------------------------------------- if export_stimulus: for key in h_file.keys(): # If key is a calibration if 'segment' in key: # print 'Seg:', key for test in h_file[key].keys(): if test == extract_test: temp_filename = filename.replace('.hdf5', '_') + test + '_stimulus.txt' try: stimulus_file = open(temp_filename, 'w') except IOError, e: self.ui.textEdit.append('Unable to open ' + get_file_name(temp_filename)) self.ui.textEdit.append('Error ' + str(e.errno) + ': ' + e.strerror + '\n') stimuli = json.loads(h_file[key][test].attrs['stim']) stimulus = stimuli[-1] for stim in stimulus['components']: stimulus_file.write(stim['stim_type'] + '\n') for value in stim: if value != 'stim_type': stimulus_file.write(str(value) + '=' + str(stim[value]) + '\n') stimulus_file.write('\n') stimulus_file.close() self.ui.textEdit.append(test + ' Stimulus Complete')