Exemple #1
0
    def load_symbols(self, rom_variant: RomVariant, silent: bool) -> None:

        maps = {
            RomVariant.CUSTOM: 'tmc.map',
            RomVariant.CUSTOM_EU: 'tmc_eu.map',
            RomVariant.CUSTOM_JP: 'tmc_jp.map',
            RomVariant.CUSTOM_DEMO_USA: 'tmc_demo_usa.map',
            RomVariant.CUSTOM_DEMO_JP: 'tmc_demo_jp.map',
        }

        map_file = path.join(settings.get_repo_location(), maps[rom_variant])
        if not path.isfile(map_file):
            if silent:
                print(f'Could not find tmc.map file at {map_file}.')
            else:
                QMessageBox.critical(
                    self, 'Load symbols from .map file',
                    f'Could not find tmc.map file at {map_file}.')
            return

        get_symbol_database().load_symbols_from_map(rom_variant, map_file)
        if not silent:
            QMessageBox.information(
                self, 'Load symbols',
                f'Successfully loaded symbols for {rom_variant} rom from tmc.map file.'
            )
Exemple #2
0
 def _prediction_historical_error(self, prediction: list) -> None:
     """Displays a message for when historical target is unavalable such that
     a graph can't be made."""
     QMessageBox.information(
         self, self.tr("Information"), f'Prediction was: {prediction}. \n '
         'Unable to display graph due to missing historical data.',
         QtWidgets.QMessageBox.Ok)
    def ExportTeams(self):

        export_dir = self.config["save_route"] if self.config["save_route"] \
                                                    is not None else THISDIR
        exported_file = QFileDialog.getSaveFileName(self, "Save File",
            export_dir, "Save files (*.zip)")

        if exported_file[0] != "":
            export_filename = exported_file[0]
            if export_filename.endswith(".zip") is False:
                export_filename += ".zip"
            files_to_export = []
            files_to_export.append("config\\teams.json")

            for root, directories, files in os.walk(THISDIR+"\\images\\logos"):
                for filename in files:
                    filepath = os.path.join(root, filename)
                    files_to_export.append(filepath)

            with ZipFile(export_filename, "w") as export_zip:
                for exp_file in files_to_export:
                    export_name = exp_file
                    if exp_file.endswith(".json"):
                        split_name = exp_file.split("\\")
                        export_name = split_name[-1]
                    if exp_file.endswith(".png"):
                        split_name = exp_file.split("\\")
                        export_name = "\\logos\\" + split_name[-1]
                    export_zip.write(exp_file, arcname=export_name)
                export_zip.close()

            if os.path.exists(export_filename):
                QMessageBox.information(self, "Export",
                    "The export was successful")
Exemple #4
0
 def remove_key_action(self):
     selected = self.keyListView.selectedIndexes()
     if not selected:
         return
     index = selected[0]
     self._remove_key(index.row())
     QMessageBox.information(self, '信息', '密钥已经移除')
Exemple #5
0
    def reload_key_action(self):
        item = self.get_selected_item()
        key: Key = item.data()
        password = None
        if Key.need_password(key.path):
            ok_pressed = True
            while ok_pressed:
                password, ok_pressed = QInputDialog.getText(
                    self, "需要密码", "输入密码:", QLineEdit.Password, "")
                if ok_pressed:
                    illegal, msg = Key.is_password_illegal(password)
                    if illegal:
                        QMessageBox.information(self, '错误', msg)
                        continue
                    break
                else:
                    return

        try:
            key.load(key.path, password)
        except Exception as e:
            QMessageBox.critical(self, '错误', '不是有效的密钥文件<br/>' + str(e))
            return

        self.update_key_icon(item)
