예제 #1
0
 def GenerateFunction(self) :
   ##checking directory path validation
   if(os.path.isdir(self.FileLocation.text()) == False):
     ErrorBox = QtWidgets.QErrorMessage()
     ErrorBox.showMessage("This Directory doesn't exist")
     ErrorBox.exec_()
   else:
     #cmd ="Hello.c"
     ##To get MCU 
     Index = self.MCU.currentIndex()
     ##To get ComN
     COMNum=self.COMEdit.text()
     ##To get the ELF_File
     ##TODO:Change elffile_name automatically
     ElfPath = self.FileLocation.text() + "Main_APP.elf"
     ##starting the ComReceiver Thread
     self.file=Import(Index,COMNum,ElfPath)
     self.file.start()
     ##checking directory path validation
     if(os.path.isfile(r'./progress.txt') == False):
       self.Status.setText("Error")
       ErrorBox = QtWidgets.QErrorMessage()
       ErrorBox.showMessage("The progress file doesn't exist")
       ErrorBox.exec_()
     else:
       ##initalization values og progress.txt
       f = open('./progress.txt','w') 
       f.write("0 0")
       f.close()
       ##starting The progressBar Thread
       QObject.connect (self.progressView , QtCore.SIGNAL("__updateProgressBar(int)"),self.__updateProgressBar)
       self.start()
       
       print("correct")
예제 #2
0
 def create_account(self):
     if self.password_field.text() == self.confirm_password_field.text():
         create_user(self.username_field.text(), self.password_field.text())
         self.close()
     else:
         error_dialog = QtWidgets.QErrorMessage()
         error_dialog.showMessage('Your password fields don\'t match!')
예제 #3
0
def reference(filePaths, isReferenced=True, useNamespace=False):
    if filePaths is not None and isReferenced:
        empty = []
        for path in filePaths:
            print "This is the path that we are working with", path
            if os.path.exists(path):
                print path, "exists"
                #TODO do we want to add multiple references in with different namespaces? You know to get rid of conflicts? Or is our current system for handling that good enough?
                # pm.system.createReference(path, namespace="HelloWorld1")
                basename = os.path.basename(path)
                millis = byuutil.timestampThisYear()
                refNamespace = basename + str(millis)
                print basename
                print str(millis)
                print refNamespace
                if useNamespace:
                    pm.system.createReference(path, namespace=refNamespace)
                else:
                    pm.system.createReference(path)
            else:
                print path, "don't exist"
                empty.append(path)

        if empty:
            empty_str = '\n'.join(empty)
            error_dialog = QtWidgets.QErrorMessage(maya_main_window())
            error_dialog.showMessage(
                "The following elements are empty. Nothing has been published to them, so they can't be referenced.\n"
                + empty_str)
예제 #4
0
    def draw_standardEllipse(self, painter):
        penColor = QtCore.Qt.blue
        pen = QtGui.QPen()
        pen.setColor(penColor)
        pen.setWidthF(self.lineWidth)
        painter.setPen(pen)

        # calculate the major axis and minor axis
        a0u = 0.0
        a0b = 0.0
        b0u = 0.0
        b0b = 0.0
        try:
            for i in range(self.numPt):
                angle = i * 2 * math.pi / self.numPt
                a0u = a0u + (self.vertices[i][0] -
                             self.center.x()) * math.cos(angle)
                a0b = a0b + math.cos(angle) * math.cos(angle)
                b0u = b0u + (self.vertices[i][2] -
                             self.center.y()) * math.sin(angle)
                b0b = b0b + math.sin(angle) * math.sin(angle)

        except IndexError:
            error_dialog = QtWidgets.QErrorMessage(self)
            error_dialog.showMessage('Please choose a data file first')
        else:
            width = a0u / a0b
            height = b0u / b0b

            painter.drawEllipse(self.center, width, height)
예제 #5
0
 def load_state(self):
     try:
         state = self.settings.value("system/state")
         if state:
             self.state = json.loads(state)
     except Exception as E:
         error = QtWidgets.QErrorMessage(self)
         error.showMessage(str(E))
예제 #6
0
 def save_state(self):
     try:
         state = json.dumps(self.state)
         self.settings.setValue("system/state", state)
     except Exception as E:
         # XXX Fail. Never displays because we're on our way out
         error = QtWidgets.QErrorMessage(self)
         error.showMessage(str(E))
예제 #7
0
 def load_db(self):
     # Abrir banco de dados
     if os.path.isfile(self.dbfile):
         self.show_full_db()
     else:
         error_dialog = QtWidgets.QErrorMessage()
         error_dialog.showMessage("Database not found")
         error_dialog.exec_()
         raise Exception("Database not found")
