Пример #1
0
    def deleteEntryini(self):
        for k in self.inicontents:
            if k in self.selected["ini"]:
                errbox = QMessageBox()
                errbox.setText("Section headers cannot be deleted.")
                errbox.exec()
                return
        confirm = QMessageBox()
        msg = "The following keys will be deleted:\n"
        for key in self.selected["ini"]:
            msg += key[0] + "\n"
        msg += "Are you sure?"
        confirm.setText(msg)
        confirm.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        if confirm.exec() != QMessageBox.Yes:
            return

        for item in self.selected["ini"]:
            for section in reversed(self.indices):
                if (item[1] + 1) > self.indices[section]:
                    self.inicontents[section].pop(item[0])
                    break

        msgbox = QMessageBox()
        msgbox.setText(
            f"Successfully removed {len(self.selected['ini'])} entries!")
        msgbox.exec()

        self.updateTables()
Пример #2
0
 def submitAll(self):
     result = super().submitAll()
     if result:
         self._deleted_rows = []
     else:
         error_code = self.lastError().nativeErrorCode()
         if error_code == '1299':
             prefix = "NOT NULL constraint failed: " + self.tableName(
             ) + "."
             if self.lastError().databaseText().startswith(prefix):
                 field_name = self.lastError().databaseText()[len(prefix):]
                 header_title = self.tableName() + ":" + self.headerData(
                     self.fieldIndex(field_name))
                 QMessageBox().warning(
                     self._view, self.tr("Data are incomplete"),
                     self.tr("Column has no valid value: " + header_title),
                     QMessageBox.Ok)
             else:
                 logging.fatal(
                     self.tr("Submit failed: ") +
                     decodeError(self.lastError().text()))
         elif error_code == '1811':  # Foreign key constraint failed
             QMessageBox().warning(
                 self._view, self.tr("Data are in use"),
                 self.
                 tr("Data are referenced in another place and can't be modified"
                    ), QMessageBox.Ok)
         else:
             logging.fatal(
                 self.tr("Submit failed: ") +
                 decodeError(self.lastError().text()))
     return result
Пример #3
0
 def onEditjson(self, item):
     if item.text() in chain.from_iterable(self.repos) or self.isColour(
             item.text()):
         return  # no change
     else:
         if not item.text():
             errbox = QMessageBox()
             errbox.setText("Path cannot be empty")
             errbox.exec()
             item.setText(self.repos[item.row()][0])
             return
         try:
             git.Repo(item.text())
         except git.exc.NoSuchPathError:
             errbox = QMessageBox()
             errbox.setText("Path not found")
             errbox.exec()
             item.setText(self.repos[item.row()][0])
             return
         except git.exc.InvalidGitRepositoryError:
             errbox = QMessageBox()
             errbox.setText("Path does not contain a valid git repository")
             errbox.exec()
             item.setText(self.repos[item.row()][0])
             return
         else:
             self.repos[item.row()][0] = item.text()
Пример #4
0
 def accepting(self):
     """
     Process the event when the user clicks "ok" in the dialog box.
     """
     # Make sure the patient weight is a number
     if self.patient_weight_entry.text() != '':
         try:
             num = float(self.patient_weight_entry.text())
             if num < 0:
                 raise ValueError
             self.accept()
         except ValueError:
             button_reply = \
                 QMessageBox(QMessageBox.Icon.Warning,
                             "Invalid Patient Weight",
                             "Please enter a valid number.",
                             QMessageBox.StandardButton.Ok, self)
             button_reply.button(
                 QMessageBox.StandardButton.Ok).setStyleSheet(
                     self.stylesheet)
             button_reply.exec_()
     # Make sure the patient weight is not blank
     else:
         button_reply = \
             QMessageBox(QMessageBox.Icon.Warning,
                         "Invalid Patient Weight",
                         "Please enter a valid number.",
                         QMessageBox.StandardButton.Ok, self)
         button_reply.button(QMessageBox.StandardButton.Ok).setStyleSheet(
             self.stylesheet)
         button_reply.exec_()
