コード例 #1
0
ファイル: main.py プロジェクト: duy-cs93/Project_1_HCMUT
    def show_invoice(self, row_amount):
        if row_amount < 1:
            print("no record")
            warning = QtWidgets.QErrorMessage(self)
            warning.setWindowTitle("No product added yet!!")
            warning.showMessage("Bạn chưa thêm vào bất cứ sản phẩm nào!!!")

        elif (self.customer_code is None) or (self.employee_code is None):
            warning2 = QtWidgets.QErrorMessage(self)
            warning2.setWindowTitle("Empty field!")
            warning2.showMessage("Bạn chưa chọn nhân viên hoặc khách hàng")

        else:
            now = datetime.datetime.now()
            bill_date = now.strftime("%Y-%m-%d")
            bill_time = now.strftime("%H:%M")
            self.bill_code = (
                now.strftime("%Y%m%d") +
                now.strftime("%H%M"))[2:]  # get the bill code from date & time
            print(self.bill_code)

            self.test = invoice.Invoice(
                self.purchased_list, self.onshift_emp, self.current_cus,
                self.bill_code, self.employee_code, bill_date, bill_time,
                self.customer_code, self.total_cost, self.discount_percentage,
                self.discount_cost)
            if self.test.exec_():
                print("ok")
                self.charge(bill_date, bill_time)
                self.erase_purchase_list(self.purchased_list.rowCount())
                self.test.close()
            else:
                print("close")
                self.test.close()
コード例 #2
0
ファイル: cnc.py プロジェクト: LiZhYun/CNC2
 def export(self):
     choose = QMessageBox(self)
     MainButton = choose.addButton("主程序", QMessageBox.ActionRole)
     SubButton = choose.addButton("子程序", QMessageBox.ActionRole)
     CancelButton = choose.addButton("取消", QMessageBox.ActionRole)
     choose.setText("主程序 | 子程序")
     choose.setWindowTitle("选择导出文件类型")
     choose.show()
     choose.exec()
     reply = choose.clickedButton()
     if reply == MainButton:
         fileName , ok= QFileDialog.getSaveFileName(self, "主程序保存",
                                                      "./",
                                                      "MPF Files (*.mpf);; TXT Files (*.txt)")
         #self.MainText.setPlainText(fileName)
         try:
             with open(fileName, 'w') as f:
                 f.write(str(self.MainText.toPlainText()))
         except FileNotFoundError as e:
             self.error_message = QtWidgets.QErrorMessage()
             self.error_message.showMessage("请选择文件或输入文件名")
     elif reply == SubButton:
         self.message = QtWidgets.QMessageBox.about(self, "提示", "请根据需要修改主程序中调用程序名和子程序文件名")
         fileName , ok= QFileDialog.getSaveFileName(self, "子程序保存",
                                                "./",
                                                "SPF Files (*.spf);; TXT Files (*.txt)")
         #self.MainText.setPlainText(fileName)
         try:
             with open(fileName, 'w') as f:
                 f.write(str(self.SubText.toPlainText()))
         except FileNotFoundError as e:
             self.error_message = QtWidgets.QErrorMessage()
             self.error_message.showMessage("请选择文件或输入文件名")
     else:
         choose.close()
コード例 #3
0
    def save(self, text, file_name=''):

        if not file_name:
            file_name = self._full_file_name_

        if self.is_opened():
            self.close()

        if os.path.isfile(file_name):
            self.open(file_name, 'w')
        else:
            self.open(file_name, 'x')

        if not self.is_opened():
            return

        if self._file_object_.writable():
            try:
                self._file_object_.write(text)
                self.close()
                self.open(file_name, 'r+')
            except OSError as error:
                error_dialog = QtWidgets.QErrorMessage()
                error_dialog.showMessage(
                    f'Error writing file {file_name}: {error.errno}!')
                return
        else:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage(f'Can not write to file {file_name}!')
            self.close()
            self.open(file_name, 'r+')
            return

        self._full_file_name_ = file_name
        self.set_modified()