예제 #8
0
 def ComFunction(self):
     ports = list(port_list.comports())
     if ports:
         for p in ports:
             tuples = re.findall(r'COM(\d+)', str(p))
             COM = tuples[0]
             self.COMEdit.setText("COM" + COM)
     if not ports:
         ErrorBox = QtWidgets.QErrorMessage()
         ErrorBox.showMessage("No COM detected")
         ErrorBox.exec_()
예제 #9
0
        def task():
            try:
                selectedCT = CT if self.inputs["fast_mode"] else InteractiveCT

                ct = selectedCT(self.inputs["img"],
                                self.inputs["rotate_angle"],
                                self.inputs["theta_angle"],
                                self.inputs["detectors_amount"],
                                self.inputs["detectors_distance"])

                self.ct_start_datetime = datetime.now()

                self.inputs["sinogram"], self.inputs["result"] = ct.run()
                self.normalizeImg(self.inputs["sinogram"])

                if not self.inputs["fast_mode"]:
                    frames = ct.getFrames()
                    self.inputs["animation_sinogram_frames"], self.inputs[
                        "animation_result_frames"] = frames

                    self.inputs["animation_sinogram_frames"].append(
                        self.inputs["sinogram"])
                    self.inputs["animation_result_frames"].append(
                        self.inputs["result"])

                    self.preprocessFrames(
                        self.inputs["animation_sinogram_frames"])
                    self.preprocessFrames(
                        self.inputs["animation_result_frames"])

                    self.plots_layout["items"]["animation_slider"][
                        "object"].setEnabled(True)
                    self.plots_layout["items"]["animation_slider"][
                        "object"].setValue(100)
                else:
                    self.plots_layout["items"]["animation_slider"][
                        "object"].setDisabled(True)

                self.plots_layout["items"]["radon_fig"]["object"].setPixmap(
                    self.preprocessFrame(self.inputs["sinogram"]))
                self.plots_layout["items"]["iradon_fig"]["object"].setPixmap(
                    self.preprocessFrame(self.inputs["result"]))

            except Exception as msg:
                QtWidgets.QErrorMessage().showMessage(str(msg))
            finally:
                self.buttons_layout["items"]["run"]["object"].setEnabled(
                    runStatus)
                self.buttons_layout["items"]["load"]["object"].setEnabled(
                    loadStauts)
                self.buttons_layout["items"]["save_dicom"][
                    "object"].setEnabled(True)
    def validateInput(self) -> bool:
        mb = QtWidgets.QErrorMessage()
        mb.setModal(True)
        if self.id_input.text() == '':
            mb.showMessage('Patient ID cannot be empty.')
            mb.exec_()
            return False
        elif self.name_input.text() == '':
            mb.showMessage('Patient name cannot be empty.')
            mb.exec_()
            return False

        return True
예제 #11
0
    def save_changes(self):
        check_expression = QtCore.QRegExp(self.rule_pattern.text())
        if not check_expression.isValid():
            error_message = QtWidgets.QErrorMessage(self)
            error_message.showMessage("Invalid regular expression: {0}".format(
                self.rule_pattern.text()))
            Logger.error("Invalid regular expression: {0}".format(
                self.rule_pattern.text()))
            return

        new_info_dict = {self.rule_name.text(): self.serialize_info()}
        self.rules_dict.update(new_info_dict)
        self.update_rule_list()
예제 #12
0
    def contextMenuEvent(self, event):
        menu = QtWidgets.QMenu(self)
        add_Action = menu.addAction("добавить")
        edit_Action = menu.addAction("редактировать")
        remove_Action = menu.addAction("удалить")
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == add_Action:
            widget = QDialog()
            ui = GoodsForm(table=self)
            ui.setupUi(widget)
            widget.exec_()
        if action == remove_Action:
            reply = QtWidgets.QMessageBox.question(
                self,
                "Удалить товар?",
                "Вы уверенны что хотите удалить?",
                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
                QtWidgets.QMessageBox.No,
            )
            if reply == QtWidgets.QMessageBox.Yes:
                values = self.parse_row()
                if values["Кол-во."] != "0":
                    # widget = QDialog()
                    error_dialog = QtWidgets.QErrorMessage(self)
                    error_dialog.showMessage("товар с количеством удалить нельзя")
                else:
                    db = Bicycle_db()
                    db.insert(
                        "DELETE FROM goods WHERE article LIKE '%{}%'".format(
                            values["Арт"]
                        )
                    )
                    self.update_table()
                    db.close()

        if action == edit_Action:
            widget = QDialog()
            ui = GoodsForm(
                table=self,
                values=self.parse_row(),
                category_widget=self.category_widget,
            )
            ui.setupUi(widget)
            widget.exec_()
