Exemple #1
0
 def score(self):
     score = self.mineSweeper.score()
     if score is not None:
         self.mineSweeper.reveal()
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         for tile in self.mineSweeper:
             tile.delegate.marked = False
         self.mineSweeper.reset()
Exemple #2
0
 def round(self, disc: FourPlay.Disc):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.player.disc = disc
     score = self.fourPlay.round(True)
     QApplication.restoreOverrideCursor()
     if score is not None:
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == 0:
             QMessageBox.warning(self, self.tr("Tie!"), self.tr("You tied :|"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         self.fourPlay.reset(True)
Exemple #3
0
 def round(self, tile: TicTacToe.Tile):
     QApplication.setOverrideCursor(Qt.WaitCursor)
     self.player.tile = tile
     score = self.ticTacToe.round(True)
     QApplication.restoreOverrideCursor()
     if score is not None:
         if score == +1:
             QMessageBox.information(self, self.tr("Victory!"), self.tr("You won :)"), QMessageBox.Ok)
         if score == 0:
             QMessageBox.warning(self, self.tr("Tie!"), self.tr("You tied :|"), QMessageBox.Ok)
         if score == -1:
             QMessageBox.critical(self, self.tr("Defeat!"), self.tr("You lost :("), QMessageBox.Ok)
         self.ticTacToe.reset(True)
Exemple #4
0
    def openPort(self):
        if self.serialport.isOpen():
            return

        _port = self.GetPort()
        if '' == _port:
            QMessageBox.information(self, "Invalid parameters", "Port is empty.")
            return

        _baudrate = self.cmbBaudRate.currentText()
        if '' == _baudrate:
            QMessageBox.information(self, "Invalid parameters", "Baudrate is empty.")
            return

        self.serialport.port     = _port
        self.serialport.baudrate = _baudrate
        self.serialport.bytesize = self.GetDataBits()
        self.serialport.stopbits = self.GetStopBits()
        self.serialport.parity   = self.GetParity()
        self.serialport.rtscts   = self.chkRTSCTS.isChecked()
        self.serialport.xonxoff  = self.chkXonXoff.isChecked()
        # self.serialport.timeout  = THREAD_TIMEOUT
        # self.serialport.writeTimeout = SERIAL_WRITE_TIMEOUT
        try:
            self.serialport.open()
        except serial.SerialException as e:
            QMessageBox.critical(self, "Could not open serial port", str(e),
                QMessageBox.Close)
        else:
            self._start_reader()
            self.setWindowTitle("%s on %s [%s, %s%s%s%s%s]" % (
                appInfo.title,
                self.serialport.portstr,
                self.serialport.baudrate,
                self.serialport.bytesize,
                self.serialport.parity,
                self.serialport.stopbits,
                self.serialport.rtscts and ' RTS/CTS' or '',
                self.serialport.xonxoff and ' Xon/Xoff' or '',
                )
            )
            pal = self.btnOpen.palette()
            pal.setColor(QtGui.QPalette.Button, QtGui.QColor(0,0xff,0x7f))
            self.btnOpen.setAutoFillBackground(True)
            self.btnOpen.setPalette(pal)
            self.btnOpen.setText('Close')
            self.btnOpen.update()
Exemple #5
0
    def transmitHex(self, hexarray):
        if len(hexarray) > 0:
            byteArray = bytearray(hexarray)
            if self.serialport.isOpen():
                try:
                    self.serialport.write(byteArray)
                except serial.SerialException as e:
                    print("Exception in transmitHex(%s)" % repr(hexarray))
                    QMessageBox.critical(self, "Exception in transmitHex", str(e),
                        QMessageBox.Close)
                else:
                    # self.txCount += len( b )
                    # self.frame.statusbar.SetStatusText('Tx:%d' % self.txCount, 2)

                    text = ''.join(['%02X ' % i for i in hexarray])
                    self.appendOutputText("\n%s T->:%s" % (self.timestamp(), text),
                        Qt.blue)
Exemple #6
0
    def sendTableRow(self, row):
        cols = self.quickSendTable.columnCount()
        try:
            data = ['0' + self.quickSendTable.item(row, col).text()
                for col in range(1, cols)
                if self.quickSendTable.item(row, col) is not None
                    and self.quickSendTable.item(row, col).text() is not '']
        except:
            print("Exception in get table data(row = %d)" % (row + 1))
        else:
            tmp = [d[-2] + d[-1] for d in data if len(d) >= 2]
            for t in tmp:
                if not is_hex(t):
                    QMessageBox.critical(self, "Error",
                        "'%s' is not hexadecimal." % (t), QMessageBox.Close)
                    return

            h = [int(t, 16) for t in tmp]
            self.transmitHex(h)
Exemple #7
0
    def runfun(self):
        result, message = self.ableCheck()
        if not result:
            QMessageBox.critical(self, "错误", message)
            return

        recent_output_path = action_def.openGetDirPathDialog(self, "选择输出保存路径", global_env.recent_output_path)
        if recent_output_path == "":
            return
        global_env.recent_output_path = recent_output_path
        audiopathlist = []
        xmlpathlist = []
        for i in range(self.audiopathlistWidget.count()):
            audiopathlist.append(self.audiopathlistWidget.item(i).text())
        for i in range(self.xmlpathlistWidget.count()):
            xmlpathlist.append(self.xmlpathlistWidget.item(i).text())
        titlelist = self.titlesplainTextEdit.toPlainText().split("\n")
        name = self.namelineEdit.text()
        mythread = AnsyWorker(self, audiopathlist, xmlpathlist, titlelist, recent_output_path, name)
        mythread.start()
def update_thumbnail(self):
    if self.path != "":
        pixmap = QPixmap(self.path)
        if pixmap.isNull():
            criticalMessageBox = QMessageBox()
            criticalMessageBox.critical(
                None,
                "Invalid Image",
                f"Image at path {self.path} could not be found.",
                criticalMessageBox.Close,
            )
        else:
            aspectRatio = pixmap.size().width() / pixmap.size().height()
            if aspectRatio > 1.78:
                scaledPixmap = pixmap.scaledToWidth(
                    self.thumbnail.size().width())
            else:
                scaledPixmap = pixmap.scaledToHeight(
                    self.thumbnail.size().height())
            self.thumbnail.setPixmap(scaledPixmap)
Exemple #9
0
    def receive_data(self):

        try:
            num = self.serial.inWaiting()
        except:
            self.close_serial_port()
            QMessageBox.critical(self, "Read Error", "读取输入缓存区数据的字节数失败!")
            return None
        print(self.serial.rts)
        print(num)
        self.received_bit_data = self.serial.read(101)
        print(self.received_bit_data)
        self.received_data = self.received_bit_data.decode('ascii')
        # 已经接收到信息说明系统已经开启,将系统状态改为开启
        if self.times == 0:
            self.system_status_button(self.start_stop_button)
            self.times += 1
        print(self.received_data)
        self.statusbar.showMessage("数据读取成功,准备处理数据")
        self.data_operation()
Exemple #10
0
 def action_abrir_archivo(self):
    # print('Abrir Archivo')
     ubicacion = QFileDialog.getOpenFileName(
        self,
        'Abrir Archivo',
        '.',
        'JSON (*.json)'
     )[0]
     if self.particulas.abrir(ubicacion):
         QMessageBox.information(
             self,
             "Exito",
             "Se abrió el archivo " + ubicacion
         )
     else:
         QMessageBox.critical(
             self,
             "Error",
             "Error al abrir el archivo " + ubicacion
         )
 def sell(self, unit_type: UnitType):
     # Don't need to remove aircraft from the inventory if we're canceling
     # orders.
     if self.pending_deliveries.units.get(unit_type, 0) <= 0:
         global_inventory = self.game_model.game.aircraft_inventory
         inventory = global_inventory.for_control_point(self.cp)
         try:
             inventory.remove_aircraft(unit_type, 1)
         except ValueError:
             QMessageBox.critical(
                 self,
                 "Could not sell aircraft",
                 f"Attempted to sell one {unit_type.id} at {self.cp.name} "
                 "but none are available. Are all aircraft currently "
                 "assigned to a mission?",
                 QMessageBox.Ok,
             )
             return
     super().sell(unit_type)
     self.hangar_status.update_label()
Exemple #12
0
 def s_plot(self):
     """display the data in a plot"""
     try:
         data = self.data.get_data()
     except Exception as e:
         QMessageBox.critical(self, self.tr("Error"), str(e))
         return
     if len(data.shape) == 2 and data.shape[0] == 2:
         # Data in line
         fig, axes = plt.subplots()
         axes.plot(data[0, :], data[1, :])
         fig.show()
     elif len(data.shape) == 2 and data.shape[1] == 2:
         # Data in column
         fig, axes = plt.subplots()
         axes.plot(data[:, 0], data[:, 1])
         fig.show()
     if self.verbose_name is not None:
         fig.canvas.manager.set_window_title(self.verbose_name)
     set_plot_gui_icon()
Exemple #13
0
 def accept(self):
     use_json_file = self.form.file_groupbox.isChecked()
     dir_ = 'x' if self.form.x_radio_button.isChecked() else 'y'
     if use_json_file:
         json_file = Path(self.form.json_file.text())
     else:
         json_file = Path(self.etabs.SapModel.GetModelFilepath()
                          ) / f'columns_pmm_beams_rebars_{dir_}.json'
     if json_file.exists():
         import table_model
         ret = self.etabs.load_from_json(json_file)
         data, headers, data2, headers2 = ret
         table_model.show_results(data, headers,
                                  table_model.ColumnsRatioModel)
         table_model.show_results(data2, headers2,
                                  table_model.BeamsRebarsModel)
     else:
         err = "Please first get weakness ration, then show it!"
         QMessageBox.critical(self, "Error", str(err))
         return None
Exemple #14
0
 def action_guardar_archivo(self):
     ubicacion = QFileDialog.getSaveFileName( 
         self,
         'Guardar Archivo',
         '.',
         'JSON (*.json)'
     )[0]
     print(ubicacion)
     if self.administrar.guardar(ubicacion):
         QMessageBox.information(
             self,
             "Exito",
             "Se pudo crear el archivo" + ubicacion 
         )
     else: 
         QMessageBox.critical(
             self,
             "Error",
             "No se pudo crear el archivo " + ubicacion
         )
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(self, "Threaded Fortune Server",
                    "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(self, "Threaded Fortune Server",
                    "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
Exemple #17
0
    def on_play(self):
        """
        Copies the ROM, including the current level, to a temporary directory, saves the current level as level 1-1 and
        opens the rom in an emulator.
        """
        temp_dir = pathlib.Path(tempfile.gettempdir()) / "smb3foundry"
        temp_dir.mkdir(parents=True, exist_ok=True)

        path_to_temp_rom = temp_dir / "instaplay.rom"

        ROM().save_to(path_to_temp_rom)

        if not self._put_current_level_to_level_1_1(path_to_temp_rom):
            return

        if not self._set_default_powerup(path_to_temp_rom):
            return

        arguments = SETTINGS["instaplay_arguments"].replace(
            "%f", str(path_to_temp_rom))
        arguments = shlex.split(arguments, posix=False)

        emu_path = pathlib.Path(SETTINGS["instaplay_emulator"])

        if emu_path.is_absolute():
            if emu_path.exists():
                emulator = str(emu_path)
            else:
                QMessageBox.critical(
                    self, "Emulator not found",
                    f"Check it under File > Settings.\nFile {emu_path} not found."
                )
                return
        else:
            emulator = SETTINGS["instaplay_emulator"]

        try:
            subprocess.run([emulator, *arguments])
        except Exception as e:
            QMessageBox.critical(self, "Emulator command failed.",
                                 f"Check it under File > Settings.\n{str(e)}")
Exemple #18
0
    def import_preset_file(self, path: Path):
        preset = VersionedPreset.from_file_sync(path)
        try:
            preset.get_preset()
        except (ValueError, KeyError):
            QMessageBox.critical(
                self._window_manager, "Error loading preset",
                "The file at '{}' contains an invalid preset.".format(path))
            return

        if self._window_manager.preset_manager.preset_for_name(
                preset.name) is not None:
            user_response = QMessageBox.warning(
                self._window_manager, "Preset name conflict",
                "A preset named '{}' already exists. Do you want to overwrite it?"
                .format(preset.name), QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No)
            if user_response == QMessageBox.No:
                return

        self._add_new_preset(preset)
    def login(self):
        user_id = self.idInput.text()
        pwd = self.pwdInput.text()
        status = usermgr.login(self.login_type, user_id, pwd)
        if status == 0:
            user_name = usermgr.get_name()
            QMessageBox.information(self, self.tr('Login Successful'),
                                    self.tr('Welcome, {}!'.format(user_name)),
                                    QMessageBox.Ok)
            # print(m)
            # self.hide()
            self.close()
            m = StudentMainWindow(self) if \
                self.login_type == LoginType.STUDENT else \
                    TeacherMainWindow(self)
            m.show()

        else:
            QMessageBox.critical(self, self.tr('Login Failed'),
                                 self.tr('Wrong ID or password!'),
                                 QMessageBox.Ok)
 def confirm_recreate(self, task: FlightType) -> None:
     result = QMessageBox.question(
         self,
         "Regenerate flight?",
         ("Changing the flight type will reset its flight plan. Do you want "
          "to continue?"),
         QMessageBox.No,
         QMessageBox.Yes,
     )
     original_task = self.flight.flight_type
     if result == QMessageBox.Yes:
         self.flight.flight_type = task
         try:
             self.planner.populate_flight_plan(self.flight)
         except PlanningError as ex:
             self.flight.flight_type = original_task
             logging.exception("Could not recreate flight")
             QMessageBox.critical(self, "Could not recreate flight",
                                  str(ex), QMessageBox.Ok)
         self.flight_waypoint_list.update_list()
         self.on_change()
Exemple #21
0
 def action_guardar_archivo(self):
     #print('Guardar_archivo')
     ubicacion = QFileDialog.getSaveFileName(
         self,
         'Guardar Archivo', #el nombre del archivo
         '.', #donde lo va a guardar, en este caso en la carpeta del proyecto
         'JSON (*.json)' #Tipo de formato
     )[0]
     print(ubicacion)
     if self.particulas.guardar(ubicacion):
         QMessageBox.information(
             self, #desde donde se manda
             "Éxito", #nombre de la ventana
             "Se pudo crear el archivo " + ubicacion #mensaje
         )
     else:
         QMessageBox.critical(
             self,
             "Error",
             "No se pudo crear el archivo " + ubicacion
         )
 def _replaceContent(self, index):
     try:
         nodes = hou.selectedItems()
     except:
         nodes = hou.selectedNodes()
     if (len(nodes) == 0):
         QMessageBox.warning(self, 'cannot replace',
                             'selection is empty')
         return
     item = index.internalPointer()
     good = QMessageBox.warning(
         self, 'sure?',
         'confirm that you want to replace the content of selected item "%s". This operation can not be undone.'
         % item.name(),
         QMessageBox.Ok | QMessageBox.Cancel) == QMessageBox.Ok
     if (not good): return
     try:
         item.setContent(hpaste.nodesToString(nodes))
     except CollectionSyncError as e:
         QMessageBox.critical(self, 'something went wrong!',
                              'Server error occured: %s' % e.message)
    def get_authorIllust(self):
        def State():
            state = True
            if self.ui.lineEdit_authorID.text(
            ) == '' or self.ui.lineEdit_path.text() == '':
                QMessageBox.warning(self.ui, '警告', 'ID与路径不能为空!!!')
                state = False
            return state

        def illust_thread():
            self.ui.textBrowser.setPlainText('======开始爬取======')
            PD.Author_iIllust(self.ui.lineEdit_authorID.text(),
                              self.ui.lineEdit_path.text())

        # if State():
        #     illust_thread()
        try:
            if State():
                illust_thread()
        except:
            QMessageBox.critical(self.ui, '错误', '爬取失败,连接超时!!!')
Exemple #24
0
    def _on_pushfunc_clicked(self):

        current_function = self._controller.current_function()
        if current_function is None:
            QMessageBox.critical(None, 'Error',
                                 "Please set the current function first.")
            return

        func = current_function

        with self._controller.state_ctx(locked=True) as state:

            # function name
            self._controller.push_function(func, state=state)

            # comments
            self._controller.remove_all_comments(func, state=state)
            self._controller.push_comments(func.comments, state=state)

            # stack variables
            self._controller.push_stack_variables(func, state=state)
 def action_abrir_archivo(self):  
     #print("Abrir archivo")
     ubicacion = QFileDialog.getOpenFileName( #Regresa ubicación del archivo modo de apertura
         self,
         'Abrir Archivo',
         '.', #Decirle desde la carpeta que se esta trabajando
         'JSON (*.json)'
     )[0] 
     if self.particulas.abrir(ubicacion):
         self.particulas.mandar_particulas_grafo()
         QMessageBox.information(
             self,
             "Éxito",
             "Se abrió el archivo " + ubicacion
         )
     else:
         QMessageBox.critical(
             self,
             "Error",
             "Error al abrir el archivo " + ubicacion
         )
 def action_guardar_archivo(self):
     #print('Guardar Archivo')
     ubicacion = QFileDialog.getSaveFileName( #Método para regresar la ubicación
         self,
         'Guardar Archivo',
         '.',
         'JSON (*.json)'
     )[0] #pirmera posición de la tupla
     #print(ubicacion)
     if self.particulas.guardar(ubicacion): #invocar método de AdminParticula()
         QMessageBox.information(
             self,
             "Éxito",
             "Se pudo crear el archivo " + ubicacion
         )
     else:
         QMessageBox.critical(
             self,
             "Error",
             "No se pudo crear el archivo " + ubicacion
         )
 def setGame(self, game: Optional[Game]):
     try:
         self.game = game
         if self.info_panel is not None:
             self.info_panel.setGame(game)
         self.sim_controller.set_game(game)
         self.game_model.set(self.game)
     except AttributeError:
         logging.exception("Incompatible save game")
         QMessageBox.critical(
             self,
             "Could not load save game",
             "The save game you have loaded is incompatible with this "
             "version of DCS Liberation.\n"
             "\n"
             f"{traceback.format_exc()}",
             QMessageBox.Ok,
         )
         GameUpdateSignal.get_instance().updateGame(None)
     finally:
         self.enable_game_actions(self.game is not None)
    def abrir_archivo(self):
        ubicacion = QFileDialog.getOpenFileName(
            self,
            'Abrir archivo',
            './examples',
            'JSON (*.json)'
        )[0]

        if self.cern.abrir(ubicacion):
            QMessageBox.information(
                self,
                "Éxito",
                "Se abrió el archivo " + ubicacion
            )
            self.mostrar()
        else:
            QMessageBox.critical(
                self,
                "Error",
                "Error al abrir el archivo " + ubicacion
            )
Exemple #29
0
    def create(self):
        if self.remove_:
            del self.vsp.text_file_items[self.remove_.text()]
            self.widget.remove(self.remove_)
            self.remove_ = None
            self.update()
        filename = self.window_ui.fileName.text()
        content = self.window_ui.content.toPlainText()
        name = self.window_ui.name.text()

        if self.vsp.check_if_same_key(name) == True:
            QMessageBox.critical(self.window, "Error", "Name Exists, Abort.")
            return
        print("create text item", content)
        if filename != "" and content != "":
            Text_File_item(name=name,
                           vsp=self.vsp,
                           file_name=filename,
                           string=content)
            self.window.close()
        self.update()
    def _try_loading(self):

        # Make sure that the binary exists
        if not os.path.isfile(self.file_path):
            QMessageBox.critical(self, "File not found",
                                 "File \"%s\" is not found." % self.file_path,
                                 QMessageBox.Ok)
            raise LoadBinaryError("File not found.")

        try:
            ld = cle.Loader(self.file_path, perform_relocations=False)

            deps = []
            processed_objects = set()
            for ident, obj in ld._satisfied_deps.items():
                if obj is ld._kernel_object or \
                        obj is ld._tls_object or \
                        obj is ld._extern_object or \
                        obj is ld.main_object:
                    continue
                if obj in processed_objects:
                    continue
                deps.append(ident)
                processed_objects.add(obj)

            dep_list = self.option_widgets['dep_list']  # type: QListWidget
            for dep in deps:
                dep_item = QListWidgetItem(dep)
                dep_item.setData(Qt.CheckStateRole, Qt.Unchecked)
                dep_list.addItem(dep_item)

        except Exception as ex:
            # I guess we will have to load it as a blob?
            l.warning("Preloading of the binary fails due to an exception.",
                      exc_info=True)
            QMessageBox.critical(
                self, "Error preloading the binary",
                "Preloading of the binary fails due to an exception %s." %
                str(ex), QMessageBox.Ok)
            raise LoadBinaryError("File not found.")
Exemple #31
0
    def setup(self):
        ip_plc = self.conf.read_config(product='config',
                                       section='plc',
                                       name='ip')
        _, self.product = self.get_project()
        self.Ui_MainWindow.lineEdit_IP_PLC.setText(ip_plc)

        self.siemens = SiemensS7Net(SiemensPLCS.S1200, ip_plc)
        self.Ui_MainWindow.label_status.setText('正在初始化,请稍候...')
        self.Ui_MainWindow.label_status.setStyleSheet(
            'background-color: rgb(255, 255, 127);')
        QApplication.processEvents()

        if self.com.check_com():  # 如果有串口,则打开指定的串口
            if self.com.open_com():  # 如果串口打开成功
                if self.siemens.ConnectServer().IsSuccess:  # 如果PLC连接成功
                    self.Ui_MainWindow.label_status.setText('初始化完成')
                    self.Ui_MainWindow.label_status.setStyleSheet(
                        'background-color: rgb(255, 255, 127);')
                    self._thread.start()
                else:  # 如果PLC连接失败
                    QMessageBox.critical(self, '错误', 'PLC连接失败!')
                    self.Ui_MainWindow.label_status.setText('PLC连接失败!')
                    self.Ui_MainWindow.label_status.setStyleSheet(
                        'background-color: rgb(255, 0, 0);')
            else:  # 如果串口打开失败
                QMessageBox.critical(self, '错误!', '串口打开失败!')
                self.Ui_MainWindow.label_status.setText('串口打开失败!')
                self.Ui_MainWindow.label_status.setStyleSheet(
                    'background-color: rgb(255, 0, 0);')
        else:
            QMessageBox.critical(self, '错误!', '未发现串口!')
            self.Ui_MainWindow.label_status.setText('未发现串口!')
            self.Ui_MainWindow.label_status.setStyleSheet(
                'background-color: rgb(255, 0, 0);')
Exemple #32
0
 def load_trace_file(self, file_path):
     if isurl(file_path):
         QMessageBox.critical(
             self, "Unsupported Action",
             "Downloading trace files is not yet supported."
             "Please specify a path to a file on disk.")
     else:
         # File
         if os.path.isfile(file_path):
             try:
                 with open(file_path, 'rb') as f:
                     loaded_sim_state = pickle.load(f)
                     analysis_params = {
                         'end_state': loaded_sim_state,
                         'start_addr': None,
                         'end_addr': None,
                         'block_addrs': None,
                     }
                     self.workspace.view_data_dependency_graph(
                         analysis_params)
                 self._recent_file(file_path)
             except pickle.PickleError:
                 QMessageBox.critical(
                     self, "Unable to load trace file",
                     "Trace file must contain a serialized SimState.")
         else:
             QMessageBox.critical(
                 self, "File not found",
                 f"angr management cannot open file {file_path}. "
                 "Please make sure that the file exists.")
    def _on_pullfunc_clicked(self):
        disasm_view = self.workspace.view_manager.first_view_in_category(
            "disassembly")
        if disasm_view is None:
            QMessageBox.critical(
                None, 'Error',
                "Cannot determine the current function. No disassembly view is open."
            )
            return

        current_function = disasm_view._current_function
        if current_function is None:
            QMessageBox.critical(
                None, 'Error',
                "No function is current in the disassembly view.")
            return

        # which user?
        u = self._team_table.selected_user()
        if u is None:
            QMessageBox.critical(
                None, 'Error', "Cannot determine which user to pull from. "
                "Please select a user in the team table first.")
            return

        self.workspace.instance.project.kb.sync.fill_function(current_function,
                                                              user=u)

        # trigger a refresh
        disasm_view.refresh()
Exemple #34
0
    def validatePage(self):
        start, end = self.get_start(), self.get_end()
        if isinstance(start, str) or isinstance(end, str):
            # do not check revisions
            return True
        try:
            start_date = to_datetime(start)
            end_date = to_datetime(end)
        except DateFormatError as exc:
            QMessageBox.critical(self, "Error", str(exc))
            return False
        current = datetime.datetime.now()
        if start_date < end_date:
            if end_date <= current:
                return True
            else:
                QMessageBox.critical(
                    self,
                    "Error",
                    "You can't define a date in the future.")
        else:
            QMessageBox.critical(
                self,
                "Error",
                "The first date must be earlier than the second one.")

        return False
Exemple #35
0
 def open_serial_port(self):
     data_bits = {
         '5': serial.FIVEBITS,
         '6': serial.SIXBITS,
         '7': serial.SEVENBITS,
         '8': serial.EIGHTBITS
     }
     parity = {
         'N': serial.PARITY_NONE,
         'Odd': serial.PARITY_ODD,
         'Even': serial.PARITY_EVEN
     }
     stop_bits = {
         '1': serial.STOPBITS_ONE,
         '1.5': serial.STOPBITS_ONE_POINT_FIVE,
         '2': serial.STOPBITS_TWO
     }
     self.ser.port = self.ui_serial.cbbSerialPorts.currentText()
     self.ser.baudrate = int(
         self.ui_serial.cbbSerialPortBaudrate.currentText())
     self.ser.bytesize = data_bits[
         self.ui_serial.cbbSerialPortDatabit.currentText()]
     self.ser.parity = parity[
         self.ui_serial.cbbSerialPortParity.currentText()]
     self.ser.stopbits = stop_bits[
         self.ui_serial.cbbSerialPortStopbit.currentText()]
     print("Serial Port: {0} {1} {2} {3}".format(self.ser.port,
                                                 self.ser.baudrate,
                                                 self.ser.parity,
                                                 self.ser.stopbits))
     try:
         self.ser.open()
     except:
         QMessageBox.critical(self, "Port Error", "Cannot open this port")
     if self.ser.isOpen():
         self.receive_timer.start(100)
         print("{0} opened".format(self.ser.port))
         self.ui_serial.btnSerialOpen.setEnabled(False)
         self.ui_serial.btnSerialCLose.setEnabled(True)
     pass
Exemple #36
0
    def _load_database(self, file_path):

        if AngrDB is None:
            QMessageBox.critical(None, 'Error',
                                 'AngrDB is not enabled. Maybe you do not have SQLAlchemy installed?')
            return

        angrdb = AngrDB()
        try:
            proj = angrdb.load(file_path)
        except angr.errors.AngrIncompatibleDBError as ex:
            QMessageBox.critical(None, 'Error',
                                 "Failed to load the angr database because of compatibility issues.\n"
                                 "Details: %s" % str(ex))
            return
        except angr.errors.AngrDBError as ex:
            QMessageBox.critical(None, 'Error',
                                 'Failed to load the angr database.\n'
                                 'Details: %s' % str(ex))
            _l.critical("Failed to load the angr database.", exc_info=True)
            return

        cfg = proj.kb.cfgs['CFGFast']
        cfb = proj.analyses.CFB()  # it will load functions from kb

        self.workspace.instance.database_path = file_path

        self.workspace.instance.initialized = True  # skip automated CFG recovery
        self.workspace.instance.project = proj
        self.workspace.instance.cfg = cfg
        self.workspace.instance.cfb = cfb

        # trigger callbacks
        self.workspace.reload()
        self.workspace.on_cfg_generated()
Exemple #37
0
    def on_action_edit_apply_laue_mask_to_polar_triggered(self):
        if not HexrdConfig().show_overlays:
            msg = 'Overlays are not displayed'
            QMessageBox.critical(self.ui, 'HEXRD', msg)
            return

        overlays = HexrdConfig().overlays
        laue_overlays = [x for x in overlays if x['type'] == OverlayType.laue]
        laue_overlays = [x for x in laue_overlays if x['visible']]
        if not laue_overlays:
            msg = 'No Laue overlays found'
            QMessageBox.critical(self.ui, 'HEXRD', msg)
            return

        data = []
        for overlay in laue_overlays:
            for det, val in overlay['data'].items():
                for ranges in val['ranges']:
                    data.append(ranges)

        if not data:
            msg = 'No Laue overlay ranges found'
            QMessageBox.critical(self.ui, 'HEXRD', msg)
            return

        HexrdConfig().polar_masks_line_data.append(data)
        self.new_mask_added.emit()
        self.update_all()
Exemple #38
0
    def loadCSV(self, path, notifyExcept = False):
        data = []
        set_rows = 0
        set_cols = 0
        try:
            with open(path) as csvfile:
                csvData = csv.reader(csvfile)
                for row in csvData:
                    data.append(row)
                    set_rows = set_rows + 1
                    if len(row) > set_cols:
                        set_cols = len(row)
        except IOError as e:
            print("({})".format(e))
            if notifyExcept:
                QMessageBox.critical(self, "Open failed", str(e), QMessageBox.Close)
            return

        rows = self.quickSendTable.rowCount()
        cols = self.quickSendTable.columnCount()
        # clear table
        for col in range(cols):
            for row in range(rows):
                self.quickSendTable.setItem(row, col, QTableWidgetItem(""))

        self._csvFilePath = path
        if (cols - 1) < set_cols:   # first colume is used by the "send" buttons.
            cols = set_cols + 10
            self.quickSendTable.setColumnCount(cols)
        if rows < set_rows:
            rows = set_rows + 20
            self.quickSendTable.setRowCount(rows)

        for row, rowdat in enumerate(data):
            if len(rowdat) > 0:
                for col, cell in enumerate(rowdat, 1):
                    self.quickSendTable.setItem(row, col, QTableWidgetItem(str(cell)))

        self.quickSendTable.resizeColumnsToContents()
Exemple #39
0
 def terminated(self):
     QMessageBox.critical(self, self.tr("Game Over!"), self.tr("You toppped out."), QMessageBox.Ok)
     self.tetris.restart()
Exemple #40
0
 def readerExcept(self, e):
     self.closePort()
     QMessageBox.critical(self, "Read failed", str(e), QMessageBox.Close)