Exemple #6
0
    def taskStart(self):
        ''' Inicia a execucao do programa, se houver algum erro durante o processo
        notifica o usuario e deixa a funcao imediatamente'''
        if self.folder.isModified() and self.path.isModified(): # o usuario entrou com os enderecos?
            start = time.time()

            # Conhece do que se trata cada coluna na tabela e armazena essa informacao.
            header = {}
            for col in range(15):
                header[self.Tabela.cellWidget(0, col).currentText()] = col

            boolean = 0 if self.ignore.isChecked() else None

            # Le o arquivo e retorna um dataframe de strings
            df_master = utils.read_file(self, header = boolean)
            df_master = dt.data_filter(self, df_master, header)
            df_master = dt.convert_dtype(self, df_master)

            # Computa os acumulados para cada intervalo de tempo (key).
            for key in self.selected:
                array = dt.compute(df_master.index.to_numpy(), df_master['Observado'].to_numpy(), key)
                df_master[self.linktimedelta[key]] = pd.Series(array, df_master.index)

            # salva o arquivo final.
            utils.save_file(self, df_master)

            # Fim do processo
            end = time.time()
            # Notifica o usuario
            QMessageBox.information(self, "Notificação", "Tarefa realizada com sucesso!\nTempo de execução: {} s.".format(round(end-start, 2)))
            # Reseta a tabela e os endereço do arquivo aberto e onde salvar, na janela principal.
            self.resetProgram()

        else:
            QMessageBox.warning(self, "Notificação", "Houve um erro no arquivo ou diretório especificado.\nPor favor, selecione um caminho válido.")
 def pyradiomics_handler(self, path, filepaths, hashed_path):
     """
     Sends signal to initiate pyradiomics analysis
     """
     if which('plastimatch') is not None:
         if hashed_path == '':
             confirm_pyradi = QMessageBox.information(
                 self, "Confirmation",
                 "Are you sure you want to perform pyradiomics? Once "
                 "started the process cannot be terminated until it "
                 "finishes.", QMessageBox.Yes, QMessageBox.No)
             if confirm_pyradi == QMessageBox.Yes:
                 self.run_pyradiomics.emit(path, filepaths, hashed_path)
             if confirm_pyradi == QMessageBox.No:
                 pass
         else:
             self.run_pyradiomics.emit(path, filepaths, hashed_path)
     else:
         exe_not_found = QMessageBox.information(
             self, "Error",
             "Plastimatch not installed. Please install Plastimatch "
             "(https://sourceforge.net/projects/plastimatch/) to carry out "
             "pyradiomics analysis. If using Windows, please ensure that "
             "your system's PATH variable inlcudes the directory where "
             "Plastimatch's executable is installed.")
Exemple #8
0
 def _training_complete_event(self, return_value: float) -> None:
     """Display information about completed model training."""
     QMessageBox.information(
         self, self.tr("Information"),
         f'Model created and saved with final R-Squared of: {return_value}',
         QtWidgets.QMessageBox.Ok)
     self.setEnabled(True)
Exemple #9
0
 def add_new_user(self):
     if self.login_thread is None:
         self.ui.setEnabled(False)
         self.login_thread = LoginThread(self.on_login)
         self.login_thread.start()
         QMessageBox.information(
             self, "Add new user", "Please log in to your YouTube account. "
             "The window will close automatically when you log in.")
Exemple #10
0
    def writeToFile(self, filename):
        """ Save all contacts in the model to a file. """
        try:
            f = open(filename, "wb")
            pickle.dump(self.tableModel.addresses, f)

        except IOError:
            QMessageBox.information(self, "Unable to open file: %s" % filename)
        finally:
            f.close()
Exemple #11
0
 def closeEvent(self, event):
     if not event.spontaneous() or not self.isVisible():
         return
     if self.trayIcon.isVisible():
         QMessageBox.information(
             self, "Systray",
             "The program will keep running in the system tray. "
             "To terminate the program, choose <b>Quit</b> in the context "
             "menu of the system tray entry.")
         self.hide()
         event.ignore()