コード例 #4
0
    def split_key(self):
        """
        Callback function for split button
        """
        try:
            m = self.mBox.value()
            n = self.nBox.value()
            mnemonics = self.mnemonicsTextEdit.toPlainText()
            language = self.languageComboBox.currentText()
            encoding = Encoding.BIP39
            if self.encodingComboBox1.currentIndex() == 1:
                encoding = Encoding.BASE58

            shares = split_shares(mnemonics, m, n, encoding, language=language)
            shares_text = "\n\n".join(shares)

            self.sharesTextEdit.setText(shares_text)

        except BadRequest as e:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage("Bad Request! Invalid Input!")

        except Exception:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage("Error!")
コード例 #5
0
    def saveTeam(self):
        try:
            if (self.batcount + self.bowcount + self.arcount +
                    self.wkcount) != 11:
                self.error_dialog = QtWidgets.QErrorMessage()
                self.error_dialog.setWindowTitle("Error")
                self.error_dialog.showMessage(
                    "Please select 11 players for your team")
            else:
                for i in range(11):
                    sql = "select value from stats where player='" + self.team[
                        i] + "'"
                    val = [val[0] for val in cur.execute(sql)]
                    try:
                        cur.execute(
                            "insert into teams(name, players, value) values(?,?,?);",
                            (self.team_name, self.team[i], val[0]))
                        Cricket.commit()
                    except Exception as e:
                        print(e)

        except Exception as e:
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.setWindowTitle("Error")
            self.error_dialog.showMessage("Unable to SAVE Team")
コード例 #6
0
    def add_user(self):
        for key, value in config_loader(dataset="MSC_login").items():
            if key not in constants.MSC_LOGIN_CACHE:
                constants.MSC_LOGIN_CACHE[key] = value
        auth = constants.MSC_LOGIN_CACHE.get(self.mscolab_server_url, (None, None))

        emailid = self.add_user_dialog.emailid.text()
        password = self.add_user_dialog.password.text()
        re_password = self.add_user_dialog.rePassword.text()
        username = self.add_user_dialog.username.text()
        if password == re_password:
            data = {
                "email": emailid,
                "password": password,
                "username": username
            }
            s = requests.Session()
            s.auth = (auth[0], auth[1])
            s.headers.update({'x-test': 'true'})
            url = f'{self.mscolab_server_url}/register'
            r = s.post(url, data=data)
            if r.status_code == 401:
                r = self.authenticate(data, r, url)
                if r.status_code == 201:
                    constants.MSC_LOGIN_CACHE[self.mscolab_server_url] = (username, password)
            if r.status_code == 201:
                self.error_dialog = QtWidgets.QErrorMessage()
                self.error_dialog.showMessage('You are registered, you can now log in.')
            else:
                self.error_dialog = QtWidgets.QErrorMessage()
                self.error_dialog.showMessage(r.json()["message"])
        else:
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.showMessage('Oh no, your passwords don\'t match')
コード例 #7
0
    def save(self, callback_save):
        """
        Saves displayed images
        :param callback_save: actual function that stores images
        """

        name = self.lineEditName.text()
        images = self.displayed_images

        if self.gridLayout.is_checkable():
            selected_positions = self.gridLayout.get_selected()
            images = [
                image for i, image in enumerate(images)
                if any(i == selected for selected in selected_positions)
            ]

        if self.displayed_images is None:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage('No images to save')
            error_dialog.show()
            error_dialog.exec_()
            return
        if not name:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage('Please set a component name')
            error_dialog.show()
            error_dialog.exec_()
            return

        callback_save(name, images)
        self.close()
コード例 #8
0
    def check_edits(self):
        y_o_a_count = 0
        names = []
        types = []
        for item in range(len(self.line_edits)):
            if self.line_edits[item].text() == '':
                self.error = QtWidgets.QErrorMessage()
                self.error.showMessage("Please fill all boxes")
                return
            if self.line_edits_type[item].currentText(
            ) == 'Year of Apprenticeship':
                y_o_a_count += 1
                if y_o_a_count > 1:
                    self.error = QtWidgets.QErrorMessage()
                    self.error.showMessage(
                        "Please enter only one year of apprenticeship")
                    return
            names.append(self.line_edits[item].text())
            types.append(self.line_edits_type[item].currentText())

        self.column_name = names
        self.column_name_type = types
        if 'Date' in self.column_name_type:
            QtWidgets.QMessageBox.question(
                self, 'Date Entering', "Please enter the dates \n"
                "yyyy-mm-dd (d = day, m = month, y = year)",
                QtWidgets.QMessageBox.Ok)

        self.accept()