예제 #13
0
    def draw_originalEllipse(self, painter):
        penColor = QtCore.Qt.red
        pen = QtGui.QPen()
        pen.setColor(penColor)
        pen.setWidthF(self.lineWidth)
        painter.setPen(pen)

        try:
            startPoint = QtCore.QPointF(self.vertices[0][0],
                                        self.vertices[0][2])
        except IndexError:
            error_dialog = QtWidgets.QErrorMessage(self)
            error_dialog.showMessage('Please choose a data file first')
        else:
            """
            for i in range(self.numPt):
                p1=QtCore.QPointF(self.vertices[i-1][0],self.vertices[i-1][2])
                p2=QtCore.QPointF(self.vertices[i][0],self.vertices[i][2])
                painter.drawLine(p1,p2)
            """
            painterPath = QtGui.QPainterPath(startPoint)
            for i in range(self.numPt):
                tmp = self.vertices[(i + 1) % self.numPt] - self.vertices[i -
                                                                          1]
                tmp /= math.sqrt(tmp[0] * tmp[0] +
                                 tmp[2] * tmp[2])  #normalise vector
                arc = self.vertices[(i + 1) % self.numPt] - self.vertices[i]
                arc = math.sqrt(arc[0] * arc[0] + arc[2] * arc[2])
                tmp = tmp * arc / 1.
                controlPt1 = tmp + self.vertices[i]

                tmp = self.vertices[i] - self.vertices[(i + 2) % self.numPt]
                tmp /= math.sqrt(tmp[0] * tmp[0] +
                                 tmp[2] * tmp[2])  #normalise vector
                tmp = tmp * arc / 1.
                controlPt2 = tmp + self.vertices[(i + 1) % self.numPt]
                painterPath.cubicTo(controlPt1[0], controlPt1[2],
                                    controlPt2[0], controlPt2[2],
                                    self.vertices[(i + 1) % self.numPt][0],
                                    self.vertices[(i + 1) % self.numPt][2])
                painterPath.moveTo(self.vertices[(i + 1) % self.numPt][0],
                                   self.vertices[(i + 1) % self.numPt][2])

            painter.drawPath(painterPath)
예제 #14
0
    def make_buy(self, button, cart_array, cart_table):
        button_value = button.text()
        if button_value == 'карта':
            button_value = 'Картка'
        if button_value == 'наличные':
            button_value = 'Готівка'
        if button_value == 'терминал':
            button_value = 'Термінал'
        print(button_value)
        if len(cart_array) > 0:
            """values from second cart table"""
            cart_values_from_table = cart_table.get_values_from_cart()
            db = Bicycle_db()
            schema = db.schema['basket']
            date = datetime.datetime.now()
            dated = date.strftime('%M/%d/%Y %H:%m:00')
            values = []
            for cart_item in range(len(cart_values_from_table)):
                if cart_values_from_table[cart_item] in cart_array:
                    values.append(
                        'VALUES((SELECT MAX(id)from basket)+1,{},{},{},{},{},{},{},{},"","{}"'
                        .format(cart_values_from_table[cart_item]['цена'],
                                cart_values_from_table[cart_item]['кол-во'],
                                cart_values_from_table[cart_item]['сумма'],
                                cart_array[cart_item]['Арт'], button_value,
                                cart_array[cart_item]['Продаж'], dated,
                                cart_array[cart_item]['Название']))
                else:
                    values.append(
                        'VALUES((SELECT MAX(id)from basket)+1,{},{},{},"",{},{},{},{},"",{}'
                        .format(cart_values_from_table['цена'],
                                cart_values_from_table['кол-во'],
                                cart_values_from_table['сумма'], button_value,
                                cart_values_from_table['цена'], dated,
                                cart_values_from_table['Название']))
            main_query = 'INSERT INTO basket ({})'.format(schema)
            for value in values:
                main_query += value
            db.insert(main_query)

        else:
            error_dialog = QtWidgets.QErrorMessage(self.tab)
            error_dialog.showMessage("Нет товаров в корзине")
예제 #15
0
    def setValues(self):
        useName = not self.chkName.isChecked()

        if useName:
            valid = len({x.currentText() for x in self.boxes}) == 3
        else:
            valid = self.cbX.currentText() != self.cbY.currentText()

        if not valid:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage(
                "Select unique properties for each requested attribute.")

            error_dialog.exec_()
            self.value = None
        else:
            self.value = SelectedProperties(self.cbX.currentText(),
                                            self.cbY.currentText(),
                                            self.cbName.currentText(), useName)