Пример #5
0
    def addRepoHandler(self):
        path = self.ui.path.text()
        for r in enumerate(self.repos):
            if r[1][0] == path:
                errbox = QMessageBox()
                errbox.setText(f"{path} is already listed in {self.json_path}")
                errbox.exec()
                return
        colour = ColorPicker().getColor()
        hexcolour = '%02x%02x%02x' % (
            int(colour[0]),  # this is actually so dumb
            int(colour[1]) if int(colour[0]) != 255 or not int(colour[1]) else
            int(colour[1]) + 1,
            int(colour[2]) if int(colour[0]) != 255 or not int(colour[2]) else
            int(colour[2]) + 1)
        if self.ui.checkBox.isChecked():
            if not re.match(self.urlregexp, self.ui.remote.text()):
                errbox = QMessageBox()
                errbox.setText("Invalid URL")
                errbox.exec()
                return
            self.addNewRepo(path, self.ui.remote.text(), hexcolour, self.repos)
        else:
            self.addRepoFromExisting(path, hexcolour, self.repos)

        self.updateTables()
Пример #6
0
def data_filter(master, df, headerdict):
    '''Recebe um dataframe de strings e filtra as colunas.'''

    # Filtra no primeiro dataframe as colunas correspondentes a: datas, precipitacao observada/registrada.
    # se estas colunas nao existirem, provoca um erro e avisa ao usuario.

    # filtra coluna correspondente a precipitação observada.
    try:
        observados = df[df.columns[headerdict["Prec. Observada"]]].str.replace(
            ',', '.')

    except:
        x = QMessageBox(QMessageBox.Warning,
                        "Erro de Seleçao",
                        'A coluna "Prec. Observada" não foi selecionada.',
                        parent=master)
        x.addButton(QMessageBox.Ok)
        x.setInformativeText(
            "Por favor, verifique a tabela e selecione a coluna correta.")
        x.exec()
        raise KeyError

    # filtra a(s) coluna(s) correspondente(s) a data/hora.
    if "Data" in headerdict.keys():
        try:
            datetime = df[df.columns[headerdict["Data"]]] + ' ' + df[
                df.columns[headerdict["Hora"]]]

        except:
            x = QMessageBox(
                QMessageBox.Warning,
                "Erro de Seleçao",
                'A coluna correspondente a "Hora" não foi selecionada',
                parent=master)
            x.addButton(QMessageBox.Ok)
            x.setInformativeText(
                "Por favor, verifique a tabela e selecione a coluna correta.")
            x.exec()
            raise KeyError

    elif "Data & Hora" in headerdict.keys():
        datetime = df[df.columns[headerdict["Data & Hora"]]]

    else:
        x = QMessageBox(
            QMessageBox.Warning,
            "Erro de Seleçao",
            'A coluna correspondente a "Data" ou "Hora" não foi selecionada',
            parent=master)
        x.addButton(QMessageBox.Ok)
        x.setInformativeText(
            "Por favor, verifique a tabela e selecione a coluna correta.")
        x.exec()
        raise KeyError

    new_df = pd.DataFrame(observados.to_numpy(),
                          datetime.to_numpy(),
                          columns=["Observado"])

    return new_df
Пример #7
0
    def deleteEntry(self):
        confirm = QMessageBox()
        msg = "The following entries will be deleted:\n"
        for path in self.selected["json"]:
            msg += path + "\n"
        msg += "Are you sure?"
        confirm.setText(msg)
        confirm.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        if confirm.exec() != QMessageBox.Yes:
            return

        delfiles = False
        confirm = QMessageBox()
        confirm.setText(
            f"Would you like to delete the folder{'s' if len(self.selected['json']) > 1 else ''} on disk as well?"
        )
        confirm.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        if confirm.exec() == QMessageBox.Yes:
            delfiles = True

        todel = []
        for repo in enumerate(self.repos):
            if repo[1][0] in self.selected['json']:
                todel.append(repo[0])
        todel.reverse()
        for i in todel:
            self.repos.pop(i)
            if delfiles:
                os.rmdir(self.repos[i][0])

        msgbox = QMessageBox()
        msgbox.setText(f"Successfully removed {len(todel)} entries!")
        msgbox.exec()

        self.updateTables()