コード例 #9
0
    def saving(self):
        if (len(self.currentteam) == 11 and len(self.teamname.text()) > 0):
            if (int(self.availablepoints.text()) >= 0):
                if (self.teamname.text() not in self.teamlist):
                    for i in self.currentteam:
                        curs.execute(
                            "INSERT INTO team('Team','player')VALUES('%s','%s')"
                            % (self.teamname.text(), i))

                        example.commit()

                    self.teamlist.append(self.teamname.text())
                    print(self.teamlist)
                else:
                    error_dialog = QtWidgets.QErrorMessage()
                    error_dialog.showMessage('Team name already exists')
                    error_dialog.exec_()

            else:
                error_dialog = QtWidgets.QErrorMessage()
                error_dialog.showMessage(
                    'You are exceeding the Available points limit!')
                error_dialog.exec_()

        else:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage(
                'team should have 11 players only or the Team Name is missing')
            error_dialog.exec_()
コード例 #10
0
 def createPbModelFun(self):
     if self.checkValidModelName():
         rootPath = "models/research/object_detection/"
         filelist = [f for f in os.listdir(rootPath+"training") if f.endswith(".index")]
         if filelist:
             checkPoint = -1
             for fileName in filelist:
                 if checkPoint < int(fileName[:-6].split('-')[1]):
                     checkPoint = int(fileName[:-6].split('-')[1])
             if os.path.exists(rootPath+'inference_graph'):
                 shutil.rmtree(rootPath+'inference_graph')
             pwd = os.popen('cd').read()[:-1].replace('\\', '/')
             cmd1 = "set PYTHONPATH="
             cmd1 += pwd + "/models/research/slim"
             cmd2 = 'python '+rootPath+'export_inference_graph.py --input_type image_tensor --pipeline_config_path '+rootPath+'training/faster_rcnn_inception_v2_pets.config --trained_checkpoint_prefix '+rootPath+'training/model.ckpt-'+str(checkPoint)+' - -output_directory '+rootPath+'inference_graph'
             MyOut = subprocess.Popen( cmd1 +" && " + cmd2,
                 stdout=subprocess.PIPE,
                 stderr=subprocess.STDOUT, shell=True)
             stdout = MyOut.communicate()[0]
             print(stdout)
             shutil.move(rootPath + "inference_graph/frozen_inference_graph.pb", "inference_graph/" + self.OPENCreateModelui.modelNameLineEdit.text()+".pb")
             self.OPENCreateModelWindow.close()
         else:
             error_dialog = QtWidgets.QErrorMessage()
             error_dialog.showMessage('Oops! Please try again, Something was wrong.')
             error_dialog.exec_()
     else:
         error_dialog = QtWidgets.QErrorMessage()
         error_dialog.showMessage('Oops! Please Enter Model Name.')
         error_dialog.exec_()
コード例 #11
0
 def evaluate_(self):
     if self.EVALUATETeamui.comboBox.currentIndex() == 0:
         error_dialog = QtWidgets.QErrorMessage()
         error_dialog.showMessage('Oops! please select match.')
         error_dialog.exec_()
     elif self.EVALUATETeamui.comboBox_2.currentIndex() == 0:
         error_dialog = QtWidgets.QErrorMessage()
         error_dialog.showMessage('Oops! please select team.')
         error_dialog.exec_()
     else:
         player_data.cur.execute(
             "SELECT * FROM teams WHERE name=?;",
             (self.EVALUATETeamui.comboBox_2.currentText(), ))
         player_ = []
         for temp in tuple(player_data.cur.fetchall()):
             player_.append(temp[1])
         score = 0
         for temp in player_:
             player_data.cur.execute(
                 "SELECT * FROM " +
                 self.EVALUATETeamui.comboBox.currentText() +
                 ''' WHERE player="''' + temp + '''";''')
             t = functions.score(player_data.cur.fetchone())
             score += t
         self.EVALUATETeamui.label_5.setText(str(score))