예제 #16
0
 def GenerateFunction(self) :
   global filename
   ##checking directory path validation
   if(os.path.isfile(self.FileLocation.text()) == False):
     ErrorBox = QtWidgets.QErrorMessage()
     ErrorBox.showMessage("This File doesn't exist")
     ErrorBox.exec_()
   else:
     ##To get MCU 
     Index = self.HW_Family.currentIndex()
     
     Target = self.HW_Family.currentText()
     
     f = open('./SelectedTarget.txt','w') 
     f.write(Target)
     f.close()
     
     ##To get the ELF_File
     ElfPath = filename[0]
     TimeStamp = os.path.getmtime(ElfPath)
     
     ##starting the ComReceiver Thread
     self.file=Import(Index,ElfPath, TimeStamp)
     self.file.start()
     
     
     ##starting the FetchNodeMCUs Thread
     ##self.fileNodeMCU=Import_NodeMCUs()
     ##self.fileNodeMCU.start()
     
     
     ##initalization values og progress.txt
     f = open('./progress.txt','w') 
     f.write("0 0")
     f.write("\n")
     f.write("0")
     f.close()
     ##starting The progressBar Thread
     QObject.connect (self.progressView , QtCore.SIGNAL("__updateProgressBar(int)"),self.__updateProgressBar)
     self.start()
     print("correct")
예제 #17
0
    def openFile(self):
        self.path = easygui.fileopenbox()

        if not self.path:
            return

        try:
            g = nx.read_graphml(self.path)
        except (nx.NetworkXError, ElementTree.ParseError) as e:
            error_dialog = QtWidgets.QErrorMessage()
            error_dialog.showMessage(str(e))

            error_dialog.exec_()
            return

        g, success = GraphUtils.sanitize(g)
        if success:
            self.graph = g
            self.setGraphInfo()
            self.draw()
        else:
            self.path = None
예제 #18
0
 def show_error(self, message):
     error_dialog = QtWidgets.QErrorMessage()
     error_dialog.showMessage(message)
     error_dialog.setWindowTitle("Error")
     error_dialog.exec_()