Пример #8
0
    def onEditini(self, item):
        if "self.updateTables" in inspect.stack(
        )[2].code_context[0]:  # come at me
            return
        elif item.column() == 0:
            secs = 3  # SEX?!?!?!?!?!?!!?!
            for section in reversed(self.indices):
                if (item.row() + 1) > self.indices[
                        section]:  # first occurrence of this must always break to avoid repeating itself
                    if item.text() in self.inicontents[section]:
                        pass  # no change
                    else:
                        # pad: no. of section headers + no. of entries in previous sections
                        pad = secs + (len(self.inicontents[list(self.indices)[0]]) if secs > 1 else 0) + \
                              (len(self.inicontents[list(self.indices)[1]]) if secs > 2 else 0)
                        # list is so they can be indexed by num
                        originalKey = list(self.inicontents[section].keys()) \
                            [item.row() - pad]
                        if not item.text():
                            errbox = QMessageBox()
                            errbox.setText("Key cannot be empty")
                            errbox.exec()
                            item.setText(originalKey)
                            return
                        self.inicontents[section][
                            item.text()] = self.ui.initable.item(
                                item.row(), 1).text()
                        self.inicontents[section].pop(originalKey)
                        # this action changes the order of the dict in most cases, so without updating the table
                        # the actual position of items can desync which leads to very buggy behaviour
                        self.updateTables()
                    break
                secs -= 1

        else:  # item is a value, which should in theory require less fuckery
            secs = 3
            for section in reversed(self.indices):
                if (item.row() + 1) > self.indices[section]:
                    key = self.ui.initable.item(item.row(), 0).text()
                    originalVal = self.inicontents[section][key]
                    if item.text() == originalVal:
                        pass
                    else:
                        if not item.text():
                            errbox = QMessageBox()
                            errbox.setText("Value cannot be empty")
                            errbox.exec()
                            item.setText(originalVal)
                            return
                        # TODO store types of keys and enforce typechecking
                        self.inicontents[section][key] = item.text()
                        self.updateTables()
                    break
                secs -= 1
Пример #9
0
    def addNewRepo(path, remote, hexcolour, repos, quiet=False):
        if os.path.exists(path):
            if os.path.isfile(path) or os.listdir(path):
                if quiet:
                    print("Path must be an empty directory")
                else:
                    errbox = QMessageBox()
                    errbox.setText("Path must be an empty directory")
                    errbox.exec()
                return 1
        else:
            if os.path.exists(path[:path.rindex('/')]):
                if quiet:
                    print(
                        "Specified folder does not exist but is in a valid directory."
                    )
                    if input(
                            "Would you like to create the folder and clone the repository there? [Y/N]: "
                    ).lower().strip() != 'y':
                        print("Exiting.")
                        return 1
                    os.mkdir(path)
                else:
                    errbox = QMessageBox()
                    errbox.setText(
                        "Specified folder does not exist but is in a valid directory.\n"
                        "Would you like to create the folder and clone the repository there?"
                    )
                    errbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
                    errbox.setDefaultButton(QMessageBox.Yes)
                    if errbox.exec() == QMessageBox.No:
                        return 1
                    os.mkdir(path)
            else:
                if quiet:
                    print("Path not found")
                else:
                    errbox = QMessageBox()
                    errbox.setText("Path not found")
                    errbox.exec()
                return 1

        os.system(f"git clone '{remote}' '{path}' -v"
                  )  # forget it im not dealing with gitpythons bs
        repos.append([path, int(hexcolour, 16)])

        if quiet:
            print(f"Repository successfully cloned to {path}")
        else:
            msgbox = QMessageBox()
            msgbox.setText(f"Repository successfully cloned to {path}")
            msgbox.exec()
        return
 def on_addText_clicked(self):
     #TODO check if valid sequence 
     if len(self.set.resources[self.active_idx].data) < 16:
         text = QInputDialog.getText(title='Enter Sequence As Text', label='Use ^ for on and _ for off')
         for character in text:
             if character not in ['^','_']:
                 QMessageBox(title='Entry problem', text='Please only use ^ and _ in your entry')
                 return
         self.set.resources[self.active_idx].add_data(text)
         self.update_resource_ui()
         self.unsaved_changes = True
     else:
         QMessageBox(title='Pattern full', text='Click a sequence to remove it.')