コード例 #12
0
    def find_images(self):
        classes_for_search = self.get_classes_for_search()

        if (len(classes_for_search) == 0):
            QtWidgets.QErrorMessage(self.__q_window_widget).showMessage(
                "No selected classes for search")
            return

        if len(self.directory_path) == 0 | str.isspace(self.directory_path):
            QtWidgets.QErrorMessage(self.__q_window_widget).showMessage(
                "Directory path can not be empty")
            return

        self.SearchingForImagesLabel.show()

        all_images = []
        for file_type in Const.IMAGE_EXTENSIONS:
            QtCore.QCoreApplication.processEvents()
            all_images.extend(
                glob.glob(self.directory_path + "/**/" + file_type,
                          recursive=True))

        found_images_listview_model = model = QtGui.QStandardItemModel(
            self.FoundImagesListView)
        found_images_number = 0
        for image_path in all_images:
            if (self.check_if_desired_class(image_path, classes_for_search)):
                self.add_image_to_result(image_path,
                                         found_images_listview_model)
                found_images_number += 1
                self.FoundImagesNumberLabel.setText(str(found_images_number))
            QtCore.QCoreApplication.processEvents()

        self.SearchingForImagesLabel.hide()
コード例 #13
0
ファイル: list.py プロジェクト: bmartins95/TagApp
    def accept(self):
        """
        Add the list to the lists table on the database. Add a empty line to the
        list in the table lines of the database. Checks if the name is used or 
        if the name is an empty string.Updates the tree interface with the new 
        list, if the project is open.
        """
        self.close()

        isProjectEmpty = not self.projectBox.currentText()
        if isProjectEmpty:
            return -1

        isNameUsed = self.checkListNameIsUsed()
        isNameEmpty = self.name.text().isspace() or not self.name.text()
        if not isNameUsed and not isNameEmpty:
            server = Server()
            listName = self.name.text()
            projectId = self.projectDict[self.projectBox.currentText()]
            server.addList(listName, projectId)

            listId = server.getListIdFromProject(listName, projectId)
            server.addLine("", "", "", "", "NULL", listId)

            self.updateTree(self.projectBox.currentText())
        elif isNameEmpty:
            error = QtWidgets.QErrorMessage()
            error.showMessage("O campo nome é obrigatório!")
            error.exec_()
        elif isNameUsed:
            error = QtWidgets.QErrorMessage()
            error.showMessage("Este nome já está sendo utilizado!")
            error.exec_()
コード例 #14
0
ファイル: var_editor.py プロジェクト: johnfhartwig/ChemBO
    def ccBrowse(self):
        fname = QtWidgets.QFileDialog.getOpenFileName(
            None, 'Open file', '~', "Numpy array files (*.npy)")[0]
        if not fname:
            return

        try:
            arr = np.load(fname, allow_pickle=True)
        except ValueError or OSError:
            err = QtWidgets.QErrorMessage(self.dialog)
            err.showMessage(
                f'Could not read {fname}. Please check that it is a Numpy array saved in the npy file format.'
            )
            return
        if len(arr.shape) != 2 or arr.shape[0] != arr.shape[1] or (
                arr != arr.T).any():
            err = QtWidgets.QErrorMessage(self.dialog)
            err.showMessage(f'{fname} must contain a 2-D symmetric array.')
            return

        self.path = fname
        if len(fname.split('/')) > 1:
            self.cc_fileLabel.setText(fname.split('/')[-1])
        else:
            self.cc_fileLabel.setText(fname.split('\\')[-1])

        for i in range(arr.shape[0]):
            item = QtWidgets.QListWidgetItem(
                f"Item {i} (double-click to edit)")
            item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable)
            self.cc_nameList.addItem(item)

        self.adj_matrix = arr