예제 #19
0
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.openFilesPath = ''

        self.errorMessageDialog = QtWidgets.QErrorMessage(self)

        frameStyle = QtWidgets.QFrame.Sunken | QtWidgets.QFrame.Panel

        self.integerLabel = QtWidgets.QLabel()
        self.integerLabel.setFrameStyle(frameStyle)
        self.integerButton = QtWidgets.QPushButton(
            "QInputDialog.get&Integer()")

        self.doubleLabel = QtWidgets.QLabel()
        self.doubleLabel.setFrameStyle(frameStyle)
        self.doubleButton = QtWidgets.QPushButton("QInputDialog.get&Double()")

        self.itemLabel = QtWidgets.QLabel()
        self.itemLabel.setFrameStyle(frameStyle)
        self.itemButton = QtWidgets.QPushButton("QInputDialog.getIte&m()")

        self.textLabel = QtWidgets.QLabel()
        self.textLabel.setFrameStyle(frameStyle)
        self.textButton = QtWidgets.QPushButton("QInputDialog.get&Text()")

        self.colorLabel = QtWidgets.QLabel()
        self.colorLabel.setFrameStyle(frameStyle)
        self.colorButton = QtWidgets.QPushButton("QColorDialog.get&Color()")

        self.fontLabel = QtWidgets.QLabel()
        self.fontLabel.setFrameStyle(frameStyle)
        self.fontButton = QtWidgets.QPushButton("QFontDialog.get&Font()")

        self.directoryLabel = QtWidgets.QLabel()
        self.directoryLabel.setFrameStyle(frameStyle)
        self.directoryButton = QtWidgets.QPushButton(
            "QFileDialog.getE&xistingDirectory()")

        self.openFileNameLabel = QtWidgets.QLabel()
        self.openFileNameLabel.setFrameStyle(frameStyle)
        self.openFileNameButton = QtWidgets.QPushButton(
            "QFileDialog.get&OpenFileName()")

        self.openFileNamesLabel = QtWidgets.QLabel()
        self.openFileNamesLabel.setFrameStyle(frameStyle)
        self.openFileNamesButton = QtWidgets.QPushButton(
            "QFileDialog.&getOpenFileNames()")

        self.saveFileNameLabel = QtWidgets.QLabel()
        self.saveFileNameLabel.setFrameStyle(frameStyle)
        self.saveFileNameButton = QtWidgets.QPushButton(
            "QFileDialog.get&SaveFileName()")

        self.criticalLabel = QtWidgets.QLabel()
        self.criticalLabel.setFrameStyle(frameStyle)
        self.criticalButton = QtWidgets.QPushButton("QMessageBox.critica&l()")

        self.informationLabel = QtWidgets.QLabel()
        self.informationLabel.setFrameStyle(frameStyle)
        self.informationButton = QtWidgets.QPushButton(
            "QMessageBox.i&nformation()")

        self.questionLabel = QtWidgets.QLabel()
        self.questionLabel.setFrameStyle(frameStyle)
        self.questionButton = QtWidgets.QPushButton("QMessageBox.&question()")

        self.warningLabel = QtWidgets.QLabel()
        self.warningLabel.setFrameStyle(frameStyle)
        self.warningButton = QtWidgets.QPushButton("QMessageBox.&warning()")

        self.errorLabel = QtWidgets.QLabel()
        self.errorLabel.setFrameStyle(frameStyle)
        self.errorButton = QtWidgets.QPushButton(
            "QErrorMessage.show&M&essage()")

        self.integerButton.clicked.connect(self.setInteger)
        self.doubleButton.clicked.connect(self.setDouble)
        self.itemButton.clicked.connect(self.setItem)
        self.textButton.clicked.connect(self.setText)
        self.colorButton.clicked.connect(self.setColor)
        self.fontButton.clicked.connect(self.setFont)
        self.directoryButton.clicked.connect(self.setExistingDirectory)
        self.openFileNameButton.clicked.connect(self.setOpenFileName)
        self.openFileNamesButton.clicked.connect(self.setOpenFileNames)
        self.saveFileNameButton.clicked.connect(self.setSaveFileName)
        self.criticalButton.clicked.connect(self.criticalMessage)
        self.informationButton.clicked.connect(self.informationMessage)
        self.questionButton.clicked.connect(self.questionMessage)
        self.warningButton.clicked.connect(self.warningMessage)
        self.errorButton.clicked.connect(self.errorMessage)

        self.native = QtWidgets.QCheckBox()
        self.native.setText("Use native file dialog.")
        self.native.setChecked(True)
        if sys.platform not in ("win32", "darwin"):
            self.native.hide()

        layout = QtWidgets.QGridLayout()
        layout.setColumnStretch(1, 1)
        layout.setColumnMinimumWidth(1, 250)
        layout.addWidget(self.integerButton, 0, 0)
        layout.addWidget(self.integerLabel, 0, 1)
        layout.addWidget(self.doubleButton, 1, 0)
        layout.addWidget(self.doubleLabel, 1, 1)
        layout.addWidget(self.itemButton, 2, 0)
        layout.addWidget(self.itemLabel, 2, 1)
        layout.addWidget(self.textButton, 3, 0)
        layout.addWidget(self.textLabel, 3, 1)
        layout.addWidget(self.colorButton, 4, 0)
        layout.addWidget(self.colorLabel, 4, 1)
        layout.addWidget(self.fontButton, 5, 0)
        layout.addWidget(self.fontLabel, 5, 1)
        layout.addWidget(self.directoryButton, 6, 0)
        layout.addWidget(self.directoryLabel, 6, 1)
        layout.addWidget(self.openFileNameButton, 7, 0)
        layout.addWidget(self.openFileNameLabel, 7, 1)
        layout.addWidget(self.openFileNamesButton, 8, 0)
        layout.addWidget(self.openFileNamesLabel, 8, 1)
        layout.addWidget(self.saveFileNameButton, 9, 0)
        layout.addWidget(self.saveFileNameLabel, 9, 1)
        layout.addWidget(self.criticalButton, 10, 0)
        layout.addWidget(self.criticalLabel, 10, 1)
        layout.addWidget(self.informationButton, 11, 0)
        layout.addWidget(self.informationLabel, 11, 1)
        layout.addWidget(self.questionButton, 12, 0)
        layout.addWidget(self.questionLabel, 12, 1)
        layout.addWidget(self.warningButton, 13, 0)
        layout.addWidget(self.warningLabel, 13, 1)
        layout.addWidget(self.errorButton, 14, 0)
        layout.addWidget(self.errorLabel, 14, 1)
        layout.addWidget(self.native, 15, 0)
        self.setLayout(layout)

        self.setWindowTitle("Standard Dialogs")