Пример #11
0
    def addRepoFromExisting(path, hexcolour, repos, quiet=False):
        try:
            repo = git.Repo(path)
        except git.exc.NoSuchPathError:
            if quiet:
                print("Path not found")
            else:
                errbox = QMessageBox()
                errbox.setText("Path not found")
                errbox.exec()  # look we've got error messages and everything
            return 1
        except git.exc.InvalidGitRepositoryError:  # means it *has* to be good code
            if quiet:
                print("Path does not contain a valid git repository")
            else:
                errbox = QMessageBox()
                errbox.setText("Path does not contain a valid git repository")
                errbox.exec()
            return 1
        if "origin" in repo.remotes:
            if not repo.remotes["origin"].url:
                if quiet:
                    print(
                        "Missing origin URL, how on earth did you manage that?"
                    )
                else:
                    errbox = QMessageBox()
                    errbox.setText(
                        "Missing origin URL, how on earth did you manage that?"
                    )
                    errbox.exec(
                    )  # if anyone manages to get this error i will be very surprised
                return 1
        else:
            if quiet:
                print("Repo has no origin")
            else:
                errbox = QMessageBox()
                errbox.setText("Repo has no origin")
                errbox.exec()
            return 1

        repos.append([path, int(hexcolour, 16)])

        if quiet:
            print(f"Successfully added repository at {path}!")
        else:
            msgbox = QMessageBox()
            msgbox.setText(f"Successfully added repository at {path}!")
            msgbox.exec()
        return
Пример #12
0
def read_file(master, nrows=None, header=None):
    extension = master.fileformat
    pathname = master.path.text()

    try:
        if extension == ".xlsx":
            data_df = pd.read_excel(pathname,
                                    header=header,
                                    engine="openpyxl",
                                    nrows=nrows,
                                    dtype='str')

        #elif self.filefomart == ".ods":
        #data_df = utils.open_odf(self, 14).to_numpy()
        else:
            data_df = pd.read_csv(pathname,
                                  sep=master.separador,
                                  nrows=nrows,
                                  dtype='str',
                                  header=header,
                                  keep_default_na=False)

    except PermissionError as Err:
        x = QMessageBox(QMessageBox.Critical,
                        "Erro de Acesso",
                        "Não foi possível salvar seu arquivo.",
                        buttons=QMessageBox.Ok,
                        parent=master)
        x.setInformativeText(
            "O arquivo que voce está tentando sobrescrever já está aberto em outro programa."
        )
        x.setDetailedText(str(Err))
        x.exec()
        raise PermissionError

    except pd.errors.ParserError as Err:
        x = QMessageBox(
            QMessageBox.Critical,
            "Erro de Acesso",
            "Não foi possível ler o arquivo com o delimitador especificado.",
            buttons=QMessageBox.Ok,
            parent=master)
        x.setInformativeText(
            "Por favor, tente utilizar um outro tipo de delimitador para os seus dados."
        )
        x.setDetailedText(str(Err))
        x.exec()
        raise pd.errors.ParserError

    return data_df