Exemple #12
0
    def scan_over(self):
        self.worker = None
        self.stop_event.clear()

        self.scan_button.setText('Scan')
        self.scan_button.setEnabled(True)
        self.setWindowTitle(TITLE)
        QMessageBox.information(
            self, TITLE,
            f'Scan complete!\n\n{self.count} password{"s have" if self.count != 1 else " has"} been found.'
        )
Exemple #13
0
    def jump_to_next_image(self) -> None:
        if len(self._list_of_images) == 0:
            self.mainWindow.statusbar.flash_message(
                red("no more"), wait=cfg.MESSAGE_FLASH_TIME_1)
            self.mainWindow.play_error_sound()
            return
        # else
        if self._curr_img_idx == len(self._list_of_images) - 1:
            self.mainWindow.statusbar.flash_message(
                red("no more"), wait=cfg.MESSAGE_FLASH_TIME_1)
            if self._curr_img.is_it_really_the_last():  # type: ignore
                self.mainWindow.play_error_sound()
            img = self._curr_img
            subreddit_name = img.extra_info.get("subreddit")  # type: ignore
            after_id = img.extra_info.get("after_id")  # type: ignore
            if img and subreddit_name and after_id:
                urls = []
                if self.mainWindow.auto_load_next_subreddit_page:
                    urls = subreddit.read_subreddit(
                        subreddit_name,
                        after_id,
                        statusbar=self.mainWindow.statusbar,
                        mainWindow=self.mainWindow)
                else:
                    reply = QMessageBox.question(
                        self.mainWindow, 'Question', "Load the next page?",
                        QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)

                    if reply == QMessageBox.No:
                        return
                    else:
                        # self.open_subreddit(subreddit, after_id)
                        urls = subreddit.read_subreddit(
                            subreddit_name,
                            after_id,
                            statusbar=self.mainWindow.statusbar,
                            mainWindow=self.mainWindow)

                if len(urls) == 0:
                    QMessageBox.information(self.mainWindow, "Info",
                                            "No new images were found.")
                else:
                    lst = [ImageProperty(url, self.mainWindow) for url in urls]
                    self._list_of_images.extend(lst)
                    self.jump_to_next_image()
                return
            else:
                return
        # else
        new_idx = self._curr_img_idx + 1
        if new_idx >= len(self._list_of_images):
            new_idx = len(self._list_of_images) - 1
        #
        self.jump_to_image(new_idx)
Exemple #14
0
 def check_for_updates_action(self):
     self.status_message("Checking for updates.. This will take a few moments..")
     if updater.check_update() is True:
         latest = updater.latest_version()
         self.status_message("New version available! (" + updater.latest_version() + ") OSCDL is out of date.")
         QMessageBox.warning(self, 'OSCDL is out of date',
                             'Please go to the GitHub page and obtain the latest release\n'
                             'Newest Version: ' + latest)
     else:
         self.status_message("OSCDL is up to date!")
         QMessageBox.information(self, 'OSCDL is up to date',
                                 'You are running the latest version of OSCDL!\n')
Exemple #15
0
    def del_records_btn_click(self):
        # 第一种方法:删除多行数据
        index_list = []
        for model_index in self.tableView.selectionModel().selectedRows():
            index = QtCore.QPersistentModelIndex(model_index)
            index_list.append(index)

        if index_list:
            for index in index_list:
                self.model.removeRow(index.row())
        else:
            MessageBox = QMessageBox()
            MessageBox.information(self.tableView, "标题", "没有选中表格中要删除的行")
    def ImportTeamImage(self):

        image_dialog = QFileDialog(self)
        image_dialog = QFileDialog.getOpenFileName(filter="Images (*.png)",
            selectedFilter="Images (*.png)")

        if image_dialog[0] != "":
            new_team_logo = Image.open(image_dialog[0]).convert("RGBA")
            if new_team_logo.size != (250, 250):
                new_team_logo.resize((250, 250))
            new_team_logo.save(THISDIR+"\\images\\logos\\team%s.png"\
                % self.num_id.text())

            QMessageBox.information(self, "Team Image", "Team image added.")
    def download(self):
        url = self.ui.txt_url.text()
        save_location = self.ui.txt_dest.text()
        try:
            urllib.request.urlretrieve(url, save_location, self.report)
        except Exception:
            QMessageBox.warning(self, "Warning", "The download failed!")
            return

        QMessageBox.information(self, "Information",
                                "The download is complete!")
        self.ui.progressBar.setValue(0)
        self.ui.txt_url.setText('')
        self.ui.txt_dest.setText('')