コード例 #15
0
    def addTable(self):
        if self.lineEdit.text() == 'База данных не выбрана':
            errorWin = QtWidgets.QErrorMessage(self)
            errorWin.showMessage('База данных не выбрана')
            return False
        tableName, yes = QtWidgets.QInputDialog.getText(self, 'Новая таблица', 'Название таблицы:')
        Cols, yes2 = QtWidgets.QInputDialog.getText(self, 'Колонки', 'Название колонок через запятую:')
        if yes and yes2:
            DB = self.lineEdit.text()
            # Подключение к БД
            db = sqlite3.connect(DB)
            sql = db.cursor()
            try:
                data = []
                insertCountCol = []
                countCol = len(Cols.split(','))

                for i in range(countCol):
                    data.append('NULL')
                    insertCountCol.append('?')

                insertCountCol = ','.join(insertCountCol)

                sql.execute(f"CREATE TABLE '%s' ({Cols})" % tableName)
                sql.executemany(f"INSERT INTO '%s' VALUES ({insertCountCol})" % tableName, [data])
                db.commit()
                self.listWidget.addItem(tableName)
            except:
                errorWin = QtWidgets.QErrorMessage(self)
                errorWin.showMessage('Таблица уже создана')
                return False
コード例 #16
0
    def _login(self):
        """Validates a user's login credentials."""

        username = self.usernameField.text()
        password = self.passwordField.text()

        if username and password:
            if self._userType is "User":
                if database.validateUser(username, password):
                    dashboard = DashboardScreen.getDashboardScreen(
                        QtWidgets.QMainWindow(), username)
                    SignInScreen._signInScreen.screen.destroy()
                    dashboard.screen.show()
                else:
                    self.error = QtWidgets.QErrorMessage()
                    self.error.setWindowTitle("Login Error")
                    self.error.showMessage("Incorrect User Credentials.")

            else:
                if database.validateAdmin(username, password):
                    adminScreen = BookEntry.getAddBookScreen(
                        QtWidgets.QMainWindow(), username)
                    SignInScreen._signInScreen.screen.destroy()
                    adminScreen.screen.show()

                else:
                    self.error = QtWidgets.QErrorMessage()
                    self.error.setWindowTitle("Login Error")
                    self.error.showMessage("Incorrect Admin Credentials.")

        else:
            self.error = QtWidgets.QErrorMessage()
            self.error.setWindowTitle("Input Error")
            self.error.showMessage("Please enter all fields.")
コード例 #17
0
    def add_project(self):
        path = self.add_proj_dialog.path.text()
        description = self.add_proj_dialog.description.toPlainText()
        if not path:
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.showMessage('Path can\'t be empty')
            return
        elif not description:
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.showMessage('Description can\'t be empty')
            return

        data = {
            "token": self.token,
            "path": path,
            "description": description
        }
        if self.add_proj_dialog.f_content is not None:
            data["content"] = self.add_proj_dialog.f_content
        r = requests.post(f'{self.mscolab_server_url}/create_project', data=data)
        if r.text == "True":
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.showMessage('Your project was created successfully')
            self.add_projects()
            p_id = self.get_recent_pid()
            self.conn.handle_new_room(p_id)
        else:
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.showMessage('The path already exists')
コード例 #18
0
    def _rentBook(self):
        """Carries out the rental of a book."""

        if self.bookTable.currentColumn() == 0:
            bookID = self.bookTable.currentItem().text()
            letters = string.ascii_letters + string.digits
            if database.addRental(
                    ''.join(random.choice(letters) for _ in range(10)),
                    self._currentUser, bookID):
                self.message = QtWidgets.QMessageBox()
                self.message.setIcon(QtWidgets.QMessageBox.Information)
                self.message.setWindowTitle("Rental Made")
                self.message.setFixedWidth(600)
                self.message.setInformativeText("Rental was successful.")
                self.message.show()
                self.populateTable()

            else:
                self.error = QtWidgets.QErrorMessage()
                self.error.setWindowTitle("Rental Error")
                self.error.showMessage("Rental was not successful.")

        else:
            self.error = QtWidgets.QErrorMessage()
            self.error.setWindowTitle("Selection Error")
            self.error.showMessage("Please select a Book ID")