Пример #13
0
 def update_db_schema(self, db_path) -> JalDBError:
     if QMessageBox().warning(
             None,
             QApplication.translate('DB', "Database format is outdated"),
             QApplication.translate(
                 'DB',
                 "Do you agree to upgrade your data to newer format?"),
             QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
         return JalDBError(JalDBError.OutdatedDbSchema)
     db = db_connection()
     version = readSQL(
         "SELECT value FROM settings WHERE name='SchemaVersion'")
     try:
         schema_version = int(version)
     except ValueError:
         return JalDBError(JalDBError.DbInitFailure)
     for step in range(schema_version, Setup.TARGET_SCHEMA):
         delta_file = db_path + Setup.UPDATES_PATH + os.sep + Setup.UPDATE_PREFIX + f"{step + 1}.sql"
         logging.info(
             f"Applying delta schema {step}->{step + 1} from {delta_file}")
         error = self.run_sql_script(delta_file)
         if error.code != JalDBError.NoError:
             db.close()
             return error
     return JalDBError(JalDBError.NoError)
Пример #14
0
    def closeEvent(self, event):
        self.account_id = self.AccountWidget.selected_id
        self.store_account = self.ReuseAccount.isChecked()
        if self.AccountWidget.selected_id == 0:
            QMessageBox().warning(None, self.tr("No selection"), self.tr("Invalid account selected"), QMessageBox.Ok)
            event.ignore()
            return

        if self.AccountWidget.selected_id == self.current_account:
            QMessageBox().warning(None, self.tr("No selection"), self.tr("Please select different account"),
                                  QMessageBox.Ok)
            event.ignore()
            return

        self.setResult(QDialog.Accepted)
        event.accept()
Пример #15
0
def main():
    sys.excepthook = exception_logger
    os.environ['QT_MAC_WANTS_LAYER'] = '1'    # Workaround for https://bugreports.qt.io/browse/QTBUG-87014

    error = init_and_check_db(get_app_path())

    if error.code == LedgerInitError.EmptyDbInitialized:  # If DB was just created from SQL - initialize it again
        error = init_and_check_db(get_app_path())

    app = QApplication([])
    language = JalDB().get_language_code(JalSettings().getValue('Language', default=1))
    translator = QTranslator(app)
    language_file = get_app_path() + Setup.LANG_PATH + os.sep + language + '.qm'
    translator.load(language_file)
    app.installTranslator(translator)

    if error.code == LedgerInitError.OutdatedDbSchema:
        error = update_db_schema(get_app_path())
        if error.code == LedgerInitError.DbInitSuccess:
            error = init_and_check_db(get_app_path())

    if error.code != LedgerInitError.DbInitSuccess:
        window = QMessageBox()
        window.setAttribute(Qt.WA_DeleteOnClose)
        window.setWindowTitle("JAL: Start-up aborted")
        window.setIcon(QMessageBox.Critical)
        window.setText(error.message)
        window.setInformativeText(error.details)
    else:
        window = MainWindow(language)
    window.show()

    app.exec()
    app.removeTranslator(translator)
Пример #16
0
 def showDialog(self, text: str, title: str, buttons, callback):
     dialog = QMessageBox(self.window)
     dialog.setWindowTitle(title)
     dialog.setText(text)
     dialog.setStandardButtons(buttons)
     dialog.buttonClicked.connect(callback)
     dialog.exec_()
Пример #17
0
    def guess(self):
        if self.ui.txt_input.text().isnumeric():

            if int(self.ui.txt_input.text()) == self.number:
                self.ui.lbl_comment.setText('✨🎁🧡تو بردی 😍🌺🎉')

            elif int(self.ui.txt_input.text()) > self.number:
                self.score -= 1
                if self.score == 0:
                    self.ui.lbl_comment.setText('نتونستی تشخیص بدی😒🤦‍♀️')
                    self.new_game()
                else:
                    self.ui.lbl_comment.setText('برو پایین تر')
            else:
                self.score -= 1
                if self.score == 0:
                    self.ui.lbl_comment.setText('نتونستی تشخیص بدی😒🤦‍♀️')
                    self.new_game()
                else:
                    self.ui.lbl_comment.setText('برو بالا تر')
            self.ui.lbl_joon.setText(str(self.score))
        else:
            msg_box = QMessageBox()
            msg_box.setText("باهوش جان، مقدار عددی وارد کن")
            msg_box.exec_()
Пример #18
0
    def handleClicked(self):
        if not self.ui.locationInput.text():
            msgBox = QMessageBox()
            msgBox.setIcon(QMessageBox.Warning)
            msgBox.setText("지역을 설정해주세요.")

        else:
            filter = json.load(open("mod.json"))["filter"]
            filter_list = []
            for c in self.checkboxes:
                if c.isChecked():
                    filter_list.append(filter[c.text()])
            filter = ":".join(filter_list)
            #thread
            self.thread = QThread()
            self.worker = Worker(self.ui.locationInput.text(), filter)
            self.worker.moveToThread(self.thread)
            self.thread.started.connect(self.worker.run)
            self.worker.finished.connect(self.thread.quit)
            self.worker.finished.connect(self.worker.deleteLater)
            self.thread.finished.connect(self.thread.deleteLater)
            self.worker.progress.connect(self.ui.progressBar.setValue)
            self.thread.start()
            self.ui.startButton.setEnabled(False)
            self.thread.finished.connect(self.handleFinished)
Пример #19
0
    def show_about(self):
        """Show About dialog."""
        from . import __version__

        msg_box = QMessageBox(self)
        text = (
            f"<img src='{image_path('mnelab_logo.png')}'><p>MNELAB {__version__}</p>"
        )
        msg_box.setText(text)

        mnelab_url = "github.com/cbrnr/mnelab"
        mne_url = "github.com/mne-tools/mne-python"

        pkgs = []
        for key, value in have.items():
            if value:
                pkgs.append(f"{key}&nbsp;({value})")
            else:
                pkgs.append(f"{key}&nbsp;(not installed)")
        version = ".".join(str(k) for k in version_info[:3])
        text = (
            f"<nobr><p>This program uses Python {version} and the following packages:"
            f"</p></nobr><p>{', '.join(pkgs)}</p>"
            f"<nobr><p>MNELAB repository: <a href=https://{mnelab_url}>{mnelab_url}</a>"
            f"</p></nobr><nobr><p>MNE repository: "
            f"<a href=https://{mne_url}>{mne_url}</a></p></nobr>"
            f"<p>Licensed under the BSD 3-clause license.</p>"
            f"<p>Copyright 2017&ndash;2021 by Clemens Brunner.</p>")
        msg_box.setInformativeText(text)
        msg_box.exec()
 def on_addEuclidean_clicked(self):
     if (len(self.set.resources[self.active_idx].data) < 16):
         self.set.resources[self.active_idx].add_data([self.steps.value(), self.length.value()])
         self.update_resource_ui()
         self.unsaved_changes = True
     else:
         QMessageBox(title='Pattern full', text='Click a sequence to remove it.')
Пример #21
0
def save_file(master, file, delimiter=';'):
    pathname = master.folder.text()
    extension = pathname[pathname.index('.'):]

    try:
        if extension == ".xlsx":
            with pd.ExcelWriter(pathname) as writer:
                file.to_excel(writer,
                              "Dados Brutos",
                              engine='openpyxl',
                              na_rep="NaN",
                              float_format="%.2f")

        else:
            decimal = ',' if master.separador == '.' else '.'
            with open(pathname, 'wb') as writer:
                file.to_csv(writer,
                            sep=master.separador,
                            na_rep="NaN",
                            float_format="%.2f",
                            decimal=decimal)

    except PermissionError as Err:
        x = QMessageBox(QMessageBox.Critical,
                        "Erro de Acesso",
                        "Não foi possível salvar seu arquivo.",
                        buttons=QMessageBox.Ok,
                        parent=master)
        x.setInformativeText(
            "O arquivo que voce está tentando sobrescrever já está aberto em outro programa."
        )
        x.setDetailedText(str(Err))
        x.exec()
        raise PermissionError
Пример #22
0
 def aboutButton(self):
     aboutMessageBox = QMessageBox(self)
     aboutMessageBox.setWindowModality(Qt.NonModal)
     aboutMessageBox.setWindowTitle("About this program")
     aboutMessageBox.setText("<h5>About content</h5>")
     aboutMessageBox.setIcon(QMessageBox.Information)
     aboutMessageBox.open()
Пример #23
0
 def message_box(self, message: str, buttons: int = 1) -> int:
     '''
     Message box with "Yes/No" or "OK" buttons. Defaults to "OK".\n
         Parameters:\n
             message (str): Message shown inside the message box.
             buttons (int): Amount of buttons, 1 - "OK" button, 2 - "Yes/No" buttons.
         Returns:\n
             choice (int): ID of the clicked button.
     '''
     pixmap = QPixmap(resource_path('icon.ico')).scaledToWidth(
         35, Qt.SmoothTransformation)
     msg_box = QMessageBox()
     msg_box.setFont(ui.font)
     msg_box.setText(message)
     if buttons == 2:
         msg_yes = msg_box.addButton(QMessageBox.Yes)
         msg_no = msg_box.addButton(QMessageBox.No)
         msg_yes.setText(self.dialog_yes)
         msg_no.setText(self.dialog_no)
         msg_yes.setProperty('class', 'button_yes')
         msg_no.setProperty('class', 'button_no')
     msg_box.setWindowFlags(Qt.Dialog | Qt.CustomizeWindowHint)
     msg_box.setIconPixmap(pixmap)
     with open(resource_path('style.css'), 'r') as file:
         msg_box.setStyleSheet(file.read())
     msg_box.move(ui.frameGeometry().center() -
                  QRect(QPoint(), msg_box.sizeHint()).center())
     choice = msg_box.exec_()
     return choice
Пример #24
0
    def checkAndSaveChanges(self):
        old, oldini = {}, {}
        if open(self.json_path).read() != '':
            old = json.load(open(self.json_path))
        else:
            old = {"repos": [], "sysupdates": []}

        if open(self.ini_path).read() != '':
            oldini = configparser.ConfigParser().read(self.ini_path)
        else:
            oldini = {}

        if (old["repos"] == self.repos and old["sysupdates"] == self.sysupdates) or \
                (oldini == self.inicontents):
            pass
        else:
            confirm = QMessageBox()
            confirm.setText(
                "You have unsaved changes. Would you like to save them now?")
            confirm.setStandardButtons(QMessageBox.Yes | QMessageBox.No
                                       | QMessageBox.Cancel)
            ret = confirm.exec()
            if ret == QMessageBox.Cancel:
                return 1
            elif ret == QMessageBox.Yes:
                self.apply()
Пример #25
0
    def show_update_info(info: dict):
        print(info)

        html_url = info.get('html_url', '')
        content = [
            f'New v{info.get("version")} (Now v{VERSION})',
            info.get('name', ''),
            html_url,
        ]
        title = 'Update available, download now?'

        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)

        msg.setText(title)
        msg.setInformativeText('\n\n'.join(content))
        msg.setWindowTitle(title)
        msg.setDetailedText(info.get('desc', ''))
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)

        btn_ret = msg.exec_()

        if btn_ret == QMessageBox.Yes:
            print('Yes clicked.')
            open_url(html_url)
        elif btn_ret == QMessageBox.Ok:
            print('Ok clicked.')
        elif btn_ret == QMessageBox.No:
            print('No clicked.')
        elif btn_ret == QMessageBox.Cancel:
            print('Cancel')