예제 #20
0
def run_ui(game: Optional[Game] = None) -> None:
    os.environ[
        "QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"  # Potential fix for 4K screens
    app = QApplication(sys.argv)

    # init the theme and load the stylesheet based on the theme index
    liberation_theme.init()
    with open("./resources/stylesheets/" +
              liberation_theme.get_theme_css_file()) as stylesheet:
        logging.info('Loading stylesheet: %s',
                     liberation_theme.get_theme_css_file())
        app.setStyleSheet(stylesheet.read())

    # Inject custom payload in pydcs framework
    custom_payloads = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   "..\\resources\\customized_payloads")
    if os.path.exists(custom_payloads):
        dcs.unittype.FlyingType.payload_dirs.append(custom_payloads)
    else:
        # For release version the path is different.
        custom_payloads = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "resources\\customized_payloads")
        if os.path.exists(custom_payloads):
            dcs.unittype.FlyingType.payload_dirs.append(custom_payloads)

    first_start = liberation_install.init()
    if first_start:
        window = QLiberationFirstStartWindow()
        window.exec_()

    logging.info("Using {} as 'Saved Game Folder'".format(
        persistency.base_path()))
    logging.info("Using {} as 'DCS installation folder'".format(
        liberation_install.get_dcs_install_directory()))

    # Splash screen setup
    pixmap = QPixmap("./resources/ui/splash_screen.png")
    splash = QSplashScreen(pixmap)
    splash.show()

    # Once splash screen is up : load resources & setup stuff
    uiconstants.load_icons()
    uiconstants.load_event_icons()
    uiconstants.load_aircraft_icons()
    uiconstants.load_vehicle_icons()
    uiconstants.load_aircraft_banners()
    uiconstants.load_vehicle_banners()

    # Replace DCS Mission scripting file to allow DCS Liberation to work
    try:
        liberation_install.replace_mission_scripting_file()
    except:
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.setWindowTitle("Wrong DCS installation directory.")
        error_dialog.showMessage(
            "Unable to modify Mission Scripting file. Possible issues with rights. Try running as admin, or please perform the modification of the MissionScripting file manually."
        )
        error_dialog.exec_()

    # Apply CSS (need works)
    GameUpdateSignal()

    # Start window
    window = QLiberationWindow(game)
    window.showMaximized()
    splash.finish(window)
    qt_execution_code = app.exec_()

    # Restore Mission Scripting file
    logging.info("QT App terminated with status code : " +
                 str(qt_execution_code))
    logging.info("Attempt to restore original mission scripting file")
    liberation_install.restore_original_mission_scripting()
    logging.info("QT process exited with code : " + str(qt_execution_code))
예제 #21
0
    def make_buy(self, button, cart_array, cart_table):
        button_value = button.text()
        if button_value == "карта":
            button_value = "Картка"
        if button_value == "Наличные":
            button_value = "Готівка"
        if button_value == "терминал":
            button_value = "Термінал"
        print(button_value)
        if len(cart_array) > 0:
            """values from second cart table"""
            cart_values_from_table = cart_table.get_values_from_cart()
            db = Bicycle_db()
            schema = ",".join(db.schema["basket"])
            date = datetime.datetime.now()
            dated = date.strftime("%m/%d/%y %H:%M:00")
            values = []
            for cart_item in range(len(cart_values_from_table)):
                for cart_array_item in cart_array:
                    if "Aрт" in cart_values_from_table[cart_item]:
                        if (cart_values_from_table[cart_item]["название"] ==
                                cart_array_item["Название"]):
                            values.append(
                                '((SELECT MAX(id)from basket)+1,{},{},{},{},"{}",{},"{}","","{}")'
                                .format(
                                    cart_values_from_table[cart_item]["цена"],
                                    cart_values_from_table[cart_item]
                                    ["кол-во"],
                                    cart_values_from_table[cart_item]["сумма"],
                                    cart_array[cart_item]["Арт"],
                                    button_value,
                                    cart_array_item["Продаж"],
                                    dated,
                                    cart_array_item["Название"],
                                ))
                            break
                    else:
                        values.append(
                            '((SELECT MAX(id)from basket)+1,{},{},{},"","{}",{},"{}","","{}")'
                            .format(
                                cart_values_from_table[cart_item]["цена"],
                                cart_values_from_table[cart_item]["кол-во"],
                                cart_values_from_table[cart_item]["сумма"],
                                button_value,
                                cart_values_from_table[cart_item]["цена"],
                                dated,
                                cart_values_from_table[cart_item]["название"],
                            ))
                        break

            main_query = "INSERT INTO basket ({}) VALUES".format(schema)
            for value in range(len(values)):
                main_query += values[value]
                if value + 1 != len(values):
                    main_query += ","

            db.insert(main_query)
            self.setDefaultTime()
            self.get_basket_items_by_date()
            self.tableWidget_2.clean_table()
            # TODO add operation for delete get values from cart array and delete each from goods table
            self.cart_items = []
            # update main_table

        else:
            error_dialog = QtWidgets.QErrorMessage(self.tab)
            error_dialog.showMessage("Нет товаров в корзине")
예제 #22
0
 def onPressed(self):
     print("helloooooooooo")
     self.error_dialog = QtWidgets.QErrorMessage()
     self.error_dialog.showMessage('Please enter valid Email')