コード例 #19
0
 def authorize(self):
     for key, value in config_loader(dataset="MSC_login").items():
         if key not in constants.MSC_LOGIN_CACHE:
             constants.MSC_LOGIN_CACHE[key] = value
     auth = constants.MSC_LOGIN_CACHE.get(self.mscolab_server_url, (None, None))
     # get mscolab /token http auth credentials from cache
     emailid = self.emailid.text()
     password = self.password.text()
     data = {
         "email": emailid,
         "password": password
     }
     s = requests.Session()
     s.auth = (auth[0], auth[1])
     s.headers.update({'x-test': 'true'})
     url = self.mscolab_server_url + '/token'
     r = s.post(url, data=data)
     if r.status_code == 401:
         r = self.authenticate(data, r, url)
         if r.status_code == 200 and not r.text == "False":
             constants.MSC_LOGIN_CACHE[self.mscolab_server_url] = (auth[0], auth[1])
         else:
             self.error_dialog = QtWidgets.QErrorMessage()
             self.error_dialog.showMessage('Oh no, server authentication were incorrect.')
     if r.text == "False":
         # popup that has wrong credentials
         self.error_dialog = QtWidgets.QErrorMessage()
         self.error_dialog.showMessage('Oh no, your credentials were incorrect.')
     else:
         # remove the login modal and put text there
         self.after_authorize(emailid, r)
コード例 #20
0
    def _returnBook(self):
        """Carries out a rental"""

        if self.rentedBookTable.currentColumn() == 0:
            rentalID = self.rentedBookTable.currentItem().text()
            bookID = self.rentedBookTable.item(
                self.rentedBookTable.currentRow(), 1).text()
            if database.removeRental(rentalID, bookID):
                self.message = QtWidgets.QMessageBox()
                self.message.setIcon(QtWidgets.QMessageBox.Information)
                self.message.setWindowTitle("Return Made")
                self.message.setFixedWidth(600)
                self.message.setInformativeText("Return was successful.")
                self.message.show()
                self.populateTable()

            else:
                self.error = QtWidgets.QErrorMessage()
                self.error.setWindowTitle("Return Error")
                self.error.showMessage("Book was not returned successfully.")

        else:
            self.error = QtWidgets.QErrorMessage()
            self.error.setWindowTitle("Selection Error")
            self.error.showMessage("Please select a Rental ID")
コード例 #21
0
    def recover_key(self):
        """
        Callback function for combine button to recover the key
        """
        try:
            input_shares = self.recoverSharesTextEdit.toPlainText().split("\n")
            language = self.languageComboBox2.currentText()
            encoding = Encoding.BIP39
            if self.encodingComboBox2.currentIndex() == 1:
                encoding = Encoding.BASE58

            shares = list()
            for share in input_shares:
                share = share.strip()
                if share != "":
                    shares.append(share)
            recovered_key = combine_shares(shares, encoding, language=language)
            self.recoveredKeyTextEdit.setText(recovered_key)

        except BadRequest as e:
            error_dialog = QtWidgets.QErrorMessage(self)
            error_dialog.showMessage("Bad Request! Invalid input!")

        except ValueError:
            error_dialog = QtWidgets.QErrorMessage(self)
            error_dialog.showMessage(
                "Bad Request! Incorrect Language Selected!")

        except Exception:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage("Error!")
コード例 #22
0
def analyze_url(url):
    try:
        req = requests.get(url)

        if(req.status_code == 200):
            soup = BeautifulSoup(req.text, 'lxml')
            images = soup.findAll('img', attrs={'class': 'slide_image'})
            return images
        else:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage("Invalid URL")
            font_4 = QtGui.QFont()
            font_4.setPointSize(14)
            error_dialog.setFont(font_4)
            error_dialog.setWindowTitle("ERROR")
            error_dialog.exec_()
            return ""
    except:
        error_dialog_1 = QtWidgets.QErrorMessage()
        error_dialog_1.showMessage("No Internet")
        font_4 = QtGui.QFont()
        font_4.setPointSize(14)
        error_dialog_1.setFont(font_4)
        error_dialog_1.setWindowTitle("WARNING")
        error_dialog_1.exec_()
        return ""
コード例 #23
0
    def export_shares(self):
        """
        Callback function for export button
        """
        shares = self.sharesTextEdit.toPlainText().split("\n\n")

        try:
            if self.singleRadioButton.isChecked():
                file_handler = open("shamir-share.txt", "w")
                for share in shares:
                    file_handler.write(share)
                    file_handler.write("\n")
                file_handler.close()
                QMessageBox.about(self, "Success",
                                  "Shares export to text file succeeded!")

            else:
                for share in shares:
                    file_handler = open(
                        "shamir-share-{}.txt".format(shares.index(share) + 1),
                        "w")
                    file_handler.write(share)
                    file_handler.close()
                QMessageBox.about(
                    self, "Success",
                    "Shares export to separate files succeeded!")

        except IOError as e:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage("Error exporting shares to file!")

        except Exception:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage("Error!")