Пример #26
0
    def updateMainRNG6(self):
        if self.mainRNG:
            values = self.manager.updateFrameCount()

            # Handle infinite loop
            if values is None:
                self.toggleMainRNG6()

                message = QMessageBox()
                message.setText("Exiting an infinite loop. Make sure no patches are installed and the game is on the latest version")
                message.exec_()

                return

            difference, initialSeed, currentSeed, frameCount, save, tiny3, tiny2, tiny1, tiny0 = values
            
            # Check to see if frame changed at all
            if difference != 0:
                self.lineEditInitialSeed6.setText(hexify(initialSeed))
                self.lineEditCurrentSeed6.setText(hexify(currentSeed))
                self.lineEditFrame6.setText(str(frameCount))
                self.lineEditSaveVariable.setText(hexify(save))
                self.lineEditTiny3.setText(hexify(tiny3))
                self.lineEditTiny2.setText(hexify(tiny2))
                self.lineEditTiny1.setText(hexify(tiny1))
                self.lineEditTiny0.setText(hexify(tiny0))
Пример #27
0
 def info(self):
     self.popup = QMessageBox(QMessageBox.Information, "Sobre",
                              "Informações")
     self.popup.setInformativeText("""Clientes \nVersão 0.5
     \nFeito com S2 por Zero \nMIT License""")
     self.popup.addButton(QMessageBox.Ok)
     self.popup.exec()