Exemple #18
0
    def readFromFile(self, filename):
        """ Read contacts in from a file. """
        try:
            f = open(filename, "rb")
            addresses = pickle.load(f)
        except IOError:
            QMessageBox.information(self, "Unable to open file: %s" % filename)
        finally:
            f.close()

        if len(addresses) == 0:
            QMessageBox.information(self, "No contacts in file: %s" % filename)
        else:
            for address in addresses:
                self.addEntry(address["name"], address["address"])
    def slot_conn_clicked(self):
        # try:
        if self.combobox.currentText() == "Connect to /dev":
            self.fd = open(self.addr_edit.text(), "wb")

        elif self.combobox.currentText() == "Connect to Server":
            self.fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.fd.connect(("127.0.0.1", int(self.port_edit.text())))
        # except :
        #     pass

        # TODO except

        QMessageBox.information(self, "success", "connected")
        self.set_send_btn_statu(True)
Exemple #20
0
    def on_update(self, value, text=""):
        """
        Update percentage and text of progress bar.
        :param value:   Percentage value to be displayed
        :param text:    To display what ROI currently being processed
        """

        # When generating the nrrd file, the percentage starts at 0
        # and reaches 25
        if value == 0:
            self.label.setText("Generating nrrd file")
        # The segmentation masks are generated between the range 25 and
        # 50
        elif value == 25:
            self.label.setText("Generating segmentation masks")
        # Above 50, pyradiomics analysis is carried out over each
        # segmentation mask
        elif value in range(50, 100):
            self.label.setText("Calculating features for " + text)
        # Set the percentage value
        self.progress_bar.setValue(value)

        # When the percentage reaches 100, send a signal to close
        # progress bar
        if value == 100:
            completion = QMessageBox.information(
                self, "Complete", "Task has been completed successfully")
            self.progress_complete.emit()
Exemple #21
0
    def slot_remove_redundant(self) -> None:
        '''
        Disables all constraints that only contain redundant information and don't create more relations
        '''

        progress_dialog = self.api.get_progress_dialog(
            'Constraint Cleaner', 'Removing redundant constraints...', False)
        progress_dialog.show()

        self.thread = QThread()
        self.worker = RemoveRedundantWorker()
        self.worker.moveToThread(self.thread)

        self.worker.signal_progress.connect(
            lambda progress: progress_dialog.set_progress(progress))
        self.worker.signal_done.connect(
            lambda: (  # https://stackoverflow.com/a/13672943
                self.thread.quit(), progress_dialog.close(),
                QMessageBox.information(
                    self.api.main_window, 'Constraint Cleaner',
                    'All redundant constraints are removed.')))
        self.worker.signal_fail.connect(lambda: (
            self.thread.quit(), progress_dialog.close(),
            QMessageBox.critical(
                self.api.main_window, 'Constraint Cleaner',
                'Failed to add a constraint.\nSee console for more information.'
            )))

        self.thread.started.connect(self.worker.process)
        self.thread.start()