예제 #23
0
    def draw_generalisedEllipse(self, painter):
        penColor = QtGui.QColor(0, 80, 0)
        pen = QtGui.QPen()
        pen.setColor(penColor)
        pen.setWidthF(self.lineWidth)
        painter.setPen(pen)
        I = self.numPt
        aConstArray = np.zeros(2 * self.J + 1)
        aCoefficientMatrix = np.ndarray(shape=(2 * self.J + 1, I),
                                        dtype=float,
                                        order='C')  # row-major
        aTrignometricMatrix = np.ndarray(shape=(I, 2 * self.J + 1),
                                         dtype=float,
                                         order='C')
        bConstArray = np.zeros(2 * self.J + 1)
        bCoefficientMatrix = np.ndarray(shape=(2 * self.J + 1, I),
                                        dtype=float,
                                        order='C')
        bTrignometricMatrix = np.ndarray(shape=(I, 2 * self.J + 1),
                                         dtype=float,
                                         order='C')
        for i in range(I):
            aCoefficientMatrix[0, i] = 1.
            aTrignometricMatrix[i, 0] = 1.
            bCoefficientMatrix[0, i] = 1.
            bTrignometricMatrix[i, 0] = 1.

        for i in range(
                I
        ):  # for aCoefficientMatrix's column, and trignomatricMatrix's row
            for j in range(
                    1, self.J + 1
            ):  # for aCoefficientMatrix's row, and trignomatricMatrix's column
                try:
                    vi = self.angles[i]
                except IndexError:
                    error_dialog = QtWidgets.QErrorMessage(self)
                    error_dialog.showMessage('Please choose a data file first')
                else:
                    aCoefficientMatrix[2 * j - 1, i] = math.cos(vi * j)
                    aCoefficientMatrix[2 * j, i] = math.sin(vi * j)
                    aTrignometricMatrix[i, 2 * j - 1] = math.cos(vi * j)
                    aTrignometricMatrix[i, 2 * j] = math.sin(vi * j)
                    # aConstAtrray[0] and bConstAtrray[0] always equal to 0 by definition!
                    aConstArray[2 * j -
                                1] += (self.vertices[i][0] -
                                       self.center.x()) * math.cos(vi * j)
                    aConstArray[2 * j] += (self.vertices[i][0] -
                                           self.center.x()) * math.sin(vi * j)

                    bCoefficientMatrix[2 * j - 1, i] = math.sin(vi * j)
                    bCoefficientMatrix[2 * j, i] = math.cos(vi * j)
                    bTrignometricMatrix[i, 2 * j - 1] = math.sin(vi * j)
                    bTrignometricMatrix[i, 2 * j] = math.cos(vi * j)
                    bConstArray[2 * j -
                                1] += (self.vertices[i][2] -
                                       self.center.y()) * math.sin(vi * j)
                    bConstArray[2 * j] += (self.vertices[i][2] -
                                           self.center.y()) * math.cos(vi * j)

        A = np.dot(aCoefficientMatrix, aTrignometricMatrix)
        self.a = np.linalg.solve(A, aConstArray)
        B = np.dot(bCoefficientMatrix, bTrignometricMatrix)
        self.b = np.linalg.solve(B, bConstArray)

        #CoefficientMatrix
        generalisedEllipseVertices = [[0 for i in range(2)] for j in range(I)]
        self.Ea = 0.0
        self.Em = 0.0
        for i in range(I):
            generalisedEllipseVertices[i][0] = self.center.x() + self.a[0]
            generalisedEllipseVertices[i][1] = self.center.y() + self.b[0]
            v = self.angles[i]
            for j in range(1, self.J + 1):
                generalisedEllipseVertices[i][
                    0] += self.a[2 * j - 1] * math.cos(
                        j * v) + self.a[2 * j] * math.sin(j * v)
                generalisedEllipseVertices[i][
                    1] += self.b[2 * j - 1] * math.sin(
                        j * v) + self.b[2 * j] * math.cos(j * v)

            di = math.sqrt(
                (self.vertices[i][0] - generalisedEllipseVertices[i][0])**2 +
                (self.vertices[i][2] - generalisedEllipseVertices[i][1])**2)
            self.d.append(di)
            self.Ea += (di / self.d_bar[i])
            if self.Em < di / self.d_bar[i]:
                self.Em = di / self.d_bar[i]
        self.Ea = self.Ea / self.numPt

        for i in range(I):
            painter.drawLine(generalisedEllipseVertices[i][0],
                             generalisedEllipseVertices[i][1],
                             generalisedEllipseVertices[(i + 1) % I][0],
                             generalisedEllipseVertices[(i + 1) % I][1])