Пример #28
0
def generate(size, dir, path, outputName, params):
    currentTime = datetime.datetime.now()
    if len(outputName) <= 0:
        batchName = currentTime.strftime("%b-%d-%Y-%H%M%p%s")
    else:
        batchName = util.checkPath(dir, outputName)

    currentDirectory = os.getcwd()
    childDirectory = dir + "/" + batchName
    childDirectory = os.mkdir(childDirectory)
    record = [['email', 'gender', 'school', 'date']]
    ID = 1
    progressBarStep = int(size / 10)
    progress = QProgressDialog("Generating Resumes", "Close", 0, 100)
    progress.setWindowModality(QtCore.Qt.WindowModal)
    progress.setAutoClose(True)
    progress.show()

    while ID <= size:
        pair = getPair(path, params)
        record.append(makeDoc(pair, 'control', ID, batchName, params))
        record.append(makeDoc(pair, 'test', ID, batchName, params))
        ID += 1
        progress.setValue(ID)

    message = QMessageBox()
    message.setText("Resume generation complete.")
    message.exec()
    del pair
    return record
Пример #29
0
    def _handle_file_open(self):
        if self.config_has_changes:
            msg = QMessageBox(
                QMessageBox.Warning,
                "Are you sure?",
                ("You have unsaved changes to your current config. "
                 "If you continue all unsaved changes will be lost."),
                buttons=QMessageBox.Open | QMessageBox.Cancel,
            )

            if msg.exec_() == QMessageBox.Cancel:
                return

        file_path = QFileDialog.getOpenFileName(
            self,
            caption="Open a new config...",
            dir=os.getcwd(),
            filter="Config Files (*.yml *.yaml)",
        )[0]

        if file_path:
            self.reset_changes(file_path)

            # update the new log location
            self.update_log_paths(file_path)

            # setup the config tabs
            self.initialise_config_tabs(self.config)
Пример #30
0
    def callBack(self, keys):
        # do nothing if keys is empty
        if not (keys):
            return

        # check that if shortcut used before.
        if keys in self.shortcuts_list:
            self.msgBox = QMessageBox()
            self.msgBox.setText(
                QCoreApplication.translate(
                    "setting_src_ui_tr",
                    "<b><center>This shortcut has been used before!\
                    Use another one!</center></b>"))
            self.msgBox.setIcon(QMessageBox.Warning)
            reply = self.msgBox.exec_()

        # set new shortcut
        else:
            selected_row = self.shortcut_table.selectionModel().selectedRows(
            )[0].row()

            item = QTableWidgetItem(keys)

            # align center
            item.setTextAlignment(0x0004 | 0x0080)

            # insert item in shortcut_table
            self.shortcut_table.setItem(selected_row, 1, item)

            # set keys in shortcuts_list
            self.shortcuts_list[selected_row] = keys