コード例 #24
0
 def on_start(self):
     """
     Check if all necessary data fields are set and there has been a change
     in settings since the method was called last, to prevent errors.
     If everything is fine, the files are moved into sequences from the input
     to the output directory.
     :author: Joschka Strüber
     """
     if self.input_dir is None:
         no_input_dialog = QtWidgets.QErrorMessage(self)
         no_input_dialog.showMessage("No input directory was chosen.")
     elif self.output_dir is None:
         no_output_dialog = QtWidgets.QErrorMessage(self)
         no_output_dialog.showMessage("No output directory was chosen.")
     elif not self.dirs_changed:
         no_dirs_changed_dialog = QtWidgets.QErrorMessage(self)
         no_dirs_changed_dialog.showMessage("The directories were not changed"
                                            " after the last ordering of sequences.")
     else:
         self.progress_bar.setRange(0, 0)
         self.dirs_changed = False
         move_type = self.directory_type.currentText()
         copy = True if self.move_method.currentText() == "Copy" else False
         empty = self.empty_info.isChecked()
         self.sequence_thread = SequencesThread(move_type=move_type,
                                                path_from=self.input_dir,
                                                path_to=self.output_dir,
                                                copy=copy,
                                                empty=empty)
         self.sequence_thread.task_finished.connect(self.on_finished)
         self.sequence_thread.start()
コード例 #25
0
    def save_results(self):

        if len(self.y) < 1:
            error = QtWidgets.QErrorMessage(self.my_obj)
            error.setWindowTitle("Load Data")
            error.showMessage("Please load datafile")
            return

        if len(self.predictions) < 1:
            error = QtWidgets.QErrorMessage(self.my_obj)
            error.setWindowTitle("Make Prediction")
            error.showMessage(
                "Please, make sure to make the predictions first")
            return

        file_path = QtWidgets.QFileDialog.getSaveFileName(
            self.my_obj, 'Open TI-RADS Results File', '.')[0]

        if len(file_path) < 1:
            return

        file_path = file_path.split(".")[0] + ".txt"

        with open(file_path, 'w') as f:
            f.write(self.output_pred)
            f.write(self.output_1margin)
コード例 #26
0
    def on_log_in_btn_cklick(self):
        login=self.login_field.text()
        password=self.password_field.text()

        if self.db is None:
            try:
                if 'db' not in self.wm.get_keys():
                    self.db=ServerAPI(self.ip_field.text(),int(self.port_field.text()))
                    self.wm.add('db',self.db)
                else:
                    self.db=self.wm.get_window('db')
            except:
                self.error_dialog = QtWidgets.QErrorMessage()
                self.error_dialog.showMessage('Invalid ip or port!')
                return
        try:
            account=self.db.auth(login,password)
        except:
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.showMessage("Some error in auth!(")
            return

        if account is None:
            self.error_dialog = QtWidgets.QErrorMessage()
            self.error_dialog.showMessage('Invalid login or password!')
            return

        self.setVisible(False)
        self.main_win=Main_win(self.wm,account)
コード例 #27
0
ファイル: cnc.py プロジェクト: LiZhYun/CNC2
 def open(self):
     choose = QMessageBox(self)
     MainButton = choose.addButton("主程序", QMessageBox.ActionRole)
     SubButton = choose.addButton("子程序", QMessageBox.ActionRole)
     CancelButton = choose.addButton("取消", QMessageBox.ActionRole)
     choose.setText("主程序 | 子程序")
     choose.setWindowTitle("选择打开文件类型")
     choose.show()
     choose.exec()
     reply = choose.clickedButton()
     if reply == MainButton:
         fileName, ok = QFileDialog.getOpenFileName(self, "主程序",
                                                    "./",
                                                    "MPF Files (*.mpf);; TXT Files (*.txt)")
         try:
             with open(fileName, 'r', encoding='utf-8', errors="ignore") as f:
                 for line in f.readlines():
                     self.MainText.appendPlainText(line)
         except FileNotFoundError as e:
             self.error_message = QtWidgets.QErrorMessage()
             self.error_message.showMessage("请选择文件或输入文件名")
     elif reply == SubButton:
         fileName, ok = QFileDialog.getOpenFileName(self, "子程序",
                                                    "./",
                                                    "SPF Files (*.spf);; TXT Files (*.txt)")
         try:
             with open(fileName, 'r') as f:
                 for line in f.readlines():
                     self.SubText.appendPlainText(line)
         except FileNotFoundError as e:
             self.error_message = QtWidgets.QErrorMessage()
             self.error_message.showMessage("请选择文件或输入文件名")
     else:
         choose.close()