예제 #24
0
def run_ui(game: Game | None, dev: bool) -> None:
    os.environ[
        "QT_ENABLE_HIGHDPI_SCALING"] = "1"  # Potential fix for 4K screens
    QApplication.setHighDpiScaleFactorRoundingPolicy(
        Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)

    app = QApplication(sys.argv)

    app.setAttribute(Qt.AA_DisableWindowContextHelpButton)
    app.setAttribute(Qt.AA_EnableHighDpiScaling,
                     True)  # enable highdpi scaling
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)  # use highdpi icons

    # init the theme and load the stylesheet based on the theme index
    liberation_theme.init()
    with open(
            "./resources/stylesheets/" + liberation_theme.get_theme_css_file(),
            encoding="utf-8",
    ) as stylesheet:
        logging.info("Loading stylesheet: %s",
                     liberation_theme.get_theme_css_file())
        app.setStyleSheet(stylesheet.read())

    first_start = liberation_install.init()
    if first_start:
        window = QLiberationFirstStartWindow()
        window.exec_()

    logging.info("Using {} as 'Saved Game Folder'".format(
        persistency.base_path()))
    logging.info("Using {} as 'DCS installation folder'".format(
        liberation_install.get_dcs_install_directory()))

    inject_custom_payloads(Path(persistency.base_path()))

    # Splash screen setup
    pixmap = QPixmap("./resources/ui/splash_screen.png")
    splash = QSplashScreen(pixmap)
    splash.show()

    # Developers are launching the game in a loop hundreds of times. We've read it.
    if not dev:
        # Give enough time to read splash screen
        time.sleep(3)

    # Once splash screen is up : load resources & setup stuff
    uiconstants.load_icons()
    uiconstants.load_event_icons()
    uiconstants.load_aircraft_icons()
    uiconstants.load_vehicle_icons()
    uiconstants.load_aircraft_banners()
    uiconstants.load_vehicle_banners()

    # Show warning if no DCS Installation directory was set
    if liberation_install.get_dcs_install_directory() == "":
        logging.warning(
            "DCS Installation directory is empty. MissionScripting file will not be replaced!"
        )
        if not liberation_install.ignore_empty_install_directory():
            ignore_checkbox = QCheckBox("Do not show again")
            ignore_checkbox.stateChanged.connect(
                set_ignore_empty_install_directory)
            message_box = QtWidgets.QMessageBox(parent=splash)
            message_box.setIcon(QtWidgets.QMessageBox.Icon.Warning)
            message_box.setWindowTitle("No DCS installation directory.")
            message_box.setText(
                "The DCS Installation directory is not set correctly. "
                "This will prevent DCS Liberation to work properly as the MissionScripting "
                "file will not be modified."
                "<br/><br/>To solve this problem, you can set the Installation directory "
                "within the preferences menu. You can also manually edit or replace the "
                "following file:"
                "<br/><br/><strong>&lt;dcs_installation_directory&gt;/Scripts/MissionScripting.lua</strong>"
                "<br/><br/>The easiest way to do it is to replace the original file with the file in dcs-liberation distribution (&lt;dcs_liberation_installation&gt;/resources/scripts/MissionScripting.lua)."
                "<br/><br/>You can find more information on how to manually change this file in the Liberation Wiki (Page: Dedicated Server Guide) on GitHub.</p>"
            )
            message_box.setDefaultButton(
                QtWidgets.QMessageBox.StandardButton.Ok)
            message_box.setCheckBox(ignore_checkbox)
            message_box.exec_()
    # Replace DCS Mission scripting file to allow DCS Liberation to work
    try:
        liberation_install.replace_mission_scripting_file()
    except:
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.setWindowTitle("Wrong DCS installation directory.")
        error_dialog.showMessage(
            "Unable to modify Mission Scripting file. Possible issues with rights. Try running as admin, or please perform the modification of the MissionScripting file manually."
        )
        error_dialog.exec_()

    # Apply CSS (need works)
    GameUpdateSignal()
    GameUpdateSignal.get_instance().game_loaded.connect(on_game_load)

    # Start window
    window = QLiberationWindow(game, dev)
    window.showMaximized()
    splash.finish(window)
    qt_execution_code = app.exec_()

    # Restore Mission Scripting file
    logging.info("QT App terminated with status code : " +
                 str(qt_execution_code))
    logging.info("Attempt to restore original mission scripting file")
    liberation_install.restore_original_mission_scripting()
    logging.info("QT process exited with code : " + str(qt_execution_code))
예제 #25
0
    # Splash screen setup
    pixmap = QPixmap("./resources/ui/splash_screen.png")
    splash = QSplashScreen(pixmap)
    splash.show()

    # Once splash screen is up : load resources & setup stuff
    uiconstants.load_icons()
    uiconstants.load_event_icons()
    uiconstants.load_aircraft_icons()
    uiconstants.load_vehicle_icons()

    # Replace DCS Mission scripting file to allow DCS Liberation to work
    try:
        liberation_install.replace_mission_scripting_file()
    except:
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.setWindowTitle("Wrong DCS installation directory.")
        error_dialog.showMessage("Unable to modify Mission Scripting file. Possible issues with rights. Try running as admin, or please perform the modification of the MissionScripting file manually.")
        error_dialog.exec_()

    # Apply CSS (need works)
    GameUpdateSignal()

    # Start window
    window = QLiberationWindow()
    window.showMaximized()
    splash.finish(window)
    qt_execution_code = app.exec_()

    # Restore Mission Scripting file
    logging.info("QT App terminated with status code : " + str(qt_execution_code))