Exemple #22
0
    def addEntry(self, name=None, address=None):
        """ Add an entry to the addressbook. """
        if name is None and address is None:
            addDialog = AddDialogWidget()

            if addDialog.exec_():
                name = addDialog.name
                address = addDialog.address

        address = {"name": name, "address": address}
        addresses = self.tableModel.addresses[:]

        # The QT docs for this example state that what we're doing here
        # is checking if the entered name already exists. What they
        # (and we here) are actually doing is checking if the whole
        # name/address pair exists already - ok for the purposes of this
        # example, but obviously not how a real addressbook application
        # should behave.
        try:
            addresses.remove(address)
            QMessageBox.information(self, "Duplicate Name",
                                    "The name \"%s\" already exists." % name)
        except ValueError:
            # The address didn't already exist, so let's add it to the model.

            # Step 1: create the  row
            self.tableModel.insertRows(0)

            # Step 2: get the index of the newly created row and use it.
            # to set the name
            ix = self.tableModel.index(0, 0, QModelIndex())
            self.tableModel.setData(ix, address["name"], Qt.EditRole)

            # Step 3: lather, rinse, repeat for the address.
            ix = self.tableModel.index(0, 1, QModelIndex())
            self.tableModel.setData(ix, address["address"], Qt.EditRole)

            # Remove the newAddressTab, as we now have at least one
            # address in the model.
            self.removeTab(self.indexOf(self.newAddressTab))

            # The screenshot for the QT example shows nicely formatted
            # multiline cells, but the actual application doesn't behave
            # quite so nicely, at least on Ubuntu. Here we resize the newly
            # created row so that multiline addresses look reasonable.
            tableView = self.currentWidget()
            tableView.resizeRowToContents(ix.row())
Exemple #23
0
    def do_it(self):
        if not self.check_input():
            return
        pd = QProgressDialog(self)
        pd.setMinimumDuration(10)
        pd.setAutoClose(True)
        pd.setAutoReset(False)
        pd.setLabelText('正在处理')
        pd.setCancelButtonText('取消')
        pd.setRange(0, len(self.file_list))
        pd.setValue(0)
        pd.setWindowModality(Qt.WindowModal)
        pd.show()

        try:
            for index, file_path in enumerate(self.file_list):

                if pd.wasCanceled():
                    break

                pd.setLabelText('正在处理 {}/{}'.format(str(index + 1),
                                                    len(self.file_list)))

                if os.path.exists(file_path):

                    p, n = os.path.split(file_path)
                    file_content = read_file(file_path)

                    if self.before_process(file_content):
                        encrypt_content = self.processor(
                            self.key.key, file_content)
                        output_file = os.path.join(self.output_dir_path, n)
                        write_file(output_file, encrypt_content)

                pd.setValue(pd.value() + 1)

            if not pd.wasCanceled():
                QMessageBox.information(pd, '处理完成', self.success_msg)
            else:
                QMessageBox.information(pd, '已经终止', '用户取消')
        except Exception as e:
            pass
            QMessageBox.critical(pd, '处理失败', str(e))
        pd.close()
        self.close()
Exemple #24
0
    def base64_files_encoding(self):
        print(self.FileOpen[0])
        file = open(self.FileOpen[0], 'r')
        decoding = file.read()

        im = Image.open(BytesIO(base64.b64decode(decoding)))
        im.save('C:/Users/'+user_name+'/Desktop/b64decode_images.png', 'PNG')
        guidance = QMessageBox.information(self, 'base64', '바탕화면에 b64decode_images.png 이 생성했습니다', QMessageBox.Ok)
        print("완료")
Exemple #25
0
    def disconnect_kv(self) -> None:
        """keyenceデバイスとの接続を切る"""

        buttons = QMessageBox.Yes | QMessageBox.No
        result = QMessageBox.information(self.view, 'Information', '切断しますか',
                                         buttons, QMessageBox.No)
        if result == QMessageBox.Yes:
            self.model.client.disconnect()
            self.switch_slot(self.ui.connect_action.triggered, self.connect_kv)
            self.view.disconnected()