コード例 #28
0
    def importData(self):
        if self.lineEdit.text() == 'База данных не выбрана':
            return False


        newFile = QtWidgets.QFileDialog.getOpenFileName(self, 'Выбери импортируемый файл', os.path.abspath(os.curdir), '*.json')

        try:
            data = functions.importFromJson(newFile[0])
        except:
            errorWin = QtWidgets.QErrorMessage(self)
            errorWin.showMessage('Произошла ошибка')

        oldRows = self.tableWidget.rowCount()
        oldCols = self.tableWidget.columnCount()
        newRows = len(data)
        newCols = len(data[0])

        if oldCols != newCols:
            errorWin = QtWidgets.QErrorMessage(self)
            errorWin.showMessage('Колонок меньше или больше')
            return False

        self.tableWidget.setRowCount(oldRows + newRows)

        row = oldRows - 1
        for element in data:
            col = oldCols
            for item in element:
                oneCell = QtWidgets.QTableWidgetItem(item)
                self.tableWidget.setItem(row, col, oneCell)
                col += 1
            row += 1
コード例 #29
0
    def trackSubcircuitWithoutButton(self, iter_value, path_value):
        """
        - Same as trackSubcircuit, but here the count value is passed directly
          without using any button as in `Add`
        - This is triggered only once, initally
        """

        self.widgetObjCount = iter_value

        self.subfile = path_value
        self.reply = self.obj_validation.validateSub(
            self.subfile, self.numPorts[self.widgetObjCount - 1])
        if self.reply == "True":
            # Setting Library to Text Edit Line
            self.entry_var[self.widgetObjCount].setText(self.subfile)
            self.subName = self.subDetail[self.widgetObjCount]

            # Storing to track it during conversion
            self.obj_trac.subcircuitTrack[self.subName] = self.subfile
        elif self.reply == "PORT":
            self.msg = QtWidgets.QErrorMessage(self)
            self.msg.setModal(True)
            self.msg.setWindowTitle("Error Message")
            self.msg.showMessage(
                "Please select a Subcircuit with correct number of ports.")
            self.msg.exec_()
        elif self.reply == "DIREC":
            self.msg = QtWidgets.QErrorMessage(self)
            self.msg.setModal(True)
            self.msg.setWindowTitle("Error Message")
            self.msg.showMessage("Please select a valid Subcircuit directory "
                                 "(Containing '.sub' file).")
            self.msg.exec_()
コード例 #30
0
 def load_session(self):
     if os.path.exists('config.ini'):
         config = configparser.ConfigParser()
         config.read("config.ini")
         user = config["Session"]["user"]
         if os.path.exists(f"user/{user}.json"):
             with open(f"user/{user}.json", 'r') as account_file:
                 card = json.load(account_file)
                 # self.setWindowTitle(f"Partisan - Messenger - user/{user}.json")
             self.account = User()
             self.active_contact = Contact(self.account)
             self.account.uuid, self.account.ip, self.account.port = \
                 card['UUID'], card['IP'], card['PORT']
             self.centralwidget.setEnabled(True)
             self.load_contact_list()
             self.actionAddAccount.setDisabled(True)
             self.lineInputMessage.setDisabled(True)
             self.listen()
         else:
             error_dialog = QtWidgets.QErrorMessage()
             error_dialog.showMessage(
                 'User file missing! Reload it manually.')
             error_dialog.exec_()
     else:
         error_dialog = QtWidgets.QErrorMessage()
         error_dialog.showMessage('Config file does not exist!')
         error_dialog.exec_()