Ejemplo n.º 1
0
    def createSaveGroup(self):
        groupBox = QGroupBox(string._('Step 3:Select save option'))

        radio1 = QRadioButton(string._('Save as file'))
        radio1.setChecked(True)
        radio2 = QRadioButton(string._('Save as web page'))
        radio2.setEnabled(False)

        self.btn_StartBackup = QPushButton(string._('Start Backup'), self)
        self.btn_StartBackup.setEnabled(False)
        self.btn_StartBackup.clicked[bool].connect(self.StartBackup)
        self.btn_OpenFolder = QPushButton(string._('Open Folder'), self)
        self.btn_OpenFolder.clicked[bool].connect(self.OpenFolder)

        vbox = QVBoxLayout()
        vbox.addWidget(radio1)
        vbox.addWidget(radio2)
        vbox.addWidget(self.btn_StartBackup)
        vbox.addWidget(self.btn_OpenFolder)
        vbox.addStretch(1)
        groupBox.setLayout(vbox)

        if not exists('iLearn'):
            makedirs('iLearn')

        return groupBox
Ejemplo n.º 2
0
class WriteModeWidget(QWidget):
    def __init__(self, parent=None):
        super(WriteModeWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.writr_mode_title = QLabel('导出设置')
        self.write_button = QCheckBox('导出docx')
        self.write_every_link_a_file = QRadioButton('每个链接对应一个文件')
        self.write_links_to_one_file = QRadioButton('保存为一个文件')

        self.write_mode_core_box = QVBoxLayout()
        self.write_mode_core_box.addWidget(self.write_every_link_a_file)
        self.write_mode_core_box.addWidget(self.write_links_to_one_file)
        self.write_mode_surface_box = QHBoxLayout()
        self.write_mode_surface_box.addSpacing(25)
        self.write_mode_surface_box.addLayout(self.write_mode_core_box)

        self.writr_mode_box = QVBoxLayout()
        self.writr_mode_title.setAlignment(Qt.AlignCenter)
        self.writr_mode_box.addWidget(self.writr_mode_title)
        self.writr_mode_box.addWidget(self.write_button)
        self.writr_mode_box.addLayout(self.write_mode_surface_box)

        self.write = True
        self.write_button.toggle()
        self.writr_mode = 'multi'
        self.write_every_link_a_file.toggle()
        self.write_mode_button_group = QButtonGroup()
        self.write_mode_button_group.addButton(self.write_every_link_a_file)
        self.write_mode_button_group.addButton(self.write_links_to_one_file)

        self.write_button.stateChanged.connect(self.onWriteButtonClicked)
        self.write_mode_button_group.buttonClicked.connect(
            self.onWriteModeButtonClicked)

        self.setLayout(self.writr_mode_box)

    def onWriteButtonClicked(self, state):
        if state == Qt.Checked:
            self.write = True
            self.setWriteModeButtonGroupEnabled(True)
        else:
            self.write = False
            self.setWriteModeButtonGroupEnabled(False)

    def onWriteModeButtonClicked(self):
        if self.write_mode_button_group.checkedButton(
        ) is self.write_every_link_a_file:
            self.writr_mode = 'multi'
        elif self.write_mode_button_group.checkedButton(
        ) is self.write_links_to_one_file:
            self.writr_mode = 'one'

    def setWriteModeButtonGroupEnabled(self, bool):
        self.write_every_link_a_file.setEnabled(bool)
        self.write_links_to_one_file.setEnabled(bool)

    def getMode(self):
        return self.write, self.writr_mode
Ejemplo n.º 3
0
    def initUI(self):
        """Initializes the widgets elements (buttons, and tools in general)"""

        self.setFixedSize(250, 300)
        self.setStyleSheet('color: white; font-size: 14px')
        layout = QVBoxLayout()
        name_label = QLabel('Frame name')
        name_edit = QLineEdit()
        name_edit.setPlaceholderText('Frame name')
        name_edit.setMaximumWidth(200)
        data_label = QLabel('Data type')
        self.button_group = QButtonGroup()
        self.button_group.setExclusive(True)
        rgb_image_data = QRadioButton('RGB Image')
        rgb_image_data.setObjectName('rgbimage')
        depth_image_data = QRadioButton('Depth Image')
        depth_image_data.setObjectName('depthimage')
        laser_data = QRadioButton('Laser Data')
        laser_data.setObjectName('laser')
        pose_data = QRadioButton('Pose3D Data')
        pose_data.setObjectName('pose')
        rgb_image_data.setChecked(True)
        depth_image_data.setEnabled(False)
        self.button_group.addButton(rgb_image_data)
        self.button_group.addButton(laser_data)
        self.button_group.addButton(pose_data)
        self.button_group.addButton(depth_image_data)
        self.aspect_ratio = QCheckBox('Keep aspect ratio')
        self.aspect_ratio.setChecked(True)
        confirm_button = QPushButton('Confirm')
        confirm_button.setMaximumWidth(200)

        self.button_group.buttonClicked.connect(self.button_handle)
        confirm_button.pressed.connect(self.confirm_configuration)
        name_edit.textChanged[str].connect(self.change_name)

        layout.addWidget(name_label, alignment=Qt.AlignCenter)
        layout.addWidget(name_edit)
        layout.addWidget(data_label, alignment=Qt.AlignCenter)
        layout.addWidget(rgb_image_data)
        layout.addWidget(depth_image_data)
        layout.addWidget(laser_data)
        layout.addWidget(pose_data)
        layout.addWidget(HLine())
        layout.addWidget(self.aspect_ratio, alignment=Qt.AlignLeft)
        layout.addWidget(confirm_button)

        self.setLayout(layout)
Ejemplo n.º 4
0
    def _create_libdmtx(self, settings):
        radio = QRadioButton('My objects are labelled with Data Matrix barcodes')
        radio.setChecked('libdmtx' == settings['engine'])
        radio.setEnabled(libdmtx_available())
        self._layout.addWidget(radio)

        prompt = QLabel(HTML_LINK_TEMPLATE.format(
            'Barcodes will be decoded using the open-source '
            '<a href="http://libdmtx.sourceforge.net/">libdmtx</a> library'
        ))
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        self._layout.addWidget(HorizontalLine())
        return radio
Ejemplo n.º 5
0
class MainWindow_style(QMainWindow):
	def __init__(self):
		super().__init__()
		self.setWindowTitle('宇宙骂人小工具')
		self.center()
		self.resize(400,200)
		self.show_btn()
		# self.statusBar()#显示状态栏
	def center(self):#设置窗口居中
		box=self.frameGeometry()#获取当前盒子的信息
		window_center=QDesktopWidget().availableGeometry().center()
		box.moveCenter(window_center)
		self.move(box.topLeft())
	def show_btn(self):#设置按钮
		self.btn1=QPushButton('设置字典')#设置字典
		self.btn2=QPushButton('设置发送速度')#设置发送速度
		self.btn3=QRadioButton('网站')#设置发送源
		self.btn4=QRadioButton('字典')#设置发送源
		self.btn5=QPushButton('发送')#开始发送
		self.btn6=QPushButton('骂人')
		hbox=QHBoxLayout()
		hbox1=QHBoxLayout()
		hbox2=QHBoxLayout()
		vbox1=QVBoxLayout()
		vbox2=QVBoxLayout()

		vbox1.addWidget(self.btn1)
		vbox1.addWidget(self.btn2)

		hbox1.addWidget(self.btn3)
		self.btn3.setChecked(True)#设置默认选中
		hbox1.addWidget(self.btn4)
		self.btn4.setEnabled(False)#设置无法选择
		vbox2.addLayout(hbox1)
		
		hbox2.addWidget(QLabel('当前状态:'))
		hbox2.addWidget(self.btn6)
		vbox2.addLayout(hbox2)
		
		vbox2.addWidget(self.btn5)
		hbox.addLayout(vbox1)
		hbox.addStretch()#设置中间的占位控件
		hbox.addLayout(vbox2)
		hbox.setContentsMargins(50,0,50,0)#设置hbox控件的外边距 左上右下
		center_window=QWidget()
		center_window.setLayout(hbox)
		self.setCentralWidget(center_window)
Ejemplo n.º 6
0
    def _create_inlite(self, settings):
        radio = QRadioButton(
            'Either my objects are labelled with a barcode not listed above '
            'or I would like the performance and reliability of a commercial '
            'library')
        radio.setChecked('inlite' == settings['engine'])
        radio.setEnabled(inlite_available())
        self._layout.addWidget(radio)

        prompt = QLabel(HTML_LINK_TEMPLATE.format(
            'Only available on Windows. '
            'Visit <a href="http://www.inliteresearch.com/">Inlite Research</a> '
            'to download and install Inlite Research\'s ClearImage library.'
        ))
        prompt.setWordWrap(True)
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        prompt = QLabel('My objects are labelled with:')
        format = settings['inlite-format']
        radio_1d = QRadioButton('1D barcodes')
        radio_1d.setChecked('1d' == format)
        radio_datamatrix = QRadioButton('Data Matrix barcodes')
        radio_datamatrix.setChecked('datamatrix' == format)
        radio_pdf417 = QRadioButton('PDF 417 barcodes')
        radio_pdf417.setChecked('pdf417' == format)
        radio_qr = QRadioButton('QR codes')
        radio_qr.setChecked('qrcode' == format)

        layout = QVBoxLayout()
        layout.addWidget(prompt)
        layout.addWidget(radio_1d)
        layout.addWidget(radio_datamatrix)
        layout.addWidget(radio_pdf417)
        layout.addWidget(radio_qr)

        group = QWidget()
        group.setLayout(layout)
        group.setStyleSheet(self.STYLESHEET)
        radio.toggled.connect(group.setEnabled)
        group.setEnabled(inlite_available() and 'inlite' == settings['engine'])

        self._layout.addWidget(group)

        return radio, radio_1d, radio_datamatrix, radio_pdf417, radio_qr
Ejemplo n.º 7
0
    def __make_cell(self, c, name, col_type, col_type_def):
        cell = QWidget(self.inner)
        rbtn = QRadioButton('', cell)
        rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c)))
        hbl = QHBoxLayout(cell)
        hbl.addWidget(rbtn)
        hbl.setContentsMargins(0, 0, 0, 0)
        hbl.setAlignment(Qt.AlignCenter)
        cell.setLayout(hbl)
        if name == 'cat':
            if col_type == 'object':
                rbtn.setChecked(True)
            self.lst_cat.append(rbtn)
        elif name == 'num':
            if col_type != 'object':
                rbtn.setChecked(True)
            if col_type_def == 'object':
                rbtn.setEnabled(False)
            self.lst_num.append(rbtn)
        elif name == 'obj':
            if col_type == 'object' and self.params.task == 'Regression':
                rbtn.setEnabled(False)
            elif col_type != 'object' and self.params.task == 'Classification':
                rbtn.setEnabled(False)
            if self.params.columns[c] == self.params.objective:
                rbtn.setChecked(True)
            self.lst_obj.append(rbtn)

        return cell
Ejemplo n.º 8
0
    def __make_cell(self, c, name, col_type, col_type_def):
        cell = QWidget(self.inner)
        rbtn = QRadioButton('', cell)
        rbtn.toggled.connect(lambda: self.rbtn_clicked(name + '_' + str(c)))
        hbl = QHBoxLayout(cell)
        hbl.addWidget(rbtn)
        hbl.setContentsMargins(0, 0, 0, 0)
        hbl.setAlignment(Qt.AlignCenter)
        cell.setLayout(hbl)
        if name == 'cat':
            if col_type == 'object':
                rbtn.setChecked(True)
            self.lst_cat.append(rbtn)
        elif name == 'num':
            if col_type != 'object':
                rbtn.setChecked(True)
            if col_type_def == 'object':
                rbtn.setEnabled(False)
            self.lst_num.append(rbtn)
        elif name == 'obj':
            if col_type == 'object' and self.params.task == 'Regression':
                rbtn.setEnabled(False)
            elif col_type != 'object' and self.params.task == 'Classification':
                rbtn.setEnabled(False)
            if self.params.columns[c] == self.params.objective:
                rbtn.setChecked(True)
            self.lst_obj.append(rbtn)

        return cell
Ejemplo n.º 9
0
class AnnouncementDownloaderUi(QWidget):
    def __init__(self, sas_if: sasIF, task_manager):
        super(AnnouncementDownloaderUi, self).__init__()

        # ---------------- ext var ----------------

        self.__sas_if = sas_if
        # self.__data_center = self.__data_hub.get_data_center() if self.__data_hub is not None else None
        # self.__data_utility = self.__data_hub.get_data_utility() if self.__data_hub is not None else None
        self.__task_manager = task_manager
        self.__translate = QtCore.QCoreApplication.translate

        # Timer for update stock list
        self.__timer = QTimer()
        self.__timer.setInterval(1000)
        self.__timer.timeout.connect(self.on_timer)
        self.__timer.start()

        # Ui component
        self.__combo_name = SecuritiesSelector(self.__sas_if, self)
        self.__radio_annual_report = QRadioButton('年报')
        self.__radio_customize_filter = QRadioButton('自定义')
        self.__line_filter_include = QLineEdit()
        self.__line_filter_exclude = QLineEdit()
        self.__button_download = QPushButton('确定')

        self.__datetime_since = QDateTimeEdit(
            QDateTime.currentDateTime().addYears(-3))
        self.__datetime_until = QDateTimeEdit(QDateTime.currentDateTime())

        self.init_ui()

    # ---------------------------------------------------- UI Init -----------------------------------------------------

    def init_ui(self):
        self.__layout_control()
        self.__config_control()

    def __layout_control(self):
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)

        main_layout.addLayout(
            horizon_layout([QLabel('股票代码'), self.__combo_name], [1, 10]))
        main_layout.addLayout(
            horizon_layout([QLabel('报告起始'), self.__datetime_since], [1, 10]))
        main_layout.addLayout(
            horizon_layout([QLabel('报告截止'), self.__datetime_until], [1, 10]))
        main_layout.addLayout(
            horizon_layout([
                QLabel('报告类型'), self.__radio_annual_report,
                self.__radio_customize_filter
            ], [1, 5, 5]))
        main_layout.addLayout(
            horizon_layout([QLabel('包含词条(以,分隔)'), self.__line_filter_include],
                           [1, 10]))
        main_layout.addLayout(
            horizon_layout([QLabel('排除词条(以,分隔)'), self.__line_filter_exclude],
                           [1, 10]))
        main_layout.addWidget(QLabel(DEFAULT_INFO))
        main_layout.addWidget(self.__button_download)

    def __config_control(self):
        # self.__combo_name.setEditable(True)
        # self.__combo_name.addItem('所有')
        # self.__combo_name.addItem('股票列表载入中')
        self.__radio_annual_report.setChecked(True)
        self.__line_filter_include.setEnabled(False)
        self.__line_filter_exclude.setEnabled(False)
        self.__radio_customize_filter.setEnabled(False)
        self.__radio_annual_report.clicked.connect(self.on_radio_report_type)
        self.__radio_customize_filter.clicked.connect(
            self.on_radio_report_type)
        self.__button_download.clicked.connect(self.on_button_download)

    def on_timer(self):
        if self.__combo_name.count() > 1:
            self.__combo_name.insertItem(0, ALL_STOCK_TEXT)
            self.__combo_name.setCurrentIndex(0)
            self.__timer.stop()
        # # Check stock list ready and update combobox
        # if self.__data_utility is not None:
        #     if self.__data_utility.stock_cache_ready():
        #         self.__combo_name.clear()
        #         self.__combo_name.addItem(ALL_STOCK_TEXT)
        #         stock_list = self.__data_utility.get_stock_list()
        #         for stock_identity, stock_name in stock_list:
        #             self.__combo_name.addItem(stock_identity + ' | ' + stock_name, stock_identity)

    def on_radio_report_type(self):
        if self.__radio_annual_report.isChecked():
            self.__line_filter_include.setEnabled(False)
            self.__line_filter_exclude.setEnabled(False)
        else:
            self.__line_filter_include.setEnabled(True)
            self.__line_filter_exclude.setEnabled(True)

    def on_button_download(self):
        # input_securities = self.__combo_name.currentText()
        # if '|' in input_securities:
        #     input_securities = input_securities.split('|')[0].strip()

        input_securities = self.__combo_name.get_input_securities()
        if input_securities == ALL_STOCK_TEXT:
            if self.__sas_if is None:
                QMessageBox.information(
                    self, QtCore.QCoreApplication.translate('main', '提示'),
                    QtCore.QCoreApplication.translate('main', '无法获取股票列表'),
                    QMessageBox.Yes, QMessageBox.No)
                return
            reply = QMessageBox.question(
                self, QtCore.QCoreApplication.translate('main', '操作确认'),
                QtCore.QCoreApplication.translate('main', DOWNLOAD_ALL_TIPS),
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply != QMessageBox.Yes:
                return
        self.__build_download_task(input_securities)

    def __build_download_task(self, securities: str):
        task = AnnouncementDownloadTask()
        task.securities = securities
        task.period_since = self.__datetime_since.dateTime().toPyDateTime()
        task.period_until = self.__datetime_until.dateTime().toPyDateTime()
        task.filter_include = self.__line_filter_include.text().split(',')
        task.filter_exclude = self.__line_filter_exclude.text().split(',')
        task.report_type = \
            AnnouncementDownloadTask.REPORT_TYPE_ANNUAL \
                if self.__radio_annual_report.isChecked() else \
            AnnouncementDownloadTask.REPORT_TYPE_NONE

        task.task_manager = self.__task_manager
        task.sas_if = self.__sas_if
        # task.data_utility = self.__data_utility

        if self.__task_manager is not None:
            self.__task_manager.append_task(task)
        else:
            task.run()
Ejemplo n.º 10
0
    fpsCheckBox = QCheckBox()
    fpsCheckBox.setText("Show FPS")
    fpsCheckBox.setChecked(False)
    fpsLabel = QLabel()

    textureDetailGroupBox = QGroupBox("Texture detail")

    lowDetailRB = QRadioButton()
    lowDetailRB.setText("Low (128x64x128)")
    lowDetailRB.setChecked(True)

    mediumDetailRB = QRadioButton()
    mediumDetailRB.setText("Generating...")
    mediumDetailRB.setChecked(False)
    mediumDetailRB.setEnabled(False)

    highDetailRB = QRadioButton()
    highDetailRB.setText("Generating...")
    highDetailRB.setChecked(False)
    highDetailRB.setEnabled(False)

    textureDetailVBox = QVBoxLayout()
    textureDetailVBox.addWidget(lowDetailRB)
    textureDetailVBox.addWidget(mediumDetailRB)
    textureDetailVBox.addWidget(highDetailRB)
    textureDetailGroupBox.setLayout(textureDetailVBox)

    areaGroupBox = QGroupBox("Show area")

    areaAllRB = QRadioButton()
Ejemplo n.º 11
0
class SettingsDialog(QDialog):
    worker = None
    config = None
    configfile = None

    saved = QtCore.pyqtSignal()

    def __init__(self, parent, worker, config, configfile):
        QDialog.__init__(self, parent)

        self.worker = worker
        self.config = config
        self.configfile = configfile
        self.setStyleSheet("QGroupBox { font-weight: bold; } ")
        self.setWindowTitle('Settings')
        layout = QGridLayout()

        # Categories
        self.category_list = QListWidget()
        category_media = QListWidgetItem(getIcon('media-playback-start'),
                                         'Media', self.category_list)
        category_sync = QListWidgetItem(getIcon('view-refresh'), 'Sync',
                                        self.category_list)
        category_ui = QListWidgetItem(getIcon('window-new'), 'User Interface',
                                      self.category_list)
        category_theme = QListWidgetItem(getIcon('applications-graphics'),
                                         'Theme', self.category_list)
        self.category_list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.category_list.setCurrentRow(0)
        self.category_list.setMaximumWidth(
            self.category_list.sizeHintForColumn(0) + 15)
        self.category_list.setFocus()
        self.category_list.currentItemChanged.connect(self.s_switch_page)

        # Media tab
        page_media = QWidget()
        page_media_layout = QVBoxLayout()
        page_media_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Media settings
        g_media = QGroupBox('Media settings')
        g_media.setFlat(True)
        g_media_layout = QFormLayout()
        self.tracker_enabled = QCheckBox()
        self.tracker_enabled.toggled.connect(self.tracker_type_change)
        self.tracker_type_local = QRadioButton('Local')
        self.tracker_type_local.toggled.connect(self.tracker_type_change)
        self.tracker_type_plex = QRadioButton('Plex media server')
        self.tracker_type_plex.toggled.connect(self.tracker_type_change)
        self.tracker_interval = QSpinBox()
        self.tracker_interval.setRange(5, 1000)
        self.tracker_interval.setMaximumWidth(60)
        self.tracker_process = QLineEdit()
        self.tracker_update_wait = QSpinBox()
        self.tracker_update_wait.setRange(0, 1000)
        self.tracker_update_wait.setMaximumWidth(60)
        self.tracker_update_close = QCheckBox()
        self.tracker_update_prompt = QCheckBox()
        self.tracker_not_found_prompt = QCheckBox()

        g_media_layout.addRow('Enable tracker', self.tracker_enabled)
        g_media_layout.addRow(self.tracker_type_local)
        g_media_layout.addRow(self.tracker_type_plex)
        g_media_layout.addRow('Tracker interval (seconds)',
                              self.tracker_interval)
        g_media_layout.addRow('Process name (regex)', self.tracker_process)
        g_media_layout.addRow('Wait before updating (seconds)',
                              self.tracker_update_wait)
        g_media_layout.addRow('Wait until the player is closed',
                              self.tracker_update_close)
        g_media_layout.addRow('Ask before updating',
                              self.tracker_update_prompt)
        g_media_layout.addRow('Ask to add new shows',
                              self.tracker_not_found_prompt)

        g_media.setLayout(g_media_layout)

        # Group: Plex settings
        g_plex = QGroupBox('Plex Media Server')
        g_plex.setFlat(True)
        self.plex_host = QLineEdit()
        self.plex_port = QLineEdit()
        self.plex_user = QLineEdit()
        self.plex_passw = QLineEdit()
        self.plex_passw.setEchoMode(QLineEdit.Password)
        self.plex_obey_wait = QCheckBox()

        g_plex_layout = QGridLayout()
        g_plex_layout.addWidget(QLabel('Host and Port'), 0, 0, 1, 1)
        g_plex_layout.addWidget(self.plex_host, 0, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_port, 0, 2, 1, 2)
        g_plex_layout.addWidget(QLabel('Use "wait before updating" time'), 1,
                                0, 1, 1)
        g_plex_layout.addWidget(self.plex_obey_wait, 1, 2, 1, 1)
        g_plex_layout.addWidget(QLabel('myPlex login (claimed server)'), 2, 0,
                                1, 1)
        g_plex_layout.addWidget(self.plex_user, 2, 1, 1, 1)
        g_plex_layout.addWidget(self.plex_passw, 2, 2, 1, 2)

        g_plex.setLayout(g_plex_layout)

        # Group: Library
        g_playnext = QGroupBox('Library')
        g_playnext.setFlat(True)
        self.player = QLineEdit()
        self.player_browse = QPushButton('Browse...')
        self.player_browse.clicked.connect(self.s_player_browse)
        lbl_searchdirs = QLabel('Media directories')
        lbl_searchdirs.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs = QListWidget()
        self.searchdirs_add = QPushButton('Add...')
        self.searchdirs_add.clicked.connect(self.s_searchdirs_add)
        self.searchdirs_remove = QPushButton('Remove')
        self.searchdirs_remove.clicked.connect(self.s_searchdirs_remove)
        self.searchdirs_buttons = QVBoxLayout()
        self.searchdirs_buttons.setAlignment(QtCore.Qt.AlignTop)
        self.searchdirs_buttons.addWidget(self.searchdirs_add)
        self.searchdirs_buttons.addWidget(self.searchdirs_remove)
        self.searchdirs_buttons.addWidget(QSplitter())
        self.library_autoscan = QCheckBox()
        self.scan_whole_list = QCheckBox()
        self.library_full_path = QCheckBox()

        g_playnext_layout = QGridLayout()
        g_playnext_layout.addWidget(QLabel('Player'), 0, 0, 1, 1)
        g_playnext_layout.addWidget(self.player, 0, 1, 1, 1)
        g_playnext_layout.addWidget(self.player_browse, 0, 2, 1, 1)
        g_playnext_layout.addWidget(lbl_searchdirs, 1, 0, 1, 1)
        g_playnext_layout.addWidget(self.searchdirs, 1, 1, 1, 1)
        g_playnext_layout.addLayout(self.searchdirs_buttons, 1, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Rescan Library at startup'), 2, 0,
                                    1, 2)
        g_playnext_layout.addWidget(self.library_autoscan, 2, 2, 1, 1)
        g_playnext_layout.addWidget(QLabel('Scan through whole list'), 3, 0, 1,
                                    2)
        g_playnext_layout.addWidget(self.scan_whole_list, 3, 2, 1, 1)
        g_playnext_layout.addWidget(
            QLabel('Take subdirectory name into account'), 4, 0, 1, 2)
        g_playnext_layout.addWidget(self.library_full_path, 4, 2, 1, 1)

        g_playnext.setLayout(g_playnext_layout)

        # Media form
        page_media_layout.addWidget(g_media)
        page_media_layout.addWidget(g_plex)
        page_media_layout.addWidget(g_playnext)
        page_media.setLayout(page_media_layout)

        # Sync tab
        page_sync = QWidget()
        page_sync_layout = QVBoxLayout()
        page_sync_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Autoretrieve
        g_autoretrieve = QGroupBox('Autoretrieve')
        g_autoretrieve.setFlat(True)
        self.autoretrieve_off = QRadioButton('Disabled')
        self.autoretrieve_always = QRadioButton('Always at start')
        self.autoretrieve_days = QRadioButton('After n days')
        self.autoretrieve_days.toggled.connect(self.s_autoretrieve_days)
        self.autoretrieve_days_n = QSpinBox()
        self.autoretrieve_days_n.setRange(1, 100)
        g_autoretrieve_layout = QGridLayout()
        g_autoretrieve_layout.setColumnStretch(0, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_off, 0, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_always, 1, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days, 2, 0, 1, 1)
        g_autoretrieve_layout.addWidget(self.autoretrieve_days_n, 2, 1, 1, 1)
        g_autoretrieve.setLayout(g_autoretrieve_layout)

        # Group: Autosend
        g_autosend = QGroupBox('Autosend')
        g_autosend.setFlat(True)
        self.autosend_off = QRadioButton('Disabled')
        self.autosend_always = QRadioButton('Immediately after every change')
        self.autosend_minutes = QRadioButton('After n minutes')
        self.autosend_minutes.toggled.connect(self.s_autosend_minutes)
        self.autosend_minutes_n = QSpinBox()
        self.autosend_minutes_n.setRange(1, 1000)
        self.autosend_size = QRadioButton('After the queue reaches n items')
        self.autosend_size.toggled.connect(self.s_autosend_size)
        self.autosend_size_n = QSpinBox()
        self.autosend_size_n.setRange(2, 20)
        self.autosend_at_exit = QCheckBox('At exit')
        g_autosend_layout = QGridLayout()
        g_autosend_layout.setColumnStretch(0, 1)
        g_autosend_layout.addWidget(self.autosend_off, 0, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_always, 1, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes, 2, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_minutes_n, 2, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size, 3, 0, 1, 1)
        g_autosend_layout.addWidget(self.autosend_size_n, 3, 1, 1, 1)
        g_autosend_layout.addWidget(self.autosend_at_exit, 4, 0, 1, 1)
        g_autosend.setLayout(g_autosend_layout)

        # Group: Extra
        g_extra = QGroupBox('Additional options')
        g_extra.setFlat(True)
        self.auto_status_change = QCheckBox('Change status automatically')
        self.auto_status_change.toggled.connect(self.s_auto_status_change)
        self.auto_status_change_if_scored = QCheckBox(
            'Change status automatically only if scored')
        self.auto_date_change = QCheckBox(
            'Change start and finish dates automatically')
        g_extra_layout = QVBoxLayout()
        g_extra_layout.addWidget(self.auto_status_change)
        g_extra_layout.addWidget(self.auto_status_change_if_scored)
        g_extra_layout.addWidget(self.auto_date_change)
        g_extra.setLayout(g_extra_layout)

        # Sync layout
        page_sync_layout.addWidget(g_autoretrieve)
        page_sync_layout.addWidget(g_autosend)
        page_sync_layout.addWidget(g_extra)
        page_sync.setLayout(page_sync_layout)

        # UI tab
        page_ui = QWidget()
        page_ui_layout = QFormLayout()
        page_ui_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Icon
        g_icon = QGroupBox('Notification Icon')
        g_icon.setFlat(True)
        self.tray_icon = QCheckBox('Show tray icon')
        self.tray_icon.toggled.connect(self.s_tray_icon)
        self.close_to_tray = QCheckBox('Close to tray')
        self.start_in_tray = QCheckBox('Start minimized to tray')
        self.tray_api_icon = QCheckBox('Use API icon as tray icon')
        self.notifications = QCheckBox(
            'Show notification when tracker detects new media')
        g_icon_layout = QVBoxLayout()
        g_icon_layout.addWidget(self.tray_icon)
        g_icon_layout.addWidget(self.close_to_tray)
        g_icon_layout.addWidget(self.start_in_tray)
        g_icon_layout.addWidget(self.tray_api_icon)
        g_icon_layout.addWidget(self.notifications)
        g_icon.setLayout(g_icon_layout)

        # Group: Window
        g_window = QGroupBox('Window')
        g_window.setFlat(True)
        self.remember_geometry = QCheckBox('Remember window size and position')
        self.remember_columns = QCheckBox('Remember column layouts and widths')
        self.columns_per_api = QCheckBox(
            'Use different visible columns per API')
        g_window_layout = QVBoxLayout()
        g_window_layout.addWidget(self.remember_geometry)
        g_window_layout.addWidget(self.remember_columns)
        g_window_layout.addWidget(self.columns_per_api)
        g_window.setLayout(g_window_layout)

        # Group: Lists
        g_lists = QGroupBox('Lists')
        g_lists.setFlat(True)
        self.filter_bar_position = QComboBox()
        filter_bar_positions = [(FilterBar.PositionHidden, 'Hidden'),
                                (FilterBar.PositionAboveLists, 'Above lists'),
                                (FilterBar.PositionBelowLists, 'Below lists')]
        for (n, label) in filter_bar_positions:
            self.filter_bar_position.addItem(label, n)
        self.inline_edit = QCheckBox('Enable in-line editing')
        g_lists_layout = QFormLayout()
        g_lists_layout.addRow('Filter bar position:', self.filter_bar_position)
        g_lists_layout.addRow(self.inline_edit)
        g_lists.setLayout(g_lists_layout)

        # UI layout
        page_ui_layout.addWidget(g_icon)
        page_ui_layout.addWidget(g_window)
        page_ui_layout.addWidget(g_lists)
        page_ui.setLayout(page_ui_layout)

        # Theming tab
        page_theme = QWidget()
        page_theme_layout = QFormLayout()
        page_theme_layout.setAlignment(QtCore.Qt.AlignTop)

        # Group: Episode Bar
        g_ep_bar = QGroupBox('Episode Bar')
        g_ep_bar.setFlat(True)
        self.ep_bar_style = QComboBox()
        ep_bar_styles = [(ShowsTableDelegate.BarStyleBasic, 'Basic'),
                         (ShowsTableDelegate.BarStyle04, 'Trackma'),
                         (ShowsTableDelegate.BarStyleHybrid, 'Hybrid')]
        for (n, label) in ep_bar_styles:
            self.ep_bar_style.addItem(label, n)
        self.ep_bar_style.currentIndexChanged.connect(self.s_ep_bar_style)
        self.ep_bar_text = QCheckBox('Show text label')
        g_ep_bar_layout = QFormLayout()
        g_ep_bar_layout.addRow('Style:', self.ep_bar_style)
        g_ep_bar_layout.addRow(self.ep_bar_text)
        g_ep_bar.setLayout(g_ep_bar_layout)

        # Group: Colour scheme
        g_scheme = QGroupBox('Color Scheme')
        g_scheme.setFlat(True)
        col_tabs = [('rows', '&Row highlights'),
                    ('progress', '&Progress widget')]
        self.colors = {}
        self.colors['rows'] = [('is_playing', 'Playing'),
                               ('is_queued', 'Queued'),
                               ('new_episode', 'New Episode'),
                               ('is_airing', 'Airing'),
                               ('not_aired', 'Unaired')]
        self.colors['progress'] = [('progress_bg', 'Background'),
                                   ('progress_fg', 'Watched bar'),
                                   ('progress_sub_bg', 'Aired episodes'),
                                   ('progress_sub_fg', 'Stored episodes'),
                                   ('progress_complete', 'Complete')]
        self.color_buttons = []
        self.syscolor_buttons = []
        g_scheme_layout = QGridLayout()
        tw_scheme = QTabWidget()
        for (key, tab_title) in col_tabs:
            page = QFrame()
            page_layout = QGridLayout()
            col = 0
            # Generate widgets from the keys and values
            for (key, label) in self.colors[key]:
                self.color_buttons.append(QPushButton())
                # self.color_buttons[-1].setStyleSheet('background-color: ' + getColor(self.config['colors'][key]).name())
                self.color_buttons[-1].setFocusPolicy(QtCore.Qt.NoFocus)
                self.color_buttons[-1].clicked.connect(
                    self.s_color_picker(key, False))
                self.syscolor_buttons.append(QPushButton('System Colors'))
                self.syscolor_buttons[-1].clicked.connect(
                    self.s_color_picker(key, True))
                page_layout.addWidget(QLabel(label), col, 0, 1, 1)
                page_layout.addWidget(self.color_buttons[-1], col, 1, 1, 1)
                page_layout.addWidget(self.syscolor_buttons[-1], col, 2, 1, 1)
                col += 1
            page.setLayout(page_layout)
            tw_scheme.addTab(page, tab_title)
        g_scheme_layout.addWidget(tw_scheme)
        g_scheme.setLayout(g_scheme_layout)

        # UI layout
        page_theme_layout.addWidget(g_ep_bar)
        page_theme_layout.addWidget(g_scheme)
        page_theme.setLayout(page_theme_layout)

        # Content
        self.contents = QStackedWidget()
        self.contents.addWidget(page_media)
        self.contents.addWidget(page_sync)
        self.contents.addWidget(page_ui)
        self.contents.addWidget(page_theme)
        if pyqt_version is not 5:
            self.contents.layout().setMargin(0)

        # Bottom buttons
        bottombox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Apply
                                     | QDialogButtonBox.Cancel)
        bottombox.accepted.connect(self.s_save)
        bottombox.button(QDialogButtonBox.Apply).clicked.connect(self._save)
        bottombox.rejected.connect(self.reject)

        # Main layout finish
        layout.addWidget(self.category_list, 0, 0, 1, 1)
        layout.addWidget(self.contents, 0, 1, 1, 1)
        layout.addWidget(bottombox, 1, 0, 1, 2)
        layout.setColumnStretch(1, 1)

        self._load()
        self.update_colors()

        self.setLayout(layout)

    def _add_dir(self, path):
        self.searchdirs.addItem(path)

    def _load(self):
        engine = self.worker.engine
        tracker_type = engine.get_config('tracker_type')
        autoretrieve = engine.get_config('autoretrieve')
        autosend = engine.get_config('autosend')

        self.tracker_enabled.setChecked(engine.get_config('tracker_enabled'))
        self.tracker_interval.setValue(engine.get_config('tracker_interval'))
        self.tracker_process.setText(engine.get_config('tracker_process'))
        self.tracker_update_wait.setValue(
            engine.get_config('tracker_update_wait_s'))
        self.tracker_update_close.setChecked(
            engine.get_config('tracker_update_close'))
        self.tracker_update_prompt.setChecked(
            engine.get_config('tracker_update_prompt'))
        self.tracker_not_found_prompt.setChecked(
            engine.get_config('tracker_not_found_prompt'))

        self.player.setText(engine.get_config('player'))
        self.library_autoscan.setChecked(engine.get_config('library_autoscan'))
        self.scan_whole_list.setChecked(engine.get_config('scan_whole_list'))
        self.library_full_path.setChecked(
            engine.get_config('library_full_path'))
        self.plex_host.setText(engine.get_config('plex_host'))
        self.plex_port.setText(engine.get_config('plex_port'))
        self.plex_obey_wait.setChecked(
            engine.get_config('plex_obey_update_wait_s'))
        self.plex_user.setText(engine.get_config('plex_user'))
        self.plex_passw.setText(engine.get_config('plex_passwd'))

        for path in engine.get_config('searchdir'):
            self._add_dir(path)

        if tracker_type == 'local':
            self.tracker_type_local.setChecked(True)
            self.plex_host.setEnabled(False)
            self.plex_port.setEnabled(False)
            self.plex_obey_wait.setEnabled(False)
        elif tracker_type == 'plex':
            self.tracker_type_plex.setChecked(True)
            self.tracker_process.setEnabled(False)

        if autoretrieve == 'always':
            self.autoretrieve_always.setChecked(True)
        elif autoretrieve == 'days':
            self.autoretrieve_days.setChecked(True)
        else:
            self.autoretrieve_off.setChecked(True)

        self.autoretrieve_days_n.setValue(
            engine.get_config('autoretrieve_days'))

        if autosend == 'always':
            self.autosend_always.setChecked(True)
        elif autosend in ('minutes', 'hours'):
            self.autosend_minutes.setChecked(True)
        elif autosend == 'size':
            self.autosend_size.setChecked(True)
        else:
            self.autosend_off.setChecked(True)

        self.autosend_minutes_n.setValue(engine.get_config('autosend_minutes'))
        self.autosend_size_n.setValue(engine.get_config('autosend_size'))

        self.autosend_at_exit.setChecked(engine.get_config('autosend_at_exit'))
        self.auto_status_change.setChecked(
            engine.get_config('auto_status_change'))
        self.auto_status_change_if_scored.setChecked(
            engine.get_config('auto_status_change_if_scored'))
        self.auto_date_change.setChecked(engine.get_config('auto_date_change'))

        self.tray_icon.setChecked(self.config['show_tray'])
        self.close_to_tray.setChecked(self.config['close_to_tray'])
        self.start_in_tray.setChecked(self.config['start_in_tray'])
        self.tray_api_icon.setChecked(self.config['tray_api_icon'])
        self.notifications.setChecked(self.config['notifications'])
        self.remember_geometry.setChecked(self.config['remember_geometry'])
        self.remember_columns.setChecked(self.config['remember_columns'])
        self.columns_per_api.setChecked(self.config['columns_per_api'])
        self.filter_bar_position.setCurrentIndex(
            self.filter_bar_position.findData(
                self.config['filter_bar_position']))
        self.inline_edit.setChecked(self.config['inline_edit'])

        self.ep_bar_style.setCurrentIndex(
            self.ep_bar_style.findData(self.config['episodebar_style']))
        self.ep_bar_text.setChecked(self.config['episodebar_text'])

        self.autoretrieve_days_n.setEnabled(self.autoretrieve_days.isChecked())
        self.autosend_minutes_n.setEnabled(self.autosend_minutes.isChecked())
        self.autosend_size_n.setEnabled(self.autosend_size.isChecked())
        self.close_to_tray.setEnabled(self.tray_icon.isChecked())
        self.start_in_tray.setEnabled(self.tray_icon.isChecked())
        self.notifications.setEnabled(self.tray_icon.isChecked())

        self.color_values = self.config['colors'].copy()

    def _save(self):
        engine = self.worker.engine

        engine.set_config('tracker_enabled', self.tracker_enabled.isChecked())
        engine.set_config('tracker_interval', self.tracker_interval.value())
        engine.set_config('tracker_process', str(self.tracker_process.text()))
        engine.set_config('tracker_update_wait_s',
                          self.tracker_update_wait.value())
        engine.set_config('tracker_update_close',
                          self.tracker_update_close.isChecked())
        engine.set_config('tracker_update_prompt',
                          self.tracker_update_prompt.isChecked())
        engine.set_config('tracker_not_found_prompt',
                          self.tracker_not_found_prompt.isChecked())

        engine.set_config('player', self.player.text())
        engine.set_config('library_autoscan',
                          self.library_autoscan.isChecked())
        engine.set_config('scan_whole_list', self.scan_whole_list.isChecked())
        engine.set_config('library_full_path',
                          self.library_full_path.isChecked())
        engine.set_config('plex_host', self.plex_host.text())
        engine.set_config('plex_port', self.plex_port.text())
        engine.set_config('plex_obey_update_wait_s',
                          self.plex_obey_wait.isChecked())
        engine.set_config('plex_user', self.plex_user.text())
        engine.set_config('plex_passwd', self.plex_passw.text())

        engine.set_config('searchdir', [
            self.searchdirs.item(i).text()
            for i in range(self.searchdirs.count())
        ])

        if self.tracker_type_local.isChecked():
            engine.set_config('tracker_type', 'local')
        elif self.tracker_type_plex.isChecked():
            engine.set_config('tracker_type', 'plex')

        if self.autoretrieve_always.isChecked():
            engine.set_config('autoretrieve', 'always')
        elif self.autoretrieve_days.isChecked():
            engine.set_config('autoretrieve', 'days')
        else:
            engine.set_config('autoretrieve', 'off')

        engine.set_config('autoretrieve_days',
                          self.autoretrieve_days_n.value())

        if self.autosend_always.isChecked():
            engine.set_config('autosend', 'always')
        elif self.autosend_minutes.isChecked():
            engine.set_config('autosend', 'minutes')
        elif self.autosend_size.isChecked():
            engine.set_config('autosend', 'size')
        else:
            engine.set_config('autosend', 'off')

        engine.set_config('autosend_minutes', self.autosend_minutes_n.value())
        engine.set_config('autosend_size', self.autosend_size_n.value())

        engine.set_config('autosend_at_exit',
                          self.autosend_at_exit.isChecked())
        engine.set_config('auto_status_change',
                          self.auto_status_change.isChecked())
        engine.set_config('auto_status_change_if_scored',
                          self.auto_status_change_if_scored.isChecked())
        engine.set_config('auto_date_change',
                          self.auto_date_change.isChecked())

        engine.save_config()

        self.config['show_tray'] = self.tray_icon.isChecked()
        self.config['close_to_tray'] = self.close_to_tray.isChecked()
        self.config['start_in_tray'] = self.start_in_tray.isChecked()
        self.config['tray_api_icon'] = self.tray_api_icon.isChecked()
        self.config['notifications'] = self.notifications.isChecked()
        self.config['remember_geometry'] = self.remember_geometry.isChecked()
        self.config['remember_columns'] = self.remember_columns.isChecked()
        self.config['columns_per_api'] = self.columns_per_api.isChecked()
        self.config['filter_bar_position'] = self.filter_bar_position.itemData(
            self.filter_bar_position.currentIndex())
        self.config['inline_edit'] = self.inline_edit.isChecked()

        self.config['episodebar_style'] = self.ep_bar_style.itemData(
            self.ep_bar_style.currentIndex())
        self.config['episodebar_text'] = self.ep_bar_text.isChecked()

        self.config['colors'] = self.color_values

        utils.save_config(self.config, self.configfile)

        self.saved.emit()

    def s_save(self):
        self._save()
        self.accept()

    def tracker_type_change(self, checked):
        if self.tracker_enabled.isChecked():
            self.tracker_interval.setEnabled(True)
            self.tracker_update_wait.setEnabled(True)
            self.tracker_type_local.setEnabled(True)
            self.tracker_type_plex.setEnabled(True)
            if self.tracker_type_local.isChecked():
                self.tracker_process.setEnabled(True)
                self.plex_host.setEnabled(False)
                self.plex_port.setEnabled(False)
                self.plex_obey_wait.setEnabled(False)
            elif self.tracker_type_plex.isChecked():
                self.plex_host.setEnabled(True)
                self.plex_port.setEnabled(True)
                self.plex_obey_wait.setEnabled(True)
                self.tracker_process.setEnabled(False)
        else:
            self.tracker_type_local.setEnabled(False)
            self.tracker_type_plex.setEnabled(False)
            self.plex_host.setEnabled(False)
            self.plex_port.setEnabled(False)
            self.plex_obey_wait.setEnabled(False)
            self.tracker_process.setEnabled(False)
            self.tracker_interval.setEnabled(False)
            self.tracker_update_wait.setEnabled(False)

    def s_autoretrieve_days(self, checked):
        self.autoretrieve_days_n.setEnabled(checked)

    def s_autosend_minutes(self, checked):
        self.autosend_minutes_n.setEnabled(checked)

    def s_autosend_size(self, checked):
        self.autosend_size_n.setEnabled(checked)

    def s_tray_icon(self, checked):
        self.close_to_tray.setEnabled(checked)
        self.start_in_tray.setEnabled(checked)
        self.tray_api_icon.setEnabled(checked)
        self.notifications.setEnabled(checked)

    def s_ep_bar_style(self, index):
        if self.ep_bar_style.itemData(index) == ShowsTableDelegate.BarStyle04:
            self.ep_bar_text.setEnabled(False)
        else:
            self.ep_bar_text.setEnabled(True)

    def s_auto_status_change(self, checked):
        self.auto_status_change_if_scored.setEnabled(checked)

    def s_player_browse(self):
        if pyqt_version is 5:
            self.player.setText(
                QFileDialog.getOpenFileName(
                    caption='Choose player executable')[0])
        else:
            self.player.setText(
                QFileDialog.getOpenFileName(
                    caption='Choose player executable'))

    def s_searchdirs_add(self):
        self._add_dir(
            QFileDialog.getExistingDirectory(caption='Choose media directory'))

    def s_searchdirs_remove(self):
        row = self.searchdirs.currentRow()
        if row != -1:
            self.searchdirs.takeItem(row)

    def s_switch_page(self, new, old):
        if not new:
            new = old

        self.contents.setCurrentIndex(self.category_list.row(new))

    def s_color_picker(self, key, system):
        return lambda: self.color_picker(key, system)

    def color_picker(self, key, system):
        if system is True:
            current = self.color_values[key]
            result = ThemedColorPicker.do()
            if result is not None and result is not current:
                self.color_values[key] = result
                self.update_colors()
        else:
            current = getColor(self.color_values[key])
            result = QColorDialog.getColor(current)
            if result.isValid() and result is not current:
                self.color_values[key] = str(result.name())
                self.update_colors()

    def update_colors(self):
        for ((key, label),
             color) in zip(self.colors['rows'] + self.colors['progress'],
                           self.color_buttons):
            color.setStyleSheet('background-color: ' +
                                getColor(self.color_values[key]).name())
Ejemplo n.º 12
0
class ConditionDialog(QDialog):
    def __init__(self, expr_pool):
        super().__init__()
        self.expr_pool = expr_pool
        self.stack = QStackedLayout()
        self.stack.addWidget(self.build_first_page())
        self.stack.addWidget(self.build_second_page())
        self.stack.addWidget(self.build_third_page())
        self.setLayout(self.stack)
        self.setWindowTitle('Add condition')

    def build_first_page(self):
        first_page = QWidget()
        expression_type_box = QGroupBox('Select condition type')
        self.simple_button = QRadioButton(
            'Simple condition\nUse an expression, a comparator and a threshold value'
            'to create a new condition. Example: B > 0')
        self.simple_button.setChecked(True)
        self.and_or_button = QRadioButton(
            'AND/OR condition\nUse two existing conditions and AND/OR operators'
            'to create a new condition. Example: (B > 0) AND (B < 100)')
        self.and_or_button.setEnabled(self.expr_pool.nb_conditions() > 1)
        vlayout = QVBoxLayout()
        vlayout.addWidget(self.simple_button)
        vlayout.addWidget(self.and_or_button)
        expression_type_box.setLayout(vlayout)
        next_button = QPushButton('Next')
        cancel_button = QPushButton('Cancel')
        for bt in (next_button, cancel_button):
            bt.setMaximumWidth(200)
            bt.setFixedHeight(30)
        hlayout = QHBoxLayout()
        hlayout.addStretch()
        hlayout.addWidget(next_button)
        hlayout.addWidget(cancel_button)
        vlayout = QVBoxLayout()
        vlayout.addWidget(expression_type_box)
        vlayout.addStretch()
        vlayout.addLayout(hlayout, Qt.AlignRight)
        first_page.setLayout(vlayout)

        next_button.clicked.connect(self.turn_page)
        cancel_button.clicked.connect(self.reject)
        return first_page

    def build_second_page(self):
        second_page = QWidget()
        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        buttons.accepted.connect(self.check)
        buttons.rejected.connect(self.reject)

        self.expression_box = QComboBox()
        self.expression_box.setFixedHeight(30)
        self.expression_box.setMinimumWidth(150)
        self.expression_box.setMaximumWidth(250)

        for i in range(1, self.expr_pool.nb_expressions() + 1):
            expr = self.expr_pool.expressions()[i]
            if expr.masked:
                continue
            self.expression_box.addItem(str(expr))

        self.comparator_box = QComboBox()
        for comparator in ['>', '<', '>=', '<=']:
            self.comparator_box.addItem(comparator)
        self.comparator_box.setFixedSize(50, 30)

        self.threshold_box = QLineEdit()
        self.threshold_box.setFixedSize(150, 30)

        vlayout = QVBoxLayout()
        glayout = QGridLayout()
        glayout.addWidget(QLabel('Expression'), 1, 1, Qt.AlignHCenter)
        glayout.addWidget(QLabel('Comparator'), 1, 2, Qt.AlignHCenter)
        glayout.addWidget(QLabel('Threshold'), 1, 3, Qt.AlignHCenter)
        glayout.addWidget(self.expression_box, 2, 1)
        glayout.addWidget(self.comparator_box, 2, 2)
        glayout.addWidget(self.threshold_box, 2, 3)
        glayout.setVerticalSpacing(12)
        glayout.setRowStretch(0, 1)
        vlayout.addLayout(glayout)
        vlayout.addStretch()
        vlayout.addWidget(buttons)
        second_page.setLayout(vlayout)
        return second_page

    def build_third_page(self):
        third_page = QWidget()
        if not self.and_or_button.isEnabled():
            return third_page
        self.and_or_box = QComboBox()
        self.and_or_box.addItem('AND')
        self.and_or_box.addItem('OR')
        self.first_box = QComboBox()
        self.second_box = QComboBox()
        ok_button = QPushButton('OK')
        cancel_button = QPushButton('Cancel')
        for bt in (ok_button, cancel_button):
            bt.setMaximumWidth(200)
            bt.setFixedHeight(30)
        for box in (self.first_box, self.second_box):
            box.setFixedHeight(30)
            box.setMaximumWidth(250)
        self.and_or_box.setFixedSize(100, 30)
        for i in range(1, self.expr_pool.nb_conditions() + 1):
            condition = str(self.expr_pool.conditions()[i])
            self.first_box.addItem(condition)
            self.second_box.addItem(condition)
        vlayout = QVBoxLayout()
        glayout = QGridLayout()
        glayout.addWidget(QLabel('Condition 1'), 1, 1, Qt.AlignHCenter)
        glayout.addWidget(QLabel('Operator'), 1, 2, Qt.AlignHCenter)
        glayout.addWidget(QLabel('Condition 2'), 1, 3, Qt.AlignHCenter)
        glayout.addWidget(self.first_box, 2, 1)
        glayout.addWidget(self.and_or_box, 2, 2)
        glayout.addWidget(self.second_box, 2, 3)
        glayout.setVerticalSpacing(12)
        glayout.setRowStretch(0, 1)
        vlayout.addLayout(glayout)
        vlayout.addStretch()
        hlayout = QHBoxLayout()
        hlayout.addStretch()
        hlayout.addWidget(ok_button)
        hlayout.addWidget(cancel_button)
        vlayout.addLayout(hlayout)
        third_page.setLayout(vlayout)

        ok_button.clicked.connect(self.check)
        cancel_button.clicked.connect(self.reject)
        return third_page

    def turn_page(self):
        if self.simple_button.isChecked():
            self.stack.setCurrentIndex(1)
        else:
            self.stack.setCurrentIndex(2)

    def check(self):
        current_page = self.stack.currentIndex()
        if current_page == 1:
            threshold = self.threshold_box.text()
            try:
                threshold = float(threshold)
            except ValueError:
                QMessageBox.critical(None, 'Error',
                                     'The threshold is not a number!',
                                     QMessageBox.Ok)
                return
            expr_text = self.expression_box.currentText()
            self.expr_pool.add_condition(
                self.expr_pool.get_expression(expr_text),
                self.comparator_box.currentText(), threshold)
        else:
            is_and = self.and_or_box.currentText() == 'AND'
            first_text, second_text = self.first_box.currentText(
            ), self.second_box.currentText()
            if first_text == second_text:
                QMessageBox.critical(
                    None, 'Error', 'The two conditions cannot be identical!',
                    QMessageBox.Ok)
                return
            success_code = self.expr_pool.add_and_or_condition(
                self.expr_pool.get_condition(first_text),
                self.expr_pool.get_condition(second_text), is_and)
            if success_code == -2:
                QMessageBox.critical(
                    None, 'Error',
                    'One condition can only use only one polygonal mask!',
                    QMessageBox.Ok)
                return
        self.accept()
Ejemplo n.º 13
0
class SingleTab(QScrollArea):
    def __init__(self, Win):
        super(SingleTab, self).__init__()
        self.Win = Win
        self.singleData = Data.Spectrum()

        #Developer parameter
        self.core_num = int(os.cpu_count() / 2)
        self.solver_max_iteration_step = 30
        self.solver_error = 1e-7
        self.DevWin = DevSettingDialog(self, self.core_num,
                                       self.solver_max_iteration_step,
                                       self.solver_error)

        self.box = QVBoxLayout()
        self.box.setSizeConstraint(QLayout.SetFixedSize)

        #general operation
        self.groupbox_general = QGroupBox("General Operation")
        self.groupbox_general.setFixedWidth(200)
        self.setvalue = QDoubleSpinBox()
        self.setvalue.setDecimals(6)
        self.setvalue.setRange(-10000, 10000)
        self.setButton = QPushButton("Set")
        self.setButton.setFixedWidth(50)
        self.setButton.clicked.connect(self.OnRemoveNaN)
        hbox_nan = QHBoxLayout()
        hbox_nan.addWidget(self.setvalue)
        hbox_nan.addWidget(self.setButton)
        vbox_general = QVBoxLayout()
        vbox_general.addWidget(QLabel("Remove NaN"))
        vbox_general.addLayout(hbox_nan)
        self.groupbox_general.setLayout(vbox_general)
        self.box.addWidget(self.groupbox_general)

        #general operation: Offset
        self.groupbox_offset = QGroupBox("General-Offset")
        self.groupbox_offset.setFixedWidth(200)
        self.xdecreaseButton = QPushButton("<")
        self.xdecreaseButton.setFixedSize(25, 25)
        self.xstep = QDoubleSpinBox()
        self.xstep.setDecimals(6)
        self.xstep.setRange(0, 10000)
        self.xincreaseButton = QPushButton(">")
        self.xincreaseButton.setFixedSize(25, 25)
        hbox_x = QHBoxLayout()
        hbox_x.addWidget(self.xdecreaseButton)
        hbox_x.addWidget(self.xstep)
        hbox_x.addWidget(self.xincreaseButton)
        self.ydecreaseButton = QPushButton("<")
        self.ydecreaseButton.setFixedSize(25, 25)
        self.ystep = QDoubleSpinBox()
        self.ystep.setDecimals(6)
        self.ystep.setRange(0, 10000)
        self.yincreaseButton = QPushButton(">")
        self.yincreaseButton.setFixedSize(25, 25)
        hbox_y = QHBoxLayout()
        hbox_y.addWidget(self.ydecreaseButton)
        hbox_y.addWidget(self.ystep)
        hbox_y.addWidget(self.yincreaseButton)
        self.zdecreaseButton = QPushButton("<")
        self.zdecreaseButton.setFixedSize(25, 25)
        self.zstep = QDoubleSpinBox()
        self.zstep.setDecimals(6)
        self.zstep.setRange(0, 10000)
        self.zincreaseButton = QPushButton(">")
        self.zincreaseButton.setFixedSize(25, 25)
        hbox_z = QHBoxLayout()
        hbox_z.addWidget(self.zdecreaseButton)
        hbox_z.addWidget(self.zstep)
        hbox_z.addWidget(self.zincreaseButton)
        self.tdecreaseButton = QPushButton("<")
        self.tdecreaseButton.setFixedSize(25, 25)
        self.tstep = QDoubleSpinBox()
        self.tstep.setDecimals(6)
        self.tstep.setRange(0, 10000)
        self.tincreaseButton = QPushButton(">")
        self.tincreaseButton.setFixedSize(25, 25)
        hbox_t = QHBoxLayout()
        hbox_t.addWidget(self.tdecreaseButton)
        hbox_t.addWidget(self.tstep)
        hbox_t.addWidget(self.tincreaseButton)
        self.xdecreaseButton.clicked.connect(self.offset)
        self.xincreaseButton.clicked.connect(self.offset)
        self.ydecreaseButton.clicked.connect(self.offset)
        self.yincreaseButton.clicked.connect(self.offset)
        self.zdecreaseButton.clicked.connect(self.offset)
        self.zincreaseButton.clicked.connect(self.offset)
        self.tdecreaseButton.clicked.connect(self.offset)
        self.tincreaseButton.clicked.connect(self.offset)
        vbox_offset = QVBoxLayout()
        vbox_offset.addWidget(QLabel("X-Axis Offset"))
        vbox_offset.addLayout(hbox_x)
        vbox_offset.addWidget(QLabel("Y-Axis Offset"))
        vbox_offset.addLayout(hbox_y)
        vbox_offset.addWidget(QLabel("Z-Axis Offset"))
        vbox_offset.addLayout(hbox_z)
        vbox_offset.addWidget(QLabel("T-Axis Offset"))
        vbox_offset.addLayout(hbox_t)
        self.groupbox_offset.setLayout(vbox_offset)
        self.box.addWidget(self.groupbox_offset)

        #general operation: Range Selection
        self.groupbox_range = QGroupBox("General-Range Selection")
        self.groupbox_range.setFixedWidth(200)
        self.xlow = QDoubleSpinBox()
        self.xlow.setDecimals(6)
        self.xlow.setRange(0, 1)
        self.xlow.setKeyboardTracking(False)
        self.xlow.valueChanged.connect(self.rangeValidator)
        self.xhigh = QDoubleSpinBox()
        self.xhigh.setDecimals(6)
        self.xhigh.setRange(0, 1)
        self.xhigh.setValue(1)
        self.xhigh.setKeyboardTracking(False)
        self.xhigh.valueChanged.connect(self.rangeValidator)
        self.ylow = QDoubleSpinBox()
        self.ylow.setDecimals(6)
        self.ylow.setRange(0, 1)
        self.ylow.setKeyboardTracking(False)
        self.ylow.valueChanged.connect(self.rangeValidator)
        self.yhigh = QDoubleSpinBox()
        self.yhigh.setDecimals(6)
        self.yhigh.setRange(0, 1)
        self.yhigh.setValue(1)
        self.yhigh.setKeyboardTracking(False)
        self.yhigh.valueChanged.connect(self.rangeValidator)
        self.zlow = QDoubleSpinBox()
        self.zlow.setDecimals(6)
        self.zlow.setRange(0, 1)
        self.zlow.setKeyboardTracking(False)
        self.zlow.valueChanged.connect(self.rangeValidator)
        self.zhigh = QDoubleSpinBox()
        self.zhigh.setDecimals(6)
        self.zhigh.setRange(0, 1)
        self.zhigh.setValue(1)
        self.zhigh.setKeyboardTracking(False)
        self.zhigh.valueChanged.connect(self.rangeValidator)
        self.tlow = QDoubleSpinBox()
        self.tlow.setDecimals(6)
        self.tlow.setRange(0, 1)
        self.tlow.setKeyboardTracking(False)
        self.tlow.valueChanged.connect(self.rangeValidator)
        self.thigh = QDoubleSpinBox()
        self.thigh.setDecimals(6)
        self.thigh.setRange(0, 1)
        self.thigh.setValue(1)
        self.thigh.setKeyboardTracking(False)
        self.thigh.valueChanged.connect(self.rangeValidator)
        self.rangeReset = QPushButton("Reset")
        self.rangeReset.clicked.connect(self.updateRange)
        label_range = QHBoxLayout()
        label_range.addStretch(4)
        label_range.addWidget(QLabel("Low"))
        label_range.addStretch(4)
        label_range.addWidget(QLabel("High"))
        label_range.addStretch(3)
        hbox_xrange = QHBoxLayout()
        hbox_xrange.addWidget(QLabel("X:"))
        hbox_xrange.addWidget(self.xlow)
        hbox_xrange.addWidget(self.xhigh)
        hbox_yrange = QHBoxLayout()
        hbox_yrange.addWidget(QLabel("Y:"))
        hbox_yrange.addWidget(self.ylow)
        hbox_yrange.addWidget(self.yhigh)
        hbox_zrange = QHBoxLayout()
        hbox_zrange.addWidget(QLabel("Z:"))
        hbox_zrange.addWidget(self.zlow)
        hbox_zrange.addWidget(self.zhigh)
        hbox_trange = QHBoxLayout()
        hbox_trange.addWidget(QLabel("T:"))
        hbox_trange.addWidget(self.tlow)
        hbox_trange.addWidget(self.thigh)
        vbox_range = QVBoxLayout()
        vbox_range.addLayout(label_range)
        vbox_range.addLayout(hbox_xrange)
        vbox_range.addLayout(hbox_yrange)
        vbox_range.addLayout(hbox_zrange)
        vbox_range.addLayout(hbox_trange)
        vbox_range.addWidget(self.rangeReset)
        self.groupbox_range.setLayout(vbox_range)
        self.box.addWidget(self.groupbox_range)

        #general merge
        self.groupbox_merge = QGroupBox("General-Merge")
        self.groupbox_merge.setFixedWidth(200)
        self.xnum = QSpinBox()
        self.xnum.setRange(1, 10000)
        self.ynum = QSpinBox()
        self.ynum.setRange(1, 10000)
        self.znum = QSpinBox()
        self.znum.setRange(1, 10000)
        self.tnum = QSpinBox()
        self.tnum.setRange(1, 10000)
        self.merge = QPushButton("Merge")
        self.merge.clicked.connect(self.OnMerge)
        hbox_xy = QHBoxLayout()
        hbox_xy.addWidget(QLabel("X:"))
        hbox_xy.addWidget(self.xnum)
        hbox_xy.addWidget(QLabel("Y:"))
        hbox_xy.addWidget(self.ynum)
        hbox_zt = QHBoxLayout()
        hbox_zt.addWidget(QLabel("Z:"))
        hbox_zt.addWidget(self.znum)
        hbox_zt.addWidget(QLabel("T:"))
        hbox_zt.addWidget(self.tnum)
        vbox_merge = QVBoxLayout()
        vbox_merge.addLayout(hbox_xy)
        vbox_merge.addLayout(hbox_zt)
        vbox_merge.addWidget(self.merge)
        self.groupbox_merge.setLayout(vbox_merge)
        self.box.addWidget(self.groupbox_merge)

        #general detector correction
        self.groupbox_detector = QGroupBox("General-Detector Correction")
        self.groupbox_detector.setFixedWidth(200)
        self.correctx = QPushButton("Balance X Direction")
        self.correctx.setToolTip("Please set proper <b>Y</b> range.")
        self.correcty = QPushButton("Balance Y Direction")
        self.correcty.setToolTip("Please set proper <b>X</b> range.")
        vbox_detector = QVBoxLayout()
        vbox_detector.addWidget(self.correctx)
        vbox_detector.addWidget(self.correcty)
        self.groupbox_detector.setLayout(vbox_detector)
        self.box.addWidget(self.groupbox_detector)

        #2D general operation
        self.groupbox_2D_general = QGroupBox("2D-General Operation")
        self.groupbox_2D_general.setFixedWidth(200)
        self.transposeButton = QPushButton("Transpose")
        self.transposeButton.clicked.connect(self.transpose2D)
        self.mirrorXButton = QPushButton("Mirror X")
        self.mirrorYButton = QPushButton("Mirror Y")
        self.mirrorXButton.clicked.connect(self.mirror2D)
        self.mirrorYButton.clicked.connect(self.mirror2D)
        self.normalXDCButton = QPushButton("Normal XDC")
        self.normalYDCButton = QPushButton("Normal YDC")
        self.normalXDCButton.clicked.connect(self.normal2D)
        self.normalYDCButton.clicked.connect(self.normal2D)
        self.crop2D = QPushButton("Crop")
        self.crop2D.clicked.connect(self.OnCropSpec)
        self.aspect = QCheckBox("Equal Proportion")
        self.aspect.stateChanged.connect(self.changeAspect2D)
        hbox_2D_mirror = QHBoxLayout()
        hbox_2D_mirror.addWidget(self.mirrorXButton)
        hbox_2D_mirror.addWidget(self.mirrorYButton)
        hbox_2D_normal = QHBoxLayout()
        hbox_2D_normal.addWidget(self.normalXDCButton)
        hbox_2D_normal.addWidget(self.normalYDCButton)
        hbox_2D_aspect = QHBoxLayout()
        hbox_2D_aspect.addStretch(1)
        hbox_2D_aspect.addWidget(self.aspect)
        hbox_2D_aspect.addStretch(1)
        vbox_2D_general = QVBoxLayout()
        vbox_2D_general.addWidget(self.transposeButton)
        vbox_2D_general.addLayout(hbox_2D_mirror)
        vbox_2D_general.addLayout(hbox_2D_normal)
        vbox_2D_general.addWidget(self.crop2D)
        vbox_2D_general.addLayout(hbox_2D_aspect)
        self.groupbox_2D_general.setLayout(vbox_2D_general)
        self.box.addWidget(self.groupbox_2D_general)

        #2D kspace conversion
        self.groupbox_2D_kspace = QGroupBox("2D-kspace Conversion")
        self.groupbox_2D_kspace.setFixedWidth(200)
        energyAxis_label = QLabel("Energy Axis:")
        energyAxis_label.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.xaxis_2D_energy = QRadioButton("X")
        self.yaxis_2D_energy = QRadioButton("Y")
        self.xaxis_2D_energy.setChecked(True)
        hbox_2D_EA = QHBoxLayout()
        hbox_2D_EA.addWidget(energyAxis_label)
        hbox_2D_EA.addWidget(self.xaxis_2D_energy, 1)
        hbox_2D_EA.addWidget(self.yaxis_2D_energy, 1)
        self.kspaceButton = QPushButton("To k-space")
        self.kspaceButton.clicked.connect(self.Tokspace2D)
        vbox_2D_kspace = QVBoxLayout()
        vbox_2D_kspace.addLayout(hbox_2D_EA)
        vbox_2D_kspace.addWidget(self.kspaceButton)
        self.groupbox_2D_kspace.setLayout(vbox_2D_kspace)
        self.box.addWidget(self.groupbox_2D_kspace)

        #3D general operation
        self.groupbox_3D_general = QGroupBox("3D-General Operation")
        self.groupbox_3D_general.setFixedWidth(200)
        self.transposeButton3D = QPushButton("Transpose")
        self.transposeButton3D.clicked.connect(self.transpose3D)
        self.YZXButton3D = QPushButton("X -> Z")
        self.ZXYButton3D = QPushButton("Y -> Z")
        self.YZXButton3D.clicked.connect(self.changeZAxis)
        self.ZXYButton3D.clicked.connect(self.changeZAxis)
        self.mirrorYButton3D = QPushButton("Mirror Y")
        self.mirrorXButton3D = QPushButton("Mirror X")
        self.mirrorYButton3D = QPushButton("Mirror Y")
        self.mirrorXButton3D.clicked.connect(self.mirror3D)
        self.mirrorYButton3D.clicked.connect(self.mirror3D)
        self.crop3D = QPushButton("Crop")
        self.crop3D.clicked.connect(self.OnCropSpec)
        self.aspect3D = QCheckBox("Equal Proportion")
        self.aspect3D.stateChanged.connect(self.changeAspect3D)
        hbox_3D_zaxis = QHBoxLayout()
        hbox_3D_zaxis.addWidget(self.YZXButton3D)
        hbox_3D_zaxis.addWidget(self.ZXYButton3D)
        hbox_3D_mirror = QHBoxLayout()
        hbox_3D_mirror.addWidget(self.mirrorXButton3D)
        hbox_3D_mirror.addWidget(self.mirrorYButton3D)
        hbox_3D_aspect = QHBoxLayout()
        hbox_3D_aspect.addStretch(1)
        hbox_3D_aspect.addWidget(self.aspect3D)
        hbox_3D_aspect.addStretch(1)
        vbox_3D_general = QVBoxLayout()
        vbox_3D_general.addWidget(self.transposeButton3D)
        vbox_3D_general.addLayout(hbox_3D_zaxis)
        vbox_3D_general.addLayout(hbox_3D_mirror)
        vbox_3D_general.addWidget(self.crop3D)
        vbox_3D_general.addLayout(hbox_3D_aspect)
        self.groupbox_3D_general.setLayout(vbox_3D_general)
        self.box.addWidget(self.groupbox_3D_general)

        #3D kspace conversion
        self.groupbox_3D_kspace = QGroupBox("3D-kspace Conversion")
        self.groupbox_3D_kspace.setFixedWidth(200)
        self.slit_h_3D = QRadioButton("Horizontal")
        self.slit_v_3D = QRadioButton("Vertical")
        self.slit_h_3D.setChecked(True)
        hbox_3D_slit = QHBoxLayout()
        hbox_3D_slit.addWidget(self.slit_h_3D, 1)
        hbox_3D_slit.addWidget(self.slit_v_3D, 1)
        self.bias_3D = QDoubleSpinBox()
        self.bias_3D.setDecimals(6)
        self.bias_3D.setRange(-360, 360)
        self.biasLabel_3D = QLabel("Bias:")
        self.biasLabel_3D.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        hbox_3D_bias = QHBoxLayout()
        hbox_3D_bias.addWidget(self.biasLabel_3D, 0)
        hbox_3D_bias.addWidget(self.bias_3D, 1)
        self.theta3DButton_3D = QPushButton("Theta Mapping")
        self.theta3DButton_3D.setToolTip(
            'This applys <b>parallel calculation</b>. Make sure: <b>Energy</b> is along <b>Z</b> axis and <b>Sweeping direction</b> is along <b>Y</b> axis.'
        )
        self.theta3DButton_3D.clicked.connect(self.Tokspace3D)
        self.azimuth3DButton_3D = QPushButton("Azimuth Mapping")
        self.azimuth3DButton_3D.setToolTip(
            'Make sure: <b>Energy</b> is along <b>Z</b> axis and <b>Sweeping direction</b> is along <b>Y</b> axis.'
        )
        self.iPot_3D = QDoubleSpinBox()
        self.iPot_3D.setDecimals(6)
        self.iPot_3D.setRange(-10000, 10000)
        self.iPotLabel_3D = QLabel("Inn. Potential:")
        self.iPotLabel_3D.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        hbox_3D_ip = QHBoxLayout()
        hbox_3D_ip.addWidget(self.iPotLabel_3D, 0)
        hbox_3D_ip.addWidget(self.iPot_3D, 1)
        self.PE3DButton_3D = QPushButton("hv Mapping")
        self.PE3DButton_3D.setToolTip(
            'Make sure: <b>Energy</b> is along <b>Z</b> axis, <b>Angle</b> is along <b>X</b> axis and <b>Photon Energy</b> is along <b>Y</b> axis.'
        )
        self.kspace2DButton_3D = QPushButton("Non-kspace Mapping")
        self.kspace2DButton_3D.setToolTip(
            'Make sure: <b>Energy</b> is along <b>X</b> axis and <b>Angle</b> is along <b>Y</b> axis.'
        )
        vbox_3D_kspace = QVBoxLayout()
        vbox_3D_kspace.addWidget(QLabel("Slit Orientation:"))
        vbox_3D_kspace.addLayout(hbox_3D_slit)
        vbox_3D_kspace.addLayout(hbox_3D_bias)
        vbox_3D_kspace.addWidget(self.theta3DButton_3D)
        vbox_3D_kspace.addWidget(self.azimuth3DButton_3D)
        vbox_3D_kspace.addLayout(hbox_3D_ip)
        vbox_3D_kspace.addWidget(self.PE3DButton_3D)
        vbox_3D_kspace.addWidget(self.kspace2DButton_3D)
        self.groupbox_3D_kspace.setLayout(vbox_3D_kspace)
        self.box.addWidget(self.groupbox_3D_kspace)

        #Save & Restore Data
        self.saveButton = QPushButton("Save")
        self.saveButton.setEnabled(False)
        self.saveButton.clicked.connect(self.SaveData)
        self.restoreButton = QPushButton("Restore")
        self.restoreButton.clicked.connect(self.RestoreData)
        hbox_save_restore = QHBoxLayout()
        hbox_save_restore.addStretch(1)
        hbox_save_restore.addWidget(self.saveButton)
        hbox_save_restore.addWidget(self.restoreButton)
        hbox_save_restore.addStretch(1)
        self.box.addLayout(hbox_save_restore)

        #Developer Setting
        self.DevSetting = QCheckBox("Developer Setting")
        self.DevSetting.stateChanged.connect(self.OpenDevSetting)
        hbox_dev = QHBoxLayout()
        hbox_dev.addStretch(1)
        hbox_dev.addWidget(self.DevSetting)
        hbox_dev.addStretch(1)
        self.box.addLayout(hbox_dev)

        self.container = QWidget()
        self.container.setStyleSheet("background-color: 'white';")
        self.container.setStyle(QStyleFactory.create('Fusion'))
        self.container.setLayout(self.box)

        self.setWidget(self.container)
        self.setStyle(QStyleFactory.create('Fusion'))
        self.setStyleSheet(
            "QScrollArea {background-color: 'white'; border: 0px}")

    def updateUI(self, data):
        if data == None:
            self.setEnabled(False)
        else:
            self.setEnabled(True)
            self.singleData = data
            if data.dims == 1:
                pass
            elif data.dims == 2:
                self.enable2Dwidget()
            elif data.dims == 3:
                self.enable3Dwidget()
            self.saveButton.setEnabled(not data.rawdataflag)

    def enable2Dwidget(self):
        self.ydecreaseButton.setEnabled(True)
        self.ystep.setEnabled(True)
        self.yincreaseButton.setEnabled(True)
        self.zdecreaseButton.setEnabled(False)
        self.zstep.setEnabled(False)
        self.zincreaseButton.setEnabled(False)
        self.tdecreaseButton.setEnabled(False)
        self.tstep.setEnabled(False)
        self.tincreaseButton.setEnabled(False)
        self.updateRange()
        self.ylow.setEnabled(True)
        self.yhigh.setEnabled(True)
        self.zlow.setEnabled(False)
        self.zhigh.setEnabled(False)
        self.tlow.setEnabled(False)
        self.thigh.setEnabled(False)
        self.ynum.setEnabled(True)
        self.znum.setEnabled(False)
        self.tnum.setEnabled(False)
        self.groupbox_detector.setEnabled(True)
        self.groupbox_2D_general.setEnabled(True)
        self.groupbox_2D_kspace.setEnabled(True)
        self.set2DEnergyAxis(self.singleData.energyAxis)
        self.groupbox_3D_general.setEnabled(False)
        self.groupbox_3D_kspace.setEnabled(False)

    def set2DEnergyAxis(self, energyAxis):
        if energyAxis != None:
            if energyAxis == 'X':
                self.xaxis_2D_energy.setChecked(True)
            else:
                self.yaxis_2D_energy.setChecked(True)
            self.xaxis_2D_energy.setEnabled(False)
            self.yaxis_2D_energy.setEnabled(False)
        else:
            self.xaxis_2D_energy.setEnabled(True)
            self.yaxis_2D_energy.setEnabled(True)

    def enable3Dwidget(self):
        self.ydecreaseButton.setEnabled(True)
        self.ystep.setEnabled(True)
        self.yincreaseButton.setEnabled(True)
        self.zdecreaseButton.setEnabled(True)
        self.zstep.setEnabled(True)
        self.zincreaseButton.setEnabled(True)
        self.tdecreaseButton.setEnabled(False)
        self.tstep.setEnabled(False)
        self.tincreaseButton.setEnabled(False)
        self.updateRange()
        self.ylow.setEnabled(True)
        self.yhigh.setEnabled(True)
        self.zlow.setEnabled(False)
        self.zhigh.setEnabled(False)
        self.tlow.setEnabled(False)
        self.thigh.setEnabled(False)
        self.ynum.setEnabled(True)
        self.znum.setEnabled(True)
        self.tnum.setEnabled(False)
        self.groupbox_detector.setEnabled(True)
        self.groupbox_2D_general.setEnabled(False)
        self.groupbox_2D_kspace.setEnabled(False)
        self.groupbox_3D_general.setEnabled(True)
        self.groupbox_3D_kspace.setEnabled(True)

    def updateRange(self):
        self.xlow.setRange(self.singleData.xmin, self.singleData.xmax)
        self.xlow.setSingleStep(self.singleData.xstep)
        self.xhigh.setRange(self.singleData.xmin, self.singleData.xmax)
        self.xhigh.setSingleStep(self.singleData.xstep)
        self.xlow.setValue(self.singleData.xmin)
        self.xhigh.setValue(self.singleData.xmax)
        if self.singleData.dims > 1:
            self.ylow.setRange(self.singleData.ymin, self.singleData.ymax)
            self.ylow.setSingleStep(self.singleData.ystep)
            self.yhigh.setRange(self.singleData.ymin, self.singleData.ymax)
            self.yhigh.setSingleStep(self.singleData.ystep)
            self.ylow.setValue(self.singleData.ymin)
            self.yhigh.setValue(self.singleData.ymax)
        if self.singleData.dims == 4:
            self.zlow.setRange(self.singleData.zmin, self.singleData.zmax)
            self.zlow.setSingleStep(self.singleData.zstep)
            self.zhigh.setRange(self.singleData.zmin, self.singleData.zmax)
            self.zhigh.setSingleStep(self.singleData.zstep)
            self.tlow.setRange(self.singleData.tmin, self.singleData.tmax)
            self.tlow.setSingleStep(self.singleData.tstep)
            self.thigh.setRange(self.singleData.tmin, self.singleData.tmax)
            self.thigh.setSingleStep(self.singleData.tstep)
            self.zlow.setValue(self.singleData.zmin)
            self.zhigh.setValue(self.singleData.zmax)
            self.tlow.setValue(self.singleData.tmin)
            self.thigh.setValue(self.singleData.tmax)

    def rangeValidator(self, value):
        if self.sender() == self.xlow:
            if value > self.xhigh.value():
                self.xlow.setValue(self.xhigh.value())
        if self.sender() == self.xhigh:
            if value < self.xlow.value():
                self.xhigh.setValue(self.xlow.value())
        if self.sender() == self.ylow:
            if value > self.yhigh.value():
                self.ylow.setValue(self.yhigh.value())
        if self.sender() == self.yhigh:
            if value < self.ylow.value():
                self.yhigh.setValue(self.ylow.value())
        if self.sender() == self.zlow:
            if value > self.zhigh.value():
                self.zlow.setValue(self.zhigh.value())
        if self.sender() == self.zhigh:
            if value < self.zlow.value():
                self.zhigh.setValue(self.zlow.value())
        if self.sender() == self.tlow:
            if value > self.thigh.value():
                self.tlow.setValue(self.thigh.value())
        if self.sender() == self.thigh:
            if value < self.tlow.value():
                self.thigh.setValue(self.tlow.value())

    def setSelectXRange(self, x0=0, x1=1):
        self.xlow.setValue(x0)
        self.xhigh.setValue(x1)

    def setSelectYRange(self, y0=0, y1=1):
        self.ylow.setValue(y0)
        self.yhigh.setValue(y1)

    def setSelectXYRange(self, x0=0, x1=1, y0=0, y1=1, cropSpec=True):
        if cropSpec:
            self.xlow.setValue(x0)
            self.xhigh.setValue(x1)
            self.ylow.setValue(y0)
            self.yhigh.setValue(y1)
        else:
            self.zlow.setValue(x0)
            self.zhigh.setValue(x1)
            self.tlow.setValue(y0)
            self.thigh.setValue(y1)

    @processGeneral
    def OnRemoveNaN(self, flag):
        mask = np.isnan(self.singleData.data)
        self.singleData.data[mask] = self.setvalue.value()

    @processGeneral
    def offset(self, flag):
        if self.sender() == self.xdecreaseButton:
            self.singleData.xscale -= self.xstep.value()
            self.singleData.xmin -= self.xstep.value()
            self.singleData.xmax -= self.xstep.value()
        if self.sender() == self.xincreaseButton:
            self.singleData.xscale += self.xstep.value()
            self.singleData.xmin += self.xstep.value()
            self.singleData.xmax += self.xstep.value()
        if self.sender() == self.ydecreaseButton:
            self.singleData.yscale -= self.ystep.value()
            self.singleData.ymin -= self.ystep.value()
            self.singleData.ymax -= self.ystep.value()
        if self.sender() == self.yincreaseButton:
            self.singleData.yscale += self.ystep.value()
            self.singleData.ymin += self.ystep.value()
            self.singleData.ymax += self.ystep.value()
        if self.sender() == self.zdecreaseButton:
            self.singleData.zscale -= self.zstep.value()
            self.singleData.zmin -= self.zstep.value()
            self.singleData.zmax -= self.zstep.value()
        if self.sender() == self.zincreaseButton:
            self.singleData.zscale += self.zstep.value()
            self.singleData.zmin += self.zstep.value()
            self.singleData.zmax += self.zstep.value()
        if self.sender() == self.tdecreaseButton:
            self.singleData.tscale -= self.tstep.value()
            self.singleData.tmin -= self.tstep.value()
            self.singleData.tmax -= self.tstep.value()
        if self.sender() == self.tincreaseButton:
            self.singleData.tscale += self.tstep.value()
            self.singleData.tmin += self.tstep.value()
            self.singleData.tmax += self.tstep.value()
        self.singleData.writeProperty(False)

    @processGeneral
    def OnCropSpec(self, flag):
        x0 = self.xlow.value()
        x1 = self.xhigh.value()
        y0 = self.ylow.value()
        y1 = self.yhigh.value()
        Data.crop(self.singleData, x0, x1, y0, y1)

    def OnMerge(self, flag):
        if self.singleData.dims == 1:
            pass
        elif self.singleData.dims == 2:
            self.Merge2D_wrapper()
        elif self.singleData.dims == 3:
            self.Merge3D_wrapper()

    @processGeneral
    def Merge2D_wrapper(self):
        xnum = self.xnum.value()
        ynum = self.ynum.value()
        Data.merge2D(self.singleData, xnum, ynum)

    @process3D
    def Merge3D_wrapper(self):
        xnum = self.xnum.value()
        ynum = self.ynum.value()
        znum = self.znum.value()
        Data.merge3D(self.singleData, xnum, ynum, znum)

    @process2D
    def transpose2D(self, flag):
        Data.transpose2D(self.singleData)
        self.set2DEnergyAxis(self.singleData.energyAxis)

    @process2D
    def mirror2D(self, flag):
        if self.sender() == self.mirrorXButton:
            Data.mirror2D(self.singleData, 'X')
        elif self.sender() == self.mirrorYButton:
            Data.mirror2D(self.singleData, 'Y')

    @process2D
    def normal2D(self, flag):
        if self.sender() == self.normalXDCButton:
            Data.normal2D(self.singleData, 'X')
        elif self.sender() == self.normalYDCButton:
            Data.normal2D(self.singleData, 'Y')

    @process2D
    def Tokspace2D(self, flag):
        if self.xaxis_2D_energy.isChecked():
            if Data.Tokspace2D(self.singleData, 'X') == 0:
                if self.singleData.energyAxis == None:
                    self.singleData.energyAxis = 'X'
        else:
            if Data.Tokspace2D(self.singleData, 'Y') == 0:
                if self.singleData.energyAxis == None:
                    self.singleData.energyAxis = 'Y'

    @process3D
    def transpose3D(self, flag):
        Data.transpose3D(self.singleData)
        #self.set2DEnergyAxis(self.singleData.energyAxis)

    @process3D
    def changeZAxis(self, flag):
        if self.sender() == self.YZXButton3D:
            Data.changeZAxis3D(self.singleData, 'X')
            #self.set2DEnergyAxis(self.singleData.energyAxis)
        elif self.sender() == self.ZXYButton3D:
            Data.changeZAxis3D(self.singleData, 'Y')
            #self.set2DEnergyAxis(self.singleData.energyAxis)

    @process3D
    def mirror3D(self, flag):
        if self.sender() == self.mirrorXButton3D:
            Data.mirror3D(self.singleData, 'X')
        elif self.sender() == self.mirrorYButton3D:
            Data.mirror3D(self.singleData, 'Y')

    @process3D_T
    def Tokspace3D(self, flag):
        dlg = waitingDialog(self.Win)
        dlg.progress.setValue(0)
        s = signal()
        s.progress.connect(dlg.progress.setValue)
        s.finished.connect(dlg.FinishedSlot)
        s.stoped.connect(dlg.StopedSlot)
        if self.sender() == self.theta3DButton_3D:
            if self.slit_h_3D.isChecked():
                t = Data.ThetaKspace3D(self.singleData, 'H',
                                       self.bias_3D.value(), dlg,
                                       self.core_num,
                                       self.solver_max_iteration_step,
                                       self.solver_error, os.getpid(), s)
            else:
                t = Data.ThetaKspace3D(self.singleData, 'V',
                                       self.bias_3D.value(), dlg,
                                       self.core_num,
                                       self.solver_max_iteration_step,
                                       self.solver_error, os.getpid(), s)
        t.start()
        return dlg.exec_()

    def changeAspect2D(self, state):
        if state == 2:
            self.Win.ImageViewer.twoDimage.changeAspect(True)
        elif state == 0:
            self.Win.ImageViewer.twoDimage.changeAspect(False)

    def changeAspect3D(self, state):
        if state == 2:
            self.Win.ImageViewer.threeDblock.changeAspect(True)
        elif state == 0:
            self.Win.ImageViewer.threeDblock.changeAspect(False)

    def OpenDevSetting(self, state):
        if state == 2:
            self.DevWin.exec_()
            self.DevSetting.setCheckState(0)

    def SaveData(self):
        self.singleData.Save()
        #self.Win.DataBrowser.InfoList.setProperty(self.singleData.property)
        #self.Win.ImageViewer.setData(self.singleData)
        self.saveButton.setEnabled(False)

    def RestoreData(self):
        self.singleData.Restore()
        self.Win.DataBrowser.InfoList.setProperty(self.singleData.property)
        self.Win.setData(self.singleData)
        self.saveButton.setEnabled(False)
Ejemplo n.º 14
0
class FunctionsMenu(QWidget):
    def __init__(self):
        super().__init__()
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        row_hight = 30
        margins = self.layout.contentsMargins()
        margins.setTop(2*row_hight + self.layout.spacing())
        margins.setLeft(20)
        self.layout.setContentsMargins(margins)

        # Initializing GUI elements
        self.ipp = QRadioButton()
        self.ippcp = QRadioButton()

        self.select_ipp = QPushButton('Select package')
        self.select_ippcp = QPushButton('Select package')
        self.select_ipp.package = utils.IPP
        self.select_ippcp.package = utils.IPPCP

        self.lib_var_list = QComboBox(self)
        self.search = QLineEdit(self)
        self.selected_libraries_list = QListWidget(self)
        self.auto_build_button = QPushButton('Autobuild')

        self.current_functions_list = {}

        # Preparing elements by giving initial values, etc
        self.ipp.setText('IPP ver. None')
        self.ippcp.setText('IPP Cryptography ver. None')
        self.search.setPlaceholderText('Search...')

        self.ipp.setDisabled(True)
        self.ippcp.setDisabled(True)
        self.auto_build_button.setDisabled(True)

        self.lib_var_list.activated[str].connect(self.on_theme_selected)
        self.search.textEdited.connect(self.on_search)
        self.selected_libraries_list.itemClicked.connect(self.on_item_selected)
        self.auto_build_button.clicked.connect(self.on_build_pressed)
        self.select_ipp.clicked.connect(self.on_select)
        self.select_ippcp.clicked.connect(self.on_select)
        self.ipp.toggled.connect(self.on_switch)

        # Setting all widgets in their places
        self.layout.addWidget(self.ipp, 0, 0, 1, 3)
        self.layout.addWidget(self.ippcp, 1, 0, 1, 3)

        self.layout.addWidget(self.select_ipp, 0, 3)
        self.layout.addWidget(self.select_ippcp, 1, 3)

        self.layout.addWidget(self.lib_var_list, 2, 0, 1, 4)
        self.layout.addWidget(self.search, 3, 0, 1, 4)
        self.layout.addWidget(self.selected_libraries_list, 4, 0, 1, 4)
        self.layout.addWidget(self.auto_build_button, 5, 0, 1, 4)

        self.select_ipp.setFixedHeight(row_hight)
        self.select_ippcp.setFixedHeight(row_hight)
        self.lib_var_list.setFixedHeight(row_hight)

        path_to_package = self.get_path_to_package()
        if path_to_package:
            package = utils.IPPCP if re.compile('.*ippcp.*').match(path_to_package) else utils.IPP
            self.set_package(package, path_to_package)
            self.init_menu()

    def init_menu(self):
        self.ipp.toggled.disconnect(self.on_switch)
        self.tl_selected = False

        if self.ipp.isEnabled():
            package = utils.IPP
            self.init_functions(utils.IPP, settings.CONFIGS[utils.IPP]['Path'])
            self.ipp.setChecked(True)

        if self.ippcp.isEnabled():
            self.init_functions(utils.IPPCP, settings.CONFIGS[utils.IPPCP]['Path'])
            if not self.ipp.isEnabled():
                package = utils.IPPCP
                self.ippcp.setChecked(True)

        self.show_menu(package)
        self.ipp.toggled.connect(self.on_switch)

    def set_package(self, package, path):
        if self.check_package(package, path):
            settings.CONFIGS[package]['Path'] = path
            if package == utils.IPP:
                self.ipp.setText('IPP ver. ' + self.get_version(path))
                self.ipp.setEnabled(True)
            else:
                self.ippcp.setText('IPP Cryptography ver. ' + self.get_version(path))
                self.ippcp.setEnabled(True)
            return True
        elif path:
            if package == utils.IPP:
                QMessageBox.information(self, 'ERROR!',
                                        'Incorrect Intel® Integrated Performance Primitives package path!')
            else:
                QMessageBox.information(self, 'ERROR!',
                                        'Incorrect Intel® Integrated Performance Primitives Cryptography package path!')

            return False

    def check_package(self, package, path):
        if not self.check_batch(package, path):
            return False

        if os.path.exists(os.path.join(path, 'include')):
            for header in os.listdir(os.path.join(path, 'include')):
                if get_mode_and_domain(header):
                    break
        else:
            return False

        lib_ia32_path = os.path.join(path, 'lib', 'ia32_' + utils.HOST_SYSTEM.lower()[:3])
        if utils.HOST_SYSTEM != MACOSX:
            lib_intel64_path = os.path.join(path, 'lib', 'intel64_' + utils.HOST_SYSTEM.lower()[:3])
        else:
            lib_intel64_path = os.path.join(path, 'lib')

        return True if self.check_libs(lib_ia32_path) or \
                       self.check_libs(lib_intel64_path) else False

    def check_batch(self, package, path):
        return os.path.exists(os.path.join(path, 'bin', package.lower() + 'vars' + BATCH_EXTENSIONS[utils.HOST_SYSTEM]))

    def check_libs(self, path):
        if os.path.exists(path):
            for lib in os.listdir(path):
                if STATIC_LIBRARIES_EXTENSIONS[utils.HOST_SYSTEM] in lib:
                    return True
        return False

    def on_select(self):
        package = self.sender().package
        while True:
            path = QFileDialog.getExistingDirectory(self, 'Select ' + package + ' package')
            if not path:
                return

            if self.set_package(package, path):
                break

        self.init_functions(package, path)

        if package == utils.IPP:
            if not self.ipp.isChecked() and not self.ippcp.isChecked():
                self.ipp.toggled.disconnect(self.on_switch)
                self.ipp.setChecked(True)
                self.ipp.toggled.connect(self.on_switch)
        else:
            if not self.ipp.isChecked() and not self.ippcp.isChecked():
                self.ippcp.setChecked(True)

        for config in settings.CONFIGS[package].keys():
            if config != 'Path' and config != 'functions_list':
                settings.CONFIGS[package][config] = False
        settings.CONFIGS[package]['functions_list'].clear()

        if package == utils.IPP and self.ipp.isChecked() or \
                package == utils.IPPCP and self.ippcp.isChecked():
            self.parent.receiver.set_configs(package)
            self.parent.receiver.functions_names.clear()
            self.parent.receiver.functions_list.clear()
            self.show_menu(package)

        self.parent.receiver.on_block()

    def on_switch(self):
        if self.ipp.isChecked():
            package = utils.IPP
            self.parent.receiver.get_configs(utils.IPPCP)
        else:
            package = utils.IPPCP
            self.parent.receiver.get_configs(utils.IPP)

        self.parent.receiver.set_configs(package)
        self.show_menu(package)
        self.parent.receiver.add_items(self.parent.receiver.functions_names)
        self.parent.receiver.on_block()

    def on_theme_selected(self, text):
        self.add_items(self.current_functions_list.get(text))
        self.on_search(self.search.text())

    def on_search(self, search_request):
        if self.current_functions_list:
            self.add_items([entry for entry in self.current_functions_list.get(self.lib_var_list.currentText())
                            if search_request.upper() in entry.upper()])

    def on_item_selected(self, item):
        self.selected_libraries_list.setCurrentItem(item)

    def on_build_pressed(self):
        information = self.parent.get_library_information()
        library_path = QFileDialog.getExistingDirectory(self, 'Select a folder')
        if library_path == '':
            return
        success = False
        self.parent.set_disabled(True)
        QMessageBox.information(self, 'Build', 'Building will start after this window is closed. '
                                               'Please wait until process is done.')

        package = utils.IPP if self.ipp.isChecked() else utils.IPPCP

        os.environ[package + 'ROOT'] = settings.CONFIGS[package]['Path']
        self.get_path_to_cnl(settings.CONFIGS[package]['Path'])

        if information['ia32']:
            success = tool.core.build(
                package,
                information['host_system'],
                information['target_system'],
                information['functions'],
                library_path,
                information['library_name'],
                tool.utils.IA32,
                information['threading'] == 'Multi-threaded',
                tool.utils.COMPILERS_AND_LIBRARIES_PATH,
                threading_layer_type=information['threading_layer_type']
            )
        if information['intel64']:
            success = tool.core.build(
                package,
                information['host_system'],
                information['target_system'],
                information['functions'],
                library_path,
                information['library_name'],
                tool.utils.INTEL64,
                information['threading'] == 'Multi-threaded',
                tool.utils.COMPILERS_AND_LIBRARIES_PATH,
                threading_layer_type=information['threading_layer_type']
            )
        self.parent.set_disabled(False)
        QMessageBox.information(self, 'Success' if success else 'Failure',
                                'Build completed!' if success else 'Build failed!')

    def add_items(self, items):
        """
        Sorts and adds items to list view
        :param items: list of strings
        """
        self.selected_libraries_list.clear()

        if items:
            items.sort()
            self.selected_libraries_list.addItems(items)
            self.selected_libraries_list.setCurrentItem(self.selected_libraries_list.item(0))

        self.selected_libraries_list.repaint()

    def add_item(self, function_name):
        """
        Adds function to left list

        :param function_name:
        """
        self.operation(list.append, function_name)
        self.add_items(self.current_functions_list.get(self.lib_var_list.currentText()))
        self.on_search(self.search.text())

    def remove_item(self, item):
        """
        Removes item from left list
        """
        if item is None:
            return None

        self.operation(list.remove, item)
        self.add_items(self.current_functions_list.get(self.lib_var_list.currentText()))
        self.on_search(self.search.text())

    def operation(self, action, function_name):
        for mode in FUNCTIONS_LIST.keys():
            for domain in FUNCTIONS_LIST[mode].keys():
                if function_name in FUNCTIONS_LIST[mode][domain]:
                    action(self.functions_list[mode][domain], function_name)
                    return

    def init_func_list(self):
        """
        Taking all domains and their functions
        """
        self.lib_var_list.clear()
        self.lib_var_list.addItems([entry for entry in self.current_functions_list.keys()])

    def init_functions(self, package, path):
        if package == utils.IPP:
            FUNCTIONS_LIST['Classical IPP'].clear()
            FUNCTIONS_LIST['IPP TL'].clear()
        else:
            FUNCTIONS_LIST['IPP Cryptography'].clear()

        get_functions_from_headers(path)
        self.functions_list = copy.deepcopy(FUNCTIONS_LIST)
        self.threaded_functions = [item for sublist in self.functions_list['IPP TL'].values() for item in
                                   sublist]
    def show_menu(self, package):
        if package == utils.IPP:
            if not self.tl_selected:
                self.current_functions_list = self.functions_list['Classical IPP']
            else:
                self.current_functions_list = self.functions_list['IPP TL']
        else:
            self.current_functions_list = self.functions_list['IPP Cryptography']

        self.init_func_list()
        self.add_items(self.current_functions_list.get(self.lib_var_list.currentText()))

    def get_path_to_package(self):
        dir_path = os.path.dirname(os.path.realpath(__file__))

        if re.compile(utils.PATH_TO_PACKAGE_REGULAR_EXPRESSION).match(dir_path):
            return re.match(utils.PATH_TO_PACKAGE_REGULAR_EXPRESSION, dir_path).group('path')
        else:
            return ''

    def get_version(self, path):
        if re.compile(utils.VERSION_REGULAR_EXPRESSION).match(path):
            return re.match(utils.VERSION_REGULAR_EXPRESSION, path).group('ver')
        else:
            return 'None'

    def get_path_to_cnl(self, path):
        if re.compile(utils.PATH_TO_CNL_REGULAR_EXPRESSION).match(path):
            utils.COMPILERS_AND_LIBRARIES_PATH = re.match(utils.PATH_TO_CNL_REGULAR_EXPRESSION, path).group('cnl')
Ejemplo n.º 15
0
class ScriptsMenu(QWidget):
    def interface_check(function):
        def wrapper(self):
            function(self)
            try:
                self.on_block()
            except:
                return wrapper

        return wrapper

    def __init__(self):
        super().__init__()
        self.layout = QGridLayout()
        self.setLayout(self.layout)

        row_hight = 30
        margins = self.layout.contentsMargins()
        margins.setTop(row_hight)
        margins.setRight(20)
        self.layout.setContentsMargins(margins)

        # Initializing GUI elements
        self.settings_label = QLabel('Settings')
        self.platform_var_list = QComboBox()
        self.thread_var_list = QComboBox()

        self.intel64 = QCheckBox('Intel 64')
        self.IA32 = QCheckBox('IA32')
        self.TL = QCheckBox('Threading layer')
        self.omp = QRadioButton('OpenMP')
        self.tbb = QRadioButton('TBB')

        self.lib_name = QLineEdit()
        self.functions_list = QListWidget()
        self.save_build_script = QPushButton('Save build script')
        self.functions_names = []
        self.status_receiver = None

        self.lib_name.setPlaceholderText('Library name...')

        # Preparing elements by giving initial values and etc
        self.settings_label.setAlignment(Qt.AlignBottom)
        self.save_build_script.setDisabled(True)

        self.save_build_script.clicked.connect(self.on_save_build_script)
        self.IA32.clicked.connect(self.on_block)
        self.intel64.clicked.connect(self.on_block)
        self.TL.clicked.connect(self.set_tl)
        self.lib_name.textEdited.connect(self.on_block)
        self.platform_var_list.currentIndexChanged.connect(self.on_target_system_selection)

        # Setting all widgets in their places
        self.layout.addWidget(self.settings_label, 0, 0)

        self.layout.addWidget(self.TL, 1, 0)
        self.layout.addWidget(self.omp, 2, 0)
        self.layout.addWidget(self.tbb, 3, 0)

        self.layout.addWidget(self.intel64, 2, 1)
        self.layout.addWidget(self.IA32, 3, 1)
        self.layout.addWidget(self.platform_var_list, 2, 2, 1, 2)
        self.layout.addWidget(self.thread_var_list, 3, 2, 1, 2)

        self.layout.addWidget(self.lib_name, 4, 0, 1, 4)
        self.layout.addWidget(self.functions_list, 5, 0, 1, 4)
        self.layout.addWidget(self.save_build_script, 6, 0, 1, 4)

        self.settings_label.setFixedHeight(row_hight)
        self.TL.setFixedHeight(row_hight)
        self.platform_var_list.setFixedHeight(row_hight)
        self.thread_var_list.setFixedHeight(row_hight)

        self.__post_check()

    def set_configs(self, package):
        self.check_configs(package)

        self.TL.setChecked(settings.CONFIGS[package]['TL'])
        self.omp.setChecked(settings.CONFIGS[package]['OpenMP'])
        self.tbb.setChecked(settings.CONFIGS[package]['TBB'])
        self.set_tl()

        self.intel64.setChecked(settings.CONFIGS[package]['intel64'])
        self.IA32.setChecked(settings.CONFIGS[package]['IA32'])

        if self.intel64.isEnabled():
            if not self.intel64.isChecked() and not self.IA32.isChecked():
                self.intel64.setChecked(True)
        elif self.IA32.isEnabled():
            self.IA32.setChecked(True)

        self.thread_var_list.setCurrentText(utils.MULTI_THREADED) if settings.CONFIGS[package]['Multi-threaded'] \
            else self.thread_var_list.setCurrentText(utils.SINGLE_THREADED)

        self.functions_names = settings.CONFIGS[package]['functions_list']

    def check_configs(self, package):
        self.intel64_libs_path = self.parent.source.path_to_libs[package][utils.INTEL64]
        self.ia32_libs_path = self.parent.source.path_to_libs[package][utils.IA32]

        if self.intel64_libs_path:
            self.intel64.setEnabled(True)
        else:
            settings.CONFIGS[package]['intel64'] = False
            self.intel64.setDisabled(True)

        if self.ia32_libs_path:
            self.IA32.setEnabled(True)
        else:
            settings.CONFIGS[package]['IA32'] = False
            self.IA32.setDisabled(True)

        if self.check_dir('tl'):
            self.TL.setEnabled(True)
        else:
            settings.CONFIGS[package]['TL'] = False
            self.TL.setDisabled(True)

        self.thread_var_list.clear()
        if self.check_dir('threaded'):
            self.thread_var_list.addItems([utils.SINGLE_THREADED,
                                           utils.MULTI_THREADED])
        else:
            self.thread_var_list.addItem(utils.SINGLE_THREADED)
            settings.CONFIGS[package]['Multi-threaded'] = False

    def check_dir(self, dir):
        return os.path.exists(os.path.join(self.intel64_libs_path, dir)) or \
                os.path.exists(os.path.join(self.ia32_libs_path, dir))

    def get_configs(self, package):
        if self.TL.isEnabled():
            settings.CONFIGS[package]['TL'] = self.TL.isChecked()

        if settings.CONFIGS[package]['TL']:
            settings.CONFIGS[package]['OpenMP'] = self.omp.isChecked()
            settings.CONFIGS[package]['TBB'] = self.tbb.isChecked()

        settings.CONFIGS[package]['intel64'] = self.intel64.isChecked()
        settings.CONFIGS[package]['IA32'] = self.IA32.isChecked()

        settings.CONFIGS[package]['Multi-threaded'] = (self.thread_var_list.currentText() == utils.MULTI_THREADED)

        settings.CONFIGS[package]['functions_list'] = self.functions_names

    def set_status_output(self, status_receiver):
        self.status_receiver = status_receiver

    def __get_interface_state(self):
        return {settings.PACKAGE: self.parent.source.ipp.isEnabled() or self.parent.source.ippcp.isEnabled(),
                settings.PLATFORM: self.IA32.isChecked() or self.intel64.isChecked(),
                settings.LIB_NAME: bool(self.lib_name.text()),
                settings.FUNCTIONS: bool(self.functions_names),
                settings.ANDK: not ((not bool(utils.ANDROID_NDK_PATH))
                           and self.platform_var_list.currentText() == utils.ANDROID)
                }

    def on_item_selected(self, item):
        self.functions_list.setCurrentItem(item)

    def on_block(self):
        autobuild_requrements = settings.AUTOBUILD_BUTTON_RULES
        script_requrements = settings.SCRIPT_BUTTON_GENERATOR_RULES
        interface_state = self.__get_interface_state()
        if autobuild_requrements == interface_state:
            self.parent.set_auto_build_disabled(False)
            self.status_receiver.showMessage("Ready to build custom library")
        else:
            self.parent.set_auto_build_disabled(True)
            differences = dict(autobuild_requrements.items() - interface_state.items())
            self.status_receiver.showMessage("Set " + sorted(differences, key=len)[0])

        if script_requrements == {i: interface_state.get(i)
                                  for i in script_requrements.keys()}:
            self.save_build_script.setDisabled(False)
        else:
            self.save_build_script.setDisabled(True)

    def set_tl(self):
        if self.TL.isEnabled():
            self.set_threading_layer_enabled(self.TL.isChecked())
            self.parent.source.tl_selected = self.TL.isChecked()
        else:
            self.set_threading_layer_enabled(False)
            self.parent.source.tl_selected = False

        if self.parent.source.ipp.isChecked():
            self.parent.source.show_menu(utils.IPP)

        if not self.omp.isChecked() and not self.tbb.isChecked():
            if self.omp.isEnabled():
                self.omp.setChecked(True)
            elif self.tbb.isEnabled():
                self.tbb.setChecked(True)

    def set_threading_layer_enabled(self, bool):
        self.omp.setEnabled(bool) if self.check_dir(os.path.join('tl', 'openmp')) else self.omp.setDisabled(True)
        self.tbb.setEnabled(bool) if self.check_dir(os.path.join('tl', 'tbb')) else self.tbb.setDisabled(True)

    def on_save_build_script(self):
        library_path = QFileDialog.getExistingDirectory(self, 'Select a folder')
        if library_path == '':
            return
        host_system = utils.HOST_SYSTEM
        target_system = self.platform_var_list.currentText()
        functions = self.functions_names
        library_name = self.lib_name.text()
        threading = self.thread_var_list.currentText() == 'Multi-threaded'
        threading_layer_type = self.parent.get_treading_layer_type()

        if self.parent.source.ipp.isChecked():
            package = utils.IPP
            root = utils.IPPROOT
        else:
            package = utils.IPPCP
            root = utils.IPPCRYPTOROOT

        os.environ[root] = settings.CONFIGS[package]['Path']

        if self.IA32.isChecked():
            generate_script(package,
                            host_system,
                            target_system,
                            functions,
                            library_path,
                            library_name,
                            utils.IA32,
                            threading,
                            threading_layer_type, )
        if self.intel64.isChecked():
            generate_script(package,
                            host_system,
                            target_system,
                            functions,
                            library_path,
                            library_name,
                            utils.INTEL64,
                            threading,
                            threading_layer_type)
        QMessageBox.about(self, 'Success', 'Generation completed!')

    @interface_check
    def on_target_system_selection(self):
        system = self.platform_var_list.currentText()
        if utils.ONLY_THREADABLE[system]:
            self.thread_var_list.setCurrentIndex(1)
            self.thread_var_list.setDisabled(True)
        else:
            self.thread_var_list.setDisabled(False)

        if not utils.SUPPORTED_ARCHITECTURES[system][utils.IA32]:
            self.IA32.setCheckState(Qt.Unchecked)
            self.IA32.setDisabled(True)
        else:
            self.IA32.setDisabled(False)
        if not utils.SUPPORTED_ARCHITECTURES[system][utils.INTEL64]:
            self.intel64.setCheckState(Qt.Unchecked)
            self.intel64.setDisabled(True)
        else:
            self.intel64.setDisabled(False)

    def add_items(self, items):
        """
        Sorts and adds items to list view

        :param items: list of strings
        """
        self.functions_list.clear()

        if items:
            items.sort()
            self.functions_list.addItems(items)
            self.functions_list.setCurrentItem(self.functions_list.item(0))

        self.functions_list.repaint()

    def add_item(self, function):
        """
        Adds new function to required list

        :param domain: domain of function
        :param function: name if function
        """
        self.functions_names.append(function)
        self.add_items(self.functions_names)

    def remove_item(self):
        """
        Removes function from required list
        """
        if self.functions_list.currentItem() is None:
            return None
        lib = self.functions_list.currentItem().text()
        self.functions_names.remove(lib)
        self.add_items(self.functions_names)
        return lib

    def __post_check(self):
        """
        Fills platforms combo box according to host system
        """
        if utils.HOST_SYSTEM == utils.LINUX:
            self.platform_var_list.addItem(utils.LINUX)
        elif utils.HOST_SYSTEM == utils.MACOSX:
            self.platform_var_list.addItem(utils.MACOSX)
        elif utils.HOST_SYSTEM == utils.WINDOWS:
            self.platform_var_list.addItem(utils.WINDOWS)
Ejemplo n.º 16
0
class My_Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(100, 100, 1400, 800)
        self.setWindowTitle('...')
        #---------------------------------------
        self.area = PaintArea(self)
        self.priv_data = None
        #------------- 添加控件 ----------------
        #--------------- QLabel ----------------
        self.high_label = QLabel('高度(cm):')
        self.index_label = QLabel('间隔(cm):')
        self.zoom_label = QLabel('比    例:')

        self.base_msg_label = QLabel('      基站信息:')
        self.X_label = QLabel('   X坐标(cm):')
        self.Y_label = QLabel('   Y坐标(cm):')
        self.base_high_label = QLabel('基站高度(cm):')
        self.base_msg_label.setEnabled(False)
        self.X_label.setEnabled(False)
        self.Y_label.setEnabled(False)
        self.base_high_label.setEnabled(False)
        #-------------- QLineEdit --------------
        self.high_edit = QLineEdit()
        self.high_edit.setText(str(300))
        self.high_edit.setAlignment(Qt.AlignRight)
        self.high_edit.setMaxLength(6)
        self.high_edit.setValidator(QDoubleValidator(0, 3000.0, 5, self))

        self.index_edit = QLineEdit()
        self.index_edit.setText(str(300))
        self.index_edit.setAlignment(Qt.AlignRight)
        self.index_edit.setMaxLength(4)
        self.index_edit.setValidator(QIntValidator(0, 1000, self))

        self.zoom_edit = QLineEdit()
        self.zoom_edit.setText(str(1.0))
        self.zoom_edit.setAlignment(Qt.AlignRight)
        self.zoom_edit.setMaxLength(5)
        self.zoom_edit.setValidator(QDoubleValidator(0.1, 100.0, 4, self))

        self.X_edit = QLineEdit()
        self.X_edit.setText(str(0))
        self.X_edit.setAlignment(Qt.AlignRight)
        self.X_edit.setMaxLength(7)
        self.X_edit.setValidator(QDoubleValidator(0, 10000.0, 5, self))
        self.X_edit.setEnabled(False)

        self.Y_edit = QLineEdit()
        self.Y_edit.setText(str(0))
        self.Y_edit.setAlignment(Qt.AlignRight)
        self.Y_edit.setMaxLength(7)
        self.Y_edit.setValidator(QDoubleValidator(0, 10000.0, 5, self))
        self.Y_edit.setEnabled(False)

        self.base_high_edit = QLineEdit()
        self.base_high_edit.setText(str(300))
        self.base_high_edit.setAlignment(Qt.AlignRight)
        self.base_high_edit.setMaxLength(6)
        self.base_high_edit.setValidator(QDoubleValidator(0, 3000.0, 5, self))
        self.base_high_edit.setEnabled(False)
        #---------- QPushButton ----------------
        self.open_button = QPushButton(self)
        self.open_button.setText('打开文件')
        self.open_button.clicked.connect(self.button_click)
        # self.open_button.setEnabled(False)

        self.cal_button = QPushButton(self)
        self.cal_button.setText('计算位置')
        self.cal_button.clicked.connect(self.button_click)
        self.cal_button.setEnabled(False)

        self.addr_button = QPushButton(self)
        self.addr_button.setText('计算地址')
        self.addr_button.clicked.connect(self.button_click)
        self.addr_button.setEnabled(False)

        self.ok_button = QPushButton(self)
        self.ok_button.setText('确定')
        self.ok_button.clicked.connect(self.button_click)
        self.ok_button.setEnabled(False)

        self.base_station_status = QRadioButton('设为基站')
        #self.base_station_status.setChecked(True)
        #self.base_station_status.toggled.connect(self.set_base_station)
        self.base_station_status.setEnabled(False)
        #-------------- 布局 -------------------
        # right layout
        rightlayout = QVBoxLayout()

        # high label,lineedit
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.high_label)
        tmp_layout.addWidget(self.high_edit)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)

        # index label,lineedit
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.index_label)
        tmp_layout.addWidget(self.index_edit)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)

        # zoom label,lineedit
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.zoom_label)
        tmp_layout.addWidget(self.zoom_edit)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)
        rightlayout.addStretch(1)

        # button
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.open_button)
        tmp_layout.addWidget(self.cal_button)
        tmp_layout.addWidget(self.addr_button)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)
        rightlayout.addStretch(1)

        # base station msg,base_station_status
        tmp_layout = QHBoxLayout()
        #tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.base_msg_label)
        tmp_layout.addWidget(self.base_station_status)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)

        # x label,lineedit
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.X_label)
        tmp_layout.addWidget(self.X_edit)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)

        # y label,lineedit
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.Y_label)
        tmp_layout.addWidget(self.Y_edit)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)

        # high label,lineedit
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.base_high_label)
        tmp_layout.addWidget(self.base_high_edit)
        tmp_layout.addStretch(1)
        rightlayout.addLayout(tmp_layout)

        # ok_button
        tmp_layout = QHBoxLayout()
        tmp_layout.addStretch(1)
        tmp_layout.addWidget(self.ok_button)
        tmp_layout.addStretch(2)
        rightlayout.addLayout(tmp_layout)

        rightlayout.addStretch(1)
        # main layout
        mainlayout = QGridLayout()
        mainlayout.setColumnStretch(0, 5)  #设置第一列和第二列的比例为5:1
        mainlayout.setColumnStretch(1, 1)
        mainlayout.addWidget(self.area, 0, 0, -1,
                             1)  #位置一行一列,占4行1列(self.area,0,0,4,1)
        mainlayout.addLayout(rightlayout, 0, 1, -1, 1)
        #---------------------------------------
        self.setLayout(mainlayout)

    def set_icon_status(self, status):
        if status == True:
            tmp = True
        else:
            tmp = False
        self.base_msg_label.setEnabled(tmp)
        self.X_label.setEnabled(tmp)
        self.Y_label.setEnabled(tmp)
        self.base_high_label.setEnabled(tmp)

        self.X_edit.setEnabled(tmp)
        self.Y_edit.setEnabled(tmp)
        self.base_high_edit.setEnabled(tmp)

        self.base_station_status.setEnabled(tmp)
        self.ok_button.setEnabled(tmp)

    def set_base_station(self, index, x, y, high, base_status):
        print('this is radio button')

        # store index of self.area.base_station
        if len(index) == 2:
            self.priv_data = index
        else:
            print('set_base_station index err')
            return

        # enable icon
        self.set_icon_status(True)

        # show x,y,high,base_status
        if base_status == True:
            self.base_station_status.setChecked(True)
        else:
            self.base_station_status.setChecked(False)

        self.X_edit.setText(str(x))
        self.Y_edit.setText(str(y))
        self.base_high_edit.setText(str(high))
        #
        if self.base_station_status.isChecked():
            print('checked')
        else:
            print('not check')

    def button_click(self):
        # high
        s = float(self.high_edit.text())
        print('high:', s)
        if 100 < s < 1000:
            self.area.high = s
        else:
            print('high input err')
            #self.area.high = 300

        # zoom
        s = float(self.zoom_edit.text())
        print('zoom:', s)
        if s > 0:
            self.area.value_zoom = s
        else:
            print('zoom input err')
            #self.area.value_zoom = 1

        tmp = self.sender()
        #-----------------------------
        if tmp != self.ok_button:
            # disable icon
            self.set_icon_status(False)
        #-----------------------------
        if tmp == self.open_button:
            print('open_button')
            try:
                tmp_file, tmp_type = QFileDialog.getOpenFileName(
                    self, '打开文件', './', 'Text Files (*.dxf)')
                file = open(tmp_file, 'r')
            except:
                print('open file err')
                return
            dxf = DataDXF(file)
            tmp = dxf.readDXF()
            #-----------------------------
            print('get_data')
            if self.area.get_data(tmp) == False:
                return

            self.cal_button.setEnabled(True)  # enable cal_button
            #-----------------------------
            self.area.update()
        elif tmp == self.cal_button:
            print('cal_button')
            try:
                index = float(self.index_edit.text())
            except:
                print('间隔 input err')
                index = 300.0

            print('index:', index)
            #-----------------------------
            '''
            try:
                file = open('./dxf_file/5.dxf','r')
            except:
                print('open file err')
                return
            dxf = DataDXF(file)
            tmp = dxf.readDXF()
            #-----------------------------
            print('get_data')
            if self.area.get_data(tmp) == False:
                return
            '''
            #---
            print('cal_point')
            if self.area.cal_point() == False:
                return
            #---
            print('cal_all_line')
            if self.area.cal_all_line(index) == False:
                return
            #---
            print('cal_device_XY')
            if self.area.cal_device_XY(index) == False:
                return
            #-----------------------------
            self.addr_button.setEnabled(True)  # enable cal_button
            self.area.update()
        elif tmp == self.addr_button:
            print('cal_addr')
            if self.area.cal_addr() == False:
                return
            #-----------------------------
            self.area.show_addr_flag = 1
            self.area.update()
        elif tmp == self.ok_button:
            print('ok_button')
            if self.priv_data == None:
                print('self.priv_data is None')
                return None

            x = float(self.X_edit.text())
            y = float(self.Y_edit.text())
            high = float(self.base_high_edit.text())
            if self.base_station_status.isChecked():
                base_status = True
            else:
                base_status = False
            if self.area.change_one_XY(self.priv_data, x, y, high,
                                       base_status) == False:
                return
            if self.area.cal_addr() == False:
                return
            #-----------------------------
            self.area.show_addr_flag = 1
            self.area.update()
Ejemplo n.º 17
0
class LLT_AddWord(QMainWindow):
    def __init__(self):
        super(LLT_AddWord, self).__init__()
        self.w = QWidget()
        self.setCentralWidget(self.w)

        self.verbDic = []
        self.nounDic = []
        self.adjDic = []
        self.phraseDic = []
        self.wordList = []

        self.w.setWindowTitle("Add Word")
        self.w.setGeometry(0, 0, 500, 500)

        self.vRad = QRadioButton("Verb")
        self.vRad.setChecked(True)
        self.nRad = QRadioButton("Noun")
        self.aRad = QRadioButton("Adjective")
        self.pRad = QRadioButton("Phrase")
        self.okBut = QPushButton("OK")
        self.okBut.clicked.connect(self.OK)

        self.entryLab = QLabel("Word: ")
        self.wordEntry = QLineEdit()
        self.wordEntry.setEnabled(False)

        self.tranLab = QLabel("Translation: ")
        self.tranEntry = QLineEdit()
        self.tranEntry.setEnabled(False)

        self.checkBut = QPushButton("Check")
        self.checkBut.clicked.connect(self.check)
        self.saveBut = QPushButton("Save")
        self.saveBut.clicked.connect(self.save)
        self.clearBut = QPushButton("Clear")
        self.clearBut.clicked.connect(self.clear)
        self.newBut = QPushButton("New word")
        self.newBut.clicked.connect(self.new)
        self.exitBut = QPushButton("Exit")
        self.exitBut.clicked.connect(self.exit)

        grid = QGridLayout()

        grid.addWidget(self.vRad, 0, 0)
        grid.addWidget(self.nRad, 0, 1)
        grid.addWidget(self.aRad, 0, 2)
        grid.addWidget(self.pRad, 0, 3)
        grid.addWidget(self.okBut, 0, 4)

        grid.addWidget(self.entryLab, 1, 0)
        grid.addWidget(self.wordEntry, 1, 1, 1, 3)
        grid.addWidget(self.tranLab, 2, 0)
        grid.addWidget(self.tranEntry, 2, 1, 1, 3)

        grid.addWidget(self.checkBut, 3, 0)
        grid.addWidget(self.saveBut, 3, 1)
        grid.addWidget(self.clearBut, 3, 2)
        grid.addWidget(self.newBut, 3, 3)
        grid.addWidget(self.exitBut, 3, 4)

        self.getDics()
        self.setLists()
        self.w.setLayout(grid)
        self.w.show()

    def OK(self):
        self.vRad.setEnabled(False)
        self.nRad.setEnabled(False)
        self.aRad.setEnabled(False)
        self.pRad.setEnabled(False)
        self.okBut.setEnabled(False)
        self.wordEntry.setEnabled(True)
        self.tranEntry.setEnabled(True)

    def check(self):
        word = self.wordEntry.text().upper()
        if word in self.wordList:
            msgBox = QMessageBox()
            msgBox.setText(word + ' already in dictionary')
            msgBox.exec_()
        else:
            msgBox = QMessageBox()
            msgBox.setText(word + ' not in dictionary yet')
            msgBox.exec_()

    def save(self):
        spanWord = self.wordEntry.text().upper()
        tranWord = self.tranEntry.text().upper()
        if spanWord in self.wordList:
            msgBox = QMessageBox()
            msgBox.setText(spanWord + ' already in dictionary')
            msgBox.exec_()
        else:
            self.wordList.append(spanWord)
            newWord = [spanWord, tranWord]
            self.wordEntry.setEnabled(False)
            self.tranEntry.setEnabled(False)
            if self.vRad.isChecked():
                self.verbDic.append(newWord)
                v = open('verb.txt', 'w')
                json.dump(self.verbDic, v)
                v.close()
            elif self.nRad.isChecked():
                self.nounDic.append(newWord)
                n = open('noun.txt', 'w')
                json.dump(self.nounDic, n)
                n.close()
            elif self.aRad.isChecked():
                self.adjDic.append(newWord)
                a = open('adj.txt', 'w')
                json.dump(self.adjDic, a)
                a.close()
            elif self.pRad.isChecked():
                self.phraseDic.append(newWord)
                p = open('phrase.txt', 'w')
                json.dump(self.phraseDic, p)
                p.close()

            else:
                msgBox = QMessageBox()
                msgBox.setText(
                    "You must select a dictionary before saving word.")
                msgBox.exec_()

    def clear(self):
        self.vRad.setEnabled(True)
        self.nRad.setEnabled(True)
        self.aRad.setEnabled(True)
        self.pRad.setEnabled(True)
        self.okBut.setEnabled(True)
        self.wordEntry.setEnabled(False)
        self.tranEntry.setEnabled(False)
        self.wordEntry.clear()
        self.tranEntry.clear()

    def new(self):
        self.vRad.setEnabled(True)
        self.nRad.setEnabled(True)
        self.aRad.setEnabled(True)
        self.pRad.setEnabled(True)
        self.okBut.setEnabled(True)
        self.wordEntry.setEnabled(False)
        self.tranEntry.setEnabled(False)
        self.wordEntry.clear()
        self.tranEntry.clear()

    def exit(self):
        confirm = QMessageBox.question(self.w, 'Quit',
                                       'Are you sure you want to exit?',
                                       QMessageBox.Yes | QMessageBox.No)
        if confirm == QMessageBox.Yes:
            self.close()
        else:
            pass

    def getDics(self):
        try:
            v = open('verb.txt', 'r')
            self.verbDic = json.load(v)
            v.close()
        except:
            self.verbDic = []

        try:
            n = open('noun.txt', 'r')
            self.nounDic = json.load(n)
            n.close()
        except:
            self.nounDic = []

        try:
            p = open('phrase.txt', 'r')
            self.phraseDic = json.load(p)
            p.close()
        except:
            self.phraseDic = []

        try:
            a = open('adj.txt', 'r')
            self.adjDic = json.load(a)
            a.close()
        except:
            self.phraseDic = []

    def setLists(self):
        for item in self.verbDic:
            self.wordList.append(item[0])
        for item in self.nounDic:
            self.wordList.append(item[0])
        for item in self.phraseDic:
            self.wordList.append(item[0])
        for item in self.adjDic:
            self.wordList.append(item[0])
Ejemplo n.º 18
0
class Layout(QWidget):

    def config(self):
        self.config_checkbox = QCheckBox('Config')
        self.layout.addWidget(self.config_checkbox)

    def mode_radio(self):
        self.fu1 = QRadioButton("FU1")
        self.controls.addWidget(self.fu1)

        self.fu2 = QRadioButton("FU2")
        self.controls.addWidget(self.fu2)

        self.fu3 = QRadioButton("FU3")
        self.controls.addWidget(self.fu3)

        self.fu4 = QRadioButton("FU4")
        self.controls.addWidget(self.fu4)

    def baudrate_select(self):
        self.baud_rate_combobox = QComboBox()
        self.baud_rate_combobox.addItems(list_to_strings([1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200]))
        self.controls.addLayout(titled_widget('Baud rate', self.baud_rate_combobox))

    def channel(self):
        self.channel_spinbox = QSpinBox()
        self.channel_spinbox.setMaximum(127)
        self.controls.addLayout(titled_widget('Channel', self.channel_spinbox))

    def address(self):
        self.address_spinbox = QSpinBox()
        self.address_spinbox.setMaximum(255)
        self.layout.addLayout(titled_widget('Address', self.address_spinbox))

    def power(self):
        self.power_combobox = QComboBox()
        self.power_combobox.addItems(list_to_strings(range(1, 9)))
        self.controls.addLayout(titled_widget('Power', self.power_combobox))

    def switch_controls(self, state: bool):
        self.fu1.setEnabled(state)
        self.fu2.setEnabled(state)
        self.fu3.setEnabled(state)
        self.fu4.setEnabled(state)

        self.baud_rate_combobox.setEnabled(state)
        self.channel_spinbox.setEnabled(state)
        self.address_spinbox.setEnabled(state)
        self.power_combobox.setEnabled(state)

    def __init__(self):
        super().__init__()
        self.layout = QHBoxLayout()
        self.controls = QHBoxLayout()

        self.config()
        self.layout.addLayout(self.controls)

        self.mode_radio()
        self.baudrate_select()
        self.channel()
        self.address()
        self.power()

        self.config_checkbox.stateChanged.connect(lambda x: self.switch_controls(x > 0))

        self.get_params_button = QPushButton('Get params')
        self.layout.addWidget(self.get_params_button)

        self.read_all = QPushButton('Read all')
        self.layout.addWidget(self.read_all)

        self.setLayout(self.layout)
        self.show()
Ejemplo n.º 19
0
class OmniRigQTControls:
    def __init__(self, operatingAsClient, sendCommandFunction=None):
        self.operatingAsClient = operatingAsClient
        self.omnirigObject = None
        self.omniRigInfo = {}
        self.sendCommandFunction = sendCommandFunction
        self.blackColorPalette = QPalette()
        self.blackColorPalette.setColor(QPalette.WindowText, QColor("black"))
        self.redColorPalette = QPalette()
        self.redColorPalette.setColor(QPalette.WindowText, QColor("red"))
        self.boldFont = QFont()
        self.boldFont.setBold(True)
        self.regularFont = QFont()
        self.regularFont.setBold(False)

        self.labelRigName = QLabel("Rig is not responding")
        self.rigSelectGroupBox = QGroupBox("Rig select:")

        self.radioBtnTRX1 = QRadioButton("Rig 1")
        self.radioBtnTRX1.setChecked(True)
        self.radioBtnTRX1.toggled.connect(self.refreshRigInformation)
        self.radioBtnTRX2 = QRadioButton("Rig 2")
        self.radioBtnTRX2.toggled.connect(self.refreshRigInformation)

        hboxRigSelect = QHBoxLayout()
        hboxRigSelect.addWidget(self.radioBtnTRX1)
        hboxRigSelect.addWidget(self.radioBtnTRX2)
        hboxRigSelect.addWidget(self.labelRigName)
        hboxRigSelect.addStretch()
        self.rigSelectGroupBox.setLayout(hboxRigSelect)
        self.rigSelectGroupBox.setMaximumWidth(360)

        self.lcdTrxFrequency = QLCDNumber(10)
        self.lcdTrxFrequency.display('00.000.00')
        self.lcdTrxFrequency.setPalette(self.blackColorPalette)
        self.lcdTrxFrequency.setMinimumHeight(50)
        self.lcdTrxFrequency.setMaximumHeight(50)
        self.lcdTrxFrequency.setMaximumWidth(275)
        self.lcdTrxFrequency.setMinimumWidth(275)

        self.labelRigModeLSB = QLabel('LSB')
        self.labelRigModeLSB.setFont(self.boldFont)
        self.labelRigModeLSB.setEnabled(False)

        self.labelRigModeUSB = QLabel('USB')
        self.labelRigModeUSB.setFont(self.boldFont)
        self.labelRigModeUSB.setEnabled(False)

        vboxMiddlePanel = QVBoxLayout()
        vboxMiddlePanel.addWidget(self.labelRigModeLSB)
        vboxMiddlePanel.addWidget(self.labelRigModeUSB)

        hboxMiddlePanel = QHBoxLayout()
        hboxMiddlePanel.addLayout(vboxMiddlePanel)
        hboxMiddlePanel.addStretch()

        self.btnBack500Hz = QPushButton("<--")
        self.btnBack500Hz.setFixedWidth(50)

        self.btnForward500Hz = QPushButton("-->")
        self.btnForward500Hz.setFixedWidth(50)
        self.btnForward500Hz.clicked.connect(self.btnOmniRigPlus500HzClick)

        self.btnOmniRigUSB = QPushButton("USB")
        self.btnOmniRigUSB.clicked.connect(self.btnOmniUSBClick)
        self.btnOmniRigUSB.setFixedWidth(50)

        self.btnOmniRigLSB = QPushButton("LSB")
        self.btnOmniRigLSB.clicked.connect(self.btnOmniLSBClick)
        self.btnOmniRigLSB.setFixedWidth(50)

        hboxRigCATControl = QHBoxLayout()
        hboxRigCATControl.addWidget(self.btnBack500Hz)
        hboxRigCATControl.addWidget(self.btnForward500Hz)
        hboxRigCATControl.addStretch()
        hboxRigCATControl.addWidget(self.btnOmniRigLSB)
        hboxRigCATControl.addWidget(self.btnOmniRigUSB)
        hboxRigCATControl.addStretch(1)

        hboxMainLayout = QHBoxLayout()
        hboxMainLayout.addWidget(self.lcdTrxFrequency)
        hboxMainLayout.addLayout(hboxMiddlePanel)

        self.vboxMainLayout = QVBoxLayout()
        self.vboxMainLayout.addWidget(self.rigSelectGroupBox)
        self.vboxMainLayout.addLayout(hboxMainLayout)
        if self.operatingAsClient is True:
            self.vboxMainLayout.addLayout(hboxRigCATControl)

    def setOmnirigObject(self, omnirigObject):
        self.omnirigObject = omnirigObject

    def btnOmniRigPlus500HzClick(self):
        try:
            self.omnirigObject = win32.Dispatch("OmniRig.OmniRigX")
        except:
            pass
        if self.omnirigObject is not None and self.operatingAsClient is False:
            if self.radioBtnTRX1.isChecked():
                self.omnirigObject.Rig1.SetSimplexMode(str(self.omnirigObject.Rig1.Freq+500))
            else:
                self.omnirigObject.Rig2.SetSimplexMode(str(self.omnirigObject.Rig1.Freq+500))
        if self.operatingAsClient is True and self.sendCommandFunction is not None:
            self.sendCommandFunction('+500=1')

    def btnOmniLSBClick(self):
        try:
            self.omnirigObject = win32.Dispatch("OmniRig.OmniRigX")
        except:
            pass
        if self.omnirigObject is not None and self.operatingAsClient is False:
            if self.radioBtnTRX1.isChecked():
                self.omnirigObject.Rig1.Mode = '67108864'
            else:
                self.omnirigObject.Rig2.Mode = '67108864'
        if self.operatingAsClient is True and self.sendCommandFunction is not None:
            self.sendCommandFunction('setLSB=1')

    def btnOmniUSBClick(self):
        try:
            self.omnirigObject = win32.Dispatch("OmniRig.OmniRigX")
        except:
            pass
        if self.omnirigObject is not None and self.operatingAsClient is False:
            if self.radioBtnTRX1.isChecked():
                self.omnirigObject.Rig1.Mode = '33554432'
            else:
                self.omnirigObject.Rig2.Mode = '33554432'

        if self.operatingAsClient is True and self.sendCommandFunction is not None:
            self.sendCommandFunction('setUSB=1')

    def setDisplayFreq(self, txtFreq):
        self.lcdTrxFrequency.display(txtFreq)

    def setOmniRigErrorText(self, msgText):
        self.labelRigName.setText(msgText)
        self.labelRigName.setPalette(self.redColorPalette)

    def setRigStatus(self, rigType):
        self.labelRigName.setText(rigType)
        self.labelRigName.setPalette(self.blackColorPalette)

    def getRigsInformation(self):
        return self.omniRigInfo

    def disableControls(self):
        self.radioBtnTRX1.setEnabled(False)
        self.radioBtnTRX2.setEnabled(False)

    def refreshRigInformation(self):
        rignum = '2'
        if self.radioBtnTRX1.isChecked():
            rignum = '1'
        if len(self.omniRigInfo) > 1:
            self.radioBtnTRX1.setText(self.omniRigInfo['1'].getRigType())
            self.radioBtnTRX2.setText(self.omniRigInfo['2'].getRigType())
            freqTxt = self.omniRigInfo[rignum].getRigFreq()
            self.setDisplayFreq(self.addDotsToFreq(freqTxt))
            self.setRigStatus(self.omniRigInfo[rignum].getRigStatus())

            if freqTxt == 0:
                self.labelRigModeUSB.setEnabled(False)
                self.labelRigModeLSB.setEnabled(False)
            else:
                if self.omniRigInfo[rignum].getRigMode() == 'LSB':
                    self.labelRigModeUSB.setEnabled(False)
                    self.labelRigModeLSB.setEnabled(True)
                else:
                    self.labelRigModeUSB.setEnabled(True)
                    self.labelRigModeLSB.setEnabled(False)

    def setRigInformation(self, omniRigInfo):
        self.omniRigInfo = omniRigInfo
        self.refreshRigInformation()

    def addDotsToFreq(self, freqvalue):
        freqTxt = str(freqvalue)
        if len(freqTxt) < 6:
            freqTxt = '00000000'

        firstPart = freqTxt[:-6]
        if len(freqTxt) == 8:
            mainPart = freqTxt[:7]
            middlePart = mainPart[2:5]
            lastPart = mainPart[5:]
        else:
            mainPart = freqTxt[:6]
            middlePart = mainPart[1:4]
            lastPart = mainPart[4:]

        return firstPart+"."+middlePart+"."+lastPart

    def getGUI(self):
        return self.vboxMainLayout
Ejemplo n.º 20
0
class MainUI(QWidget):
    def __init__(self, status_bar):
        super().__init__()
        self.tables = dict()
        self.tables_for_ui = dict()
        self.dbs = list()
        self.prod_db_list = list()
        self.test_db_list = list()
        self.prod_tables = dict()
        self.test_tables = dict()
        self.columns = list()
        self.prod_connect = False
        self.test_connect = False
        self.logging_level = logging.DEBUG
        self.logger = logging.getLogger("dbComparator")
        self.logger.setLevel(level=self.logging_level)
        formatter = logging.Formatter(
            '%(asctime)s [%(levelname)s] - %(message)s')
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        self.logger.addHandler(ch)
        self._toggle = True
        self.OS = operating_system
        if self.OS == "Windows":
            # TODO: add creation of both directories below
            self.service_dir = "C:\\comparator\\"
            self.test_dir = "C:\\comparator\\test_results\\"
        else:
            self.service_dir = os.path.expanduser('~') + "/comparator/"
            Path(self.service_dir).mkdir(parents=True, exist_ok=True)
            self.test_dir = os.path.expanduser(
                '~') + "/comparator/test_results/"
            Path(self.test_dir).mkdir(parents=True, exist_ok=True)
        fh = logging.FileHandler(self.service_dir + 'dbcomparator.log')
        fh.setLevel(self.logging_level)
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)
        self.logger.debug('File handler added successfully')
        self.logger.info('Logger successfully initialized')
        self.statusBar = status_bar
        grid = QGridLayout()
        grid.setSpacing(10)
        self.setLayout(grid)

        # Labels

        self.prod_host_label = QLabel('prod.sql-host')
        self.prod_user_label = QLabel('prod.sql-user', self)
        self.prod_password_label = QLabel('prod.sql-password', self)
        self.prod_db_label = QLabel('prod.sql-db', self)
        self.prod_db_label.hide()
        self.test_host_label = QLabel('test.sql-host', self)
        self.test_user_label = QLabel('test.sql-user', self)
        self.test_password_label = QLabel('test.sql-password', self)
        self.test_db_label = QLabel('test.sql-db', self)
        self.test_db_label.hide()
        self.send_mail_to_label = QLabel('Send mail to', self)
        self.checking_mode_label = QLabel('Checking mode:', self)
        self.only_tables_label = QLabel('Only tables', self)
        self.excluded_tables_label = QLabel('Skip tables', self)
        self.hide_columns_label = QLabel('Skip columns', self)

        # Line edits

        self.le_prod_host = QLineEdit(self)
        self.le_prod_host.textChanged.connect(
            lambda: self.check_sqlhost('prod'))
        self.le_prod_user = QLineEdit(self)
        self.le_prod_user.textChanged.connect(
            lambda: self.check_sqlhost('prod'))
        self.le_prod_password = QLineEdit(self)
        self.le_prod_password.setEchoMode(QLineEdit.Password)
        self.le_prod_password.textChanged.connect(
            lambda: self.check_sqlhost('prod'))
        self.le_prod_db = ClickableLineEdit(self)
        self.le_prod_db.textChanged.connect(lambda: self.check_db('prod'))
        self.le_prod_db.clicked.connect(self.set_prod_db)
        self.le_prod_db.hide()
        self.le_test_host = QLineEdit(self)
        self.le_test_host.textChanged.connect(
            lambda: self.check_sqlhost('test'))
        self.le_test_user = QLineEdit(self)
        self.le_test_user.textChanged.connect(
            lambda: self.check_sqlhost('test'))
        self.le_test_password = QLineEdit(self)
        self.le_test_password.setEchoMode(QLineEdit.Password)
        self.le_test_password.textChanged.connect(
            lambda: self.check_sqlhost('test'))
        self.le_test_db = ClickableLineEdit(self)
        self.le_test_db.textChanged.connect(lambda: self.check_db('test'))
        self.le_test_db.clicked.connect(self.set_test_db)
        self.le_test_db.hide()
        self.le_send_mail_to = QLineEdit(self)
        self.le_excluded_tables = ClickableLineEdit(self)
        self.le_excluded_tables.clicked.connect(self.set_excluded_tables)
        self.le_only_tables = ClickableLineEdit(self)
        self.le_only_tables.clicked.connect(self.set_included_tables)
        self.le_skip_columns = ClickableLineEdit(self)
        self.le_skip_columns.clicked.connect(self.set_excluded_columns)

        # Checkboxes

        self.cb_enable_schema_checking = QCheckBox('Compare schema', self)
        self.cb_enable_schema_checking.toggle()
        self.cb_fail_with_first_error = QCheckBox('Only first error', self)
        self.cb_fail_with_first_error.toggle()
        self.cb_reports = QCheckBox('Reports', self)
        self.cb_reports.setChecked(self._toggle)
        self.cb_reports.clicked.connect(self.toggle)
        self.cb_entities = QCheckBox('Entities and others', self)
        self.cb_entities.setChecked(self._toggle)
        self.cb_entities.clicked.connect(self.toggle)
        self.cb_enable_dataframes = QCheckBox('Enable dataframes', self)
        self.cb_enable_dataframes.toggle()
        self.cb_enable_dataframes.setChecked(False)

        # Buttons

        self.btn_set_configuration = QPushButton('       Compare!       ',
                                                 self)
        self.btn_set_configuration.setShortcut('Ctrl+G')
        self.btn_set_configuration.clicked.connect(self.start_work)
        self.btn_set_configuration.setEnabled(False)
        self.btn_clear_all = QPushButton('Clear all', self)
        self.btn_clear_all.clicked.connect(self.clear_all)
        self.btn_advanced = QPushButton('Advanced', self)
        self.btn_advanced.clicked.connect(self.advanced)

        # Radiobuttons

        self.day_summary_mode = QRadioButton('Day summary')
        self.day_summary_mode.setChecked(True)
        self.section_summary_mode = QRadioButton('Section summary')
        self.section_summary_mode.setChecked(False)
        self.detailed_mode = QRadioButton('Detailed')
        self.detailed_mode.setChecked(False)

        self.set_default_values()

        # Set tooltips

        self.prod_host_label.setToolTip(
            'Input host, where prod-db located.\nExample: samaradb03.maxifier.com'
        )
        self.le_prod_host.setToolTip(self.le_prod_host.text())
        self.prod_user_label.setToolTip(
            'Input user for connection to prod-db.\nExample: itest')
        self.le_prod_user.setToolTip(self.le_prod_user.text())
        self.prod_password_label.setToolTip(
            'Input password for user from prod.sql-user field')
        self.prod_db_label.setToolTip('Input prod-db name.\nExample: irving')
        self.le_prod_db.setToolTip(self.le_prod_db.text())
        self.test_host_label.setToolTip(
            'Input host, where test-db located.\nExample: samaradb03.maxifier.com'
        )
        self.le_test_host.setToolTip(self.le_test_host.text())
        self.test_user_label.setToolTip(
            'Input user for connection to test-db.\nExample: itest')
        self.le_test_user.setToolTip(self.le_test_user.text())
        self.test_password_label.setToolTip(
            'Input password for user from test.sql-user field')
        self.test_db_label.setToolTip('Input test-db name.\nExample: irving')
        self.le_test_db.setToolTip(self.le_test_db.text())
        self.cb_enable_schema_checking.setToolTip(
            'If you set this option, program will compare also schemas of dbs')
        self.cb_fail_with_first_error.setToolTip(
            'If you set this option, comparing will be finished after first error'
        )
        self.send_mail_to_label.setToolTip(
            'Add one or list of e-mails for receiving results of comparing')
        self.le_send_mail_to.setToolTip(self.le_send_mail_to.text().replace(
            ',', ',\n'))
        self.only_tables_label.setToolTip(
            'Set comma-separated list of tables, which should be compared')
        self.le_only_tables.setToolTip(self.le_only_tables.text().replace(
            ',', ',\n'))
        self.excluded_tables_label.setToolTip(
            'Set tables, which should not be checked')
        self.le_excluded_tables.setToolTip(
            self.le_excluded_tables.text().replace(',', ',\n'))
        self.hide_columns_label.setToolTip(
            'Set columns, which should not be compared during checking')
        self.le_skip_columns.setToolTip(self.le_skip_columns.text().replace(
            ',', ',\n'))
        self.checking_mode_label.setToolTip('Select type of checking')
        self.day_summary_mode.setToolTip(
            'Compare sums of impressions for each date')
        self.section_summary_mode.setToolTip(
            'Compare sums of impressions for each date and each section')
        self.detailed_mode.setToolTip(
            'Compare all records from table for setted period')
        self.btn_clear_all.setToolTip('Reset all fields to default values')
        self.btn_set_configuration.setToolTip('Start comparing of dbs')

        grid.addWidget(self.prod_host_label, 0, 0)
        grid.addWidget(self.le_prod_host, 0, 1)
        grid.addWidget(self.prod_user_label, 1, 0)
        grid.addWidget(self.le_prod_user, 1, 1)
        grid.addWidget(self.prod_password_label, 2, 0)
        grid.addWidget(self.le_prod_password, 2, 1)
        grid.addWidget(self.prod_db_label, 3, 0)
        grid.addWidget(self.le_prod_db, 3, 1)
        grid.addWidget(self.test_host_label, 0, 2)
        grid.addWidget(self.le_test_host, 0, 3)
        grid.addWidget(self.test_user_label, 1, 2)
        grid.addWidget(self.le_test_user, 1, 3)
        grid.addWidget(self.test_password_label, 2, 2)
        grid.addWidget(self.le_test_password, 2, 3)
        grid.addWidget(self.test_db_label, 3, 2)
        grid.addWidget(self.le_test_db, 3, 3)
        grid.addWidget(self.send_mail_to_label, 6, 0)
        grid.addWidget(self.le_send_mail_to, 6, 1)
        grid.addWidget(self.only_tables_label, 7, 0)
        grid.addWidget(self.le_only_tables, 7, 1)
        grid.addWidget(self.excluded_tables_label, 8, 0)
        grid.addWidget(self.le_excluded_tables, 8, 1)
        grid.addWidget(self.hide_columns_label, 9, 0)
        grid.addWidget(self.le_skip_columns, 9, 1)
        grid.addWidget(self.cb_enable_schema_checking, 10, 0)
        grid.addWidget(self.cb_fail_with_first_error, 11, 0)
        grid.addWidget(self.cb_reports, 10, 1)
        grid.addWidget(self.cb_entities, 11, 1)
        grid.addWidget(self.cb_enable_dataframes, 10, 2)
        grid.addWidget(self.checking_mode_label, 6, 3)
        grid.addWidget(self.day_summary_mode, 7, 3)
        grid.addWidget(self.section_summary_mode, 8, 3)
        grid.addWidget(self.detailed_mode, 9, 3)
        grid.addWidget(self.btn_clear_all, 5, 1)
        grid.addWidget(self.btn_advanced, 10, 3)
        grid.addWidget(self.btn_set_configuration, 11, 3)

        self.setWindowTitle('dbComparator')
        self.setWindowIcon(QIcon('./resources/slowpoke.png'))
        self.show()

    def get_only_reports(self):
        result = dict()
        for table in self.tables:
            if self.tables.get(table).get('is_report'):
                columns = self.tables.get(table).get('columns')
                result.update({table: columns})
            else:
                continue
        return result

    def get_only_entities(self):
        result = dict()
        for table in self.tables:
            if not self.tables.get(table).get('is_report'):
                columns = self.tables.get(table).get('columns')
                result.update({table: columns})
            else:
                continue
        return result

    @pyqtSlot()
    def toggle(self):
        if all([self.cb_entities.isChecked(), self.cb_reports.isChecked()]):
            self.cb_entities.setEnabled(True)
            self.cb_reports.setEnabled(True)
            self.day_summary_mode.setEnabled(True)
            self.section_summary_mode.setEnabled(True)
            self.detailed_mode.setEnabled(True)
            self.tables_for_ui = self.tables.copy()
        elif self.cb_entities.isChecked():
            self.cb_entities.setEnabled(False)
            self.day_summary_mode.setEnabled(False)
            self.section_summary_mode.setEnabled(False)
            self.detailed_mode.setEnabled(False)
            self.tables_for_ui = self.get_only_entities()
        elif self.cb_reports.isChecked():
            self.cb_reports.setEnabled(False)
            self.day_summary_mode.setEnabled(True)
            self.section_summary_mode.setEnabled(True)
            self.detailed_mode.setEnabled(True)
            self.tables_for_ui = self.get_only_reports()

    def clear_all(self):
        self.le_prod_host.clear()
        self.le_prod_user.clear()
        self.le_prod_password.clear()
        self.le_prod_db.clear()
        self.le_test_host.clear()
        self.le_test_user.clear()
        self.le_test_password.clear()
        self.le_test_db.clear()
        self.le_send_mail_to.clear()
        self.le_only_tables.clear()
        self.set_default_values()
        self.prod_db_label.hide()
        self.le_prod_db.hide()
        self.test_db_label.hide()
        self.le_test_db.hide()
        self.statusBar.showMessage('Prod disconnected, test disconnected')

    def advanced(self):
        defaults = {
            'logging_level': self.logging_level,
            'comparing_step': self.comparing_step,
            'depth_report_check': self.depth_report_check,
            'schema_columns': self.schema_columns,
            'retry_attempts': self.retry_attempts,
            'path_to_logs': self.path_to_logs,
            'table_timeout': self.table_timeout,
            'strings_amount': self.strings_amount
        }
        self.adv = AdvancedSettingsItem(operating_system, defaults)
        self.adv.exec_()
        self.logging_level = self.adv.logging_level
        self.logger.setLevel(self.logging_level)
        self.comparing_step = self.adv.comparing_step
        self.depth_report_check = self.adv.depth_report_check
        self.schema_columns = self.adv.schema_columns
        self.retry_attempts = self.adv.retry_attempts
        self.path_to_logs = self.adv.path_to_logs
        self.table_timeout = self.adv.table_timeout
        self.strings_amount = self.adv.strings_amount

    def calculate_table_list(self):
        if all([self.prod_connect, self.test_connect]):
            tables = list(
                set(self.prod_tables.keys()) & set(self.test_tables.keys()))
            tables.sort()
            for table in tables:
                prod_columns = self.prod_tables.get(table).get('columns')
                test_columns = self.test_tables.get(table).get('columns')
                if prod_columns == test_columns:
                    self.tables.update({table: self.prod_tables.get(table)})
                else:
                    self.logger.error(
                        f"There is different columns for table {table}.")
                    self.logger.warning(
                        f"Table {table} excluded from comparing")
                    prod_uniq_columns = set(prod_columns) - set(test_columns)
                    test_uniq_columns = set(test_columns) - set(prod_columns)
                    if prod_uniq_columns:
                        self.logger.info(
                            f"Uniq columns for prod {table}: {prod_uniq_columns}"
                        )
                    if test_uniq_columns:
                        self.logger.info(
                            f"Uniq columns for test {table}: {test_uniq_columns}"
                        )
            self.tables_for_ui = self.tables.copy()
            self.calculate_excluded_columns()

    def calculate_excluded_columns(self):
        excluded_tables = self.le_excluded_tables.text().split(',')
        self.columns = list()
        for table in self.tables_for_ui:
            if table not in excluded_tables:
                columns = self.tables_for_ui.get(table)
                for column in columns:
                    if column not in self.columns:
                        self.columns.append(column)
        self.columns.sort()

    def set_default_values(self):
        self.le_excluded_tables.setText(
            'databasechangelog,download,migrationhistory,mntapplog,reportinfo,'
            +
            'synchistory,syncstage,synctrace,synctracelink,syncpersistentjob,'
            + 'forecaststatistics,migrationhistory')
        self.le_excluded_tables.setCursorPosition(0)
        self.le_skip_columns.setText(
            'archived,addonFields,hourOfDayS,dayOfWeekS,impCost,id')
        self.le_skip_columns.setCursorPosition(0)
        self.comparing_step = 10000
        self.depth_report_check = 7
        self.schema_columns = (
            'TABLE_CATALOG,TABLE_NAME,COLUMN_NAME,ORDINAL_POSITION,COLUMN_DEFAULT,'
            +
            'IS_NULLABLE,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,CHARACTER_OCTET_LENGTH,'
            +
            'NUMERIC_PRECISION,NUMERIC_SCALE,DATETIME_PRECISION,CHARACTER_SET_NAME,'
            +
            'COLLATION_NAME,COLUMN_TYPE,COLUMN_KEY,EXTRA,COLUMN_COMMENT,GENERATION_EXPRESSION'
        )
        self.retry_attempts = 5
        if operating_system == 'Windows':
            # TODO: add defining disc
            if not os.path.exists('C:\\DbComparator\\'):
                os.mkdir('C:\\DbComparator\\')
            self.path_to_logs = 'C:\\DbComparator\\DbComparator.log'
        elif operating_system == 'Linux':
            log_path = os.path.expanduser('~') + '/DbComparator/'
            if not os.path.exists(log_path):
                os.mkdir(log_path)
            self.path_to_logs = log_path + 'DbComparator.log'
        self.table_timeout = 5
        self.strings_amount = 1000
        self.cb_enable_schema_checking.setChecked(True)
        self.cb_fail_with_first_error.setChecked(True)
        self.day_summary_mode.setChecked(True)
        self.section_summary_mode.setChecked(False)
        self.detailed_mode.setChecked(False)
        self.logging_level = 'DEBUG'

    def set_prod_db(self):
        prod_db = self.le_prod_db.text()
        select_db_view = RadiobuttonItemsView(self.prod_db_list, prod_db)
        select_db_view.exec_()
        self.le_prod_db.setText(select_db_view.selected_db)
        self.le_prod_db.setToolTip(self.le_prod_db.text())

    def set_test_db(self):
        test_db = self.le_test_db.text()
        select_db_view = RadiobuttonItemsView(self.test_db_list, test_db)
        select_db_view.exec_()
        self.le_test_db.setText(select_db_view.selected_db)
        self.le_test_db.setToolTip(self.le_test_db.text())

    def set_excluded_tables(self):
        if all([self.prod_connect, self.test_connect]):
            tables_to_skip = self.le_excluded_tables.text().split(',')
            skip_tables_view = ClickableItemsView(self.tables_for_ui,
                                                  tables_to_skip)
            skip_tables_view.exec_()
            self.le_excluded_tables.setText(','.join(
                skip_tables_view.selected_items))
            self.le_excluded_tables.setToolTip(
                self.le_excluded_tables.text().replace(',', ',\n'))
            self.calculate_excluded_columns()

    def set_included_tables(self):
        if all([self.prod_connect, self.test_connect]):
            tables_to_include = self.le_only_tables.text().split(',')
            only_tables_view = ClickableItemsView(self.tables_for_ui,
                                                  tables_to_include)
            only_tables_view.exec_()
            self.le_only_tables.setText(','.join(
                only_tables_view.selected_items))
            self.le_only_tables.setToolTip(self.le_only_tables.text().replace(
                ',', ',\n'))

    def set_excluded_columns(self):
        columns_to_skip = self.le_skip_columns.text().split(',')
        skip_columns = ClickableItemsView(self.columns, columns_to_skip)
        skip_columns.exec_()
        self.le_skip_columns.setText(','.join(skip_columns.selected_items))
        self.le_skip_columns.setToolTip(self.le_skip_columns.text().replace(
            ',', ',\n'))

    @staticmethod
    def set_value(widget, value):
        widget.setText(value)
        widget.setCursorPosition(0)

    def load_configuration(self):
        current_dir = f'{os.getcwd()}/resources/properties/'
        fname = QFileDialog.getOpenFileName(PyQt5.QtWidgets.QFileDialog(),
                                            'Open file', current_dir)[0]
        self.clear_all()
        try:
            with open(fname, 'r') as file:
                data = file.read()
                for record in data.split('\n'):
                    string = record.replace(' ', '')
                    value = string[string.find('=') + 1:]
                    if 'prod.host' in string:
                        self.set_value(self.le_prod_host, value)
                    if 'prod.user' in string:
                        self.set_value(self.le_prod_user, value)
                    if 'prod.password' in string:
                        self.set_value(self.le_prod_password, value)
                    if 'prod.db' in string:
                        self.le_prod_db.show()
                        self.prod_db_label.show()
                        self.set_value(self.le_prod_db, value)
                    elif 'test.host' in string:
                        self.set_value(self.le_test_host, value)
                    elif 'test.user' in string:
                        self.set_value(self.le_test_user, value)
                    elif 'test.password' in string:
                        self.set_value(self.le_test_password, value)
                    elif 'test.db' in string:
                        self.test_db_label.show()
                        self.le_test_db.show()
                        self.set_value(self.le_test_db, value)
                    elif 'only_tables' in string:
                        tmp = ''
                        for table in value.split(','):
                            if self.tables:
                                if table in self.tables:
                                    tmp = tmp + table + ','
                                else:
                                    self.logger.warning(
                                        f'Table {table} excluded from only_table section '
                                        f'because it differs on both databases'
                                    )
                        self.set_value(self.le_only_tables, tmp)
                    elif 'skip_tables' in string:
                        self.set_value(self.le_excluded_tables, value)
                    elif 'comparing_step' in string:
                        self.comparing_step = value
                    elif 'depth_report_check' in string:
                        self.depth_report_check = value
                    elif 'schema_columns' in string:
                        self.schema_columns = value
                    elif 'retry_attempts' in string:
                        self.retry_attempts = value
                    elif 'path_to_logs' in string:
                        self.path_to_logs = value
                    elif 'send_mail_to' in string:
                        self.set_value(self.le_send_mail_to, value)
                    elif 'skip_columns' in string:
                        self.set_value(self.le_skip_columns, value)
                    elif 'compare_schema' in string:
                        compare_schema = value
                        if compare_schema == 'True':
                            if self.cb_enable_schema_checking.isChecked():
                                pass
                            else:
                                self.cb_enable_schema_checking.setChecked(True)
                        else:
                            if self.cb_enable_schema_checking.isChecked():
                                self.cb_enable_schema_checking.setChecked(
                                    False)
                            else:
                                pass
                    elif 'fail_with_first_error' in string:
                        only_first_error = value
                        if only_first_error == 'True':
                            if self.cb_fail_with_first_error.isChecked():
                                pass
                            else:
                                self.cb_fail_with_first_error.setChecked(True)
                        else:
                            if self.cb_fail_with_first_error.isChecked():
                                self.cb_fail_with_first_error.setChecked(False)
                            else:
                                pass
                    elif 'reports' in string:
                        reports = value
                        if reports == 'True':
                            if self.cb_reports.isChecked():
                                pass
                            else:
                                self.cb_reports.setChecked(True)
                        else:
                            if self.cb_reports.isChecked():
                                self.cb_reports.setChecked(False)
                            else:
                                pass
                    elif 'entities' in string:
                        entities = value
                        if entities == 'True':
                            if self.cb_entities.isChecked():
                                pass
                            else:
                                self.cb_entities.setChecked(True)
                        else:
                            if self.cb_entities.isChecked():
                                self.cb_entities.setChecked(False)
                            else:
                                pass
                    elif 'logging_level' in string:
                        self.logging_level = value
                    elif 'table_timeout' in string:
                        self.table_timeout = value
                    elif 'mode' in string:
                        mode = value
                        if mode == 'day-sum':
                            self.day_summary_mode.setChecked(True)
                        elif mode == 'section-sum':
                            self.section_summary_mode.setChecked(True)
                        else:
                            self.detailed_mode.setChecked(True)
        except FileNotFoundError as err:
            self.logger.warning(
                f'File not found, or, probably, you just pressed cancel. Warn: {err.args[1]}'
            )

        # Set tooltips

        self.le_prod_host.setToolTip(self.le_prod_host.text())
        self.le_prod_user.setToolTip(self.le_prod_user.text())
        self.le_prod_db.setToolTip(self.le_prod_db.text())
        self.le_test_host.setToolTip(self.le_test_host.text())
        self.le_test_user.setToolTip(self.le_test_user.text())
        self.le_test_db.setToolTip(self.le_test_db.text())
        self.le_only_tables.setToolTip(self.le_only_tables.text().replace(
            ',', ',\n'))
        self.le_excluded_tables.setToolTip(
            self.le_excluded_tables.text().replace(',', ',\n'))
        self.le_skip_columns.setToolTip(self.le_skip_columns.text().replace(
            ',', ',\n'))
        self.le_send_mail_to.setToolTip(self.le_send_mail_to.text().replace(
            ',', ',\n'))

    def save_configuration(self):
        text = []
        non_verified = {}
        if self.le_prod_host.text() != '':
            text.append(f'prod.host = {self.le_prod_host.text()}')
        if self.le_prod_user.text() != '':
            text.append(f'prod.user = {self.le_prod_user.text()}')
        if self.le_prod_password.text() != '':
            text.append(f'prod.password = {self.le_prod_password.text()}')
        if self.le_prod_db.text() != '':
            text.append(f'prod.dbt = {self.le_prod_db.text()}')
        if self.le_test_host.text() != '':
            text.append(f'test.host = {self.le_test_host.text()}')
        if self.le_test_user.text() != '':
            text.append(f'test.user = {self.le_test_user.text()}')
        if self.le_test_password.text() != '':
            text.append(f'test.password = {self.le_test_password.text()}')
        if self.le_test_db.text() != '':
            text.append(f'test.db = {self.le_test_db.text()}')
        if self.le_send_mail_to.text() != '':
            raw_array = self.le_send_mail_to.text().split(',')
            raw_array.sort()
            recepients = str(raw_array).strip('[]').replace("'", "").replace(
                ' ', '')
            text.append(f'send_mail_to = {recepients}')
        if self.le_only_tables.text() != '':
            raw_array = self.le_only_tables.text().split(',')
            raw_array.sort()
            table_list = str(raw_array).strip('[]').replace("'", "").replace(
                ' ', '')
            text.append(f'only_tables = {table_list}')
        if self.le_excluded_tables.text() != '':
            raw_array = self.le_excluded_tables.text().split(',')
            raw_array.sort()
            skip_tables = str(raw_array).strip('[]').replace("'", "").replace(
                ' ', '')
            text.append(f'skip_tables = {skip_tables}')
        if self.le_skip_columns.text() != '':
            raw_array = self.le_skip_columns.text().split(',')
            raw_array.sort()
            skip_columns = str(raw_array).strip('[]').replace("'", "").replace(
                ' ', '')
            text.append(f'skip_columns = {skip_columns}')
        if self.comparing_step != '' and self.comparing_step != '10000':
            try:
                int(self.comparing_step)
                text.append(f'comparing_step = {self.comparing_step}')
            except ValueError:
                non_verified.update({'Comparing step': self.comparing_step})
        if self.depth_report_check != '' and self.depth_report_check != '7':
            try:
                int(self.depth_report_check)
                text.append(f'depth_report_check = {self.depth_report_check}')
            except ValueError:
                non_verified.update({'Days in past': self.depth_report_check})
        default_column_text = (
            'TABLE_CATALOG,TABLE_NAME,COLUMN_NAME,ORDINAL_POSITION,COLUMN_DEFAULT,'
            +
            'IS_NULLABLE,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,CHARACTER_OCTET_LENGTH,'
            +
            'NUMERIC_PRECISION,NUMERIC_SCALE,DATETIME_PRECISION,CHARACTER_SET_NAME,COLLATION_NAME,'
            +
            'COLUMN_TYPE,COLUMN_KEY,EXTRA,COLUMN_COMMENT,GENERATION_EXPRESSION'
        )

        if self.schema_columns != '' and self.schema_columns != default_column_text:
            raw_array = self.schema_columns.split(',')
            raw_array.sort()
            schema_columns = str(raw_array).strip('[]').replace("'",
                                                                "").replace(
                                                                    ' ', '')
            text.append(f'schema_columns = {schema_columns}')
        if self.retry_attempts != '' and self.retry_attempts != '5':
            try:
                int(self.retry_attempts)
                text.append(f'retry_attempts = {self.retry_attempts}')
            except ValueError:
                non_verified.update({'Retry attempts': self.retry_attempts})
        if self.path_to_logs != '':
            text.append(f'path_to_logs = {self.path_to_logs}')
        if self.table_timeout != '':
            try:
                int(self.table_timeout)
                text.append(f'table_timeout = {self.table_timeout}')
            except ValueError:
                non_verified.update(
                    {'Timeout for single table': self.table_timeout})
        if self.strings_amount != '':
            try:
                int(self.strings_amount)
                text.append(f'string_amount = {self.strings_amount}')
            except ValueError:
                non_verified.update(
                    {'Amount of stored uniq strings': self.strings_amount})
        if non_verified:
            text = ''
            for item in non_verified.keys():
                text = f'{text}\n{item}: {non_verified.get(item)}'
            QMessageBox.warning(PyQt5.QtWidgets.QMessageBox(), 'Error',
                                (f"Incorrect value(s):\n{text}\n\n" +
                                 "Please, input a number!"), QMessageBox.Ok,
                                QMessageBox.Ok)
            return False
        if self.cb_enable_schema_checking.isChecked():
            text.append('compare_schema = True')
        if not self.cb_enable_schema_checking.isChecked():
            text.append('compare_schema = False')
        if self.cb_fail_with_first_error.isChecked():
            text.append('fail_with_first_error = True')
        if not self.cb_fail_with_first_error.isChecked():
            text.append('fail_with_first_error = False')
        if self.day_summary_mode.isChecked():
            text.append('mode = day-sum')
        elif self.section_summary_mode.isChecked():
            text.append('mode = section-sum')
        elif self.detailed_mode.isChecked():
            text.append('mode = detailed')
        text.append(f'logging_level = {self.logging_level}')
        file_name, _ = QFileDialog.getSaveFileName(
            PyQt5.QtWidgets.QFileDialog(), "QFileDialog.getSaveFileName()", "",
            "All Files (*);;Text Files (*.txt)")
        if file_name:
            with open(file_name, 'w') as file:
                file.write('\n'.join(text))
            print(f'Configuration successfully saved to {file_name}'
                  )  # TODO: fix this

    @staticmethod
    def exit():
        sys.exit(0)

    def change_bar_message(self, stage_type, value):
        current_message = self.statusBar.currentMessage().split(', ')
        if stage_type == 'prod':
            db = f'{self.le_prod_db.text()}'
            if value:
                self.statusBar.showMessage(
                    f'{db} connected, {current_message[1]}')
                self.prod_connect = True
            else:
                self.statusBar.showMessage(
                    f'{db} disconnected, {current_message[1]}')
                self.prod_connect = False
        elif stage_type == 'test':
            db = f'{self.le_test_db.text()}'
            if value:
                self.statusBar.showMessage(
                    f'{current_message[0]}, {db} connected')
                self.test_connect = True
            else:
                self.statusBar.showMessage(
                    f'{current_message[0]}, {db} disconnected')
                self.test_connect = False
        if all([self.prod_connect, self.test_connect]):
            self.btn_set_configuration.setEnabled(True)
            self.calculate_table_list()

    def check_db(self, instance_type):
        if instance_type not in ['prod', 'test']:
            self.logger.critical(
                f'Unknown instance type {instance_type}, fix this in code!')
            sys.exit(1)  # TODO: use fail-fast
        if instance_type == 'prod':
            host = self.le_prod_host.text()
            user = self.le_prod_user.text()
            password = self.le_prod_password.text()
            db = self.le_prod_db.text()
        else:
            host = self.le_test_host.text()
            user = self.le_test_user.text()
            password = self.le_test_password.text()
            db = self.le_test_db.text()
        if all([host, user, password, db]):
            access_data = {
                'host': host,
                'user': user,
                'password': password,
                'db': db
            }
            if instance_type == 'prod':
                self.prod_sql_connection = dbcmp_sql_helper.DbAlchemyHelper(
                    access_data, self.logger)
                self.prod_tables = self.prod_sql_connection.get_tables_columns(
                )
                if self.prod_tables is not None:
                    self.logger.info(
                        f"Connection to {access_data.get('host')}/{access_data.get('db')} established successfully!"
                    )
                    self.change_bar_message('prod', True)
                    return True
                else:
                    self.logger.warning(
                        f"Connection to {access_data.get('host')}/{access_data.get('db')} failed"
                    )
                    QMessageBox.warning(
                        PyQt5.QtWidgets.QMessageBox(), 'Warning',
                        f"Connection to {access_data.get('host')}/{access_data.get('db')} "
                        f"failed\n\n", QMessageBox.Ok, QMessageBox.Ok)
                    self.change_bar_message('prod', False)
                    return False
            else:
                self.test_sql_connection = dbcmp_sql_helper.DbAlchemyHelper(
                    access_data, self.logger)
                self.test_tables = self.test_sql_connection.get_tables_columns(
                )
                if self.test_tables is not None:
                    self.logger.info(
                        f"Connection to db {access_data.get('host')}/"
                        f"{access_data.get('db')} established successfully!")
                    self.change_bar_message('test', True)
                    return True
                else:
                    self.logger.warning(
                        f"Connection to {access_data.get('host')}/{access_data.get('db')} failed"
                    )
                    QMessageBox.warning(
                        PyQt5.QtWidgets.QMessageBox(), 'Warning',
                        f"Connection to {access_data.get('host')}/{access_data.get('db')} failed\n\n",
                        QMessageBox.Ok, QMessageBox.Ok)
                    self.change_bar_message('test', False)
                    return False
        else:
            if not host:
                self.logger.debug(
                    f'Field {instance_type}.sql-host is not filled')
            elif not user:
                self.logger.debug(
                    f'Field {instance_type}.sql-user is not filled')
            elif not password:
                self.logger.debug(
                    f'Field {instance_type}.sql-password is not filled')
            else:
                self.logger.debug(
                    f'Field {instance_type}.sql-db is not filled')

    def check_sqlhost(self, instance_type):
        self.check_db(instance_type)
        if instance_type not in ['prod', 'test']:
            self.logger.critical(
                f'Unknown instance type {instance_type}, fix this in code!')
            sys.exit(1)  # TODO: use fail-fast
        if instance_type == 'prod':
            host = self.le_prod_host.text()
            user = self.le_prod_user.text()
            password = self.le_prod_password.text()
        else:
            host = self.le_test_host.text()
            user = self.le_test_user.text()
            password = self.le_test_password.text()
        if all([host, user, password]):
            access_data = {'host': host, 'user': user, 'password': password}
            try:
                if instance_type == 'prod':
                    self.prod_db_list = dbcmp_sql_helper.DbAlchemyHelper(
                        access_data, self.logger).db_list
                    self.prod_db_label.show()
                    self.le_prod_db.show()
                    self.logger.info(
                        f"Connection to {access_data.get('host')} established successfully!"
                    )
                    self.change_bar_message('prod', True)
                    return True
                else:
                    self.test_db_list = dbcmp_sql_helper.DbAlchemyHelper(
                        access_data, self.logger).db_list
                    self.test_db_label.show()
                    self.le_test_db.show()
                    self.logger.info(
                        f"Connection to {access_data.get('host')} established successfully!"
                    )
                    self.change_bar_message('test', True)
                    return True
            except pymysql.OperationalError as err:
                self.logger.warning(
                    f"Connection to {access_data.get('host')} failed\n\n{err.args[1]}"
                )
                QMessageBox.warning(
                    PyQt5.QtWidgets.QMessageBox(), 'Warning',
                    f"Connection to {access_data.get('host')} failed\n\n{err.args[1]}",
                    QMessageBox.Ok, QMessageBox.Ok)
                return False
            except pymysql.InternalError as err:
                self.logger.warning(
                    f"Connection to {access_data.get('host')} failed\n\n{err.args[1]}"
                )
                QMessageBox.warning(
                    PyQt5.QtWidgets.QMessageBox(), 'Warning',
                    f"Connection to {access_data.get('host')} failed\n\n{err.args[1]}",
                    QMessageBox.Ok, QMessageBox.Ok)
                return False
        else:
            return False

    def get_sql_params(self):
        empty_fields = []
        if not self.le_prod_host.text():
            empty_fields.append('prod.host')
        if not self.le_prod_user.text():
            empty_fields.append('prod.user')
        if not self.le_prod_password.text():
            empty_fields.append('prod.password')
        if not self.le_prod_db.text():
            empty_fields.append('prod.db')
        if not self.le_test_host.text():
            empty_fields.append('test.host')
        if not self.le_test_user.text():
            empty_fields.append('test.user')
        if not self.le_test_password.text():
            empty_fields.append('test.password')
        if not self.le_test_db.text():
            empty_fields.append('test.db')
        if empty_fields:
            if len(empty_fields) == 1:
                QMessageBox.question(
                    PyQt5.QtWidgets.QMessageBox(), 'Error',
                    "Please, set this parameter:\n\n" +
                    "\n".join(empty_fields), QMessageBox.Ok, QMessageBox.Ok)
                return False
            else:
                QMessageBox.question(
                    PyQt5.QtWidgets.QMessageBox(), 'Error',
                    "Please, set this parameters:\n\n" +
                    "\n".join(empty_fields), QMessageBox.Ok, QMessageBox.Ok)
                return False
        else:
            prod_host = self.le_prod_host.text()
            prod_user = self.le_prod_user.text()
            prod_password = self.le_prod_password.text()
            prod_db = self.le_prod_db.text()
            test_host = self.le_test_host.text()
            test_user = self.le_test_user.text()
            test_password = self.le_test_password.text()
            test_db = self.le_test_db.text()
            prod_dict = {
                'host': prod_host,
                'user': prod_user,
                'password': prod_password,
                'db': prod_db
            }
            test_dict = {
                'host': test_host,
                'user': test_user,
                'password': test_password,
                'db': test_db
            }
            connection_sql_parameters = {'prod': prod_dict, 'test': test_dict}
            return connection_sql_parameters

    @staticmethod
    def get_checkbox_state(checkbox):
        if checkbox.checkState() == 2:
            return True
        else:
            return False

    def get_properties(self):
        check_schema = self.get_checkbox_state(self.cb_enable_schema_checking)
        fail_with_first_error = self.get_checkbox_state(
            self.cb_fail_with_first_error)
        reports = self.get_checkbox_state(self.cb_reports)
        entities = self.get_checkbox_state(self.cb_entities)

        if self.day_summary_mode.isChecked():
            mode = 'day-sum'
        elif self.section_summary_mode.isChecked():
            mode = 'section-sum'
        else:
            mode = 'detailed'

        path_to_logs = self.path_to_logs
        if path_to_logs == '':
            path_to_logs = None

        properties_dict = {
            'check_schema': check_schema,
            'fail_with_first_error': fail_with_first_error,
            'send_mail_to': self.le_send_mail_to.text(),
            'mode': mode,
            'skip_tables': self.le_excluded_tables.text(),
            'hide_columns': self.le_skip_columns.text(),
            'strings_amount': self.strings_amount,
            # 'check_type': check_type,
            'logger': self.logger,
            'comparing_step': self.comparing_step,
            'depth_report_check': self.depth_report_check,
            'schema_columns': self.schema_columns,
            'retry_attempts': self.retry_attempts,
            'only_tables': self.le_only_tables.text(),
            'reports': reports,
            'entities': entities,
            'table_timeout': int(self.table_timeout),
            'os': operating_system
        }
        return properties_dict

    @staticmethod
    def check_service_dir(service_dir):
        if os.path.exists(service_dir):
            shutil.rmtree(service_dir)
        os.mkdir(service_dir)

    @pyqtSlot()
    def start_work(self):
        connection_dict = self.get_sql_params()
        properties = self.get_properties()
        if connection_dict and properties:
            if all([self.prod_connect, self.test_connect]):
                self.check_service_dir(self.service_dir)
                self.check_service_dir(self.test_dir)
                comparing_info = table_data.Info(self.logger)
                comparing_info.update_table_list(
                    "prod", self.prod_sql_connection.get_tables())
                comparing_info.update_table_list(
                    "test", self.test_sql_connection.get_tables())
                mapping = query_constructor.prepare_column_mapping(
                    self.prod_sql_connection, self.logger)
                comparing_object = sql_comparing.Object(
                    self.prod_sql_connection, self.test_sql_connection,
                    properties, comparing_info)
                self.logger.info('Comparing started!')
                check_schema = self.get_checkbox_state(
                    self.cb_enable_schema_checking)
                only_tables = properties.get('only_tables')
                if only_tables:
                    result_tables = dict()
                    for table in only_tables.split(','):
                        result_tables.update({table: self.tables.get(table)})
                    self.tables = result_tables
                else:
                    for table in properties.get('skip_tables').split(','):
                        if table in self.tables:
                            self.tables.pop(table)
                            self.logger.debug(
                                f'Deleted table {table} from self.tables list')
                enabled_dfs = self.cb_enable_dataframes.isChecked()
                progress = ProgressWindow(comparing_object, self.tables,
                                          check_schema, mapping,
                                          self.service_dir, self.logger,
                                          enabled_dfs)
                progress.exec()
Ejemplo n.º 21
0
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.left = 200  # Left Position of the window relative to the screen
        self.top = 200  # Top Position of the window relative to the screen
        self.title = 'Fast evaluation of machine learning models performance'
        self.width = 924  # Window width size
        self.height = 600  # Window height size
        self.std_toogle_state = True
        self.custom_set = False
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.m = PlotCanvas(self, width=5, height=4)
        self.m.plot_default()  # By default, plot nothing
        self.m.move(50,
                    50)  # Controls the canvas position relative to the parent

        ############# BUTTONS ######################
        button1 = QPushButton(self)
        # button.setToolTip('This s an example button')
        icon = QIcon("test.png")
        button1.setIcon(icon)
        button1.move(505, 0)
        button1.resize(50, 50)
        button1.clicked.connect(self.btn1_listener)

        self.button_set = QPushButton('Set Columns', self)
        self.button_set.move(650, 150)
        self.button_set.clicked.connect(self.btn_set_listener)
        self.button_set.setEnabled(False)

        self.button_batch = QPushButton('Set batch', self)
        self.button_batch.move(770, 10)
        self.button_batch.clicked.connect(self.btn_batch)
        self.button_batch.setEnabled(False)

        ############# LIST OF ELEMENTS ######################
        items = [
            'Logistic Regression', 'Support Vector Machine', 'Random Forest',
            'K-nearest Neighbors', 'Gaussian Naive Bayes', 'Neural Network'
        ]

        self.lv = QComboBox(
            self
        )  # Self definition is only needed when a method for that specific object is used... outside the function containing it...
        self.lv.addItems(items)
        self.lv.move(130, 550)
        self.lv.resize(200, 20)
        self.lv.currentTextChanged.connect(self.itemChanged)
        self.lv.setEnabled(False)

        ############# TextEdit ######################
        self.edit = QLineEdit(self)
        self.edit.move(50, 15)
        self.edit.resize(450, 20)

        self.edit_start = QLineEdit(self)
        self.edit_start.move(640, 75)
        self.edit_start.resize(40, 20)

        self.edit_end = QLineEdit(self)
        self.edit_end.move(730, 75)
        self.edit_end.resize(40, 20)

        self.edit_label = QLineEdit(self)
        self.edit_label.move(700, 120)
        self.edit_label.resize(40, 20)

        self.edit_batch = QLineEdit(self)
        self.edit_batch.move(725, 15)
        self.edit_batch.resize(40, 20)

        ############ RADIO BUTTONS ################
        self.b1 = QRadioButton("Linear", self)
        self.b1.setChecked(True)
        self.b1.setEnabled(False)
        self.b1.toggled.connect(lambda: self.btnstate(self.b1))

        self.b2 = QRadioButton("Polynomial", self)
        self.b2.setEnabled(False)
        self.b2.toggled.connect(lambda: self.btnstate(self.b2))

        self.b3 = QRadioButton("RBF", self)
        self.b3.setEnabled(False)
        self.b3.toggled.connect(lambda: self.btnstate(self.b3))

        self.b4 = QRadioButton("Sigmoid", self)
        self.b4.setEnabled(False)
        self.b4.toggled.connect(lambda: self.btnstate(self.b4))

        self.b5 = QRadioButton("Cosine", self)
        self.b5.setEnabled(False)
        self.b5.toggled.connect(lambda: self.btnstate(self.b5))

        self.b1.move(30, 500)
        self.b2.move(130, 500)
        self.b3.move(250, 500)
        self.b4.move(350, 500)
        self.b5.move(450, 500)

        ######### LABELS ######
        l1 = QLabel(self)
        l1.setText("PCA Kernel")
        l1.resize(150, 20)
        l1.move(250, 480)

        l2 = QLabel(self)
        l2.setText("Classsifier")
        l2.resize(150, 20)
        l2.move(50, 548)

        l_feature = QLabel(self)
        l_feature.setText("Sample Features")
        l_feature.resize(150, 20)
        l_feature.move(635, 50)

        l_start = QLabel(self)
        l_start.setText("Start:")
        l_start.resize(35, 20)
        l_start.move(600, 75)

        l_end = QLabel(self)
        l_end.setText("End:")
        l_end.resize(30, 20)
        l_end.move(700, 75)

        l_end = QLabel(self)
        l_end.setText("Sample Labels:")
        l_end.resize(100, 20)
        l_end.move(600, 120)

        self.l_accuracy = QLabel(self)
        self.l_accuracy.setText("Model Accuracy:")
        self.l_accuracy.resize(200, 15)
        self.l_accuracy.move(600, 350)

        self.l_precision = QLabel(self)
        self.l_precision.setText("Model Precision:")
        self.l_precision.resize(200, 15)
        self.l_precision.move(600, 370)

        self.l_recall = QLabel(self)
        self.l_recall.setText("Model Recall:")
        self.l_recall.resize(200, 15)
        self.l_recall.move(600, 390)

        self.l_f1 = QLabel(self)
        self.l_f1.setText("Model F1 score:")
        self.l_f1.resize(200, 15)
        self.l_f1.move(600, 410)

        ######## CHECK BOX ###########
        self.check_box = QCheckBox('Data Standardization', self)
        self.check_box.resize(200, 20)
        self.check_box.move(600, 200)
        self.check_box.stateChanged.connect(self.clickBox)

        self.check_box_train = QCheckBox('Custom training \n batch size (%)',
                                         self)
        self.check_box_train.resize(120, 40)
        self.check_box_train.move(600, 5)
        self.check_box_train.stateChanged.connect(self.clickBox_train)

        self.show()

    def btn1_listener(self):
        global start
        start = True
        global path_global
        print("Button 1 clicked")
        path_global = str(QFileDialog.getOpenFileName()[0])
        self.edit.setText(path_global)

        self.button_set.setEnabled(True)

    def btn_set_listener(self):
        print("Button SET clicked")
        global col_start, col_end, col_label, start, std_data
        start = True

        col_start = int(self.edit_start.text())
        col_end = int(self.edit_end.text())
        col_label = int(self.edit_label.text())
        print(col_start, col_end, col_label)

        if self.custom_set:
            X_train, y_train, cmap, markers, = load_dataset(
                path_global, train_size=self.train_size / 100)

        else:
            X_train, y_train, cmap, markers, = load_dataset(path_global)

        self.X_train = X_train
        self.y_train = y_train
        self.cmap = cmap
        self.markers = markers
        self.kernel_opc = 1  # Default parameter
        self.opc = 1  # Default parameter
        std_data = self.check_box.isChecked()
        print(std_data)

        self.m.plot(self.opc, self.kernel_opc, self.X_train, self.y_train,
                    self.cmap, self.markers)  # opc = 1 by default
        self.lv.setEnabled(True)
        self.b1.setEnabled(True)
        self.b2.setEnabled(True)
        self.b3.setEnabled(True)
        self.b4.setEnabled(True)
        self.b5.setEnabled(True)
        start = False
        self.b1.setChecked(True)
        self.lv.setCurrentIndex(
            0
        )  # Resets the classifier to Logistic regression (element index 0)

    def btn_batch(self):
        self.train_size = float(self.edit_batch.text())
        self.custom_set = True
        print(self.train_size)

    def itemChanged(self):
        self.opc = self.lv.currentIndex() + 1
        print("Classifier selected: ", self.opc)
        self.m.plot(self.opc, self.kernel_opc, self.X_train, self.y_train,
                    self.cmap, self.markers)

    def btnstate(self, b):
        if b.text() == "Linear":
            if b.isChecked() == True:
                print('B1 is selected...')
                self.kernel_opc = 1
                self.m.plot(self.opc, self.kernel_opc, self.X_train,
                            self.y_train, self.cmap,
                            self.markers)  # opc = 1 by default

        elif b.text() == "Polynomial":
            if b.isChecked():
                print('B2 is selected...')
                self.kernel_opc = 2
                self.m.plot(self.opc, self.kernel_opc, self.X_train,
                            self.y_train, self.cmap,
                            self.markers)  # opc = 1 by default

        elif b.text() == "RBF":
            if b.isChecked():
                print('B3 is selected...')
                self.kernel_opc = 3
                self.m.plot(self.opc, self.kernel_opc, self.X_train,
                            self.y_train, self.cmap,
                            self.markers)  # opc = 1 by default

        elif b.text() == "Sigmoid":
            if b.isChecked():
                print('B4 is selected...')
                self.kernel_opc = 4
                self.m.plot(self.opc, self.kernel_opc, self.X_train,
                            self.y_train, self.cmap,
                            self.markers)  # opc = 1 by default

        elif b.text() == "Cosine":
            if b.isChecked():
                print('B5 is selected...')
                self.kernel_opc = 5
                self.m.plot(self.opc, self.kernel_opc, self.X_train,
                            self.y_train, self.cmap,
                            self.markers)  # opc = 1 by default

    def clickBox(self, state):
        global std_data
        if state == QtCore.Qt.Checked:
            print('Checked')
            std_data = True
            self.std_toogle_state = True
            if not start:
                self.m.plot(self.opc, self.kernel_opc, self.X_train,
                            self.y_train, self.cmap, self.markers)
            # print(std_data)

        else:
            print('Unchecked')
            std_data = False
            self.std_toogle_state = True

            if not start:
                self.m.plot(self.opc, self.kernel_opc, self.X_train,
                            self.y_train, self.cmap, self.markers)
            # print(std_data)

    def clickBox_train(self, state):

        if state == QtCore.Qt.Checked:
            print('CB train Checked')
            self.button_batch.setEnabled(True)

        else:
            print('CB train Unchecked')
            self.button_batch.setEnabled(False)
Ejemplo n.º 22
0
class Tasmotizer(QDialog):
    def __init__(self):
        super().__init__()
        self.settings = QSettings("tasmotizer.cfg", QSettings.IniFormat)

        self.nam = QNetworkAccessManager()
        self.nrRelease = QNetworkRequest(
            QUrl("http://thehackbox.org/tasmota/release/release.php"))
        self.nrDevelopment = QNetworkRequest(
            QUrl("http://thehackbox.org/tasmota/development.php"))

        self.setWindowTitle("Tasmotizer 1.1")
        self.setMinimumWidth(480)

        self.mode = 0  # BIN file
        self.bin_file = ""

        self.release_data = b""
        self.development_data = b""

        self.createUI()

        self.refreshPorts()
        self.getHackBoxFeeds()

    def createUI(self):
        vl = VLayout()
        self.setLayout(vl)

        # Banner
        banner = QLabel()
        banner.setPixmap(QPixmap(":/banner.png"))
        vl.addWidget(banner)

        # Port groupbox
        gbPort = GroupBoxH("Select port", 3)
        self.cbxPort = QComboBox()
        pbRefreshPorts = QPushButton("Refresh")
        gbPort.addWidget(self.cbxPort)
        gbPort.addWidget(pbRefreshPorts)
        gbPort.layout().setStretch(0, 4)
        gbPort.layout().setStretch(1, 1)

        # Firmware groupbox
        gbFW = GroupBoxV("Select image", 3)

        hl_rb = HLayout(0)
        rbFile = QRadioButton("BIN file")
        self.rbRelease = QRadioButton("Release")
        self.rbRelease.setEnabled(False)
        self.rbDev = QRadioButton("Development")
        self.rbDev.setEnabled(False)

        rbgFW = QButtonGroup(gbFW)
        rbgFW.addButton(rbFile, 0)
        rbgFW.addButton(self.rbRelease, 1)
        rbgFW.addButton(self.rbDev, 2)

        hl_rb.addWidgets([rbFile, self.rbRelease, self.rbDev])
        gbFW.addLayout(hl_rb)

        self.wFile = QWidget()
        hl_file = HLayout(0)
        self.file = QLineEdit()
        self.file.setReadOnly(True)
        self.file.setPlaceholderText("Click 'Open' to select the image")
        pbFile = QPushButton("Open")
        hl_file.addWidgets([self.file, pbFile])
        self.wFile.setLayout(hl_file)

        self.cbHackboxBin = QComboBox()
        self.cbHackboxBin.setVisible(False)
        self.cbHackboxBin.setEnabled(False)

        self.cbBackup = QCheckBox("Backup original firmware")
        self.cbBackup.setToolTip(
            "Firmware backup is ESPECIALLY recommended when you flash a Sonoff, Tuya, Shelly etc. for the first time.\nWithout a backup you won't be able to restore the original functionality."
        )

        self.cbErase = QCheckBox("Erase before flashing")
        self.cbErase.setToolTip(
            "Erasing previous firmware ensures all flash regions are clean for Tasmota, which prevents many unexpected issues.\nIf unsure, leave enabled."
        )
        self.cbErase.setChecked(True)

        gbFW.addWidgets(
            [self.wFile, self.cbHackboxBin, self.cbBackup, self.cbErase])

        # Buttons
        self.pbTasmotize = QPushButton("Tasmotize!")
        self.pbTasmotize.setFixedHeight(50)
        self.pbTasmotize.setStyleSheet("background-color: #223579;")

        self.pbConfig = QPushButton("Send config")
        self.pbConfig.setStyleSheet("background-color: #571054;")
        self.pbConfig.setFixedHeight(50)

        self.pbQuit = QPushButton("Quit")
        self.pbQuit.setStyleSheet("background-color: #c91017;")
        self.pbQuit.setFixedSize(QSize(50, 50))

        hl_btns = HLayout([50, 3, 50, 3])
        hl_btns.addWidgets([self.pbTasmotize, self.pbConfig, self.pbQuit])

        vl.addWidgets([gbPort, gbFW])
        vl.addLayout(hl_btns)

        pbRefreshPorts.clicked.connect(self.refreshPorts)
        rbgFW.buttonClicked[int].connect(self.setBinMode)
        rbFile.setChecked(True)
        pbFile.clicked.connect(self.openBinFile)

        self.pbTasmotize.clicked.connect(self.start_process)
        self.pbConfig.clicked.connect(self.send_config)
        self.pbQuit.clicked.connect(self.reject)

    def refreshPorts(self):
        self.cbxPort.clear()
        ports = reversed(
            sorted(port.portName()
                   for port in QSerialPortInfo.availablePorts()))
        for p in ports:
            port = QSerialPortInfo(p)
            self.cbxPort.addItem(port.portName(), port.systemLocation())

    def setBinMode(self, radio):
        self.mode = radio
        self.wFile.setVisible(self.mode == 0)
        self.cbHackboxBin.setVisible(self.mode > 0)

        if self.mode == 1:
            self.processReleaseInfo()
        elif self.mode == 2:
            self.processDevelopmentInfo()

    def getHackBoxFeeds(self):
        self.release_reply = self.nam.get(self.nrRelease)
        self.release_reply.readyRead.connect(self.appendReleaseInfo)
        self.release_reply.finished.connect(
            lambda: self.rbRelease.setEnabled(True))

        self.development_reply = self.nam.get(self.nrDevelopment)
        self.development_reply.readyRead.connect(self.appendDevelopmentInfo)
        self.development_reply.finished.connect(
            lambda: self.rbDev.setEnabled(True))

    def appendReleaseInfo(self):
        self.release_data += self.release_reply.readAll()

    def appendDevelopmentInfo(self):
        self.development_data += self.development_reply.readAll()

    def processReleaseInfo(self):
        reply = json.loads(str(self.release_data, 'utf8'))
        version, bins = list(reply.items())[0]
        self.rbRelease.setText("Release {}".format(version.lstrip("release-")))
        if len(bins) > 0:
            self.cbHackboxBin.clear()
            for img in bins:
                img['filesize'] //= 1024
                self.cbHackboxBin.addItem(
                    "{binary} [{filesize}kB]".format(**img),
                    "{otaurl};{binary}".format(**img))
            self.cbHackboxBin.setEnabled(True)

    def processDevelopmentInfo(self):
        reply = json.loads(str(self.development_data, 'utf8'))
        _, cores = list(reply.items())[0]

        if len(cores) > 0:
            self.cbHackboxBin.clear()

            for core in list(cores.keys()):
                for img in cores[core]:
                    img['filesize'] //= 1024
                    self.cbHackboxBin.addItem(
                        "{binary} [{version}@{}, {commit}, {filesize}kB]".
                        format(core, **img),
                        "{otaurl};{}-dev-{version}-{commit}.bin".format(
                            img['binary'].rstrip(".bin"), **img))
            self.cbHackboxBin.setEnabled(True)

    def openBinFile(self):
        previous_file = self.settings.value("bin_file")
        file, ok = QFileDialog.getOpenFileName(self,
                                               "Select Tasmota image",
                                               previous_file,
                                               filter="BIN files (*.bin)")
        if ok:
            self.file.setText(file)

    def send_config(self):
        dlg = SendConfigDialog()
        if dlg.exec_() == QDialog.Accepted:
            if dlg.commands:
                try:
                    self.port = QSerialPort(self.cbxPort.currentData())
                    self.port.setBaudRate(115200)
                    self.port.open(QIODevice.ReadWrite)
                    bytes_sent = self.port.write(bytes(dlg.commands, 'utf8'))
                except Exception as e:
                    QMessageBox.critical(self, "Port error", e)
                else:
                    self.settings.setValue("gbWifi", dlg.gbWifi.isChecked())
                    self.settings.setValue("AP", dlg.leAP.text())

                    self.settings.setValue("gbRecWifi",
                                           dlg.gbRecWifi.isChecked())

                    self.settings.setValue("gbMQTT", dlg.gbMQTT.isChecked())
                    self.settings.setValue("Broker", dlg.leBroker.text())
                    self.settings.setValue("Port", dlg.sbPort.value())
                    self.settings.setValue("Topic", dlg.leTopic.text())
                    self.settings.setValue("FullTopic", dlg.leFullTopic.text())
                    self.settings.setValue("FriendlyName",
                                           dlg.leFriendlyName.text())
                    self.settings.setValue("MQTTUser", dlg.leMQTTUser.text())

                    self.settings.setValue("gbModule",
                                           dlg.gbModule.isChecked())
                    self.settings.setValue("ModuleMode",
                                           dlg.rbgModule.checkedId())
                    self.settings.setValue("Module",
                                           dlg.cbModule.currentText())
                    self.settings.setValue("Template", dlg.leTemplate.text())
                    self.settings.sync()

                    QMessageBox.information(
                        self, "Done",
                        "Configuration sent ({} bytes)\nDevice will restart.".
                        format(bytes_sent))
                finally:
                    if self.port.isOpen():
                        self.port.close()
            else:
                QMessageBox.information(self, "Done", "Nothing to send")

    def start_process(self):
        ok = True

        if self.mode == 0:
            if len(self.file.text()) > 0:
                self.bin_file = self.file.text()
                self.settings.setValue("bin_file", self.bin_file)

            else:
                ok = False
                QMessageBox.information(
                    self, "Nothing to do...",
                    "Select a local BIN file or select which one to download.")

        if ok:
            dlg = FlashingDialog(self)
            if dlg.exec_() == QDialog.Accepted:
                QMessageBox.information(
                    self, "Done",
                    "Flashing successful! Power cycle the device.")

            else:
                if dlg.error_msg:
                    QMessageBox.critical(self, "Error", dlg.error_msg)
                else:
                    QMessageBox.critical(
                        self, "Flashing aborted",
                        "Flashing process has been aborted by the user.")

    def mousePressEvent(self, e):
        self.old_pos = e.globalPos()

    def mouseMoveEvent(self, e):
        delta = e.globalPos() - self.old_pos
        self.move(self.x() + delta.x(), self.y() + delta.y())
        self.old_pos = e.globalPos()
Ejemplo n.º 23
0
class TestTab(QWidget):
    def __init__(self, path='dictionary_5_js.txt', parent=None):
        super(QWidget, self).__init__(parent)
        self.tableWidget = QTableWidget()
        self.tabSingle = QTableWidget()
        self.path = path
        self.vet_p = ['', '', '']
        self.initUI()

    def initUI(self):
        newfont = QFont("Helvetica", 15, QFont.Bold)
        self.title_test = QLabel("Confusion matrix EXAMPLE")
        self.title_paz = QLabel(
            "List of patient, double click to see the patient confusion matrix."
        )
        self.title_single_paz = QLabel("Confusion matrix of a single patient")
        self.title_selection = QLabel(
            "Select the data set to show the confusion matrix:")

        self.title_paz.setFont(newfont)
        self.title_test.setFont(newfont)
        self.title_single_paz.setFont(newfont)
        self.traincm = QRadioButton('Train')
        self.traincm.setEnabled(False)
        self.traincm.toggled.connect(self.cm_train)
        self.valcm = QRadioButton('Validation')
        self.valcm.setEnabled(False)
        self.valcm.toggled.connect(self.cm_val)
        self.testcm = QRadioButton('Test')
        self.testcm.setEnabled(False)
        self.testcm.toggled.connect(self.cm_test)
        self.mode_group = QButtonGroup()
        self.mode_group.addButton(self.traincm)
        self.mode_group.addButton(self.valcm)
        self.mode_group.addButton(self.testcm)

        self.h_sel = QHBoxLayout()
        self.h_sel.addWidget(self.traincm)
        self.h_sel.addWidget(self.valcm)
        self.h_sel.addWidget(self.testcm)
        self.h_sel.addStretch(1)

        cm = self.get_data(self.path)

        self.createTable(cm)
        self.createTable_sigle(cm)

        self.v_list = QVBoxLayout()
        self.v_list.addWidget(self.title_paz)
        self.v_list.addWidget(self.list_pat)

        self.v_tab = QVBoxLayout()
        self.v_tab.addWidget(self.title_single_paz)
        self.v_tab.addWidget(self.tabSingle)

        self.h = QHBoxLayout()
        self.h.addLayout(self.v_list)
        self.h.addLayout(self.v_tab)

        # Add box layout, add table to box layout and add box layout to widget
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.title_selection)
        self.layout.addLayout(self.h_sel)
        self.layout.addWidget(QHLine())
        self.layout.addWidget(self.title_test)
        self.layout.addWidget(self.tableWidget)
        self.layout.addLayout(self.h)
        self.setLayout(self.layout)

        # Show widget
        self.show()

    def get_paths(self, train=None, val=None, test=None):
        if train is not None:
            self.vet_p[0] = train
        elif val is not None:
            self.vet_p[1] = val
        elif test is not None:
            self.vet_p[2] = test
        else:
            pass

    def cm_train(self):
        self.path = self.vet_p[0]
        cm = self.get_data(self.path)
        self.title_test.setText('Confusion matrix TRAIN')
        self.createTable(cm)
        self.createTable_sigle(cm)

    def cm_val(self):
        self.path = self.vet_p[1]
        cm = self.get_data(self.path)
        self.title_test.setText('Confusion matrix VAL')
        self.createTable(cm)
        self.createTable_sigle(cm)

    def cm_test(self):
        self.path = self.vet_p[2]
        cm = self.get_data(self.path)
        self.title_test.setText('Confusion matrix TEST')
        self.createTable(cm)
        self.createTable_sigle(cm)

    def w_list_paz(self, dizio):
        vet_paz = [dizio[m]['name'] for m in dizio]
        print('voci diz', len(vet_paz))
        vet_paz = list(set(vet_paz))

        self.list_pat = QListWidget()
        self.list_pat.addItems(vet_paz)
        self.list_pat.itemDoubleClicked.connect(self.sasa)

    def sasa(self, item):
        self.paz = item.text()
        print(item.text())
        cm = self.get_data_sigle_sub(self.path, self.paz)
        self.createTable_sigle(cm)

    def load_js(self, path):

        with open(path, 'r') as myfile:
            openf = myfile.read()
        dizio = json.loads(openf)

        return dizio

    def get_data(self, path):
        dizio = self.load_js(path)

        self.w_list_paz(dizio)
        pred_class = [dizio[m]['pred_class'] for m in dizio]
        true_class = [dizio[m]['true_class'] for m in dizio]

        cm = np.round(
            100 * confusion_matrix(
                true_class, pred_class, labels=['AC', 'H', 'AD']) /
            len(true_class), 2)
        return cm

    def get_data_sigle_sub(self, path, pat):
        dizio = self.load_js(path)

        pred_class = [
            dizio[m]['pred_class'] for m in dizio if dizio[m]['name'] == pat
        ]
        true_class = [
            dizio[m]['true_class'] for m in dizio if dizio[m]['name'] == pat
        ]

        cm = np.round(
            100 * confusion_matrix(
                true_class, pred_class, labels=['AC', 'H', 'AD']) /
            len(true_class), 2)
        return cm

    def createTable_sigle(self, cm):

        self.tabSingle.setRowCount(3)
        self.tabSingle.setColumnCount(3)
        self.tabSingle.setItem(0, 0, QTableWidgetItem(str(cm[0, 0]) + '%'))
        self.tabSingle.setItem(0, 1, QTableWidgetItem(str(cm[0, 1]) + '%'))
        self.tabSingle.setItem(0, 2, QTableWidgetItem(str(cm[0, 2]) + '%'))

        self.tabSingle.setItem(1, 0, QTableWidgetItem(str(cm[1, 0]) + '%'))
        self.tabSingle.setItem(1, 1, QTableWidgetItem(str(cm[1, 1]) + '%'))
        self.tabSingle.setItem(1, 2, QTableWidgetItem(str(cm[1, 2]) + '%'))

        self.tabSingle.setItem(2, 0, QTableWidgetItem(str(cm[2, 0]) + '%'))
        self.tabSingle.setItem(2, 1, QTableWidgetItem(str(cm[2, 1]) + '%'))
        self.tabSingle.setItem(2, 2, QTableWidgetItem(str(cm[2, 2]) + '%'))
        a = ['AC', 'H', 'AD']
        self.tabSingle.setHorizontalHeaderLabels(a)
        self.tabSingle.setVerticalHeaderLabels(a)

    def createTable(self, cm):

        self.tableWidget.setRowCount(3)
        self.tableWidget.setColumnCount(3)
        self.tableWidget.setItem(0, 0, QTableWidgetItem(str(cm[0, 0]) + '%'))
        self.tableWidget.setItem(0, 1, QTableWidgetItem(str(cm[0, 1]) + '%'))
        self.tableWidget.setItem(0, 2, QTableWidgetItem(str(cm[0, 2]) + '%'))

        self.tableWidget.setItem(1, 0, QTableWidgetItem(str(cm[1, 0]) + '%'))
        self.tableWidget.setItem(1, 1, QTableWidgetItem(str(cm[1, 1]) + '%'))
        self.tableWidget.setItem(1, 2, QTableWidgetItem(str(cm[1, 2]) + '%'))

        self.tableWidget.setItem(2, 0, QTableWidgetItem(str(cm[2, 0]) + '%'))
        self.tableWidget.setItem(2, 1, QTableWidgetItem(str(cm[2, 1]) + '%'))
        self.tableWidget.setItem(2, 2, QTableWidgetItem(str(cm[2, 2]) + '%'))
        a = ['AC', 'H', 'AD']
        self.tableWidget.setHorizontalHeaderLabels(a)
        self.tableWidget.setVerticalHeaderLabels(a)
Ejemplo n.º 24
0
class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'PyProject'
        self.left = 550
        self.top = 350
        self.width = 625
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        fileButton = QPushButton('Select a DataSet', self)
        fileButton.move(60, 30)
        fileButton.clicked.connect(self.getfile)
        self.applyButton = QPushButton('Apply Tests', self)
        self.applyButton.move(215, 30)
        self.applyButton.clicked.connect(self.newWindow)
        self.applyButton.setEnabled(False)

        self.displayText = QLabel("", self)
        self.displayText.move(375, 0)
        self.displayText.setFixedHeight(150)
        self.displayText.setFixedWidth(250)
        self.displayText.setAlignment(Qt.AlignTop)
        self.displayText.setAlignment(Qt.AlignLeft)
        self.displayText.setWordWrap(True)
        self.displayText.setAutoFillBackground(True)
        self.displayText.setStyleSheet(
            "QLabel { background-color: rgba(169,169,169); }")

        self.displayResult = QLabel("", self)
        self.displayResult.move(375, 155)
        self.displayResult.setFixedHeight(200)
        self.displayResult.setFixedWidth(250)
        self.displayResult.setAlignment(Qt.AlignTop)
        self.displayResult.setAlignment(Qt.AlignLeft)
        self.displayResult.setWordWrap(True)
        self.displayResult.setAutoFillBackground(True)
        self.displayResult.setStyleSheet(
            "QLabel { background-color: rgba(169,169,169); }")

        paraNonPara = QButtonGroup(self)
        anovaPara = QButtonGroup(self)
        pairUnPair = QButtonGroup(self)
        studentAnova = QButtonGroup(self)

        self.anova = QRadioButton('Anova', self)
        self.anova.move(250, 90)
        self.anova.setChecked(False)
        self.student = QRadioButton('Student-T', self)
        self.student.move(60, 90)
        self.student.setChecked(False)
        studentAnova.addButton(self.anova)
        studentAnova.addButton(self.student)

        self.stuPara = QRadioButton('Parametric', self)
        self.stuPara.move(10, 120)
        self.stuPara.setChecked(False)
        self.stuNonpara = QRadioButton('non-Parametric', self)
        self.stuNonpara.move(10, 150)
        self.stuNonpara.setChecked(False)
        paraNonPara.addButton(self.stuPara)
        paraNonPara.addButton(self.stuNonpara)

        self.anoPara = QRadioButton('Parametric', self)
        self.anoPara.move(250, 120)
        self.anoPara.setChecked(False)
        self.anoNonpara = QRadioButton('non-Parametric', self)
        self.anoNonpara.move(250, 150)
        self.anoNonpara.setChecked(False)
        anovaPara.addButton(self.anoPara)
        anovaPara.addButton(self.anoNonpara)

        self.pair = QRadioButton('Paired', self)
        self.pair.move(130, 120)
        self.pair.setChecked(False)
        self.unPair = QRadioButton('Unpaired', self)
        self.unPair.move(130, 150)
        self.unPair.setChecked(False)
        pairUnPair.addButton(self.pair)
        pairUnPair.addButton(self.unPair)

        self.pair.setEnabled(False)
        self.unPair.setEnabled(False)
        self.anoPara.setEnabled(False)
        self.anoNonpara.setEnabled(False)
        self.stuPara.setEnabled(False)
        self.stuNonpara.setEnabled(False)
        self.anova.setEnabled(False)
        self.student.setEnabled(False)

    def newWindow(self):
        if (self.student.isChecked()):
            #para=student t, non-para-paird=signrank, non-para-unpaird=ranksum
            if (self.stuPara.isChecked()):
                if (self.pair.isChecked()):
                    self.displayResult.setText(
                        stats.ttest_rel(df.iloc[:, 0], df.iloc[:,
                                                               1]).__str__())
                else:
                    self.displayResult.setText(
                        stats.ttest_ind(df.iloc[:, 0],
                                        df.iloc[:, 1],
                                        equal_var=False).__str__())
            else:
                if (self.pair.isChecked()):
                    self.displayResult.setText(
                        stats.wilcoxon(df.iloc[:, 0],
                                       df.iloc[:, 1],
                                       zero_method='wilcox',
                                       correction=False).__str__())
                else:
                    self.displayResult.setText(
                        stats.ranksums(df.iloc[:, 0], df.iloc[:, 1]).__str__())
        if (self.anova.isChecked()):
            #para=anova, non-para=kruskalwallis
            #pca reduce to 3 or 2
            if (self.anoPara.isChecked()):
                self.displayResult.setText(
                    stats.f_oneway(df.iloc[:, 0], df.iloc[:, 1],
                                   df.iloc[:, 2]).__str__())
            else:
                self.displayResult.setText(
                    stats.kruskal(df.iloc[:, 0], df.iloc[:, 1],
                                  df.iloc[:, 2]).__str__())

    def getfile(self):
        #get the file name and if it is not empty do stuff
        filename = askopenfilename()
        if (filename != ''):
            #check that it is an xlsx file
            if (filename.endswith('.xlsx')):
                xls_file = pd.ExcelFile(filename)
                sheetName = xls_file.sheet_names
                tempParse = xls_file.parse(sheetName[0])
                tempParse = tempParse.dropna(axis=1, how='all')
                #if the data set is empty
                if (len(tempParse.columns) == 0):
                    self.displayText.setText("DataSet is Empty!")
                    self.displayResult.setText("")
                    self.applyButton.setEnabled(False)
                    self.pair.setEnabled(False)
                    self.unPair.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuNonpara.setEnabled(False)
                    self.anova.setEnabled(False)
                    self.student.setEnabled(False)
                    return
                if (len(tempParse.columns) > 3):
                    self.displayText.setText("DataSet is too Large!")
                    self.displayResult.setText("")
                    self.applyButton.setEnabled(False)
                    self.pair.setEnabled(False)
                    self.unPair.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuNonpara.setEnabled(False)
                    self.anova.setEnabled(False)
                    self.student.setEnabled(False)
                    return
                tempParse = list(tempParse)
                global df
                #use tempParse to check if file had headers
                if (isinstance(tempParse[0], float)
                        or isinstance(tempParse[0], int)):
                    df = xls_file.parse(sheetName[0], header=None)
                else:
                    df = xls_file.parse(sheetName[0])
                #cut the NaN columns out
                df = df.dropna(axis=1, how='all')
                #cut any NaN values out
                df = df.dropna()
                #activate the buttons and radio buttons depending on your data set
                self.displayText.setText(
                    df.describe(include='all').to_string())
                self.displayResult.setText("")
                if (len(df.columns) == 1):
                    self.applyButton.setEnabled(False)
                    self.student.setEnabled(False)
                    self.student.setChecked(False)
                    self.pair.setEnabled(False)
                    self.pair.setChecked(False)
                    self.unPair.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuPara.setChecked(False)
                    self.stuNonpara.setEnabled(False)
                    self.anova.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                elif (len(df.columns) == 2):
                    self.applyButton.setEnabled(True)
                    self.student.setEnabled(True)
                    self.student.setChecked(True)
                    self.pair.setEnabled(True)
                    self.pair.setChecked(True)
                    self.unPair.setEnabled(True)
                    self.stuPara.setEnabled(True)
                    self.stuPara.setChecked(True)
                    self.stuNonpara.setEnabled(True)
                    self.anova.setEnabled(False)
                    self.anoPara.setEnabled(False)
                    self.anoNonpara.setEnabled(False)
                else:
                    self.applyButton.setEnabled(True)
                    self.anova.setEnabled(True)
                    self.anova.setChecked(True)
                    self.anoPara.setEnabled(True)
                    self.anoPara.setChecked(True)
                    self.anoNonpara.setEnabled(True)
                    self.student.setEnabled(False)
                    self.pair.setEnabled(False)
                    self.unPair.setEnabled(False)
                    self.stuPara.setEnabled(False)
                    self.stuNonpara.setEnabled(False)
            else:
                #need warning for wrong file type
                self.displayText.setText("Wrong file type")
                self.displayResult.setText("")
                self.applyButton.setEnabled(False)
                self.pair.setEnabled(False)
                self.unPair.setEnabled(False)
                self.anoPara.setEnabled(False)
                self.anoNonpara.setEnabled(False)
                self.stuPara.setEnabled(False)
                self.stuNonpara.setEnabled(False)
                self.anova.setEnabled(False)
                self.student.setEnabled(False)
        else:
            #need warning for no file chosen
            self.displayText.setText("No file selected")
            self.displayResult.setText("")
            self.applyButton.setEnabled(False)
            self.pair.setEnabled(False)
            self.unPair.setEnabled(False)
            self.anoPara.setEnabled(False)
            self.anoNonpara.setEnabled(False)
            self.stuPara.setEnabled(False)
            self.stuNonpara.setEnabled(False)
            self.anova.setEnabled(False)
            self.student.setEnabled(False)
Ejemplo n.º 25
0
class Ui_Form(object):
    def __init__(self, obj):
        super().__init__()
        self.setupUi(obj)
        self.retranslateUi(obj)
        self.graphicsView = QGraphicsView(obj)
        self.graphicsView.setGeometry(QtCore.QRect(10, 10, 791, 441))
        self.graphicsView.setObjectName("graphicsView")
        self.scene = QtWidgets.QGraphicsScene()
        self.graphicsView.setScene(self.scene)

        pen = QtGui.QPen(QtCore.Qt.GlobalColor.gray)
        for i in range(-1 * self.graphicsView.height() // 2 + 10,
                       self.graphicsView.height() // 2 - 10):
            r1 = QtCore.QRectF(QtCore.QPointF(0, i), QtCore.QSizeF(1, 1))
            self.scene.addRect(r1, pen)

        for i in range(-1 * self.graphicsView.width() // 2 + 10,
                       self.graphicsView.width() // 2 - 10):
            r2 = QtCore.QRectF(QtCore.QPointF(i, 0), QtCore.QSizeF(1, 1))
            self.scene.addRect(r2, pen)

        self.coordsContainer = []
        self.centersContainer = []
        self.clastersContainer = []
        self.distance = None

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(815, 678)

        self.startPushButton = QPushButton(Form)
        self.startPushButton.clicked.connect(
            self.startPushButton_button_clicked)
        self.startPushButton.setGeometry(QtCore.QRect(260, 620, 261, 41))
        self.startPushButton.setObjectName("startPushButton")

        self.coordsTextBox = QtWidgets.QPlainTextEdit(Form)
        self.coordsTextBox.setGeometry(QtCore.QRect(260, 470, 261, 81))
        self.coordsTextBox.setObjectName("coordsTextBox")

        self.CentersTextBox = QtWidgets.QPlainTextEdit(Form)
        self.CentersTextBox.setGeometry(QtCore.QRect(540, 470, 261, 81))
        self.CentersTextBox.setObjectName("CentersTextBox")

        self.addCordsPushButton = QPushButton(Form)
        self.addCordsPushButton.clicked.connect(
            self.addCordsPushButton_button_clicked)
        self.addCordsPushButton.setGeometry(QtCore.QRect(260, 570, 541, 31))
        self.addCordsPushButton.setObjectName("addCordsPushButton")

        self.groupBox = QtWidgets.QGroupBox(Form)
        self.groupBox.setGeometry(QtCore.QRect(10, 460, 241, 91))
        self.groupBox.setObjectName("groupBox")

        self.euclidRadioButton = QRadioButton(self.groupBox)
        self.euclidRadioButton.toggled.connect(self.euclidRadioButton_clicked)
        self.euclidRadioButton.setGeometry(QtCore.QRect(10, 20, 221, 31))
        self.euclidRadioButton.setObjectName("euclidRadioButton")

        self.chebishevRadioButton = QRadioButton(self.groupBox)
        self.chebishevRadioButton.toggled.connect(
            self.chebishevRadioButton_clicked)
        self.chebishevRadioButton.setGeometry(QtCore.QRect(10, 50, 221, 41))
        self.chebishevRadioButton.setObjectName("chebishevRadioButton")

        self.stepPushButton = QPushButton(Form)
        self.stepPushButton.clicked.connect(self.stepPushButton_button_clicked)
        self.stepPushButton.setGeometry(QtCore.QRect(540, 620, 261, 41))
        self.stepPushButton.setObjectName("stepPushButton")

        self.restartPushButton = QPushButton(Form)
        self.restartPushButton.clicked.connect(
            self.restartPushButton_button_clicked)
        self.restartPushButton.setGeometry(QtCore.QRect(10, 620, 241, 41))
        self.restartPushButton.setObjectName("restartPushButton")

        self.testPushButton = QPushButton(Form)
        self.testPushButton.clicked.connect(self.testPushButton_button_clicked)
        self.testPushButton.setGeometry(QtCore.QRect(10, 570, 241, 31))
        self.testPushButton.setObjectName("testPushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.startPushButton.setText(_translate("Form", "START"))
        self.addCordsPushButton.setText(_translate("Form", "ADD COORDINATES"))
        self.groupBox.setTitle(_translate("Form", "Distance"))
        self.euclidRadioButton.setText(_translate("Form", "Euclid"))
        self.chebishevRadioButton.setText(_translate("Form", "Chebishev"))
        self.stepPushButton.setText(_translate("Form", "STEP"))
        self.restartPushButton.setText(_translate("Form", "RESTART"))
        self.testPushButton.setText(_translate("Form", "Set Test Dataset"))

    def drawLineToDot(self):
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.blue)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.blue)
        pen.setWidth(2)
        pen.setColor(QtCore.Qt.GlobalColor.blue)

        for i in range(len(self.clastersContainer)):
            for j in self.clastersContainer[i]:
                self.scene.addLine(
                    QtCore.QLineF(4 * j[0], -4 * j[1],
                                  4 * self.centersContainer[i][0],
                                  -4 * self.centersContainer[i][1]), pen)

    def stringParser(self, coords, centers):
        coords_l = None
        centers_l = None
        try:
            coords_string_array = coords.split(';')
            centers_string_array = centers.split(';')
            coords_l = []
            centers_l = []

            for i in coords_string_array:
                l = [float(k) for k in i.strip('()').split(',')]
                coords_l.append(l)

            for i in centers_string_array:
                l = [float(k) for k in i.strip('()').split(',')]
                centers_l.append(l)
        except:
            self.CentersTextBox.clear()
            self.coordsTextBox.clear()
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Format Error")
            msg.setInformativeText('Follow the format!')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            pass
        return coords_l, centers_l

    def add_coordinates_to_GraphView(self):
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.black)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.black)
        side = 4
        for i in self.coordsContainer:
            self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7, 7,
                                  pen, brush)

        pen = QtGui.QPen(QtCore.Qt.GlobalColor.red)
        brush = QtGui.QBrush(QtCore.Qt.GlobalColor.red)

        for i in self.centersContainer:
            self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7, 7,
                                  pen, brush)

    def addCordsPushButton_button_clicked(self):
        coordinates = self.coordsTextBox.toPlainText()
        centers = self.CentersTextBox.toPlainText()
        if coordinates == '' or centers == '':
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Data Empty")
            msg.setInformativeText('Please, enter coords')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return

        coordinates_l, centers_l = self.stringParser(coordinates, centers)

        if coordinates_l is not None and centers_l is not None:
            co = self.coordsContainer.copy()
            ce = self.centersContainer.copy()

            co += coordinates_l.copy()
            ce += centers_l.copy()

            co.sort()
            ce.sort()

            co_new = list(num for num, _ in itertools.groupby(co))
            ce_new = list(num for num, _ in itertools.groupby(ce))

            self.centersContainer = ce_new.copy()
            self.coordsContainer = co_new.copy()

            print(self.centersContainer)
            print(self.coordsContainer)

            self.add_coordinates_to_GraphView()

    def startPushButton_button_clicked(self):
        if self.coordsContainer == [] or self.centersContainer == []:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Data Empty")
            msg.setInformativeText('Please, enter coords')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return
        self.chebishevRadioButton.setEnabled(False)
        self.euclidRadioButton.setEnabled(False)
        self.addCordsPushButton.setEnabled(False)
        self.coordsTextBox.setEnabled(False)
        self.CentersTextBox.setEnabled(False)
        self.startPushButton.setEnabled(False)
        self.testPushButton.setEnabled(False)

        if self.distance == 'E':

            for _ in range(len(self.centersContainer)):
                self.clastersContainer.append([])

            for i in self.coordsContainer:
                range_l = []
                for c in self.centersContainer:
                    range_l.append(
                        math.sqrt((i[0] - c[0])**2 + (i[1] - c[1])**2))

                minindex = range_l.index(min(range_l))
                self.clastersContainer[minindex].append(i)
            self.drawLineToDot()
        elif self.distance == 'H':
            for _ in range(len(self.centersContainer)):
                self.clastersContainer.append([])

            for i in self.coordsContainer:
                range_l = []
                for c in self.centersContainer:
                    range_l.append(max(abs(i[0] - c[0]), abs(i[1] - c[1])))

                minindex = range_l.index(min(range_l))
                self.clastersContainer[minindex].append(i)
            self.drawLineToDot()

    def stepPushButton_button_clicked(self):
        if self.centersContainer is None or self.coordsContainer is None:
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Empty Error")
            msg.setInformativeText('Not enough dots!')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            return

        claster_backup = self.clastersContainer.copy()
        new_centers = []
        for i in self.clastersContainer:
            new_x, new_y = 0, 0
            for k in i:
                new_x += k[0]
                new_y += k[1]
            new_x /= len(i)
            new_y /= len(i)
            new_centers.append([new_x, new_y])

        self.centersContainer = new_centers.copy()
        self.redrow(False)
        self.add_coordinates_to_GraphView()
        self.clastersContainer.clear()
        for _ in range(len(self.centersContainer)):
            self.clastersContainer.append([])

        for i in self.coordsContainer:
            range_l = []
            for c in new_centers:
                range_l.append(math.sqrt((i[0] - c[0])**2 + (i[1] - c[1])**2))

            minindex = range_l.index(min(range_l))
            self.clastersContainer[minindex].append(i)
        self.drawLineToDot()
        new_back_clasters = self.clastersContainer.copy()

        if claster_backup == new_back_clasters:
            self.stepPushButton.setEnabled(False)

    def redrow(self, full):
        self.scene.clear()
        pen = QtGui.QPen(QtCore.Qt.GlobalColor.gray)
        for i in range(-1 * self.graphicsView.height() // 2 + 10,
                       self.graphicsView.height() // 2 - 10):
            r1 = QtCore.QRectF(QtCore.QPointF(0, i), QtCore.QSizeF(1, 1))
            self.scene.addRect(r1, pen)

        for i in range(-1 * self.graphicsView.width() // 2 + 10,
                       self.graphicsView.width() // 2 - 10):
            r2 = QtCore.QRectF(QtCore.QPointF(i, 0), QtCore.QSizeF(1, 1))
            self.scene.addRect(r2, pen)
        if not full:

            pen2 = QtGui.QPen(QtCore.Qt.GlobalColor.black)
            brush2 = QtGui.QBrush(QtCore.Qt.GlobalColor.black)

            side = 4
            for i in self.coordsContainer:
                self.scene.addEllipse(i[0] * side - 3, -1 * i[1] * side - 3, 7,
                                      7, pen2, brush2)

    def restartPushButton_button_clicked(self):
        self.chebishevRadioButton.setEnabled(True)
        self.euclidRadioButton.setEnabled(True)
        self.addCordsPushButton.setEnabled(True)
        self.coordsTextBox.setEnabled(True)
        self.CentersTextBox.setEnabled(True)
        self.testPushButton.setEnabled(True)
        self.startPushButton.setEnabled(True)
        self.stepPushButton.setEnabled(True)
        self.redrow(True)

        self.coordsContainer.clear()
        self.centersContainer.clear()
        self.clastersContainer.clear()

    def testPushButton_button_clicked(self):
        self.coordsTextBox.setPlainText(TEST_COORDS)
        if self.distance == 'E':
            self.CentersTextBox.setPlainText(EUCLID_TEST_CENTERS)
        elif self.distance == 'H':
            self.CentersTextBox.setPlainText(CHEBISHEV_TEST_CENTERS)
        else:
            self.coordsTextBox.clear()
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Critical)
            msg.setText("Distance not set")
            msg.setInformativeText('Please, pick the distance')
            msg.setWindowTitle("Error")
            msg.setStyleSheet("QLabel{font-size: 20px;}")
            msg.exec_()
            pass

    def euclidRadioButton_clicked(self):
        if self.euclidRadioButton.isChecked():
            self.distance = 'E'

    def chebishevRadioButton_clicked(self):
        if self.chebishevRadioButton.isChecked():
            self.distance = 'H'
Ejemplo n.º 26
0
class FindInFilesDialog(QDialog):

    """Dialog to configure and trigger the search in the files."""
    findStarted = pyqtSignal()
    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"), translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(QCompleter(
            ["*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(
            translations.TR_TEXT_FOR_REPLACE + "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.open_button.clicked['bool'].connect(self._select_dir)
        self.find_button.clicked['bool'].connect(self._find_in_files)
        self.cancel_button.clicked['bool'].connect(self._kill_thread)
        self._find_thread.found_pattern.connect(self._found_match)
        self._find_thread.finished.connect(self._find_thread_finished)
        self.type_checkbox.stateChanged[int].connect(self._change_radio_enabled)
        self.check_replace.stateChanged[int].connect(self._replace_activated)
        self.words_radio.clicked['bool'].connect(self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.finished.emit(0)
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(self, translations.TR_OPEN,
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.findStarted.emit()
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
Ejemplo n.º 27
0
class CalibWin(QWidget, _calf.calib_functions_mixin, _ie.Imp_Exp_Mixin):
    """ Energy calibration window

    For the names of the children widgets, I tried to put suffixes that indicate clearly their types:
    *_btn -> QPushButton,
    *_le -> QLineEdit,
    *_lb -> QLabel,
    *layout -> QHBoxLayout, QVBoxLayout or QGridLayout,
    *_box -> QGroupBox,
    *_cb -> QCheckBox,
    *_rb -> QRadioButton

    The functions that are connected to a widget's event have the suffix _lr (for 'listener'). For example, a button named
    test_btn will be connected to a function test_lr.
    Some functions may be connected to widgets but without the suffix _lr in their names. It means that they are not only
    called when interacting with the widget.
    """

    ##################################################################################
    ############################ Widget Initialization ###############################

    def __init__(self, parent=None):
        """Initialization of the window

        the main layout is called mainLayout. It is divided in two:
            - graphLayout: the left part, contains all the figures
            - commandLayout: the right part, contains all the buttons, fields, checkboxes...
        Both graphLayout and commandLayout are divided into sub-layouts.

        This function calls several functions to initialize each part of the window. The name of these functions contains
        'init_*layout'.
        """
        super(CalibWin, self).__init__(parent=parent)

        self.setWindowTitle("Energy Calibration")
        self.mainlayout = QHBoxLayout()
        self.graphlayout = QVBoxLayout()
        self.commandlayout = QVBoxLayout()
        self.commandlayout.setSpacing(10)

        # initialization of all the widgets/layouts
        self.init_btnlayout()
        self.init_tof2evlayout()
        self.init_eparlayout()
        self.init_fitparlayout()
        self.init_envectlayout()
        self.init_tofgraphlayout()
        self.init_graphauxlayout()

        # making the buttons not resizable
        for widget in self.children():
            if isinstance(widget, QPushButton):
                widget.setSizePolicy(0, 0)

        self.mainlayout.addLayout(self.graphlayout)
        self.mainlayout.addLayout(self.commandlayout)
        self.setLayout(self.mainlayout)

        self.init_var()

        self.show()

    def init_var(self):
        ''' Initialization of instance attributes'''

        self.withsb_bool = False
        self.calibloaded = False
        self.dataloaded = False
        self.bgndremoved = False
        self.threshyBool = False
        self.threshxminBool = False
        self.threshxmaxBool = False
        self.showexppeaksBool = False
        self.calibBool = False
        self.peaksfound = False

        self.thxmin = 0
        self.thy = 0
        self.thxmax = 0

        self.counts = []

        self.gas_combo.setCurrentIndex(2)  # Argon

    def init_btnlayout(self):
        ''' In commandLayout - Initialization of the top right part of the layout, with 6 buttons (see just below)'''

        btnlayout = QGridLayout()
        btnlayout.setSpacing(10)

        self.load_btn = QPushButton("Load data", self)
        self.rmbgnd_btn = QPushButton("Remove bgnd", self)
        self.findpeaks_btn = QPushButton("Find peaks", self)
        self.rmpeaks_btn = QPushButton("Remove peaks", self)
        self.exportcalib_btn = QPushButton("Export calib", self)
        self.importcalib_btn = QPushButton("Import calib", self)
        self.exportXUV_btn = QPushButton("Export XUV", self)

        self.rmbgnd_btn.setEnabled(False)
        self.findpeaks_btn.setEnabled(False)
        self.rmpeaks_btn.setEnabled(False)
        self.exportcalib_btn.setEnabled(False)
        self.importcalib_btn.setEnabled(False)
        self.exportXUV_btn.setEnabled(False)

        self.load_btn.clicked.connect(self.loadfile_lr)
        self.rmbgnd_btn.clicked.connect(self.rmbgnd_lr)
        self.findpeaks_btn.clicked.connect(self.findpeaks_lr)
        self.importcalib_btn.clicked.connect(self.importcalib_lr)
        self.rmpeaks_btn.clicked.connect(self.removepeaks_lr)
        self.exportXUV_btn.clicked.connect(self.exportXUV_lr)
        self.exportcalib_btn.clicked.connect(self.exportcalib_lr)

        btnlayout.addWidget(self.load_btn, 0, 0)
        btnlayout.addWidget(self.rmbgnd_btn, 0, 1)
        btnlayout.addWidget(self.findpeaks_btn, 1, 0)
        btnlayout.addWidget(self.rmpeaks_btn, 1, 1)
        btnlayout.addWidget(self.exportcalib_btn, 1, 3)
        btnlayout.addWidget(self.importcalib_btn, 1, 2)
        btnlayout.addWidget(self.exportXUV_btn, 0, 3)
        self.commandlayout.addLayout(btnlayout)

    def init_tof2evlayout(self):
        ''' In commandLayout - Initialization of the tof to eV section: parameters of the af.find_local_maxima function,
            'TOF to energy' button and 'with sidebands checkbox' '''

        tof2evlayout = QHBoxLayout()
        flmlayout = QGridLayout()
        flmlayout.setSpacing(10)
        self.flm_box = QGroupBox(self)
        self.flm_box.setTitle("Find local maxima parameters")

        self.sm1_le = QLineEdit("5", self)
        self.sm2_le = QLineEdit("100", self)
        self.mindt_le = QLineEdit("10", self)

        flmlayout.addWidget(QLabel("smooth1"), 0, 0)
        flmlayout.addWidget(self.sm1_le, 1, 0)
        flmlayout.addWidget(QLabel("smooth2"), 0, 1)
        flmlayout.addWidget(self.sm2_le, 1, 1)
        flmlayout.addWidget(QLabel("min dt"), 0, 2)
        flmlayout.addWidget(self.mindt_le, 1, 2)
        self.flm_box.setLayout(flmlayout)

        for widget in self.flm_box.children():
            if isinstance(widget, QLineEdit):
                widget.setSizePolicy(0, 0)
                widget.setFixedSize(50, 20)

        self.tof2en_btn = QPushButton("TOF to energy", self)
        self.tof2en_btn.clicked.connect(self.tof2en_lr)
        self.tof2en_btn.setEnabled(False)

        self.withsb_cb = QCheckBox("With sidebands", self)
        self.withsb_cb.stateChanged.connect(self.withsb_fn)

        tof2evlayout.addWidget(self.flm_box)
        tof2evlayout.addWidget(self.withsb_cb)
        tof2evlayout.addWidget(self.tof2en_btn)
        self.commandlayout.addLayout(tof2evlayout)

    def init_eparlayout(self):
        ''' In commandLayout - Initialization of the experimental parameters section: Retarding potential, TOF length,
            wavelength, gas and first harmonic expected to see.'''

        gases = cts.GASLIST

        epar_box = QGroupBox(self)
        epar_box.setTitle("Experimental parameters")
        epar_box.setSizePolicy(0, 0)
        eparlayout = QGridLayout()
        eparlayout.setSpacing(10)

        self.retpot_le = QLineEdit(str(cts.cur_Vp), self)
        self.toflength_le = QLineEdit(str(cts.cur_L), self)
        self.wvlength_le = QLineEdit(str(cts.lambda_start), self)
        self.gas_combo = QComboBox(self)
        self.gas_combo.addItems(gases)
        self.firstharm_le = QLineEdit(str(cts.first_harm), self)

        self.retpot_le.returnPressed.connect(self.update_cts_fn)
        self.toflength_le.returnPressed.connect(self.update_cts_fn)
        self.wvlength_le.returnPressed.connect(self.update_cts_fn)
        self.firstharm_le.returnPressed.connect(self.update_cts_fn)
        self.gas_combo.currentIndexChanged.connect(self.gas_combo_lr)

        eparlayout.addWidget(QLabel("Ret. pot. (V)"), 0, 0)
        eparlayout.addWidget(self.retpot_le, 1, 0)
        eparlayout.addWidget(QLabel("TOF length (m)"), 0, 1)
        eparlayout.addWidget(self.toflength_le, 1, 1)
        eparlayout.addWidget(QLabel("lambda (nm)"), 0, 2)
        eparlayout.addWidget(self.wvlength_le, 1, 2)
        eparlayout.addWidget(QLabel("gas"), 0, 3)
        eparlayout.addWidget(self.gas_combo, 1, 3)
        eparlayout.addWidget(QLabel("1st harm."), 0, 4)
        eparlayout.addWidget(self.firstharm_le, 1, 4)

        epar_box.setLayout(eparlayout)

        for widget in epar_box.children():
            if isinstance(widget, QLineEdit) or isinstance(widget, QComboBox):
                widget.setFixedSize(50, 20)
                widget.setSizePolicy(0, 0)

        self.commandlayout.addWidget(epar_box)

    def init_fitparlayout(self):
        ''' In commandLayout - Initialization of the fit parameter section with a, t0 and c. First line: guess values calculated
            from the experimental parameters. Second line: fitted values.'''

        fitpar_box = QGroupBox()
        fitpar_box.setTitle("Calibration parameters")
        fitpar_box.setSizePolicy(0, 0)
        fitparlayout = QGridLayout()
        fitparlayout.setSpacing(10)

        self.aguess_lb = QLabel(self)
        self.afit_lb = QLabel(self)
        self.t0guess_lb = QLabel(self)
        self.t0fit_lb = QLabel(self)
        self.cguess_lb = QLabel(self)
        self.cfit_lb = QLabel(self)

        fitparlayout.addWidget(QLabel("a"), 0, 0)
        fitparlayout.addWidget(self.aguess_lb, 1, 0)
        fitparlayout.addWidget(self.afit_lb, 2, 0)
        fitparlayout.addWidget(QLabel("t0"), 0, 1)
        fitparlayout.addWidget(self.t0guess_lb, 1, 1)
        fitparlayout.addWidget(self.t0fit_lb, 2, 1)
        fitparlayout.addWidget(QLabel("c"), 0, 2)
        fitparlayout.addWidget(self.cguess_lb, 1, 2)
        fitparlayout.addWidget(self.cfit_lb, 2, 2)
        fitparlayout.addWidget(QLabel("guess"), 1, 3)
        fitparlayout.addWidget(QLabel("calc"), 2, 3)
        text = "q=a*1/(t-t0)²+c"
        fitparlayout.addWidget(QLabel(text), 1, 4)

        fitpar_box.setLayout(fitparlayout)

        for widget in fitpar_box.children():
            if isinstance(widget, QLabel) and widget.text() != text:
                widget.setSizePolicy(0, 0)
                widget.setFixedSize(55, 15)

        self.commandlayout.addWidget(fitpar_box)

    def init_envectlayout(self):
        ''' In commandLayout - Initialization of the resulting energy vector section, with elow, ehigh and dE'''

        envect_box = QGroupBox()
        envect_box.setTitle("Energy vector parameters")
        envect_box.setSizePolicy(0, 0)
        envectlayout = QGridLayout()
        envectlayout.setSpacing(10)

        self.elow_le = QLineEdit("{:.2f}".format(cts.elow), self)
        self.ehigh_le = QLineEdit("{:.2f}".format(cts.ehigh), self)
        self.dE_le = QLineEdit(str(cts.dE), self)

        self.elow_le.returnPressed.connect(self.update_envect_fn)
        self.ehigh_le.returnPressed.connect(self.update_envect_fn)
        self.dE_le.returnPressed.connect(self.update_envect_fn)

        envectlayout.addWidget(QLabel("E low (eV)"), 0, 0)
        envectlayout.addWidget(self.elow_le, 1, 0)
        envectlayout.addWidget(QLabel("E high (eV)"), 0, 1)
        envectlayout.addWidget(self.ehigh_le, 1, 1)
        envectlayout.addWidget(QLabel("dE (eV)"), 0, 2)
        envectlayout.addWidget(self.dE_le, 1, 2)

        envect_box.setLayout(envectlayout)

        for widget in envect_box.children():
            if isinstance(widget, QLabel) or isinstance(widget, QLineEdit):
                widget.setSizePolicy(0, 0)
                widget.setFixedSize(55, 20)

        self.commandlayout.addWidget(envect_box)
        self.update_envect_fn()

    def init_tofgraphlayout(self):
        ''' In graphLayout - Initialization of the top figure on the window, where the time of flight is plotted'''

        tof_fig = Figure(figsize=(4, 3), dpi=100)
        self.tof_fc = FigureCanvas(tof_fig)
        self.tof_fc.mpl_connect('button_press_event', self.onclick)
        self.tof_ax = self.tof_fc.figure.add_subplot(111)
        self.tof_fc.draw()
        tof_nav = NavigationToolbar2QT(self.tof_fc, self)
        tof_nav.setStyleSheet("QToolBar { border: 0px }")

        tgparalayout = QGridLayout()
        self.threshtype_bgroup = QButtonGroup()
        rblayout = QGridLayout()
        self.setth_cb = QCheckBox("Set threshold", self)
        self.setth_cb.setEnabled(False)
        self.setth_cb.stateChanged.connect(self.setth_lr)
        self.addpeak_cb = QCheckBox("Add peak", self)
        self.addpeak_cb.setEnabled(False)
        self.addpeak_cb.stateChanged.connect(self.addpeak_lr)
        self.showexppeaks_cb = QCheckBox("Show expected peaks", self)
        self.showexppeaks_cb.stateChanged.connect(self.showexppeaks_lr)
        self.showexppeaks_cb.setEnabled(False)

        self.clear_btn = QPushButton("Clear", self)
        self.clear_btn.clicked.connect(self.clear_lr)
        self.clear_btn.setEnabled(False)

        self.Y_rb = QRadioButton("Y", self)
        self.Y_rb.value = "Y"
        self.Y_rb.toggled.connect(self.threshtype_lr)
        self.Y_rb.toggle()
        self.Y_rb.setEnabled(False)

        self.xmin_rb = QRadioButton("X min", self)
        self.xmin_rb.value = "Xm"
        self.xmin_rb.toggled.connect(self.threshtype_lr)
        self.xmin_rb.setEnabled(False)

        self.xmax_rb = QRadioButton("X max", self)
        self.xmax_rb.value = "XM"
        self.xmax_rb.toggled.connect(self.threshtype_lr)
        self.xmax_rb.setEnabled(False)

        self.minus_sign_cb = QCheckBox("*(-1)", self)
        self.minus_sign_cb.setEnabled(False)
        self.minus_sign_cb.stateChanged.connect(self.minus_sign_lr)

        self.threshtype_bgroup.addButton(self.Y_rb)
        self.threshtype_bgroup.addButton(self.xmin_rb)
        self.threshtype_bgroup.addButton(self.xmax_rb)

        rblayout.addWidget(self.Y_rb, 0, 0)
        rblayout.addWidget(self.xmin_rb, 0, 1)
        rblayout.addWidget(self.xmax_rb, 0, 2)
        tgparalayout.addWidget(self.setth_cb, 0, 0)
        tgparalayout.addWidget(self.addpeak_cb, 0, 1)
        tgparalayout.addWidget(self.showexppeaks_cb, 0, 2)
        tgparalayout.addWidget(self.clear_btn, 0, 3)
        tgparalayout.addLayout(rblayout, 1, 0, 1, 3)
        tgparalayout.addWidget(self.minus_sign_cb, 1, 3)

        self.graphlayout.addWidget(self.tof_fc)
        self.graphlayout.addWidget(tof_nav)
        self.graphlayout.addLayout(tgparalayout)

    def init_graphauxlayout(self):
        ''' In graphLayout - Initialization the two bottom figures on the window'''

        graphauxlayout = QHBoxLayout()
        ga1layout = QVBoxLayout()
        ga2layout = QVBoxLayout()

        fit_fig = Figure(figsize=(2, 2), dpi=100)
        self.fit_fc = FigureCanvas(fit_fig)
        self.fit_fc.setSizePolicy(1, 0)
        self.fit_ax = self.fit_fc.figure.add_subplot(111)
        self.fit_ax.tick_params(labelsize=8)
        ga1layout.addWidget(self.fit_fc)
        self.fit_fc.draw()

        en_fig = Figure(figsize=(2, 2), dpi=100)
        self.en_fc = FigureCanvas(en_fig)
        #self.en_fc.setSizePolicy(1, 0)
        self.en_ax = self.en_fc.figure.add_subplot(111)
        self.en_ax.tick_params(labelsize=8)
        self.en_fc.draw()
        en_nav = NavigationToolbar2QT(self.en_fc, self)
        en_nav.setStyleSheet("QToolBar { border: 0px }")
        ga2layout.addWidget(self.en_fc)
        ga2layout.addWidget(en_nav)

        graphauxlayout.addLayout(ga1layout)
        graphauxlayout.addLayout(ga2layout)
        self.graphlayout.addLayout(graphauxlayout)

    #################################################################################
    ############################ Other methods ######################################

    def update_fitpar_fn(self):
        ''' Updating the fit parameters on the window'''

        if (self.calibBool):
            self.afit_lb.setText("{:.3e}".format(cts.afit))
            self.t0fit_lb.setText("{:.3e}".format(cts.t0fit))
            self.cfit_lb.setText("{:.3f}".format(cts.cfit))

    def update_envect_fn(self):
        ''' Updating th energy vector parameters with the values written in the associated QLineEdit objects'''

        cts.elow = float(self.elow_le.text())
        cts.ehigh = float(self.ehigh_le.text())
        cts.dE = float(self.dE_le.text())
        self.elow_le.setText("{:.2f}".format(cts.elow))
        self.ehigh_le.setText("{:.2f}".format(cts.ehigh))
        self.window().updateglobvar_fn()

    def gas_combo_lr(self, i):
        ''' Gas QCombobox listener'''
        cts.cur_Ip = cts.IPLIST[i]
        cts.first_harm = cts.FIRST_HARMLIST[i]
        self.firstharm_le.setText(str(cts.first_harm))
        cts.elow = (cts.first_harm - 1) * cts.HEV * cts.cur_nu
        self.elow_le.setText("{:.2f}".format(cts.elow))
        self.update_cts_fn()

    def threshtype_lr(self):
        ''' Listener of the threshold radiobuttons: Y, Xmin or Xmax'''
        rb = self.sender()
        self.threshtype = rb.value

    def withsb_fn(self, state):
        ''' "with sidebands" checkbox listener '''
        if state == Qt.Checked:
            self.withsb_bool = True
        else:
            self.withsb_bool = False

    def showexppeaks_lr(self, state):
        ''' "show expected peaks" checkbox listener '''
        if state == Qt.Checked:
            self.showexppeaksBool = True
        else:
            self.showexppeaksBool = False
        self.refreshplot_fn()

    def setth_lr(self):
        ''' "set threshold" checkbox listener '''
        if self.setth_cb.isChecked():
            self.addpeak_cb.setCheckState(Qt.Unchecked)

    def addpeak_lr(self):
        ''' "add peak" checkbox listener '''
        if self.addpeak_cb.isChecked():
            self.setth_cb.setCheckState(Qt.Unchecked)

    def removepeaks_lr(self):
        ''' "remove peaks" button listener '''
        rmp = rmPeaksDialog(self)  # new class defined below

    def refreshplot_fn(self):
        ''' Updating the top left (TOF) graph'''
        xmin, xmax = self.tof_ax.get_xlim()
        ymin, ymax = self.tof_ax.get_ylim()
        self.tof_ax.cla()

        self.tof_ax.xaxis.set_major_formatter(FormatStrFormatter('%2.e'))
        self.tof_ax.yaxis.set_major_formatter(FormatStrFormatter('%1.e'))
        self.tof_ax.set_ylabel("counts (arb. units)")
        self.tof_ax.set_xlabel("TOF (s)")

        if self.dataloaded:
            self.tof_ax.plot(self.counts[:, 0], self.counts[:, 1])
        if self.threshyBool:
            self.tof_ax.plot(self.threshyline[:, 0], self.threshyline[:, 1],
                             'k')
        if self.threshxminBool:
            self.tof_ax.plot(self.threshxminline[:, 0],
                             self.threshxminline[:, 1], 'k')
        if self.threshxmaxBool:
            self.tof_ax.plot(self.threshxmaxline[:, 0],
                             self.threshxmaxline[:, 1], 'k')
        if self.peaksfound:
            self.tof_ax.plot(self.maximaIndices, self.maximaIntensity, 'ro')
            self.tof_ax.plot(self.counts[:, 0], self.convolvedsignal)

        if self.showexppeaksBool:
            qq2 = np.arange(cts.first_harm, 35, 1)

            y = np.linspace(ymax - (ymax - ymin) * 0.2, ymax, 100)
            for i in range((len(qq2))):
                if qq2[i] % 2 == 0:
                    c = 'r'
                else:
                    c = 'k'
                try:
                    xval = float(
                        np.math.sqrt(0.5 * cts.ME * cts.cur_L**2 / cts.QE /
                                     (qq2[i] * cts.HEV * cts.cur_nu -
                                      cts.cur_Ip)) + 6e-8)
                    # NB: cts.QE is used to convert the energy from eV to Joules. It's not the electron's charge
                    x = np.full((100, 1), xval)
                except Exception:
                    print(traceback.format_exception(*sys.exc_info()))
                self.tof_ax.plot(x, y, color=c, linewidth=1.0)

        if self.bgndremoved:
            self.bgndremoved = False  #this means that when we remove bgnd, we don't keep the same scale
        else:
            self.tof_ax.set_ylim(ymin, ymax)

        self.tof_ax.set_xlim(xmin, xmax)
        self.tof_fc.draw()

    def onclick(self, event):
        ''' called when double-clicking on the TOF graph'''
        if self.dataloaded and self.addpeak_cb.isChecked(
        ):  #add a peak on clicking on the figure
            i = 0
            ifound = False
            while (i < len(self.maximaIndices) and ifound == False):
                if (self.maximaIndices[i] < event.xdata):
                    i += 1
                else:
                    ifound = True
            self.maximaIndices.insert(i, event.xdata)
            self.maximaIntensity.insert(i, event.ydata)
            self.refreshplot_fn()

        if self.dataloaded and self.setth_cb.isChecked():
            if self.Y_rb.isChecked():
                self.thy = event.ydata
                self.threshyline = np.full((len(self.counts), 2), self.thy)
                self.threshyline[:, 0] = self.counts[:, 0]
                self.threshyBool = True
            elif self.xmin_rb.isChecked():
                self.thxmin = event.xdata
                self.threshxminline = np.full((len(self.counts), 2),
                                              self.thxmin)
                self.threshxminline[:, 1] = self.counts[:, 1]
                self.threshxminBool = True
            elif self.xmax_rb.isChecked():
                self.thxmax = event.xdata
                self.threshxmaxline = np.full((len(self.counts), 2),
                                              self.thxmax)
                self.threshxmaxline[:, 1] = self.counts[:, 1]
                self.threshxmaxBool = True
            self.refreshplot_fn()

    def exportXUV_lr(self):
        ''' "Export XUV" button listener. Saving the energy vector and the energy-converted TOF signal'''
        filename = QFileDialog.getSaveFileName(self, 'Save XUV')
        fname = filename[0]
        if fname:
            XUV_array = np.vstack((self.Eevlin, self.signal)).T
            np.savetxt(fname, XUV_array, delimiter='\t')

    def clear_lr(self):
        ''' "Clear" button listener. Resets all the objects, but not the global variables'''
        self.tof_ax.cla()
        self.fit_ax.cla()
        self.en_ax.cla()

        self.dataloaded = False
        self.threshyBool = False
        self.threshxminBool = False
        self.threshxmaxBool = False
        self.calibloaded = False
        self.calibBool = False

        self.Y_rb.setEnabled(False)
        self.xmin_rb.setEnabled(False)
        self.xmax_rb.setEnabled(False)
        self.minus_sign_cb.setEnabled(False)

        for w in self.children():
            if isinstance(w, QPushButton) or isinstance(w, QCheckBox):
                w.setEnabled(False)
        self.load_btn.setEnabled(True)
        self.importcalib_btn.setEnabled(False)

        self.minus_sign_cb.setEnabled(False)

        self.tof_fc.draw()
        self.fit_fc.draw()
        self.en_fc.draw()

        cts.clear_varlist()
        self.window().updateglobvar_fn()
Ejemplo n.º 28
0
class ErrorTab(QWidget):
    def __init__(self):
        super().__init__()
       # self.error_dar("Voltage Error:",self.checkVerror(), self.checkTerror())

        self.v_box = QVBoxLayout()
        self.setLayout(self.v_box)
        # set layout with the label and its icon
        h_box1 = QHBoxLayout()
        self.l = QLabel("Voltage Error:")
        self.p = QLabel('')
        self.i = QPixmap('C:/Users/iheb/BMS_UI/icons/voltage.ico')
        self.p.setPixmap(self.i.scaled(25, 25))

        h_box1.addWidget(self.p)
        h_box1.addWidget(self.l)
        h_box1.addStretch()
        # set layout with the label and its icon
        h_box2 = QHBoxLayout()
        self.l1 = QLabel("Temperature Error:")
        self.p1 = QLabel('')
        self.i1 = QPixmap('C:/Users/iheb/BMS_UI/icons/temperature.ico')
        self.p1.setPixmap(self.i1.scaled(25, 25))

        h_box2.addWidget(self.p1)
        h_box2.addWidget(self.l1)
        h_box2.addStretch()

        h_box3 = QHBoxLayout()
        self.l2 = QLabel('Current Error:')
        self.p2 = QLabel('')
        self.i2 = QPixmap('C:/Users/iheb/BMS_UI/icons/voltage.ico')
        self.p2.setPixmap(self.i2.scaled(25, 25))

        h_box3.addWidget(self.p2)
        h_box3.addWidget(self.l2)
        h_box3.addStretch()
        # set the final label
        '''self.v_box.addLayout(h_box3)
        self.v_box.addStretch()

        self.v_box.addSpacing(10)

        .c = self.error_dar('c')
        self.c_l = QHBoxLayout()
        self.c_l.addLayout(self.c)
        self.refresh(self.c_l,'c')
        self.v_box.addLayout(self.c_l)
        #self.update_c()
        self.v_box.addSpacing(10)
        self.v_box.addStretch()'''

        self.v_box.addLayout(h_box1)
        self.v_box.addStretch()

        self.v = self.error_dar('v')
        self.v_l = QHBoxLayout()
        self.v_l.addLayout(self.v)
        self.refresh(self.v_l, 'v')

        self.v_box.addLayout(self.v_l)
        self.v_box.addStretch()

        self.v_box.addLayout(h_box2)
        self.v_box.addStretch()

        self.t = self.error_dar('t')
        self.t_l = QHBoxLayout()
        self.t_l.addLayout(self.t)
        self.refresh(self.t_l, 't')

        self.v_box.addLayout(self.t_l)
        self.v_box.addStretch()





    def unfill(self, box): #methode that deletes the layout and its content
        def deleteItems(layout):
            if layout is not None:
                while layout.count():
                    item = layout.takeAt(0)
                    widget = item.widget()
                    if widget is not None:
                        widget.deleteLater()
                    else:
                        deleteItems(item.layout())

        deleteItems(box)










    def error_dar(self,types): #methode that represent the cells errors in a radio button widget and returns Layouts
        self.grid = QGridLayout()
        '''threading.Thread(target=self.data.fillData(150,'v')).start()
        threading.Thread(target=self.data.fillData(80, 't')).start()
        threading.Thread(target=self.data.fillData(150, 'c')).start()'''


        values = np.array([7, 8, 21, 22, 35, 36, 49, 50,  63, 64, 77, 78, 91, 92, 105, 106,119, 120, 133, 134,
                  6, 9, 20, 23, 34, 37, 48, 51,  62, 65, 76, 79, 90, 93, 104, 107,118, 121, 132, 135,
                  5, 10, 19, 24, 33, 38, 47, 52, 61, 66, 75, 80, 89, 94, 103, 108,117, 122, 131, 136,
                  4, 11, 18, 25, 32, 39, 46, 53, 60, 67, 74, 81, 88, 95, 102, 109,116, 123, 130, 137,
                  3, 12, 17, 26, 31, 40, 45, 54, 59, 68, 73, 82, 87, 96, 101, 110,115, 124, 129, 138,
                  2, 13, 16, 27, 30, 41, 44, 55, 58, 69, 72, 83, 86, 97, 100, 111,114, 125, 128, 139,
                  1, 14, 15, 28, 29, 42, 43, 56, 57, 70, 71, 84, 85, 98, 99,  112,113, 126, 127, 140,
                  ])
        positions = np.array([(i,j) for i in range(7) for j in range(20)])

        values1 = np.array([4,5,12,13,20,21,28,29,36,37,44,45,52,53,60,61,68,69,76,77,
                   3,6,11,14,19,22,27,30,35,38,43,46,51,54,59,62,67,70,75,78,
                   2,7,10,15,18,23,26,31,34,39,42,47,50,55,58,63,66,71,74,79,
                   1,8, 9,16,17,24,25,32,33,40,41,48,49,56,57,64,65,72,73,80])

        positions1 = np.array([(i, j) for i in range(4) for j in range(20)])


        if types == 'v':

            #self.data.checkErrors(140, 'v')
            h_box1 = QHBoxLayout()

            for position, value in zip(positions, values):
                #print('position = ' + str(position))
                #print('value = ' + str(values))
                if value == '':
                    continue
                self.b= QRadioButton(str(value))
                self.b.setEnabled(False)
                if not(self.getErrors(value,'v')): #check errors for every cell while creating the radiobutton
                    self.b.setChecked(True)
                else:
                    self.b.setChecked(False)
                self.grid.addWidget(self. b, *position)
            h_box1.addLayout(self.grid)
            return h_box1







        elif types == 't':
            #self.data.checkErrors(80, 't')
            h_box2 = QHBoxLayout()
            for position, value in zip(positions1, values1):

                if value == '':
                    continue
                self.b = QRadioButton(str(value))
                self.b.setEnabled(False)
                if not(self.getErrors(value,'t')):
                    self.b.setChecked(True)

                else:
                    self.b.setChecked(False)

                if value %4 ==1:
                    self.b.setChecked(True)

                self.grid.addWidget(self.b, *position)

            h_box2.addLayout(self.grid)
            return h_box2



        '''elif types == 'c':
            #self.data.checkErrors(140, 'c')
            self.b1 = QRadioButton('No Error')
            self.b2 = QRadioButton('Error')
            h_box = QHBoxLayout()
            h_box.addWidget(self.b1)
            h_box.addStretch()
            h_box.addWidget(self.b2)
            h_box.addStretch()
            self.b1.setEnabled(False)
            self.b2.setEnabled(False)
            if not(self.getErrors(1,'c')):
                self.b1.setChecked(True)
            else:
                self.b2.setChecked(True)

            return h_box'''



    def update_error(self,layout, type ): #methode that updates the errors representation
        try:



            if type == 'v':
                self.unfill(layout)
                layout.addLayout(self.error_dar('v'))
            elif type == 't':
                self.unfill(layout)
                layout.addLayout(self.error_dar('t'))
            elif type =='c':
                self.unfill(layout)
                layout.addLayout(self.error_dar('c'))
        except TypeError:
            print('error with Error-update')



    def refresh(self, layout, type): #methode that times the updates of the errors representation
        try:

            if type == 'v':
                self.timer1 = QTimer()
                self.timer1.timeout.connect(lambda: self.update_error(layout,'v'))

                self.timer1.start(3000)
            elif type == 't':
                self.timer2 = QTimer()
                self.timer2.timeout.connect(lambda: self.update_error(layout, 't'))

                self.timer2.start(3000)
            elif type == 'c':
                self.timer3 = QTimer()
                self.timer3.timeout.connect(lambda: self.update_error(layout, 'c'))

                self.timer3.start(3000)



        except TypeError:
            print('problem with Error-refresh')









    def getErrors(self, cell , type): #methode that returns the errors from the Data class


        threading.Thread(target=BMS_Data.setErrors(p.numberOfCells, 'v')).start()
        threading.Thread(target=BMS_Data.setErrors(p.numberOfTempSensors, 't')).start()


        if (type == 'v'):
            return BMS_Data.getErrors(cell-1,'v')
        if (type == 't'):
            return BMS_Data.getErrors(cell-1,'t')













####################################################################################################################
Ejemplo n.º 29
0
    def add_options_panel(self):
        # Prepare the sliders
        options_layout = QVBoxLayout()

        options_layout.addStretch()  # Centralize the sliders
        sliders_layout = QVBoxLayout()
        max_label_width = -1

        # Get min and max for all dof
        ranges = []
        for i in range(self.model.nbSegment()):
            seg = self.model.segment(i)
            for r in seg.QRanges():
                ranges.append([r.min(), r.max()])

        for i in range(self.model.nbDof()):
            slider_layout = QHBoxLayout()
            sliders_layout.addLayout(slider_layout)

            # Add a name
            name_label = QLabel()
            name = f"{self.model.nameDof()[i].to_string()}"
            name_label.setText(name)
            name_label.setPalette(self.palette_active)
            label_width = name_label.fontMetrics().boundingRect(
                name_label.text()).width()
            if label_width > max_label_width:
                max_label_width = label_width
            slider_layout.addWidget(name_label)

            # Add the slider
            slider = QSlider(Qt.Horizontal)
            slider.setMinimumSize(100, 0)
            slider.setMinimum(ranges[i][0] * self.double_factor)
            slider.setMaximum(ranges[i][1] * self.double_factor)
            slider.setPageStep(self.double_factor)
            slider.setValue(0)
            slider.valueChanged.connect(self.__move_avatar_from_sliders)
            slider.sliderReleased.connect(
                partial(self.__update_muscle_analyses_graphs, False, False,
                        False, False))
            slider_layout.addWidget(slider)

            # Add the value
            value_label = QLabel()
            value_label.setText(f"{0:.2f}")
            value_label.setPalette(self.palette_active)
            slider_layout.addWidget(value_label)

            # Add to the main sliders
            self.sliders.append((name_label, slider, value_label))
        # Adjust the size of the names
        for name_label, _, _ in self.sliders:
            name_label.setFixedWidth(max_label_width + 1)

        # Put the sliders in a scrollable area
        sliders_widget = QWidget()
        sliders_widget.setLayout(sliders_layout)
        sliders_scroll = QScrollArea()
        sliders_scroll.setFrameShape(0)
        sliders_scroll.setWidgetResizable(True)
        sliders_scroll.setWidget(sliders_widget)
        options_layout.addWidget(sliders_scroll)

        # Add reset button
        button_layout = QHBoxLayout()
        options_layout.addLayout(button_layout)
        reset_push_button = QPushButton("Reset")
        reset_push_button.setPalette(self.palette_active)
        reset_push_button.released.connect(self.reset_q)
        button_layout.addWidget(reset_push_button)

        # Add the radio button for analyses
        option_analyses_group = QGroupBox()
        option_analyses_layout = QVBoxLayout()
        # Add text
        analyse_text = QLabel()
        analyse_text.setPalette(self.palette_active)
        analyse_text.setText("Analyses")
        option_analyses_layout.addWidget(analyse_text)
        # Add the no analyses
        radio_none = QRadioButton()
        radio_none.setPalette(self.palette_active)
        radio_none.setChecked(True)
        radio_none.toggled.connect(
            lambda: self.__select_analyses_panel(radio_none, 0))
        radio_none.setText("None")
        option_analyses_layout.addWidget(radio_none)
        # Add the muscles analyses
        radio_muscle = QRadioButton()
        radio_muscle.setPalette(self.palette_active)
        radio_muscle.toggled.connect(
            lambda: self.__select_analyses_panel(radio_muscle, 1))
        radio_muscle.setText("Muscles")
        option_analyses_layout.addWidget(radio_muscle)
        # Add the layout to the interface
        option_analyses_group.setLayout(option_analyses_layout)
        options_layout.addWidget(option_analyses_group)

        # Finalize the options panel
        options_layout.addStretch()  # Centralize the sliders

        # Animation panel
        animation_layout = QVBoxLayout()
        animation_layout.addWidget(self.vtk_window.avatar_widget)

        # Add the animation slider
        animation_slider_layout = QHBoxLayout()
        animation_layout.addLayout(animation_slider_layout)
        load_push_button = QPushButton("Load movement")
        load_push_button.setPalette(self.palette_active)
        load_push_button.released.connect(self.__load_movement_from_button)
        animation_slider_layout.addWidget(load_push_button)

        # Controllers
        self.play_stop_push_button = QPushButton()
        self.play_stop_push_button.setIcon(self.start_icon)
        self.play_stop_push_button.setPalette(self.palette_active)
        self.play_stop_push_button.setEnabled(False)
        self.play_stop_push_button.released.connect(
            self.__start_stop_animation)
        animation_slider_layout.addWidget(self.play_stop_push_button)

        slider = QSlider(Qt.Horizontal)
        slider.setMinimum(0)
        slider.setMaximum(100)
        slider.setValue(0)
        slider.setEnabled(False)
        slider.valueChanged.connect(self.__animate_from_slider)
        animation_slider_layout.addWidget(slider)

        self.record_push_button = QPushButton()
        self.record_push_button.setIcon(self.record_icon)
        self.record_push_button.setPalette(self.palette_active)
        self.record_push_button.setEnabled(True)
        self.record_push_button.released.connect(self.__record)
        animation_slider_layout.addWidget(self.record_push_button)

        self.stop_record_push_button = QPushButton()
        self.stop_record_push_button.setIcon(self.stop_icon)
        self.stop_record_push_button.setPalette(self.palette_active)
        self.stop_record_push_button.setEnabled(False)
        self.stop_record_push_button.released.connect(self.__stop_record, True)
        animation_slider_layout.addWidget(self.stop_record_push_button)

        # Add the frame count
        frame_label = QLabel()
        frame_label.setText(f"{0}")
        frame_label.setPalette(self.palette_inactive)
        animation_slider_layout.addWidget(frame_label)

        self.movement_slider = (slider, frame_label)

        # Global placement of the window
        self.vtk_window.main_layout.addLayout(options_layout, 0, 0)
        self.vtk_window.main_layout.addLayout(animation_layout, 0, 1)
        self.vtk_window.main_layout.setColumnStretch(0, 1)
        self.vtk_window.main_layout.setColumnStretch(1, 2)

        # Change the size of the window to account for the new sliders
        self.vtk_window.resize(self.vtk_window.size().width() * 2,
                               self.vtk_window.size().height())

        # Prepare all the analyses panel
        self.muscle_analyses = MuscleAnalyses(self.analyses_muscle_widget,
                                              self)
        if biorbd.currentLinearAlgebraBackend() == 1:
            radio_muscle.setEnabled(False)
        else:
            if self.model.nbMuscles() == 0:
                radio_muscle.setEnabled(False)
        self.__select_analyses_panel(radio_muscle, 1)
Ejemplo n.º 30
0
Archivo: SafeB.py Proyecto: lebik/SafeB
class SafeB(QWidget):
    def __init__(self):
        super().__init__()
        self.setAcceptDrops(True)
        self.initUI()

    def initUI(self):
        self.center()
        self.setFixedSize(435, 400)
        self.setWindowTitle('SafeB')
        self.setWindowIcon(QIcon('logo.png'))

        # Add LineEdit for Puth
        self.line_edit = QLineEdit(self)
        self.line_edit.setReadOnly(True)
        self.line_edit.resize(250, 23)
        self.line_edit.move(5, 5)
        self.line_edit.setText('Path to file')
        self.line_edit.setStyleSheet("color: rgb(167, 167, 167);")
        self.line_edit.setAcceptDrops(True)
        self.line_edit.textChanged.connect(self.onChangedPath)

        self.radio1 = QRadioButton(self)
        self.radio1.setText('one image')
        self.radio1.move(262, 37)
        self.radio1.setChecked(True)
        config.rad1 = self.radio1

        self.radio2 = QRadioButton(self)
        self.radio2.setText('few images')
        self.radio2.move(340, 37)
        config.rad2 = self.radio2

        # Add LineEdit for Username
        self.username = QLineEdit(self)
        self.username.resize(250, 23)
        self.username.move(5, 33)
        self.username.setText('Username')
        self.username.setStyleSheet("color: rgb(167, 167, 167);")
        self.username.textChanged.connect(self.onChanged2)
        self.username.mousePressEvent = lambda _: \
            self.username.selectAll()
        config.usern = self.username

        # Add LineEdit for Password
        self.password = QLineEdit(self)
        self.password.resize(250, 23)
        self.password.move(5, 61)
        self.password.setText('Password')
        self.password.setStyleSheet("color: rgb(167, 167, 167);")
        self.password.textChanged.connect(self.onChanged)
        self.password.mousePressEvent = lambda _: \
            self.password.selectAll()
        config.pwd = self.password

        # Add result textline
        self.resultText = QLabel(self)
        self.resultText.move(262, 50) #262
        self.resultText.resize(200, 46)
        self.resultText.setText('Score: ')
        self.resultText.setStyleSheet("color: rgb(167, 167, 167);")
        config.res = self.resultText


        # Add LineEdit for classifier_ids
        self.classifier_ids = QLineEdit(self)
        self.classifier_ids.resize(250, 23)
        self.classifier_ids.move(5, 89)
        self.classifier_ids.setText('Classifier_ids')
        self.classifier_ids.setStyleSheet("color: rgb(167, 167, 167);")
        self.classifier_ids.textChanged.connect(self.onChanged3)
        self.classifier_ids.mousePressEvent = lambda _: \
            self.classifier_ids.selectAll()
        config.c_id = self.classifier_ids

        # image for send
        self.pic = QLabel(self)
        self.pic.resize(567, 278)
        self.pic.move(5, 117)
        config.pic = self.pic

        # Add AddButton to type the Puth
        self.btn_add = QPushButton('Add', self)
        self.btn_add.resize(self.btn_add.sizeHint())
        self.btn_add.move(260, 5)
        self.btn_add.clicked.connect(self.showDialog)
        config.addB = self.btn_add

        # Add SendButton to send a picture
        self.btn_send = QPushButton('Send', self)
        self.btn_send.resize(self.btn_send.sizeHint())
        self.btn_send.move(340, 5)
        self.btn_send.clicked.connect(self.sendPic)
        config.sendB = self.btn_send

        self.show()

    def showDialog(self):
        if self.radio1.isChecked():
            path = QFileDialog.getOpenFileName()
        else:
            path = QFileDialog.getExistingDirectory()
        if ''.join(path) != '':
            config.path = ''.join(path)
            self.line_edit.setText(config.path)

    def onChangedPath(self, text):
        self.line_edit.setStyleSheet("color: rgb(0, 0, 0);")
        if text[0:8] == 'file:///':
            config.path = text[8:]
            self.line_edit.setText(config.path)
        # use full ABSOLUTE path to the image, not relative
        try:
            self.pic.setPixmap(QtGui.QPixmap(config.path).scaledToHeight(278))
        except:
            print('Not image!')
        str = config.path
        str_split = str.split('/')
        if parse_name(str_split):
            self.radio1.setChecked(True)
        else:
            self.radio2.setChecked(True)

    def onChanged(self, text):
        config.password = text
        self.password.setEchoMode(2)
        self.password.setStyleSheet("color: rgb(0, 0, 0);")

    def onChanged2(self, text):
        config.username = text
        self.username.setStyleSheet("color: rgb(0, 0, 0);")

    def onChanged3(self, text):
        config.classifier_ids = text
        self.classifier_ids.setStyleSheet("color: rgb(0, 0, 0);")

    def sendPic(self):
        self.resultText.setText('Processing...')
        self.resultText.setStyleSheet("color: rgb(0, 0, 0);")
        self.btn_send.setEnabled(False)
        self.btn_add.setEnabled(False)
        self.radio1.setEnabled(False)
        self.radio2.setEnabled(False)
        config.usern.setEnabled(False)
        config.pwd.setEnabled(False)
        config.c_id.setEnabled(False)
        runnable = Runnable()
        QtCore.QThreadPool.globalInstance().start(runnable)

    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            super(SafeB, self).dragEnterEvent(event)

    def dropEvent(self, e):
        self.line_edit.setStyleSheet("color: rgb(0, 0, 0);")
        self.line_edit.setText(e.mimeData().text())
        config.path = self.line_edit.text()
Ejemplo n.º 31
0
class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        con = sqlite3.connect("Launch_Data.db")
        self.cur = con.cursor()
        self.setGeometry(0, 0, 1500, 800)
        self.setWindowTitle('Моделирование движения ракеты')
        layout = QVBoxLayout(
        )  # установка стиля расположения UI элементов вертикально

        # создание интерфэйса
        # Поле для ввода широты
        self.Latitudelabel = QLabel(self)
        self.Latitudelabel.setText("Latitude")
        self.Latitudelabel.move(20, 30)
        self.Latitudelabel.resize(120, 20)
        layout.addWidget(self.Latitudelabel)

        self.LatitudeInput = QLineEdit(self)
        self.LatitudeInput.setText('70')
        self.LatitudeInput.move(80, 30)
        self.LatitudeInput.resize(125, 20)
        layout.addWidget(self.LatitudeInput)
        # при изменений значения поля ввода вызывается функция adjustLatitude
        self.LatitudeInput.textChanged.connect(self.adjustLatitude)

        # поля для ввода долготы
        self.LongitudeLabel = QLabel(self)
        self.LongitudeLabel.setText("Longitude")
        self.LongitudeLabel.move(20, 60)
        layout.addWidget(self.LongitudeLabel)

        self.LongitudeInput = QLineEdit(self)
        self.LongitudeInput.setText('-90')
        self.LongitudeInput.move(80, 60)
        self.LongitudeInput.resize(125, 20)
        layout.addWidget(self.LongitudeInput)
        self.LongitudeInput.textChanged.connect(self.adjustLongitude)

        # поля для ввода высоты над уровнем моря
        self.ElevationLabel = QLabel(self)
        self.ElevationLabel.setText("Elevation")
        self.ElevationLabel.move(20, 90)
        layout.addWidget(self.ElevationLabel)

        self.ElevationInput = QLineEdit(self)
        self.ElevationInput.setText('560')
        self.ElevationInput.move(80, 90)
        self.ElevationInput.resize(125, 20)
        layout.addWidget(self.ElevationInput)

        # поля для ввода угла наклона ракеты
        self.InclinationLabel = QLabel(self)
        self.InclinationLabel.setText("Inclination")
        layout.addWidget(self.InclinationLabel)

        self.InclinationInput = QLineEdit(self)
        self.InclinationInput.setText('85')
        layout.addWidget(self.InclinationInput)
        self.InclinationInput.textChanged.connect(self.adjustInclination)

        # поля для ввода даты запуска
        self.DateLabel = QLabel(self)
        self.DateLabel.move(20, 120)
        self.DateLabel.setText("Date")
        layout.addWidget(self.DateLabel)

        # текущяя дата
        now = datetime.datetime.now()
        self.DateInput = QDateEdit(self)
        self.DateInput.setDate(now)
        self.DateInput.move(80, 120)
        self.DateInput.resize(125, 20)
        layout.addWidget(self.DateInput)
        self.DateInput.dateTimeChanged.connect(self.adjustDate)

        # кнопка для получения графиков об атмосферных условиях в ту дату
        self.EnvironmentInfo = QPushButton("Environment")
        self.EnvironmentInfo.move(20, 150)
        layout.addWidget(self.EnvironmentInfo)
        self.EnvironmentInfo.clicked.connect(self.EnvironmentD)

        # группирование все радио кнопок для выбора ввида мотора
        self.motorgroup = QButtonGroup()

        self.m7450 = QRadioButton("Cesaroni 7450M2505")
        self.m7450.move(20, 180)
        self.motorgroup.addButton(self.m7450)
        layout.addWidget(self.m7450)
        # заранее активирование одной радио кнопки
        self.m7450.setEnabled(True)
        # каждый раз при выборе этой радикнопки вызывается функция для установки текущего выбора
        self.m7450.toggled.connect(lambda: self.setMotor(self.m7450.text()))

        self.j360 = QRadioButton("Cesaroni J360")
        self.j360.move(20, 210)
        self.motorgroup.addButton(self.j360)
        layout.addWidget(self.j360)
        self.j360.toggled.connect(lambda: self.setMotor(self.j360.text()))

        self.m1300 = QRadioButton("Cesaroni M1300")
        self.motorgroup.addButton(self.m1300)
        layout.addWidget(self.m1300)
        self.m1300.toggled.connect(lambda: self.setMotor(self.m1300.text()))

        self.m1400 = QRadioButton("Cesaroni M1400")
        self.motorgroup.addButton(self.m1400)
        layout.addWidget(self.m1400)
        self.m1400.toggled.connect(lambda: self.setMotor(self.m1400.text()))

        self.m1540 = QRadioButton("Cesaroni M1540")
        self.motorgroup.addButton(self.m1540)
        layout.addWidget(self.m1540)
        self.m1540.toggled.connect(lambda: self.setMotor(self.m1540.text()))

        self.m1670 = QRadioButton("Cesaroni M1670")
        self.motorgroup.addButton(self.m1670)
        layout.addWidget(self.m1670)
        self.m1670.toggled.connect(lambda: self.setMotor(self.m1670.text()))

        self.m3100 = QRadioButton("Cesaroni M3100")
        self.motorgroup.addButton(self.m3100)
        layout.addWidget(self.m3100)
        self.m3100.toggled.connect(lambda: self.setMotor(self.m3100.text()))

        self.j115 = QRadioButton("Hypertek J115")
        self.motorgroup.addButton(self.j115)
        layout.addWidget(self.j115)
        self.j115.toggled.connect(lambda: self.setMotor(self.j115.text()))

        # кнопка для вывода графика сопротивления со временем мотора
        self.motorinfo = QPushButton("Motor")
        layout.addWidget(self.motorinfo)
        # при нажатий вызывается функция для вывода графика
        self.motorinfo.clicked.connect(self.motorInfo)

        # группирование всех радио кнопок для выбора ракеты
        self.rocketgroup = QButtonGroup()

        self.caldene = QRadioButton("Caldene")
        self.rocketgroup.addButton(self.caldene)
        layout.addWidget(self.caldene)
        self.caldene.toggled.connect(
            lambda: self.setRocket(self.caldene.text()))
        # заранее выбор одной из радио кнопок
        self.caldene.setEnabled(True)

        # создание радио кнопок для выбора вида ракеты
        self.calisto = QRadioButton("Calisto")
        self.rocketgroup.addButton(self.calisto)
        layout.addWidget(self.calisto)
        # при выборе вызов функций меняющий текущий вид ракеты
        self.calisto.toggled.connect(
            lambda: self.setRocket(self.calisto.text()))

        self.europia = QRadioButton("Euporia")
        self.rocketgroup.addButton(self.europia)
        layout.addWidget(self.europia)
        self.europia.toggled.connect(
            lambda: self.setRocket(self.europia.text()))

        self.jiboia = QRadioButton("Jiboia")
        self.rocketgroup.addButton(self.jiboia)
        layout.addWidget(self.jiboia)
        self.jiboia.toggled.connect(lambda: self.setRocket(self.jiboia.text()))

        self.keron = QRadioButton("Keron")
        self.rocketgroup.addButton(self.keron)
        layout.addWidget(self.keron)
        self.keron.toggled.connect(lambda: self.setRocket(self.keron.text()))

        self.mandioca = QRadioButton("Mandioca")
        self.rocketgroup.addButton(self.mandioca)
        layout.addWidget(self.mandioca)
        self.mandioca.toggled.connect(
            lambda: self.setRocket(self.mandioca.text()))

        # кнопка при нажатий выдаёт график траекторий полёта ракеты
        self.trajectory = QPushButton("Trajectory")
        layout.addWidget(self.trajectory)
        self.trajectory.clicked.connect(self.GetTrajectory)

        # кнопка при нажатий выдаёт график кинематических данных полёта
        self.kinematics = QPushButton("Kinematics data")
        layout.addWidget(self.kinematics)
        self.kinematics.clicked.connect(self.GetKinematics)

        # кнопка при нажатий выдаёт график скоростный данных
        self.altitude = QPushButton("Altitude data")
        layout.addWidget(self.altitude)
        self.altitude.clicked.connect(self.GetAltitude)

        # кнопка при нажатий выдаёт график данных об энергий во время полёта
        self.energy = QPushButton("Energy Data")
        layout.addWidget(self.energy)
        self.energy.clicked.connect(self.GetEnergy)

        # "растягиваем" расположение чтобы элементы UI оказались на верхней стороне окна
        layout.addStretch(1)
        # добавляем новый стиль горизонтального расположения
        horlayout = QHBoxLayout()
        # "растягиваем" горизонтальное расположение чтобы UI оказался на правой стороне
        horlayout.addStretch(1)
        # соедениям оба стиля расположения в одно
        horlayout.addLayout(layout)
        # устанавливаем расположение
        self.setLayout(horlayout)

    # функция проверяет поле широты на попадание в диапозон -90,90 иначе меняет значение на полях
    def adjustLatitude(self):
        latitude = self.LatitudeInput.text()
        if latitude != '' and latitude != '-':
            latitude = int(latitude)
            if latitude < -90:
                self.LatitudeInput.setText("-90")
            elif latitude > 90:
                self.LatitudeInput.setText("90")

    # функция проверяет поле долготы на попадание в диапозон -180,180 иначе меняет значение на полях
    def adjustLongitude(self):
        longitude = self.LongitudeInput.text()
        if longitude != '' and longitude != '-':
            longitude = int(longitude)
            if longitude < -180:
                self.LongitudeInput.setText("-180")
            elif longitude > 180:
                self.LongitudeInput.setText("180")

    # функция проверяет поле угла наклона ракеты на попадание в диапозон 0,90 иначе меняет значение на полях
    def adjustInclination(self):
        inclination = self.InclinationInput.text()
        if inclination != '' and inclination != '-':
            inclination = int(inclination)
            if inclination < 0:
                self.InclinationInput.setText("0")
            elif inclination > 90:
                self.InclinationInput.setText("90")

    # функция проверяет введенный год на попадание в диапозон 2017,2020 иначе меняет значение года
    def adjustDate(self):
        date = self.DateInput.date()
        if date.year() < 2017:
            date.setDate(2017, date.month(), date.day())
        elif date.year() > 2020:
            date.setDate(2020, date.month(), date.day())
        self.DateInput.setDate(date)

    # функция выводящее график об атмосферных данных в введенную дату и в введенных координатах
    def EnvironmentD(self):
        self.setEnvironment()
        self.Env.info()

    # функция инициализируещее атмосферные данные в модуле Environment
    def setEnvironment(self):
        self.longitude = int(self.LongitudeInput.text())
        self.elevation = int(self.ElevationInput.text())
        self.date = self.DateInput.date()
        self.latitude = int(self.LatitudeInput.text())

        # подстраивание значений под диапозоны имеющихся данных
        if self.latitude > -90 and self.latitude < -30:
            self.Env = Environment(
                railLength=5.2,
                date=(self.date.year() - 2, self.date.month(), self.date.day(),
                      6),
                latitude=-7.5 + 3 * (-90 - self.latitude) / -60,
                longitude=324 + (2.25 * (-180 - self.longitude) / -360),
                elevation=self.elevation)
            # получение значения файла о погоде из базы данных
            weatherfile = self.cur.execute(
                '''SELECT File_Path FROM WeatherFiles WHERE File_Path LIKE "%CLBI%" AND Year=?''',
                (self.date.year(), )).fetchone()

            self.Env.setAtmosphericModel(type='Reanalysis',
                                         file=weatherfile[0],
                                         dictionary='ECMWF')
        elif self.latitude >= -30 and self.latitude < 30:
            self.Env = Environment(
                railLength=5.2,
                date=(self.date.year() - 2, self.date.month(), self.date.day(),
                      6),
                latitude=-3.75 + 5.25 * (-30 - self.latitude) / -60,
                longitude=314.25 + 3 * (-180 - self.longitude) / -360,
                elevation=self.elevation)

            weatherfile = self.cur.execute(
                '''SELECT File_Path FROM WeatherFiles WHERE File_Path LIKE "%Alcantara%" AND Year=?''',
                (self.date.year(), )).fetchone()

            self.Env.setAtmosphericModel(type='Reanalysis',
                                         file=weatherfile[0],
                                         dictionary='ECMWF')
        elif self.latitude >= 30 and self.latitude <= 90:
            self.Env = Environment(
                railLength=5.2,
                date=(self.date.year() - 2, self.date.month(), self.date.day(),
                      6),
                latitude=31.5 + 3 * (90 - self.latitude) / 60,
                longitude=252 + 2.25 * (-180 - self.longitude) / -360,
                elevation=self.elevation)
            weatherfile = self.cur.execute(
                '''SELECT File_Path FROM WeatherFiles WHERE File_Path LIKE "%Spaceport%" AND Year=?''',
                (self.date.year(), )).fetchone()

            self.Env.setAtmosphericModel(type='Reanalysis',
                                         file=weatherfile[0],
                                         dictionary='ECMWF')

    # функция назначает имя текущего выбранного мотора из группы радиокнопок
    def setMotor(self, name):
        name = name.split()
        name = '_'.join(name)
        self.motorName = name

    # функция инициализирует модель ракеты внутри модуля SolidMotor
    def setMotorModel(self):
        motorfile = self.cur.execute(
            'SELECT File_Path FROM Motors WHERE Motor_Name=?',
            (self.motorName, )).fetchone()
        motorfile = str(motorfile[0])
        self.motor_model = SolidMotor(thrustSource=motorfile,
                                      burnOut=3.9,
                                      grainNumber=5,
                                      grainSeparation=5 / 1000,
                                      grainDensity=1815,
                                      grainOuterRadius=33 / 1000,
                                      grainInitialInnerRadius=15 / 1000,
                                      grainInitialHeight=120 / 1000,
                                      nozzleRadius=33 / 1000,
                                      throatRadius=11 / 1000,
                                      interpolationMethod='linear')

    # функция выводит график сопротивления мотора
    def motorInfo(self):
        self.setMotorModel()
        self.motor_model.info()

    # функция назначает текущее имя выбранного типа ракеты
    def setRocket(self, name):
        self.rocketName = name

    # функция инициализирует модель ракеты с помощью модуля Rocket
    def setRocketModel(self):
        self.inclination = int(self.InclinationInput.text())
        # получение файла толчка из базы данных
        thrustcurve = self.cur.execute(
            'SELECT File_Path FROM Rockets WHERE Rocket_Name=?',
            (self.rocketName, )).fetchone()
        thrustcurve = str(thrustcurve[0])
        self.RocketModel = Rocket(
            motor=self.motor_model,
            radius=127 / 2000,
            mass=19.197 - 2.956,
            inertiaI=6.60,
            inertiaZ=0.0351,
            distanceRocketNozzle=-1.255,
            distanceRocketPropellant=-0.85704,
            powerOffDrag="data/calisto/powerOffDragCurve.csv",
            powerOnDrag=thrustcurve)
        self.RocketModel.setRailButtons([0.2, -0.5])
        # добавление деталей в модель ракеты по модулю Rocket
        NoseCone = self.RocketModel.addNose(length=0.55829,
                                            kind="vonKarman",
                                            distanceToCM=0.71971)

        FinSet = self.RocketModel.addFins(4,
                                          span=0.100,
                                          rootChord=0.120,
                                          tipChord=0.040,
                                          distanceToCM=-1.04956)

        Tail = self.RocketModel.addTail(topRadius=0.0635,
                                        bottomRadius=0.0435,
                                        length=0.060,
                                        distanceToCM=-1.194656)
        # добавление парашютов
        Main = self.RocketModel.addParachute('Main',
                                             CdS=10.0,
                                             trigger=self.mainTrigger,
                                             samplingRate=105,
                                             lag=1.5,
                                             noise=(0, 8.3, 0.5))

        Drogue = self.RocketModel.addParachute('Drogue',
                                               CdS=1.0,
                                               trigger=self.drogueTrigger,
                                               samplingRate=105,
                                               lag=1.5,
                                               noise=(0, 8.3, 0.5))

        self.TestFlight = Flight(rocket=self.RocketModel,
                                 environment=self.Env,
                                 inclination=self.inclination,
                                 heading=0)

    # функции активаций парашютов
    def drogueTrigger(self, p, y):
        return True if y[5] < 0 else False

    def mainTrigger(self, p, y):
        return True if y[5] < 0 and y[2] < 800 else False

    # функция выдаёт траекторию ракеты
    def GetTrajectory(self):
        self.setMotorModel()
        self.setEnvironment()
        self.setRocketModel()
        self.TestFlight.plot3dTrajectory()

    # функция выдаёт график кинематических данных
    def GetKinematics(self):
        self.setMotorModel()
        self.setEnvironment()
        self.setRocketModel()
        self.TestFlight.plotLinearKinematicsData()

    # функция выдаёт график скоростных данных
    def GetAltitude(self):
        self.setMotorModel()
        self.setEnvironment()
        self.setRocketModel()
        self.TestFlight.plotAttitudeData()

    # функция выдаёт график энергий во время полёта
    def GetEnergy(self):
        self.setMotorModel()
        self.setEnvironment()
        self.setRocketModel()
        self.TestFlight.plotEnergyData()
Ejemplo n.º 32
0
    def setupTab1(self, tab1):
        """Basic widgets for preview panel"""
        scrollContainer = QVBoxLayout()
        scrollArea = QScrollArea()
        scrollArea.setWidgetResizable(True)
        mainWidget = QWidget()
        layout = QVBoxLayout()
        mainWidget.setLayout(layout)
        mainWidget.setMinimumSize(QSize(420, 800))
        scrollArea.setWidget(mainWidget)
        scrollContainer.addWidget(scrollArea)
        tab1.setLayout(scrollContainer)

        # Label TextBox
        group1 = QGroupBox("Text")
        group1.setCheckable(True)
        group1layout = QHBoxLayout()
        group1.setLayout(group1layout)
        layout.addWidget(group1)
        layoutCol1 = QFormLayout()
        layoutCol2 = QFormLayout()
        group1layout.addLayout(layoutCol1)
        group1layout.addLayout(layoutCol2)

        label1 = QLabel(self.tr("User Name(&Id):"))
        text1 = QLineEdit("default")
        label1.setBuddy(text1)
        label2 = QLabel(self.tr("data 1:"))
        text2 = QLineEdit()
        text2.setPlaceholderText(self.tr("input"))
        lebel3 = QLabel(self.tr("<b>Pasword</b>:"))
        text3 = QLineEdit("******")
        text3.setEchoMode(QLineEdit.Password)
        label4 = QLabel(self.tr("link label:"))
        label5 = QLabel(
            self.
            tr("<a href='https://github.com/hustlei/'>github.com/hustlei</a>"))
        label5.setOpenExternalLinks(True)
        label6 = QLabel(self.tr("icon label:"))
        label7 = QLabel("icon")
        label7.setPixmap(QPixmap(":appres.img/book_address.png"))
        layoutCol1.addRow(label1, text1)
        layoutCol1.addRow(label2, text2)
        layoutCol1.addRow(lebel3, text3)
        layoutCol1.addRow(label4, label5)
        layoutCol1.addRow(label6, label7)

        text4 = QLineEdit()
        text4.setInputMask("0000-00-00")
        text5 = QLineEdit()
        text5.setInputMask("HH:HH:HH:HH:HH:HH;_")
        text6 = QLineEdit()
        text6.setInputMask("XXXXXX")
        text7 = QLineEdit()
        validator1 = QDoubleValidator()
        validator1.setRange(0, 100)
        validator1.setDecimals(2)
        text7.setValidator(validator1)
        text8 = QLineEdit()
        validator2 = QRegExpValidator()
        reg = QRegExp("[a-zA-Z0-9]+$")
        validator2.setRegExp(reg)
        text8.setValidator(validator2)
        layoutCol2.addRow(self.tr("Date Mask:"), text4)
        layoutCol2.addRow(self.tr("Mac Mask"), text5)
        layoutCol2.addRow(self.tr("String Mask"), text6)
        layoutCol2.addRow(self.tr("Double Validate:"), text7)
        layoutCol2.addRow(self.tr("Regexp Validate:"), text8)

        text9 = QLineEdit()
        text9.setPlaceholderText("input email")
        text9.setToolTip("please input a email address.")
        model = QStandardItemModel(0, 1, self)
        completer = QCompleter(model, self)
        text9.setCompleter(completer)

        def textch(texts):
            if "@" in texts:
                return
            strList = [
                "@163.com", "@qq.com", "@gmail.com", "@hotmail.com", "@126.com"
            ]
            model.removeRows(0, model.rowCount())
            for i in strList:
                model.insertRow(0)
                model.setData(model.index(0, 0), texts + i)

        text9.textChanged.connect(textch)
        text10 = QLineEdit("ReadOnly")
        text10.setReadOnly(True)
        layoutCol1.addRow(self.tr("auto complete:"), text9)
        layoutCol2.addRow("Readonly:", text10)

        # Button
        group2 = QGroupBox("Button")
        group2.setCheckable(True)
        group2layout = QVBoxLayout()
        group2.setLayout(group2layout)
        layout.addWidget(group2)
        layoutRow1 = QHBoxLayout()
        layoutRow2 = QHBoxLayout()
        group2layout.addLayout(layoutRow1)
        group2layout.addLayout(layoutRow2)

        btn1 = QPushButton("Button")
        btn2 = QPushButton("IconBtn")
        btn2.setIcon(QIcon(":appres.img/yes.png"))
        btn3 = QPushButton("Disabled")
        btn3.setEnabled(False)
        btn4 = QPushButton("Default")
        btn4.setDefault(True)

        btn5 = QPushButton("Switch")
        btn5.setCheckable(True)
        btn6 = QToolButton()
        # btn6.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        btn6.setText("ToolButton")
        btn6.setPopupMode(QToolButton.MenuButtonPopup)
        m = QMenu()
        m.addAction("action1")
        m.addAction("action2")
        m.addAction("action3")
        btn6.setMenu(m)
        btn7 = QCommandLinkButton("LinkBtn")
        layoutRow1.addWidget(btn1)
        layoutRow1.addWidget(btn2)
        layoutRow1.addWidget(btn3)
        layoutRow1.addWidget(btn4)
        layoutRow2.addWidget(btn5)
        layoutRow2.addWidget(btn6)
        layoutRow2.addWidget(btn7)

        # Checkable Item
        group3 = QGroupBox("Checkable")
        group3Layout = QVBoxLayout()
        layoutRow1 = QHBoxLayout()
        layoutRow2 = QHBoxLayout()
        group3Layout.addLayout(layoutRow1)
        group3Layout.addLayout(layoutRow2)
        group3.setLayout(group3Layout)
        layout.addWidget(group3)

        group3.setCheckable(True)
        ch1 = QRadioButton("Radio")
        ch2 = QRadioButton("Iconradio")
        ch2.setIcon(QIcon(":appres.img/Flag_blueHS.png"))
        ch3 = QRadioButton("Iconradio")
        ch3.setIcon(QIcon(":appres.img/Flag_greenHS.png"))
        ch4 = QRadioButton("Disable")
        ch4.setEnabled(False)
        ch5 = QCheckBox("CheckBox")
        ch6 = QCheckBox("CheckBox")
        ch6.setIcon(QIcon(":appres.img/Flag_blueHS.png"))
        ch7 = QCheckBox("TriState")
        ch7.setTristate(True)
        ch7.setCheckState(Qt.PartiallyChecked)
        ch8 = QCheckBox("Disable")
        ch8.setEnabled(False)
        layoutRow1.addWidget(ch1)
        layoutRow1.addWidget(ch2)
        layoutRow1.addWidget(ch3)
        layoutRow1.addWidget(ch4)
        layoutRow2.addWidget(ch5)
        layoutRow2.addWidget(ch6)
        layoutRow2.addWidget(ch7)
        layoutRow2.addWidget(ch8)

        # Selecting Input
        group4 = QGroupBox("Selectable")
        group4.setCheckable(True)
        group4Layout = QVBoxLayout()
        layoutRow1 = QHBoxLayout()
        group4Layout.addLayout(layoutRow1)
        group4.setLayout(group4Layout)
        layout.addWidget(group4)

        s1 = QSpinBox()
        s1.setValue(50)
        s2 = QDoubleSpinBox()
        s2.setRange(0, 1)
        s2.setValue(0.5)
        s3 = QComboBox()
        s3.addItems(["aaa", "bbb", "ccc"])
        s3.setEditable(True)
        s3.setCurrentIndex(2)
        s4 = QComboBox()
        s4.addItems(["aaa", "bbb", "ccc"])
        layoutRow1.addWidget(s1)
        layoutRow1.addWidget(s2)
        layoutRow1.addWidget(s3)
        layoutRow1.addWidget(s4)

        # TextEdit
        group5 = QGroupBox("TextEdit")
        group5.setCheckable(True)
        group5Layout = QVBoxLayout()
        group5.setLayout(group5Layout)
        layout.addWidget(group5)

        group5Layout.addWidget(
            QTextEdit(
                self.
                tr("If you do not leave me, I will be by your side until the end."
                   )))

        layout.addStretch(1)
Ejemplo n.º 33
0
    def request_trezor_init_settings(self, wizard, method, device_id):
        vbox = QVBoxLayout()
        next_enabled = True

        devmgr = self.device_manager()
        client = devmgr.client_by_id(device_id)
        if not client:
            raise Exception(_("The device was disconnected."))
        model = client.get_trezor_model()
        fw_version = client.client.version
        capabilities = client.client.features.capabilities
        have_shamir = Capability.Shamir in capabilities

        # label
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        # Backup type
        gb_backuptype = QGroupBox()
        hbox_backuptype = QHBoxLayout()
        gb_backuptype.setLayout(hbox_backuptype)
        vbox.addWidget(gb_backuptype)
        gb_backuptype.setTitle(_('Select backup type:'))
        bg_backuptype = QButtonGroup()

        rb_single = QRadioButton(gb_backuptype)
        rb_single.setText(_('Single seed (BIP39)'))
        bg_backuptype.addButton(rb_single)
        bg_backuptype.setId(rb_single, BackupType.Bip39)
        hbox_backuptype.addWidget(rb_single)
        rb_single.setChecked(True)

        rb_shamir = QRadioButton(gb_backuptype)
        rb_shamir.setText(_('Shamir'))
        bg_backuptype.addButton(rb_shamir)
        bg_backuptype.setId(rb_shamir, BackupType.Slip39_Basic)
        hbox_backuptype.addWidget(rb_shamir)
        rb_shamir.setEnabled(Capability.Shamir in capabilities)
        rb_shamir.setVisible(False)  # visible with "expert settings"

        rb_shamir_groups = QRadioButton(gb_backuptype)
        rb_shamir_groups.setText(_('Super Shamir'))
        bg_backuptype.addButton(rb_shamir_groups)
        bg_backuptype.setId(rb_shamir_groups, BackupType.Slip39_Advanced)
        hbox_backuptype.addWidget(rb_shamir_groups)
        rb_shamir_groups.setEnabled(Capability.ShamirGroups in capabilities)
        rb_shamir_groups.setVisible(False)  # visible with "expert settings"

        # word count
        word_count_buttons = {}

        gb_numwords = QGroupBox()
        hbox1 = QHBoxLayout()
        gb_numwords.setLayout(hbox1)
        vbox.addWidget(gb_numwords)
        gb_numwords.setTitle(_("Select seed/share length:"))
        bg_numwords = QButtonGroup()
        for count in (12, 18, 20, 24, 33):
            rb = QRadioButton(gb_numwords)
            word_count_buttons[count] = rb
            rb.setText(_("{:d} words").format(count))
            bg_numwords.addButton(rb)
            bg_numwords.setId(rb, count)
            hbox1.addWidget(rb)
            rb.setChecked(True)

        def configure_word_counts():
            if model == "1":
                checked_wordcount = 24
            else:
                checked_wordcount = 12

            if method == TIM_RECOVER:
                if have_shamir:
                    valid_word_counts = (12, 18, 20, 24, 33)
                else:
                    valid_word_counts = (12, 18, 24)
            elif rb_single.isChecked():
                valid_word_counts = (12, 18, 24)
                gb_numwords.setTitle(_('Select seed length:'))
            else:
                valid_word_counts = (20, 33)
                checked_wordcount = 20
                gb_numwords.setTitle(_('Select share length:'))

            word_count_buttons[checked_wordcount].setChecked(True)
            for c, btn in word_count_buttons.items():
                btn.setVisible(c in valid_word_counts)

        bg_backuptype.buttonClicked.connect(configure_word_counts)
        configure_word_counts()

        # set up conditional visibility:
        # 1. backup_type is only visible when creating new seed
        gb_backuptype.setVisible(method == TIM_NEW)
        # 2. word_count is not visible when recovering on TT
        if method == TIM_RECOVER and model != "1":
            gb_numwords.setVisible(False)

        # PIN
        cb_pin = QCheckBox(_('Enable PIN protection'))
        cb_pin.setChecked(True)
        vbox.addWidget(WWLabel(RECOMMEND_PIN))
        vbox.addWidget(cb_pin)

        # "expert settings" button
        expert_vbox = QVBoxLayout()
        expert_widget = QWidget()
        expert_widget.setLayout(expert_vbox)
        expert_widget.setVisible(False)
        expert_button = QPushButton(_("Show expert settings"))
        def show_expert_settings():
            expert_button.setVisible(False)
            expert_widget.setVisible(True)
            rb_shamir.setVisible(True)
            rb_shamir_groups.setVisible(True)
        expert_button.clicked.connect(show_expert_settings)
        vbox.addWidget(expert_button)

        # passphrase
        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        expert_vbox.addWidget(passphrase_msg)
        expert_vbox.addWidget(passphrase_warning)
        expert_vbox.addWidget(cb_phrase)

        # ask for recovery type (random word order OR matrix)
        bg_rectype = None
        if method == TIM_RECOVER and model == '1':
            gb_rectype = QGroupBox()
            hbox_rectype = QHBoxLayout()
            gb_rectype.setLayout(hbox_rectype)
            expert_vbox.addWidget(gb_rectype)
            gb_rectype.setTitle(_("Select recovery type:"))
            bg_rectype = QButtonGroup()

            rb1 = QRadioButton(gb_rectype)
            rb1.setText(_('Scrambled words'))
            bg_rectype.addButton(rb1)
            bg_rectype.setId(rb1, RecoveryDeviceType.ScrambledWords)
            hbox_rectype.addWidget(rb1)
            rb1.setChecked(True)

            rb2 = QRadioButton(gb_rectype)
            rb2.setText(_('Matrix'))
            bg_rectype.addButton(rb2)
            bg_rectype.setId(rb2, RecoveryDeviceType.Matrix)
            hbox_rectype.addWidget(rb2)

        # no backup
        cb_no_backup = None
        if method == TIM_NEW:
            cb_no_backup = QCheckBox(f'''{_('Enable seedless mode')}''')
            cb_no_backup.setChecked(False)
            if (model == '1' and fw_version >= (1, 7, 1)
                    or model == 'T' and fw_version >= (2, 0, 9)):
                cb_no_backup.setToolTip(SEEDLESS_MODE_WARNING)
            else:
                cb_no_backup.setEnabled(False)
                cb_no_backup.setToolTip(_('Firmware version too old.'))
            expert_vbox.addWidget(cb_no_backup)

        vbox.addWidget(expert_widget)
        wizard.exec_layout(vbox, next_enabled=next_enabled)

        return TrezorInitSettings(
            word_count=bg_numwords.checkedId(),
            label=name.text(),
            pin_enabled=cb_pin.isChecked(),
            passphrase_enabled=cb_phrase.isChecked(),
            recovery_type=bg_rectype.checkedId() if bg_rectype else None,
            backup_type=bg_backuptype.checkedId(),
            no_backup=cb_no_backup.isChecked() if cb_no_backup else False,
        )
Ejemplo n.º 34
0
class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.days = 0
        self.totalPapers = 0

        self.perfect = {
            '1': [[6, 2], [1, 4, 5, 8], [3, 7]],
            '2': [[1, 2, 8], [6, 7], [3, 4, 5]],
            '3': [[4, 5, 6, 1, 3], [8], [2, 7]],
            '4': [[7], [], [1, 2, 3, 4, 5, 6, 8]],
            '5': [[1, 7], [8, 2], [3, 4, 5, 6]],
            '6': [[2, 8, 1, 7], [3], [4, 5, 6]],
            '7': [[6, 3, 7, 4, 5], [1], [2, 8]],
            '8': [[8, 2, 6, 4], [1, 5], [3, 7]]
        }
        self.levelOfKnowledge = 0
        self.setFont(QtGui.QFont("Bahnschrift Light SemiCondensed", 20))
        self.setMouseTracking(True)
        self.setWindowTitle('Game maker')
        self.setGeometry(10, 10, 1024, 768)
        self.setFixedSize(1024, 768)
        palette = QPalette()
        img = QImage('mainWindow.png')
        scaled = img.scaled(self.size(),
                            Qt.KeepAspectRatioByExpanding,
                            transformMode=Qt.SmoothTransformation)
        palette.setBrush(QPalette.Window, QBrush(scaled))
        self.setPalette(palette)
        pixmap = QPixmap('shopButton.png')
        self.shopButton = QLabel('', self)
        self.shopButton.setPixmap(pixmap)
        self.shopButton.setMouseTracking(True)
        self.shopButton.move(500, 7)
        pixmap = QPixmap('devButton.png')
        self.devButton = QLabel('', self)
        self.devButton.setMouseTracking(True)
        self.devButton.setPixmap(pixmap)
        self.devButton.move(700, 7)
        self.cash = 100
        self.money = QLabel("Деньги:\n    100$", self)
        self.money.move(10, 7)
        self.subs = QLabel("Фанаты:\n   0", self)
        self.subs.move(140, 7)
        self.date = QLabel("Дни:\n     0", self)
        self.date.move(280, 7)
        self.table = QLabel(
            'Создайте свою первую игру! \n  \nЗаработано за все дни: \n 0',
            self)
        self.table.move(150, 200)
        self.table.setStyleSheet(
            'border-style: solid; border-width: 3px; border-color: black;'
            'background-color: rgb(207, 162, 98);')
        self.nalog = QLabel("До налога: 30 \n Налог: 0", self)
        self.nalog.move(800, 105)
        self.nalog.setStyleSheet(
            'border-style: solid; border-width: 3px; border-color: black;'
            'background-color: rgb(207, 162, 98);')
        self.shop = QWidget(self)
        self.shop.move(10000, 10000)
        self.shop.resize(400, 353)
        self.shop.setMouseTracking(True)
        self.shopItem1 = QLabel('', self.shop)
        self.shopItem1.setPixmap(QPixmap('shopItem1.png'))
        self.shopItem1.move(10, 10)
        self.shopItem1.setMouseTracking(True)
        self.shopItem2 = QLabel('', self.shop)
        self.shopItem2.setPixmap(QPixmap('shopItem22.png'))
        self.shopItem2.move(200, 10)
        self.shopItem2.setMouseTracking(True)
        self.shopItem3 = QLabel('', self.shop)
        self.shopItem3.setPixmap(QPixmap('shopItem4.png'))
        self.shopItem3.move(10, 250)
        self.shopItem3.setMouseTracking(True)
        self.shopItem4 = QLabel('', self.shop)
        self.shopItem4.setPixmap(QPixmap('shopItem4.png'))
        self.shopItem4.move(200, 250)
        self.shopItem4.setMouseTracking(True)
        self.shopExit = QLabel('', self.shop)
        self.shopExit.setPixmap(QPixmap('shopExit.png'))
        self.shopExit.move(360, 10)
        self.shopExit.setMouseTracking(True)
        self.shop.setStyleSheet(
            'border-style: solid; border-width: 3px; border-color: black;'
            'background-color: rgb(207, 162, 98);')
        self.shopOn = False

        self.devPage1 = QWidget(self)
        self.devPage1.move(10000, 10000)
        self.devPage1.resize(600, 330)
        self.devPage1.setMouseTracking(True)
        self.devPage1.setStyleSheet(
            'border-style: solid; border-width: 3px; border-color: black;'
            'background-color: rgb(207, 162, 98);')
        self.theme = 0
        self.style = 0
        self.type = 0
        self.platform = 0
        self.styles = QGroupBox('Жанры', self.devPage1)
        self.styles.move(10, 10)
        self.styles.setMouseTracking(True)
        self.style1 = QRadioButton('Приключения', self.styles)
        self.style1.move(10, 20)
        self.style1.toggle()
        self.style2 = QRadioButton('Шутер', self.styles)
        self.style2.move(100, 20)
        self.style3 = QRadioButton('Слэшэр', self.styles)
        self.style3.move(10, 45)
        self.style4 = QRadioButton('MMO', self.styles)
        self.style4.move(100, 45)
        self.style5 = QRadioButton('MOBA', self.styles)
        self.style5.move(10, 70)
        self.style6 = QRadioButton('RPG', self.styles)
        self.style6.move(100, 70)
        self.style7 = QRadioButton('Симулятор', self.styles)
        self.style7.move(10, 95)
        self.style8 = QRadioButton('Кооператив', self.styles)
        self.style8.move(100, 95)
        self.styles.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.styles.setFont(QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.style1.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style2.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style3.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style4.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style5.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style6.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style7.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style8.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.style1.adjustSize()
        self.style2.adjustSize()
        self.style3.adjustSize()
        self.style4.adjustSize()
        self.style5.adjustSize()
        self.style6.adjustSize()
        self.style7.adjustSize()
        self.style8.adjustSize()
        self.styles.adjustSize()

        self.themes = QGroupBox('Темы', self.devPage1)
        self.themes.move(300, 10)
        self.themes.setMouseTracking(True)
        self.theme1 = QRadioButton('Космос', self.themes)
        self.theme1.move(10, 20)
        self.theme1.toggle()
        self.theme2 = QRadioButton('Вестерн', self.themes)
        self.theme2.move(120, 20)
        self.theme3 = QRadioButton('Фэнтэзи', self.themes)
        self.theme3.move(10, 45)
        self.theme4 = QRadioButton('Ферма', self.themes)
        self.theme4.move(120, 45)
        self.theme5 = QRadioButton('Детектив', self.themes)
        self.theme5.move(10, 70)
        self.theme6 = QRadioButton('Война', self.themes)
        self.theme6.move(120, 70)
        self.theme7 = QRadioButton('Средневековье', self.themes)
        self.theme7.move(10, 95)
        self.theme8 = QRadioButton('Будущее', self.themes)
        self.theme8.move(120, 95)
        self.themes.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.themes.setFont(QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.theme1.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme2.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme3.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme4.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme5.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme6.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme7.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme8.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.theme1.adjustSize()
        self.theme2.adjustSize()
        self.theme3.adjustSize()
        self.theme4.adjustSize()
        self.theme5.adjustSize()
        self.theme6.adjustSize()
        self.theme7.adjustSize()
        self.theme8.adjustSize()
        self.themes.adjustSize()

        self.platforms = QGroupBox('Платформы', self.devPage1)
        self.platforms.move(10, 150)
        self.platforms.setMouseTracking(True)
        self.platform1 = QRadioButton('MacOs', self.platforms)
        self.platform1.move(10, 20)
        self.platform1.toggle()
        self.platform2 = QRadioButton('Android', self.platforms)
        self.platform2.move(120, 20)
        self.platform3 = QRadioButton('IOS', self.platforms)
        self.platform3.move(10, 45)
        self.platform4 = QRadioButton('PC', self.platforms)
        self.platform4.move(120, 45)
        self.platforms.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.platforms.setFont(
            QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.platform1.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.platform2.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.platform3.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.platform4.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.platform1.adjustSize()
        self.platform2.adjustSize()
        self.platform3.adjustSize()
        self.platform4.adjustSize()
        self.platforms.adjustSize()

        self.types = QGroupBox('Тип', self.devPage1)
        self.types.move(300, 150)
        self.types.setMouseTracking(True)
        self.type1 = QRadioButton('Инди', self.types)
        self.type1.move(10, 20)
        self.type1.toggle()
        self.type2 = QRadioButton('A', self.types)
        self.type2.move(120, 20)
        self.type3 = QRadioButton('AA', self.types)
        self.type3.move(10, 45)
        self.type4 = QRadioButton('AAA', self.types)
        self.type4.move(120, 45)
        self.types.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.types.setFont(QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.type1.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.type2.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.type3.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.type4.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.type1.adjustSize()
        self.type2.adjustSize()
        self.type3.adjustSize()
        self.type4.adjustSize()
        self.types.adjustSize()

        self.pushToDev = QPushButton('Начать', self.devPage1)
        self.pushToDev.setMouseTracking(True)
        self.pushToDev.move(280, 270)
        self.pushToDev.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;'
            'background-color: rgb(207, 162, 198);')
        self.pushToDev.clicked.connect(self.showDevPage2)

        self.devPage2 = QWidget(self)
        self.devPage2.move(10000, 10000)
        self.devPage2.resize(600, 330)
        self.devPage2.setMouseTracking(True)
        self.devPage2.setStyleSheet(
            'border-style: solid; border-width: 3px; border-color: black;'
            'background-color: rgb(207, 162, 98);')
        self.devPage1On = False
        self.devPage2On = False

        self.levelOne = QGroupBox('Знания I', self.devPage2)
        self.levelOne.move(10, 10)
        self.levelOne.setMouseTracking(True)
        self.techno11 = QCheckBox('2D(5$)', self.levelOne)
        self.techno11.move(10, 20)
        self.techno11.setMouseTracking(True)
        self.techno12 = QCheckBox('6 Bit Sound(15$)', self.levelOne)
        self.techno12.move(150, 20)
        self.techno13 = QCheckBox('HD(25$)', self.levelOne)
        self.techno13.move(10, 80)
        self.techno14 = QCheckBox('C++(35$)', self.levelOne)
        self.techno14.move(150, 80)
        self.levelOne.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.levelOne.setFont(
            QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.techno11.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno12.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno13.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno14.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno14.adjustSize()
        self.techno13.adjustSize()
        self.techno12.adjustSize()
        self.techno11.adjustSize()
        self.levelOne.adjustSize()
        self.techno12.setMouseTracking(True)
        self.techno13.setMouseTracking(True)
        self.techno14.setMouseTracking(True)

        self.levelTwo = QGroupBox('Знания II', self.devPage2)
        self.levelTwo.move(10, 170)
        self.levelTwo.setMouseTracking(True)
        self.techno21 = QCheckBox('3D(100$)', self.levelTwo)
        self.techno21.move(10, 20)
        self.techno21.setMouseTracking(True)
        self.techno22 = QCheckBox('8 Bit Sound(300$)', self.levelTwo)
        self.techno22.move(150, 20)
        self.techno23 = QCheckBox('Full HD(500$)', self.levelTwo)
        self.techno23.move(10, 80)
        self.techno24 = QCheckBox('C(1000$)', self.levelTwo)
        self.techno24.move(150, 80)
        self.levelTwo.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.levelTwo.setFont(
            QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.techno21.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno22.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno23.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno24.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno24.adjustSize()
        self.techno23.adjustSize()
        self.techno22.adjustSize()
        self.techno21.adjustSize()
        self.levelTwo.adjustSize()
        self.techno22.setMouseTracking(True)
        self.techno23.setMouseTracking(True)
        self.techno24.setMouseTracking(True)

        self.levelThree = QGroupBox('Знания III', self.devPage2)
        self.levelThree.move(280, 10)
        self.levelThree.setMouseTracking(True)
        self.techno31 = QCheckBox('4D(3500$)', self.levelThree)
        self.techno31.move(10, 20)
        self.techno31.setMouseTracking(True)
        self.techno32 = QCheckBox('16 Bit Sound(7000$)', self.levelThree)
        self.techno32.move(150, 20)
        self.techno33 = QCheckBox('2K HD(13000$)', self.levelThree)
        self.techno33.move(10, 80)
        self.techno34 = QCheckBox('C#(20000$)', self.levelThree)
        self.techno34.move(150, 80)
        self.levelThree.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.levelThree.setFont(
            QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.techno31.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno32.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno33.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno34.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno34.adjustSize()
        self.techno33.adjustSize()
        self.techno32.adjustSize()
        self.techno31.adjustSize()
        self.techno31.setMouseTracking(True)
        self.techno32.setMouseTracking(True)
        self.techno34.setMouseTracking(True)
        self.techno33.setMouseTracking(True)
        self.levelThree.adjustSize()

        self.timeToEnd = 0
        self.timeDev = False

        self.levelFour = QGroupBox('Знания IV', self.devPage2)
        self.levelFour.move(280, 170)
        self.levelFour.setMouseTracking(True)
        self.techno41 = QCheckBox('5D(50000$)', self.levelFour)
        self.techno41.setMouseTracking(True)
        self.techno41.move(10, 20)
        self.techno42 = QCheckBox('24 Bit Sound(60000$)', self.levelFour)
        self.techno42.move(150, 20)
        self.techno43 = QCheckBox('Ultra HD(70000$)', self.levelFour)
        self.techno43.move(10, 80)
        self.techno44 = QCheckBox('Python(90000$)', self.levelFour)
        self.techno44.move(150, 80)
        self.levelFour.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;')
        self.levelFour.setFont(
            QtGui.QFont("Bahnschrift Light SemiCondensed", 12))
        self.techno41.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno42.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno43.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno44.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')
        self.techno44.adjustSize()
        self.techno43.adjustSize()
        self.techno42.adjustSize()
        self.techno41.adjustSize()
        self.techno42.setMouseTracking(True)
        self.techno44.setMouseTracking(True)
        self.techno43.setMouseTracking(True)
        self.levelFour.adjustSize()

        self.pushToStartDev = QPushButton('Начать', self.devPage2)
        self.pushToStartDev.setMouseTracking(True)
        self.pushToStartDev.move(280, 290)
        self.pushToStartDev.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;'
            'background-color: rgb(207, 162, 198);')
        self.pushToStartDev.clicked.connect(self.showDevPage3)

        self.timeToEnd = 5
        self.totalMoney = QLabel('Итого: 0', self.devPage2)
        self.totalMoney.move(100, 290)
        self.totalMoney.setStyleSheet(
            'border-style: solid; border-width: 1px; border-color: black;'
            'background-color: rgb(207, 162, 198);')

        self.devPage1Exit = QLabel('', self.devPage1)
        self.devPage1Exit.setPixmap(QPixmap('shopExit.png'))
        self.devPage1Exit.move(560, 5)
        self.devPage1Exit.adjustSize()
        self.devPage1Exit.setMouseTracking(True)

        self.devPage2Exit = QLabel('', self.devPage2)
        self.devPage2Exit.setPixmap(QPixmap('shopExit.png'))
        self.devPage2Exit.move(560, 5)
        self.devPage2Exit.adjustSize()
        self.devPage2Exit.setMouseTracking(True)

        self.devPage3 = QWidget(self)
        self.devPage3.move(10000, 10000)
        self.devPage3.resize(600, 330)
        self.devPage3.setMouseTracking(True)
        self.devPage3.setStyleSheet(
            'border-style: solid; border-width: 3px; border-color: black;'
            'background-color: rgb(207, 162, 98);')

        self.warning = QLabel('', self.devPage2)
        self.warning.move(400, 290)
        self.warning.setFont(QtGui.QFont("Bahnschrift Light SemiCondensed",
                                         10))
        self.warning.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;')

        self.timeDev = False
        self.timeSale = False
        self.fans = 0
        # ////

        self.startPage = QWidget(self)
        self.startPage.move(0, 0)
        self.startPage.setFont(
            QtGui.QFont("Bahnschrift Light SemiCondensed", 30))
        self.startPage.resize(1024, 768)
        self.startPage.setStyleSheet(
            'border-style: solid; border-width: 3px; border-color: black;'
            'background-color: rgb(207, 162, 98);')
        self.startText = QLabel(
            'Здравствуй, начинающий разработчик! Начиная игру, сначала \n тебе потребуются'
            'купить набор "Знания I" в магазине, затем \nты можешь начать разработку своей '
            'первой игры в разделе\n "Разработка". на первом этапе ты можешь выбрать тему и '
            'жанр\n игры, а также платформу и тип,\которые открываются с каждым\n набором знаний. '
            'На втором этапе тебе будет доступен выбор \nтехнологий, который с каждым набором '
            'знаний\n будет увеличиваться. Так же каждые 30 дней тебе придется \nплатить налог, '
            'так что будь осторожен!. Удачи!! ', self.startPage)
        self.startText.setStyleSheet(
            'border-style: solid; border-width: 0px; border-color: black;'
            'background-color: rgb(207, 162, 98);')
        self.startText.move(10, 10)
        self.startButton = QPushButton('Начать', self.startPage)
        self.startButton.move(700, 600)
        self.startButton.adjustSize()
        self.startButton.clicked.connect(self.start)

    def start(self):  # начало игры
        self.startPage.move(10000, 10000)
        self.timer.start(1550)

    def mouseMoveEvent(self, event):  # обработка передвижения мыши
        if 500 <= event.x() <= 645 and 7 <= event.y() <= 95:
            self.shopButton.setPixmap(QPixmap('shopButton2.png'))
        elif 700 <= event.x() <= 845 and 7 <= event.y() <= 95:
            self.devButton.setPixmap(QPixmap('devButton2.png'))
        elif 310 <= event.x() <= 455 and 211 <= event.y(
        ) <= 297 and self.shopOn:
            self.shopItem1.setPixmap(QPixmap('shopItem12.png'))
        elif 500 <= event.x() <= 644 and 211 <= event.y(
        ) <= 297 and self.shopOn:
            self.shopItem2.setPixmap(QPixmap('shopItem2.png'))
        elif 310 <= event.x() <= 455 and 461 <= event.y(
        ) <= 547 and self.shopOn:
            self.shopItem3.setPixmap(QPixmap('shopItem32.png'))
        elif 500 <= event.x() <= 644 and 461 <= event.y(
        ) <= 547 and self.shopOn:
            self.shopItem4.setPixmap(QPixmap('shopItem42.png'))
        elif self.devPage2On:
            self.totalMon = self.cashToDev
            if self.techno11.isChecked():
                self.totalMon += 5
            if self.techno12.isChecked():
                self.totalMon += 10
            if self.techno13.isChecked():
                self.totalMon += 20
            if self.techno14.isChecked():
                self.totalMon += 35
            if self.techno21.isChecked():
                self.totalMon += 100
            if self.techno22.isChecked():
                self.totalMon += 300
            if self.techno23.isChecked():
                self.totalMon += 500
            if self.techno24.isChecked():
                self.totalMon += 1000
            if self.techno31.isChecked():
                self.totalMon += 3500
            if self.techno32.isChecked():
                self.totalMon += 7000
            if self.techno33.isChecked():
                self.totalMon += 13000
            if self.techno34.isChecked():
                self.totalMon += 20000
            if self.techno41.isChecked():
                self.totalMon += 50000
            if self.techno42.isChecked():
                self.totalMon += 60000
            if self.techno43.isChecked():
                self.totalMon += 70000
            if self.techno44.isChecked():
                self.totalMon += 90000
            self.totalMoney.setText('Итого: ' + str(self.totalMon))
            self.totalMoney.adjustSize()
        else:
            self.shopButton.setPixmap(QPixmap('shopButton.png'))
            self.shopItem1.setPixmap(QPixmap('shopItem1.png'))
            self.devButton.setPixmap(QPixmap('devButton.png'))
            self.shopItem2.setPixmap(QPixmap('shopItem22.png'))
            self.shopItem3.setPixmap(QPixmap('shopItem3.png'))
            self.shopItem4.setPixmap(QPixmap('shopItem4.png'))

    def mousePressEvent(self, event):  # обработка нажатия кнопок мыши
        if event.button() == Qt.LeftButton:
            if 500 <= event.x() <= 645 and 7 <= event.y() <= 95:
                self.showShop()
            elif 700 <= event.x() <= 845 and 7 <= event.y() <= 95:
                self.showDev()
            elif 660 <= event.x() <= 690 and 211 <= event.y(
            ) <= 241 and self.shopOn:
                self.shopOn = False
                self.shop.move(10000, 10000)
            elif 760 <= event.x() <= 790 and 105 <= event.y(
            ) <= 135 and self.devPage1On:
                self.devPage1On = False
                self.devPage1.move(1000, 1000)
                self.timer.start()
            elif 760 <= event.x() <= 790 and 105 <= event.y(
            ) <= 135 and self.devPage2On:
                self.devPage2On = False
                self.timer.start()
                self.devPage2.move(10000, 10000)
            elif 310 <= event.x() <= 455 and 211 <= event.y(
            ) <= 297 and self.shopOn:
                if self.levelOfKnowledge < 1 and self.cash >= 5:
                    self.levelOfKnowledge = 1
                    self.cash -= 5
                    self.money.setText('Деньги: \n   ' + str(self.cash))
            elif 500 <= event.x() <= 644 and 211 <= event.y(
            ) <= 297 and self.shopOn:
                if self.levelOfKnowledge < 2 and self.cash >= 500:
                    self.levelOfKnowledge = 2
                    self.cash -= 500
                    self.money.setText('Деньги: \n   ' + str(self.cash))
            elif 310 <= event.x() <= 455 and 461 <= event.y(
            ) <= 547 and self.shopOn:
                if self.levelOfKnowledge < 3 and self.cash >= 20000:
                    self.levelOfKnowledge = 3
                    self.cash -= 20000
                    self.money.setText('Деньги: \n   ' + str(self.cash))
            elif 500 <= event.x() <= 644 and 461 <= event.y(
            ) <= 547 and self.shopOn:
                if self.levelOfKnowledge < 4 and self.cash >= 200000:
                    self.levelOfKnowledge = 4
                    self.cash -= 200000
                    self.money.setText('Деньги: \n   ' + str(self.cash))

    def showShop(self):  # активация окошка магазина
        self.shopOn = True
        self.shop.move(300, 200)

    def showDev(self):  # активация окошка первого этапа разработки игры
        self.devPage1On = True
        self.timer.stop()
        self.platform1.setEnabled(False)
        self.platform2.setEnabled(False)
        self.platform3.setEnabled(False)
        self.platform4.setEnabled(False)
        self.type1.setEnabled(False)
        self.type2.setEnabled(False)
        self.type3.setEnabled(False)
        self.type4.setEnabled(False)
        if self.levelOfKnowledge >= 1:
            self.platform1.setEnabled(True)
            self.type1.setEnabled(True)
        if self.levelOfKnowledge >= 2:
            self.platform2.setEnabled(True)
            self.type2.setEnabled(True)
        if self.levelOfKnowledge >= 3:
            self.platform3.setEnabled(True)
            self.type3.setEnabled(True)
        if self.levelOfKnowledge >= 4:
            self.platform4.setEnabled(True)
            self.type4.setEnabled(True)
        self.devPage1.move(200, 100)

    def tick(self):  # описание действия таймера
        if self.cash < 0:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)

            msg.setText("Вы проиграли!:(")
            msg.setWindowTitle("Проигрыш")
            retval = msg.exec_()
            if retval == QMessageBox.Ok:
                sys.exit(app.exec_())
        self.days += 1
        self.date.setText('Дни:\n   ' + str(self.days))
        self.date.adjustSize()
        if self.timeDev:
            if self.timeToEnd > 1:
                self.timeToEnd -= 1
                self.table.setText('Дней до релиза: \n' + str(self.timeToEnd))
                self.table.adjustSize()
            else:
                self.relise()
        elif self.timeSale:
            if self.timeToEnd > 0:
                self.timeToEnd -= 1
                self.sale()
            else:
                self.table.setText(
                    'Конец продаж! \n  \nЗаработано за все дни: \n' +
                    str(self.totalPapers))
                self.table.adjustSize()
                self.timeSale = False
                self.timeToEnd = 5
        if self.days % 30 == 0:
            print(2)
            self.nalog.setText('Плоти Налог!!')
            self.nalog.adjustSize()
            self.cash -= int(
                (self.totalPapers / (self.days / 30) + self.fans /
                 (self.days / 30))) + self.levelOfKnowledge * self.days * 2
            self.money.setText('Деньги: \n   ' + str(self.cash))
            self.money.adjustSize()
        else:
            self.nalog.setText("До налога:" + str(30 - self.days % 30) +
                               "\n Налог: " + str(
                                   int((self.totalPapers /
                                        (self.days / 30) + self.fans /
                                        (self.days / 30))) +
                                   self.levelOfKnowledge * self.days * 2))
            self.nalog.adjustSize()

    def showDevPage2(self):  # показывается окошко второго этапа разработки
        self.cashToDev = 0
        if self.levelOfKnowledge > 0:
            if self.theme1.isChecked():
                self.theme = 1
            elif self.theme2.isChecked():
                self.theme = 2
            elif self.theme3.isChecked():
                self.theme = 3
            elif self.theme4.isChecked():
                self.theme = 4
            elif self.theme5.isChecked():
                self.theme = 5
            elif self.theme6.isChecked():
                self.theme = 6
            elif self.theme7.isChecked():
                self.theme = 7
            elif self.theme8.isChecked():
                self.theme = 8
            if self.style1.isChecked():
                self.style = 1
            elif self.style2.isChecked():
                self.style = 2
            elif self.style3.isChecked():
                self.style = 3
            elif self.style4.isChecked():
                self.style = 4
            elif self.style5.isChecked():
                self.style = 5
            elif self.style6.isChecked():
                self.style = 6
            elif self.style7.isChecked():
                self.style = 7
            elif self.style8.isChecked():
                self.style = 8
            elif self.type1.isChecked():
                self.type = 1
                self.cashToDev += 10
            elif self.type2.isChecked():
                self.type = 2
                self.cashToDev += 300
            elif self.type3.isChecked():
                self.type = 3
                self.cashToDev += 4000
            elif self.type4.isChecked():
                self.cashToDev += 40000
                self.type = 4
            if self.platform1.isChecked():
                self.platform = 1
                self.cashToDev += 10
            elif self.platform2.isChecked():
                self.platform = 2
                self.cashToDev += 400
            elif self.platform3.isChecked():
                self.platform = 3
                self.cashToDev += 10000
            elif self.platform4.isChecked():
                self.platform = 4
                self.cashToDev += 60000
            self.devPage1On = False
            self.totalMoney.setText('Итого: ' + str(self.cashToDev))
            self.totalMoney.adjustSize()
            self.devPage1.move(10000, 10000)
            self.levelOne.setEnabled(False)
            self.levelTwo.setEnabled(False)
            self.levelThree.setEnabled(False)
            self.levelFour.setEnabled(False)

            self.type4.setEnabled(False)
            if self.levelOfKnowledge >= 1:
                self.levelOne.setEnabled(True)
            if self.levelOfKnowledge >= 2:
                self.levelTwo.setEnabled(True)
            if self.levelOfKnowledge >= 3:
                self.levelThree.setEnabled(True)
            if self.levelOfKnowledge >= 4:
                self.levelFour.setEnabled(True)
            self.devPage2On = True
            self.devPage2.move(200, 100)

    def showDevPage3(self):
        self.totalTechno = 0
        if self.techno11.isChecked():
            self.totalTechno += 0.5
        if self.techno12.isChecked():
            self.totalTechno += 0.5
        if self.techno13.isChecked():
            self.totalTechno += 0.5
        if self.techno14.isChecked():
            self.totalTechno += 1
        if self.techno21.isChecked():
            self.totalTechno += 4
        if self.techno22.isChecked():
            self.totalTechno += 4
        if self.techno23.isChecked():
            self.totalTechno += 4
        if self.techno24.isChecked():
            self.totalTechno += 8
        if self.techno31.isChecked():
            self.totalTechno += 64
        if self.techno32.isChecked():
            self.totalTechno += 64
        if self.techno33.isChecked():
            self.totalTechno += 64
        if self.techno34.isChecked():
            self.totalTechno += 64
        if self.techno41.isChecked():
            self.totalTechno += 256
        if self.techno42.isChecked():
            self.totalTechno += 256
        if self.techno43.isChecked():
            self.totalTechno += 512
        if self.techno44.isChecked():
            self.totalTechno += 512
        if self.cash < self.totalMon:
            self.warning.setText('Недостаточно денег')
            self.warning.adjustSize()
        elif self.totalTechno == 0:
            self.warning.setText('Выберите хотя бы 1 технологию')
            self.warning.adjustSize()
        else:
            self.cash -= self.totalMon
            self.money.setText("Деньги: \n" + str(self.cash))
            self.startDev()

    def relise(self):  # метод для релиза игры
        self.table.setText('Релиз! \n  \nЗаработано за все дни: \n' +
                           str(self.totalPapers))
        self.table.adjustSize()
        self.timeDev = False
        self.timeToEnd = 5
        self.timeSale = True

    def startDev(self):  # метод для описания процесса разработки
        self.timeDev = True
        self.tick()
        self.timer.start()
        self.devPage2On = False
        self.devPage2.move(10000, 10000)
        self.table.setText('Дней до релиза: \n' + str(self.timeToEnd))
        self.table.adjustSize()

    def sale(self):  # метод для процесса продажи игры
        myltiply1 = 10 + self.platform + self.type
        if self.style in self.perfect[str(self.theme)][0]:
            myltiply2 = 2
        elif self.style in self.perfect[str(self.theme)][1]:
            myltiply2 = 1
        else:
            myltiply2 = 0.5
        a = int(
            randint(self.totalTechno * 10, self.totalTechno * 20) * myltiply2 /
            10 * myltiply1 + (self.fans * 10 + 1))
        if myltiply2 > 1:
            self.fans += a // 10
        elif myltiply2 < 1:
            self.fans -= a // 10
        self.totalPapers += a
        self.cash += a
        self.subs.setText('Фанаты: \n  ' + str(self.fans))
        self.money.setText('Деньги: \n   ' + str(self.cash))
        self.money.adjustSize()
        self.subs.adjustSize()
        self.table.setText('Заработано сегодня: \n' + str(a) +
                           '\nЗаработано за все дни: \n' +
                           str(self.totalPapers))
        self.table.adjustSize()