Exemple #26
0
    def open_new_patient(self):
        """
        Function to handle the Open patient button being clicked
        """
        confirmation_dialog = QMessageBox.information(
            self, 'Open new patient?',
            'Opening a new patient will close the currently opened patient. '
            'Would you like to continue?', QMessageBox.Yes | QMessageBox.No)

        if confirmation_dialog == QMessageBox.Yes:
            self.open_patient_window.emit()
Exemple #27
0
    def base64_files_encoding(self):
        
        with open(self.FileOpen[0], 'rb') as imagefile:
            byteform = base64.b64encode(imagefile.read())

        f = open('C:/Users/'+user_name+'/Desktop/base64encoding.bin', 'wb')
        f.write(byteform)
        f.close()

        guidance = QMessageBox.information(self, 'base64', '바탕화면에 base64encoding.bin 파일이 생성했습니다', QMessageBox.Ok)
        print('완료')
 def confirm_button_onClicked(self):
     confirmation_dialog = QMessageBox.information(
         self, 'Delete ROI(s)?',
         'Region(s) of Interest in the To Delete table will be deleted. '
         'Would you like to continue?', QMessageBox.Yes | QMessageBox.No)
     if confirmation_dialog == QMessageBox.Yes:
         progress_window = DeleteROIProgressWindow(
             self, QtCore.Qt.WindowTitleHint)
         progress_window.signal_roi_deleted.connect(self.on_rois_deleted)
         progress_window.start_deleting(self.dataset_rtss,
                                        self.regions_of_interest_to_delete)
         progress_window.show()
Exemple #29
0
    def add_key_action(self):
        file_name, _ = QFileDialog.getOpenFileName(self, '选择密钥文件')

        if len(file_name.strip()) == 0:
            return

        password = None
        if Key.need_password(file_name):
            ok_pressed = True
            while ok_pressed:
                password, ok_pressed = QInputDialog.getText(
                    self, "需要密码", "输入密码:", QLineEdit.Password, "")
                if ok_pressed:
                    illegal, msg = Key.is_password_illegal(password)
                    if illegal:
                        QMessageBox.information(self, '错误', msg)
                        continue
                    break
                else:
                    return

        key = Key()
        try:
            key.load(file_name, password)
        except Exception as e:
            QMessageBox.critical(self, '错误', '不是有效的密钥文件<br/>' + str(e))
            return

        row_len = self.list_model.rowCount()
        for i in range(0, row_len):
            item: QStandardItem = self.list_model.item(i, 0)
            k: Key = item.data()
            if k.id == key.id:
                QMessageBox.information(self, '信息', '相同的密钥已经加载')
                return

        item = self.make_item(key)
        self._add_key(item, key)

        return
Exemple #30
0
    def slot_multiple_pointers_discovered(self, controller: HexViewerController, base_address: int, count: int) -> None:
        print(base_address)
        for i in range(0, count):
            address = base_address + i * 4
            points_to = controller.get_as_pointer(address)

            if points_to < ROM_OFFSET or points_to > ROM_OFFSET + ROM_SIZE:
                        QMessageBox.critical(self.parent(), 'Add pointer and constraints', f'Address {hex(points_to)} is not inside the rom.')
                        return
            pointer = Pointer(controller.rom_variant, controller.address_resolver.to_local(
                address), points_to, 5, settings.get_username())
            
            try:
                if self.add_pointers_and_constraints(pointer):
                    if i == count -1:
                        QMessageBox.information(self.parent(), 'Add constraints', 'A constraint that changes the relations was added.')
                    elif QMessageBox.question(self.parent(), 'Add pointer and constraints', 'A constraint that changes the relations was added.\nDo you want to continue adding the rest of the pointers?') != QMessageBox.Yes:
                        return

            except InvalidConstraintError as e:
                QMessageBox.critical(self.parent(), 'Add constraints', 'Invalid Constraint')
                return