def _new_sink(self):
     sinks = sorted(self.Sinks.keys())
     sinks.remove('SinkSelector')
     name, ok = QInputDialog.getItem(self, "Output", "Select output device",
                                     sinks, editable=False)
     if ok:
         self.__add_sink({'name': name})
Beispiel #2
1
 def msg(self):
      #后面四个数字的作用依次是 初始值 最小值 最大值 小数点后位数
     doubleNum,ok1 = QInputDialog.getDouble(self, "标题","计数:", 37.56, -10000, 10000, 2)
      #后面四个数字的作用依次是 初始值 最小值 最大值 步幅
     intNum,ok2 = QInputDialog.getInt(self, "标题","计数:", 37, -10000, 10000, 2)
      #第三个参数可选 有一般显示 (QLineEdit.Normal)、密碼显示( QLineEdit. Password)与不回应文字输入( QLineEdit. NoEcho)
     stringNum,ok3 = QInputDialog.getText(self, "标题","姓名:",QLineEdit.Normal, "王尼玛")
      #1为默认选中选项目,True/False  列表框是否可编辑。
     items = ["Spring", "Summer", "Fall", "Winter"]
     item, ok4 = QInputDialog.getItem(self, "标题","Season:", items, 1, True)
     text, ok5 = QInputDialog.getMultiLineText(self, "标题", "Address:", "John Doe\nFreedom Street")
Beispiel #3
0
    def doBulk(self):
        qidxes = self.ui.bugList.selectionModel().selectedIndexes()
        cols = set(qidx.column() for qidx in qidxes)
        if len(cols) != 1:
            return

        col, = cols
        colname = self.mdl.headerData(col, Qt.Horizontal, Qt.DisplayRole)
        if colname not in ('status', 'assignee'):
            return

        objs = [qidx.data(ResultModel.RoleObject) for qidx in qidxes]
        project = objs[0].project
        if colname == 'status':
            vals = [status.name for status in project.statuses or []]
            val, ok = QInputDialog.getItem(self, self.tr('Bulk edit'), self.tr('Select new status for selected items'), vals, 0, False)
        elif colname == 'assignee':
            vals = [user.name for user in project.members or []]
            val, ok = QInputDialog.getItem(self, self.tr('Bulk edit'), self.tr('Select new assignee for selected items'), vals, 0, False)
        if not ok:
            return

        for obj in objs:
            change = Change()
            change.field = colname
            change.new = val

            update = Update()
            update.changes = [change]

            self.weboob.do('update_issue', obj, update, backends=(obj.backend,))
Beispiel #4
0
 def hgQueueDeletePatch(self, name):
     """
     Public method to delete a selected unapplied patch.
     
     @param name file/directory name (string)
     """
     # find the root of the repo
     repodir = self.vcs.splitPath(name)[0]
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return
     
     args = self.vcs.initCommand("qdelete")
     patchnames = sorted(self.__getPatchesList(repodir,
                                               Queues.UNAPPLIED_LIST))
     if patchnames:
         patch, ok = QInputDialog.getItem(
             None,
             self.tr("Select Patch"),
             self.tr("Select the patch to be deleted:"),
             patchnames,
             0, False)
         if ok and patch:
             args.append(patch)
             
             dia = HgDialog(self.tr("Delete Patch"), self.vcs)
             res = dia.startProcess(args, repodir)
             if res:
                 dia.exec_()
     else:
         E5MessageBox.information(
             None,
             self.tr("Select Patch"),
             self.tr("""No patches to select from."""))
Beispiel #5
0
 def on_addInstalledApiFileButton_clicked(self):
     """
     Private slot to add an API file from the list of installed API files
     for the selected lexer language.
     """
     installedAPIFiles = self.__currentAPI.installedAPIFiles()
     if installedAPIFiles:
         installedAPIFilesPath = QFileInfo(installedAPIFiles[0]).path()
         installedAPIFilesShort = []
         for installedAPIFile in installedAPIFiles:
             installedAPIFilesShort.append(
                 QFileInfo(installedAPIFile).fileName())
         file, ok = QInputDialog.getItem(
             self,
             self.tr("Add from installed APIs"),
             self.tr("Select from the list of installed API files"),
             installedAPIFilesShort,
             0, False)
         if ok:
             self.apiList.addItem(Utilities.toNativeSeparators(
                 QFileInfo(QDir(installedAPIFilesPath), file)
                 .absoluteFilePath()))
     else:
         E5MessageBox.warning(
             self,
             self.tr("Add from installed APIs"),
             self.tr("""There are no APIs installed yet."""
                     """ Selection is not available."""))
         self.addInstalledApiFileButton.setEnabled(False)
     self.prepareApiButton.setEnabled(self.apiList.count() > 0)
Beispiel #6
0
    def delFunction(self, fva, parent=None):
        if parent == None:
            parent = self

        yn, ok = QInputDialog.getItem(self, 'Delete Function', 'Confirm:', ('No', 'Yes'), 0, False)
        if ok and yn == 'Yes':
            self.vw.delFunction(fva)
    def setItem(self):    
        items = ("Spring", "Summer", "Fall", "Winter")

        item, ok = QInputDialog.getItem(self, "QInputDialog.getItem()",
                "Season:", items, 0, False)
        if ok and item:
            self.itemLabel.setText(item)
Beispiel #8
0
 def on_namedReferenceButton_clicked(self):
     """
     Private slot to handle the named reference toolbutton.
     """
     # determine cursor position as length into text
     length = self.regexpTextEdit.textCursor().position()
     
     # only present group names that occur before the
     # current cursor position
     regex = self.regexpTextEdit.toPlainText()[:length]
     names = self.namedGroups(regex)
     if not names:
         E5MessageBox.information(
             self,
             self.tr("Named reference"),
             self.tr("""No named groups have been defined yet."""))
         return
     
     groupName, ok = QInputDialog.getItem(
         self,
         self.tr("Named reference"),
         self.tr("Select group name:"),
         names,
         0, True)
     if ok and groupName:
         self.__insertString("(?P={0})".format(groupName))
 def addButtonClicked(self):
     shop = self.shopModel.record(self.list.currentIndex().row())
     query = QSqlQuery("SELECT detail.id as id, CONCAT(detail.article, \": \", detail.name) as name \
         FROM detail WHERE NOT(detail.id IN (SELECT detail_id FROM shop_detail \
             WHERE shop_id={}))".format(shop.value("id")))
     details = {}
     while query.next():
         details[query.value("name")] = query.value("id")
     if not details:
         return QMessageBox.warning(None, "Ошибка добавления",
             "Не удалось добавить новый товар на склад: все возможные товары уже добавлены.")
     choice, ok = QInputDialog.getItem(None, "Товар", "Укажите товар:",
         list(details.keys()), 0, False)
     if not ok: return
     qnt, ok = QInputDialog.getInt(None, "Количество", "Укажите количество товара:",
         1, 1)
     if not ok: return
     detail_id = details[choice]
     shop_id = shop.value("id")
     query = QSqlQuery("INSERT INTO shop_detail (shop_id, detail_id, quantity) \
         VALUES ({}, {}, {})".format(shop_id, detail_id, qnt))
     if not query.isActive():
         print(query.lastError().text())
     self.setShopIndex(self.list.currentIndex().row())
     self.table.selectionModel().clearSelection()
 def set_icon(self, icon=None):
     """Return a string with opendesktop standard icon name for Qt."""
     if not icon:
         icon = QInputDialog.getItem(None, __doc__, "<b>Choose Icon name?:",
                                     STD_ICON_NAMES, 0, False)[0]
     if icon:
         log.debug("Setting Tray Icon name to: {}.".format(icon))
         return self.setIcon(QIcon.fromTheme("{}".format(icon)))
Beispiel #11
0
def choose_from_list(title, caption, item_list, parent, current=0):
    (item_text, ok) = QInputDialog.getItem(
        parent,
        title, caption,
        item_list, current,
        editable=False)
    if ok : return item_text
    return None
Beispiel #12
0
	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in QTextCodec.availableCodecs()],
			0, False)
		if ok:
			self.currentTab.readTextFromFile(encoding)
Beispiel #13
0
	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		codecsSet = set(bytes(QTextCodec.codecForName(alias).name())
		                for alias in QTextCodec.availableCodecs())
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in sorted(codecsSet)],
			0, False)
		if ok:
			self.currentTab.readTextFromFile(None, encoding)
 def __showProfileData(self):
     """
     Private method to handle the show profile data context menu action.
     """
     itm = self.model().item(self.currentIndex())
     fn = itm.fileName()
     pfn = self.project.getMainScript(True)
     
     files = []
     
     if pfn is not None:
         tpfn = Utilities.getTestFileName(pfn)
         basename = os.path.splitext(pfn)[0]
         tbasename = os.path.splitext(tpfn)[0]
         
         f = "{0}.profile".format(basename)
         tf = "{0}.profile".format(tbasename)
         if os.path.isfile(f):
             files.append(f)
         if os.path.isfile(tf):
             files.append(tf)
     
     if fn is not None:
         tfn = Utilities.getTestFileName(fn)
         basename = os.path.splitext(fn)[0]
         tbasename = os.path.splitext(tfn)[0]
         
         f = "{0}.profile".format(basename)
         tf = "{0}.profile".format(tbasename)
         if os.path.isfile(f) and f not in files:
             files.append(f)
         if os.path.isfile(tf) and tf not in files:
             files.append(tf)
             
     if files:
         if len(files) > 1:
             pfn, ok = QInputDialog.getItem(
                 None,
                 self.tr("Profile Data"),
                 self.tr("Please select a profile file"),
                 files,
                 0, False)
             if not ok:
                 return
         else:
             pfn = files[0]
     else:
         return
         
     from DataViews.PyProfileDialog import PyProfileDialog
     self.profiledata = PyProfileDialog()
     self.profiledata.show()
     self.profiledata.start(pfn, fn)
Beispiel #15
0
 def blankStock(self):
     printTypes = ("Brother", "Breeze", "Embroidery", "Kornit")
     barcode, ok = QInputDialog.getText(self, "Enter barcode", "Please scan or enter barcode:")
     if ok:
         bc = barcode
         printType, ok = QInputDialog.getItem(self, "Select Print Type", "Print Type", printTypes, 0, True)
         if ok and printType:
             pt = printType
             quantity, ok = QInputDialog.getInt(self, "Quantity", "Please enter quantity:", 1, 0, 25, 1)
             if ok:
                 qty = quantity
                 ImportExportDB.insBlankStock(self, bc, pt, qty)
 def add_functional_dependency_closure():
     this_table = self.database.get_table(table)
     columns = this_table.columns
     column_names = list(
         map(
             lambda column: column["name"],
             columns
         )
     )
     child, ok_child = QInputDialog.getItem(
         self,
         'Add Functional Dependency',
         'Child',
         column_names,
         0,
         False
     )
     if(child):
         column_names = list(set(column_names) - set([child]))
     if(ok_child):
         ok_parent = True
         parents = []
         while(ok_parent):
             parent, ok_parent = QInputDialog.getItem(
                 self,
                 'Add Functional Dependency',
                 'Parent',
                 column_names,
                 0,
                 False
             )
             if(parent and ok_parent):
                 column_names = list(set(column_names) - set([parent]))
                 parents.append(parent)
         if(parents):
             this_table.add_functional_dependency(
                 child,
                 parents
             )
             self.update_tree_view()
 def set_icon(self, icon: (None, str)=None) -> str:
     """Return a string with opendesktop standard icon name for Qt."""
     if not icon:
         try:
             cur_idx = STD_ICON_NAMES.index(self.windowIcon().name())
         except ValueError:
             cur_idx = 0
         icon = QInputDialog.getItem(None, __doc__, "<b>Choose Icon name?:",
                                     STD_ICON_NAMES, cur_idx, False)[0]
     if icon:
         log.debug("Setting Tray and Window Icon name to:{}.".format(icon))
         self.tray.setIcon(QIcon.fromTheme("{}".format(icon)))
         self.setWindowIcon(QIcon.fromTheme("{}".format(icon)))
     return icon
 def __askForkTo(self):
     """
     Private method to ask the user which branch of a fork to follow.
     """
     selections = [self.tr("Parent Process"),
                   self.tr("Child process")]
     res, ok = QInputDialog.getItem(
         None,
         self.tr("Client forking"),
         self.tr("Select the fork branch to follow."),
         selections,
         0, False)
     if not ok or res == selections[0]:
         self.__sendCommand(DebugProtocol.ResponseForkTo + 'parent\n')
     else:
         self.__sendCommand(DebugProtocol.ResponseForkTo + 'child\n')
Beispiel #19
0
 def hgQueueGuardsDropAll(self, name):
     """
     Public method to drop all guards of the current or a named patch.
     
     @param name file/directory name (string)
     """
     # find the root of the repo
     repodir = self.vcs.splitPath(name)[0]
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return
     
     patchnames = sorted(
         self.__getPatchesList(repodir, Queues.SERIES_LIST))
     if patchnames:
         patch, ok = QInputDialog.getItem(
             None,
             self.tr("Drop All Guards"),
             self.tr("Select the patch to drop guards for"
                     " (leave empty for the current patch):"),
             [""] + patchnames,
             0, False)
         if ok:
             args = self.vcs.initCommand("qguard")
             if patch:
                 args.append(patch)
             args.append("--none")
             
             client = self.vcs.getClient()
             if client:
                 client.runcommand(args)
             else:
                 process = QProcess()
                 process.setWorkingDirectory(repodir)
                 process.start('hg', args)
                 procStarted = process.waitForStarted(5000)
                 if procStarted:
                     process.waitForFinished(30000)
     else:
         E5MessageBox.information(
             None,
             self.tr("Drop All Guards"),
             self.tr("""No patches available to define guards for."""))
 def add_column_closure():
     this_table = self.database.get_table(table)
     name, ok_column = QInputDialog.getText(
         self,
         'Add Column',
         'Column Name',
     )
     if(ok_column):
         datatype, ok_data = QInputDialog.getText(
             self,
             'Add Column',
             'Column Data Type',
         )
     if(ok_data):
         ok_flag = True
         flags = []
         flag_names = [
             "NOT NULL",
             "UNIQUE INDEX",
             "BINARY",
             "UNSIGNED",
             "ZEROFILL",
             "AUTO_INCREMENT",
         ]
         while(ok_flag):
             flag, ok_flag = QInputDialog.getItem(
                 self,
                 'Add Column',
                 'Flag',
                 flag_names,
                 0,
                 False
             )
             if(flag and ok_flag):
                 flag_names = list(set(flag_names) - set([flag]))
                 flags.append(flag)
         if(flags):
             this_table.add_column(
                 name,
                 datatype,
                 flags
             )
         self.update_tree_view()
         self.update_sql_code(self.database.export_database())
 def on_allEolFillButton_clicked(self):
     """
     Private method used to set the eolfill for all styles of a selected
     lexer.
     """
     on = self.tr("Enabled")
     off = self.tr("Disabled")
     selection, ok = QInputDialog.getItem(
         self,
         self.tr("Fill to end of line"),
         self.tr("Select fill to end of line for all styles"),
         [on, off],
         0, False)
     if ok:
         enabled = selection == on
         self.eolfillCheckBox.setChecked(enabled)
         for style in list(self.lexer.ind2style.values()):
             self.lexer.setEolFill(enabled, style)
         self.__styleAllItems()
Beispiel #22
0
    def choose_warband(self):
        """Choose a warband to be loaded into cache and then shown on screen"""
        
        # get list of save files
        warbands = show_warbands()

        # Let user choose out of save files
        wbname, okPressed = QInputDialog.getItem(self, "Choose", "Choose your warband", warbands, 0, False)
        if okPressed and wbname:
            # Load warband dictionary 
            wbdict = load_warband(wbname)
            # convert warband dict to object
            wbobj = Warband.from_dict(wbdict)
            # set chosen warband as object in main window
            self.mainwindow.wbid = wbobj

            # set empty current unit to main window
            self.mainwindow.currentunit = Character.create_template()

            # Restart the main window to force changes
            self.mainwindow.initUI() 
    def on_sampleIntensitySetButton_clicked(self):
        """ User input for correlation calculation to toggle between using all samples and only those with intensity above threshold """

        options = ("All samples", "Intensity filtered samples")
        option, ok = QInputDialog.getItem(
            self, "",
            "Calculate correlation on all samples or (relative) intensity filtered sample set: ",
            options, 0, False)

        if ok and option:

            self.Attributes['sampleIntensitySet'] = option
            self.correlationMethodText.setText(
                'Calculate correlation on all samples or (relative) intensity filtered sample set:  '
                + self.Attributes['sampleIntensitySet'])

            if self.Attributes['sampleIntensitySet'] == 'All samples':
                self.Attributes['sampleIntensityThreshold'] = None
                self.sampleIntensityThresholdText.setText(
                    'Driver (relative) intensity threshold for defining sample set for correlation calculation: '
                    + str(self.Attributes['sampleIntensityThreshold']))
Beispiel #24
0
    def kategoriSil(self):
        item, okPressed = QInputDialog.getItem(self, "Kategori Silme İşlemi",
                                               "Silineek Kategoriyi Seçin:",
                                               self.kategoriListesi, 0, False)
        if okPressed and item:
            if item != "Kategori Seçin":
                try:
                    with conn:
                        cur = conn.cursor()
                        cur.execute("DELETE FROM GRUPLAR Where GRUP_ADI=(?)",
                                    [item])

                    self.kategoriListesi.remove(item)
                    self.ui.comboBox.clear()
                    self.ui.comboBox.addItems(self.kategoriListesi)
                    self.ui.listWidget.clear()
                    self.ui.listWidget.addItems(self.kelimeListesi)
                    QMessageBox.information(self, "Kategroi Silme",
                                            "Kategori Silindi")
                except Exception as e:
                    print(e)
Beispiel #25
0
    def run(self):
        """

        User's menu for defining starting level of client

        """
        self.chose_user, okBtnPressed = QInputDialog.getItem(
            self, "Выберите ваш уровеньзнания английского",
            "Выберите ваш уровеньзнания английского",
            ('A1 - beginner ', 'A2 - elementary', 'B1 - pre-intermediate',
             'B2 - intermediate', 'C1 - upper-intermediate', 'C2 - advanced'),
            1, False)
        self.chose_user = self.chose_user[:2]

        name, okBtnPressed_2 = QInputDialog.getText(self, "Введите имя",
                                                    "Как тебя зовут?", False)
        self.user.create_user(person, name, self.chose_user)

        print(self.user.level, self.user.name)

        return [self.chose_user, self.user.name]
Beispiel #26
0
def choose_device(app, args, dev, name, def1, set1):
    devs = dev.get_devices()
    if len(devs) == 0:
        exit_error(app, 'no {} found'.format(name), ValueError)
    elif def1 is not None and def1 not in devs:
        exit_error(
            app, '{d} {n} not detected, available {d} are {ll}'.format(
                d=name, n=def1, ll=str(devs)), ValueError)
    elif def1 is None:
        if len(devs) == 1:
            set1(devs[0])
        else:
            if app:
                item, ok = QInputDialog.getItem(
                    None, '', 'select ' + name + ':', devs, 0, False)
                if ok and item:
                    set1(item)
                else:
                    sys.exit(0)
            else:
                raise ValueError('must specify a device name')
    def open_teamf(self):
        try:
            teams = items_combobox()
            list = []
            for i in teams:
                list.append(*i)
            con_tup = tuple(list)
            items = con_tup
            item, ok = QInputDialog.getItem(self, "select input dialog",
                                            "Open a Team", items, 0, False)
            if ok and item:
                players_in_team = opening_team(item)
                self.list_2.clear()
                for i in players_in_team:
                    self.list_2.addItem(*i)
                    self.update_labels()

        except Exception as ex:
            template = "An exception of type {0} occurred. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)
 def on_addPluginApiFileButton_clicked(self):
     """
     Private slot to add an API file from the list of API files installed
     by plugins for the selected lexer language.
     """
     pluginAPIFiles = self.pluginManager.getPluginApiFiles(
         self.currentApiLanguage)
     pluginAPIFilesDict = {}
     for apiFile in pluginAPIFiles:
         pluginAPIFilesDict[QFileInfo(apiFile).fileName()] = apiFile
     file, ok = QInputDialog.getItem(
         self,
         self.tr("Add from Plugin APIs"),
         self.tr(
             "Select from the list of API files installed by plugins"),
         sorted(pluginAPIFilesDict.keys()),
         0, False)
     if ok:
         self.apiList.addItem(Utilities.toNativeSeparators(
             pluginAPIFilesDict[file]))
     self.prepareApiButton.setEnabled(self.apiList.count() > 0)
    def dialog_new_magic(mainwindow):
        records = load_reference("magics")

        # categories
        categories = []
        for record in records:
            pk = record.primarykey
            category = record.recorddict["category"]
            subcategory = record.recorddict["name"]
            source = record.recorddict["source"]
            text = f"{pk}-{source}-{category}-{subcategory}"
            categories.append(text)

        magic, okPressed = QInputDialog.getItem(mainwindow, "Select Magic", "Choose a Magic", categories, 0, False)
        if okPressed and magic:

            # take the primary key from the chosen awnser and get the python object
            pk = int(magic.split('-', 1)[0])
            new_magic = Magic.from_database(primarykey=pk)

            return new_magic
Beispiel #30
0
 def on_addPluginApiFileButton_clicked(self):
     """
     Private slot to add an API file from the list of API files installed
     by plugins for the selected lexer language.
     """
     pluginAPIFiles = self.pluginManager.getPluginApiFiles(
         self.currentApiLanguage)
     pluginAPIFilesDict = {}
     for apiFile in pluginAPIFiles:
         pluginAPIFilesDict[QFileInfo(apiFile).fileName()] = apiFile
     file, ok = QInputDialog.getItem(
         self,
         self.tr("Add from Plugin APIs"),
         self.tr(
             "Select from the list of API files installed by plugins"),
         sorted(pluginAPIFilesDict.keys()),
         0, False)
     if ok:
         self.apiList.addItem(Utilities.toNativeSeparators(
             pluginAPIFilesDict[file]))
     self.prepareApiButton.setEnabled(self.apiList.count() > 0)
Beispiel #31
0
 def install_info(self):
     """
     This is a dialog box to warn the user. If you are on the robot, you are 
     prompted for the install directory, although we can't actually move the
     application to the install directory for you. We tell the user this, and
     let them know they will have to move the application to this directory
     at the end of the process. 
     """
     #TODO make note of this in the FAQ- moving into wrong dir could break the app
     layout = QVBoxLayout()
     dialog = QInputDialog()
     layout.addWidget(dialog)
     item, ok = dialog.getItem(
                  QWidget(),
                  'Chosen Install Directory',
                  'Once the install process has finished, you must copy the application over into its final destination, which you just chose. Be sure to write it down if needed, the install process can take up to twenty minutes on a clean machine.\nThe install directory you chose is:\n{}'.format(self.install_directory),
                  ['OK'],
     )
     if ok:
         self.catkin_directory()
     return layout
Beispiel #32
0
 def onCloseFiles(self):
     # 关闭文件
     item, ok = QInputDialog.getItem(
         self, self.tr('关闭方式'),
         self.tr('all=true关闭所有打开的文件,忽略files参数\n否则只关闭files参数指定的文件'),
         ['True', 'Files'], 0, False)
     if not ok:
         return
     if item == 'True':
         self.setParams({
             'method': 'closeFiles',
             'all': True
         }, '\n\nall=true 关闭所有打开的文件并忽略 files参数\nfiles=[...] 只关闭files参数指定的文件'
                        )
         return
     if self._files:
         self.setParams({
             'method': 'closeFiles',
             'files': self._files
         }, '\n\nall=true 关闭所有打开的文件并忽略 files参数\nfiles=[...] 只关闭files参数指定的文件'
                        )
Beispiel #33
0
 def copy_test(self):
     item, ok = QInputDialog.getItem(self, "Выбор проекта", "Проект",
                                     tuple(self.projects), 0, False)
     if ok and item:
         cur_path = os.path.join(self.path, self.current_project,
                                 self.current_test)
         new_path = os.path.join(self.path, item,
                                 self.current_test + "-copy")
         try:
             os.mkdir(new_path)
             paths = [
                 i for i in os.listdir(
                     os.path.join(self.path, self.current_project,
                                  self.current_test))
                 if ('.xlsx' in i) or ('.data' in i)
             ]
             for p in paths:
                 shutil.copy(os.path.join(cur_path, p), new_path)
         except FileExistsError:
             QMessageBox.about(self, "Предупреждение",
                               "Копия уже была создана")
    def connect_conditioner_by_usb(self):
        self.connection_type = 'USB'

        items =[] 
        for device in serial.tools.list_ports.comports():
            items.append("{} - {}".format(device.device, device.description))
        logger.debug(items)
        com_port, okPressed = QInputDialog.getItem(self, "Select COM Port","CAN Logger USB Serial Port:", items, 0, False)
        if okPressed and com_port:
            logger.debug("Selected: {}".format(com_port))
            self.comport = com_port.split('-')[0].strip()
        else:
            return
        logger.debug("Trying to connect USB serial.")
        try:
            self.ser.close()
            del self.ser
        except AttributeError:
            pass

        try:
            self.ser = serial.Serial(self.comport)
            self.ser.set_buffer_size(rx_size = 2147483647, tx_size = 2000)
            self.connected = True
            logger.debug("Connected to Serial Port.")
            self.serial_queue = queue.Queue()
            self.serial_thread = SerialListener(self.serial_queue,self.ser)
            self.serial_thread.setDaemon(True) #needed to close the thread when the application closes.
            self.serial_thread.start()
            logger.debug("Started Serial Thread.")

            return True
        except serial.serialutil.SerialException:
            logger.debug(traceback.format_exc())
            self.connected = False
            if "PermissionError" in repr(traceback.format_exc()):
                QMessageBox.information(self,"USB Status","The port {} is already in use. Please unplug and replug the unit.".format(self.comport))
            else:
                self.connected = False
                return False
Beispiel #35
0
    def hgQueueGuardsDropAll(self, name):
        """
        Public method to drop all guards of the current or a named patch.
        
        @param name file/directory name (string)
        """
        # find the root of the repo
        repodir = self.vcs.splitPath(name)[0]
        while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
            repodir = os.path.dirname(repodir)
            if os.path.splitdrive(repodir)[1] == os.sep:
                return

        patchnames = sorted(self.__getPatchesList(repodir, Queues.SERIES_LIST))
        if patchnames:
            patch, ok = QInputDialog.getItem(
                None, self.tr("Drop All Guards"),
                self.tr("Select the patch to drop guards for"
                        " (leave empty for the current patch):"),
                [""] + patchnames, 0, False)
            if ok:
                args = self.vcs.initCommand("qguard")
                if patch:
                    args.append(patch)
                args.append("--none")

                client = self.vcs.getClient()
                if client:
                    client.runcommand(args)
                else:
                    process = QProcess()
                    process.setWorkingDirectory(repodir)
                    process.start('hg', args)
                    procStarted = process.waitForStarted(5000)
                    if procStarted:
                        process.waitForFinished(30000)
        else:
            E5MessageBox.information(
                None, self.tr("Drop All Guards"),
                self.tr("""No patches available to define guards for."""))
Beispiel #36
0
    def del_region(self):
        items = (self.region_dict.values())
        name_list = []
        for item in items:
            name_list.append(item[0])
        # items = ("Red","Blue","Green")
        item, okPressed = QInputDialog.getItem(self, "Select Region",
                                               "Delete Regions:", name_list, 0,
                                               False)
        if okPressed and item:
            for index, value in enumerate(items):
                print(value)
                if item in value:
                    if self.log is not None:
                        self.log(str(("Deleting " + str(item))))

                    # key = items.index(index)
                    # print(items)
                    key = list(self.region_dict.keys())[index]
                    print("KEY", key)
                    del self.region_dict[key]
                    return
Beispiel #37
0
    def export_case_attribute_log(project,progress_dialog):
        file_path, ok = QFileDialog.getSaveFileName(None,None,"Save Log",options=QFileDialog.DontUseCustomDirectoryIcons,filter="CSV files (*.csv)")
        if not ok:
            return False
        delimiterList = ["; (Semicolon)", ", (Coma)", "\\t (TAB)", " (SPACE)", "Other"]
        delimiter, ok = QInputDialog.getItem(None, "Chose the Delimiter", "Delimiter:", delimiterList)
        if not ok:
            return False
        option = delimiterList.index(delimiter)
        if option == 0:
            delimiter = ";"
        elif option == 1:
            delimiter = ","
        elif option == 2:
            delimiter = "\t"
        elif option == 3:
            delimiter = " "
        elif option == 4:
            delimiter, ok = QInputDialog.getText(None, "Type your Custom Delimiter", "Delimiter")
            if not ok:
                return False
        ret = QMessageBox().question(None, '', "Does your file contains a legend row?",
                                     QMessageBox.Yes | QMessageBox.No)

        if ret == QMessageBox.Yes:
            keep_legend_bool = True
        else:
            keep_legend_bool = False

        if len(project.case_attribute_model)>1:
            ret = QMessageBox().question(None, '', "Your Project has more than 1 attribute Model.\nDo you want to export the first one?\n",                                         QMessageBox.Yes | QMessageBox.Cancel)
            if ret == QMessageBox.Cancel:
                return False

        progress_dialog.show()
        project.export_case_attribute_log(file_path,progress_dialog,keep_legend_bool,delimiter)
        progress_dialog.close()

        return True
Beispiel #38
0
 def delete(self):
     i, okBtnPressed = QInputDialog.getItem(self, "Вы уверены", "Вы уверены?", ("Да", "Нет"), 1, False)
     if okBtnPressed:
         if i == 'Нет':
             oImage = QImage('Стандарт.jpg')
             sImage = oImage.scaled(QSize(900, 700), Qt.KeepAspectRatioByExpanding, transformMode = Qt.SmoothTransformation)
             palette = QPalette()
             palette.setBrush(QPalette.Window, QBrush(sImage))
             self.setPalette(palette)        
             self.show()                
             return
     else:
         oImage = QImage('Стандарт.jpg')
         sImage = oImage.scaled(QSize(900, 700), Qt.KeepAspectRatioByExpanding, transformMode = Qt.SmoothTransformation)
         palette = QPalette()
         palette.setBrush(QPalette.Window, QBrush(sImage))
         self.setPalette(palette)        
         self.show()            
         return
     for currentdir, dirs, files in os.walk(self.a):
         for el in files:        
             shutil.move(self.a + '\\' + el, '0trash' + '\\' + el)
Beispiel #39
0
    def getOpenCLPlatform(self):
        # Pop dialogs to get user to choose OpenCL platform
        platforms = cl.get_platforms()

        platlist = [str(p.name) for p in platforms]
        platdict = dict(list(zip(platlist, list(range(len(platlist))))))

        if len(platlist) == 1:
            self.clPlatformNum = 0
            return True

        qsPlatformName, ok = QInputDialog.getItem(self, \
                                            'Choose OpenCL platform', \
                                            'Available platforms:', \
                                            platlist, \
                                            editable=False)
        if not ok:
            print("You didn't select a OpenCL platform...")
            return False
        else:
            self.clPlatformNum = platdict[qsPlatformName]
            return True
Beispiel #40
0
    def create_warband(self):
        """Create a new warband and store it in cache"""
        name, okPressed = QInputDialog.getText(self, "Create", "Name your warband:")
        if okPressed and name:
            
            # get all warbands from the database
            wbtable = load_reference("warbands")
            if wbtable == None:
                QMessageBox(self, f"Error", f"Could not load database files")
                return

            # create a list of choices
            warbands = []
            for record in wbtable:
                pk = record.primarykey
                race = record.recorddict["race"]
                source = record.recorddict["source"]
                base = record.recorddict["base"]
                warbandtext = f"{pk}-{race}-{source}-{base}"

                warbands += [warbandtext]
            
            # let user choose from the list
            warband, okPressed = QInputDialog.getItem(self, "Create", "Choose a warband", warbands, 0, False)
            if okPressed and warband:
                
                # take the primary key from the chosen awnser and get the python object
                pk = int(warband.split('-', 1)[0])
                warband_object = Warband.from_database(primarykey=pk)
                warband_object.name = name

                # Load warband object to main window
                self.mainwindow.wbid = warband_object

                # set an empty character as currentunit
                self.mainwindow.currentunit = Character.create_template()
                
                # restart ui to force changes
                self.mainwindow.initUI()
 def delete_node(self):
     nodes = [
         item for item in self.graphicsView.scene().items()
         if isinstance(item, Node)
     ]
     if not nodes:
         QMessageBox.critical(self, "Warning!",
                              "There are no nodes on the graph.")
         return
     node_selected, ok = QInputDialog.getItem(self, "Delete Node", "Node: ",
                                              [node.name for node in nodes],
                                              0, False)
     if ok:
         delete_choice = QMessageBox.question(
             self, "Delete Node",
             "Are you sure you want to delete %s and all its edges?" %
             (node_selected), QMessageBox.Yes | QMessageBox.No)
         if delete_choice == QMessageBox.No:
             return
         node = [node for node in nodes if node.name == node_selected][0]
         node_count = node.getNodesToUpdate()
         i = 0
         while len(node_count) > 0:
             if i < len(
                     node.getNodesToUpdate()[0].edges()
             ) and node.getNodesToUpdate()[0].edges()[i].destNode() == node:
                 self.graphicsView.scene().removeItem(
                     node.getNodesToUpdate()[0].edges()[i])
                 node.getNodesToUpdate()[0].deleteEdge(i)
             else:
                 if node_count != node.getNodesToUpdate():
                     node_count = node.getNodesToUpdate()
                     i = 0
                 else:
                     i += 1
         while len(node.edges()):
             self.graphicsView.scene().removeItem(node.popEdge())
         self.graphicsView.scene().removeItem(node)
     return
Beispiel #42
0
 def clickAct(self, event):
     sender = self.sender()
     if sender == self.btn_1:
         text, ok = QInputDialog.getText(self, "修改姓名", "请输入姓名:")
         if ok:
             self.label_1.setText(text)
     if sender == self.btn_2:
         text, ok = QInputDialog.getInt(self, '修改年龄', '请输入年龄:', min=1)
         if ok:
             self.label_2.setText(str(text))
     if sender == self.btn_3:
         text, ok = QInputDialog.getItem(self, "修改性别", "请选择性别", ['男', '女'])
         if ok:
             self.label_3.setText(text)
     if sender == self.btn_4:
         text, ok = QInputDialog.getDouble(self, "修改身高", "修改身高", min=1.0)
         if ok:
             self.label_4.setText(str(text))
     if sender == self.btn_5:
         text, ok = QInputDialog.getMultiLineText(self, "修改简介", "修改简介")
         if ok:
             self.textBrowser.setText(str(text))
Beispiel #43
0
 def mouseDoubleClickEvent(self, event):
     x = event.x()
     y = event.y()
     for obj in self.coordinates:
         x_o = self.coordinates[obj][0] + 300
         y_o = self.coordinates[obj][1] + 10
         if (x_o - self.rect_gr // 2 < x < x_o + self.rect_gr
                 and y_o - self.rect_gr // 2 < y < y_o + self.rect_gr):
             value, flag = QInputDialog.getItem(self, 'сюда или отсюда',
                                                'отсюда или сюда?',
                                                ('сюда', 'отсюда'), 1,
                                                False)
             if flag:
                 if value == 'отсюда':
                     self.start_point = obj
                     self.start_lbl.setText(
                         self.dict_of_names[self.start_point])
                 else:
                     self.end_point = obj
                     self.end_lbl.setText(
                         self.dict_of_names[self.end_point])
             break
Beispiel #44
0
    def create_new(self):
        """Create a new squad and store it in this warband"""

        name, okPressed = QInputDialog.getText(self, "Create",
                                               "Name your squad:")
        if okPressed and name:

            # get applicable characters to choose from
            character_list = self.mainwindow.wbid.get_characters()
            categories = []

            for character in character_list:
                if character.recorddict["ishero"] == 0:
                    pk = character.primarykey
                    category = character.recorddict["name"]
                    charactertext = f"{pk}-{category}"
                    categories.append(charactertext)

            category, okPressed = QInputDialog.getItem(self, "Create",
                                                       "Choose a category",
                                                       categories, 0, False)
            if okPressed and category:
                # take the primary key from the chosen awnser and get the character object
                pk = int(category.split('-', 1)[0])
                new_squad = Squad.from_database(primarykey=pk, name=name)
                new_squad.name = name

                wbidgold = self.mainwindow.wbid.treasury.gold
                squadprice = new_squad.get_price(
                ) * new_squad.get_totalhenchman()

                if wbidgold >= squadprice:
                    self.mainwindow.wbid.treasury.gold = wbidgold - squadprice
                    self.mainwindow.wbid.squadlist.append(new_squad)
                    self.mainwindow.currentunit = new_squad.henchmanlist[0]
                    self.mainwindow.initUI()
                else:
                    QMessageBox.information(self, "Can't add squad!",
                                            "Lack of funds!", QMessageBox.Ok)
Beispiel #45
0
    def openMenuCam(self):
        '''create a message box to choose a camera
        '''
        items = cameraIds
        item, ok = QInputDialog.getItem(self,
                                        "Select Guppy camera",
                                        "List of avaible camera",
                                        items,
                                        0,
                                        False,
                                        flags=QtCore.Qt.WindowStaysOnTopHint)

        if ok and item:
            items = list(items)
            index = items.index(item)
            self.cam0 = Vimba().camera(cameraIds[index])
            self.isConnected = True
            self.nbcam = 'camDefault'
            self.camID = cameraIds[index]
        if self.isConnected == True:
            self.setCamParameter()
        return self.isConnected
Beispiel #46
0
    def configure_ip(self):
        """
        Prompt user for whether they want custom IP and hostnames.

        If yes, next window is called and gets them. Else we execute
        the install process.
        """
        QMessageBox.about(
            self.window, "Custom IP Address Configuration",
            "The remote computer and the base computer each need to know " +
            "their Internet Protocol (IP) addresses in order to " +
            "communicate with each other across an Ethernet network.\n\n" +
            "The next screen will ask if you would like to use some default " +
            "IP addresses and hostnames that" +
            "we have assigned, or if you would like to input " +
            "your own.\n\n" + "[Hostname]\t[IP]" +
            "\n--------------------------------------------------" +
            "\nrobot\t\t10.0.0.2" + "\nbase\t\t10.0.0.1")

        layout = QVBoxLayout()
        dialog = QInputDialog()
        layout.addWidget(dialog)
        item, ok = dialog.getItem(
            QWidget(),
            'Configuring IPs',
            'Use default IP configurations?',
            ['Yes', 'No'],
        )
        if ok:
            if str(item).lower() == "no":
                self.get_custom_ip_settings()
            elif str(item).lower() == "yes":
                self.exec_install()
            else:
                self.invalid_input()
                self.configure_ip()
        else:
            self.first_page()
        return layout
Beispiel #47
0
    def on_namedReferenceButton_clicked(self):
        """
        Private slot to handle the named reference toolbutton.
        """
        # determine cursor position as length into text
        length = self.regexpTextEdit.textCursor().position()

        # only present group names that occur before the
        # current cursor position
        regex = self.regexpTextEdit.toPlainText()[:length]
        names = self.namedGroups(regex)
        if not names:
            E5MessageBox.information(
                self, self.tr("Named reference"),
                self.tr("""No named groups have been defined yet."""))
            return

        groupName, ok = QInputDialog.getItem(self, self.tr("Named reference"),
                                             self.tr("Select group name:"),
                                             names, 0, True)
        if ok and groupName:
            self.__insertString("(?P={0})".format(groupName))
Beispiel #48
0
    def create_new(self):
        """Create a new hero, store it in the warband object and set to currentunit"""
        name, okPressed = QInputDialog.getText(self, "Create",
                                               "Name your hero:")
        if okPressed and name:

            # get applicable characters to choose from
            character_list = self.mainwindow.wbid.get_characters()
            categories = []

            for character in character_list:
                print(character.recorddict)
                if character.recorddict["ishero"] == 1:
                    pk = character.primarykey
                    category = character.recorddict["name"]
                    charactertext = f"{pk}-{category}"
                    categories.append(charactertext)

            category, okPressed = QInputDialog.getItem(self, "Create",
                                                       "Choose a character",
                                                       categories, 0, False)
            if okPressed and category:
                # take the primary key from the chosen awnser and get the character object
                pk = int(category.split('-', 1)[0])
                new_hero = Hero.from_database(primarykey=pk)
                new_hero.name = name

                # add hero to warband and deduct from gold
                wbidgold = self.mainwindow.wbid.treasury.gold
                if wbidgold >= new_hero.price:
                    self.mainwindow.wbid.treasury.gold = wbidgold - new_hero.price
                    self.mainwindow.wbid.herolist.append(new_hero)
                    self.mainwindow.currentunit = new_hero
                    self.mainwindow.initUI()
                else:
                    message = QMessageBox.information(
                        self, 'Lack of funds!',
                        "Can't add new hero, lack of funds", QMessageBox.Ok)
Beispiel #49
0
    def initData(self):

        self.startPoint = QPoint(28, 64)
        self.goalPoint = QPoint(40, 70)
        self.data = np.zeros((self.MapWidth, self.MapHeight))
        self.data.fill(np.inf)
        for y in range(5, 75):
            self.data[33][y] = -1
        for x in range(5, 34):
            self.data[x][75] = -1
        self.par = np.empty((self.MapWidth, self.MapHeight), dtype=tuple)
        self.par.fill((-1, -1))

        dic = {
            "Distance 0":
            lambda x, y: 0,
            "Euclidean Distance":
            lambda x, y: np.hypot(x - self.goalPoint.x(), y - self.goalPoint.y(
            )),
            "Manhattan Distance":
            lambda x, y: np.abs(x - self.goalPoint.x()) + np.abs(
                y - self.goalPoint.y()),
            "Diagonal Distance":
            self.diagonal
        }

        htype, choosed = QInputDialog.getItem(self, "Choose Heuristic",
                                              "Choose Heuristic:", dic.keys(),
                                              0, False)
        if not choosed:
            exit(-1)
        self.h = dic[htype]

        self.queue = queue.PriorityQueue()
        self.data[self.startPoint.x()][self.startPoint.y()] = 0
        self.queue.put((self.f(0, self.startPoint.x(), self.startPoint.y()), 0,
                        self.startPoint.x(), self.startPoint.y()))
        self.found = False
 def del_row(self, AdminWindow):  #Delete selected query
     queries = []
     queries_text = []
     conn = sqlite3.connect('Covid.db')
     cursor = conn.cursor()
     query = '''select query_title from queries;'''
     cursor.execute(query)
     info = cursor.fetchall()
     for q in info:
         for x in q:
             queries.append(
                 x)  #List of queries in queries table(contains image query)
     query = '''select query_title from queries_text;'''
     cursor.execute(query)
     info2 = cursor.fetchall()
     for q in info2:
         for x in q:
             queries_text.append(
                 x
             )  #List of queries in queries_text table (contains test output query)
     all_queries = queries + queries_text  #Combines both list
     data = QInputDialog.getItem(AdminWindow, "List of Queries", "Query",
                                 all_queries)  #Open a dropwdown dialog
     print(data)
     name = data[0]  #Name of query
     ok = data[1]  #True or False
     if ok:  #If user has selected any option
         if (name in queries
             ):  #If the selected query name is from queries list
             cursor.execute("DELETE FROM queries WHERE query_title = ?",
                            (name, ))  #Delete query
             conn.commit()
             conn.close()
         if (name in queries_text):  #If query is from query_text list
             cursor.execute("DELETE FROM queries_text WHERE query_title=?",
                            (name, ))  #Delete query
             conn.commit()
             conn.close()
Beispiel #51
0
    def on_btn_filter_clicked(self):
        list = ["指定源IP地址", "指定目的IP地址", "指定源端口", "指定目的端口", "指定协议类型", "自定义规则"]

        #第三个参数可选 有一般显示 (QLineEdit.Normal)、密碼显示( QLineEdit. Password)与不回应文字输入( QLineEdit. NoEcho)
        #stringNum,ok3 = QInputDialog.getText(self, "标题","姓名:",QLineEdit.Normal, "王尼玛")
        #1为默认选中选项目,True/False  列表框是否可编辑。
        item, ok = QInputDialog.getItem(self, "选项", "规则列表", list, 1, False)
        type = 0
        if ok:
            if item == "指定源IP地址":
                filter, ok_1 = QInputDialog.getText(self, "标题", "请输入指定源IP地址:",
                                                    QLineEdit.Normal,
                                                    "*.*.*.*")
                rule = "src host " + filter
            elif item == "指定目的IP地址":
                filter, ok_2 = QInputDialog.getText(self, "标题", "请输入指定目的IP地址:",
                                                    QLineEdit.Normal,
                                                    "*.*.*.*")
                rule = "dst host " + filter
            elif item == "指定源端口":
                filter, ok_3 = QInputDialog.getInt(self, "标题", "请输入指定源端口:", 80,
                                                   0, 65535)
                rule = "src port " + str(filter)
            elif item == "指定目的端口":
                filter, ok_4 = QInputDialog.getInt(self, "标题", "请输入指定目的端口:",
                                                   80, 0, 65535)
                rule = "dst port " + str(filter)
            elif item == "指定协议类型":
                filter, ok_2 = QInputDialog.getText(self, "标题", "请输入指定协议类型:",
                                                    QLineEdit.Normal, "icmp")
                rule = filter
            elif item == "自定义规则":
                filter, ok_2 = QInputDialog.getText(self, "标题", "请输入规则:",
                                                    QLineEdit.Normal,
                                                    "host 202.120.2.1")
                rule = filter
            rule = rule.lower()
            self.set_filter(rule)
Beispiel #52
0
 def qwerty(self): #функция перехода из одной раскладки в другую
     ru_en = {'а': 'f', 'б': ',', 'в': 'd', 'г': 'u', 'д': 'l', 'е': 't',
                 'ё': '`', 'ж': ';', 'з': 'p', 'и': 'b', 'й': 'q',
                 'к': 'r', 'л': 'k', 'м': 'v', 'н': 'y', 'о': 'j', 'п': 'g',
                 'р': 'h', 'с': 'c', 'т': 'n', 'у': 'e', 'ф': 'a',
                 'х': '[', 'ц': 'w', 'ч': 'x', 'ш': 'i', 'щ': 'o',
                 'ы': 's', 'э': '\'', 'ю': '.', 'я': 'z', 'ь': 'm',
                 'ъ': ']', 'Э': '"', 'Ж': ':', 'Ъ': '}', 'Х': '{', 'Б': '<',
                 'Ю': '>', '.': '/', ',': '?'}
     en_ru = dict([(v, k) for k, v in ru_en.items()]) #обратный словарь
     print(en_ru)
     i, okBtnPressed = QInputDialog.getItem(
         self, "Раскладка", "Из какой раскладки вы хотите перевод?",
         ('русская', 'английская'), 1, False) 
     if okBtnPressed:
         text = self.fin.read()
         n_text = ''
         if i == 'русская':
             for letter in text:
                 if letter in ru_en:
                     n_text += ru_en[letter]
                 elif letter.lower() in ru_en:
                     n_text += ru_en[letter.lower()].upper()
                 else:
                     n_text += letter
         else:
             for letter in text:
                 if letter in en_ru:
                     n_text += en_ru[letter]
                 elif letter.lower() in en_ru:
                     n_text += en_ru[letter.lower()].upper()
                 else:
                     n_text += letter
         self.fout.write(n_text)
         self.fout.close()
         self.end.show()
         for button in self.buttons:
             button.setEnabled(False) 
 def add_primary_key_closure():
     this_table = self.database.get_table(table)
     columns = this_table.columns
     primary_keys = this_table.primary_keys
     column_names = list(
         map(
             lambda column: column["name"],
             columns
         )
     )
     column_names = list(set(column_names) - set(primary_keys))
     primary_key, ok_primary_key = QInputDialog.getItem(
         self,
         'Add Primary Key',
         'Primary Key',
         column_names,
         0,
         False
     )
     if(ok_primary_key):
         this_table.add_primary_key(primary_key)
         self.update_tree_view()
         self.update_sql_code(self.database.export_database())
Beispiel #54
0
 def addButtonClicked(self):
     order = self.form.currentRecord()
     query = QSqlQuery("SELECT detail.id as id, CONCAT(detail.article, \": \", detail.name) as name \
         FROM detail WHERE NOT(detail.id IN (SELECT detail_id FROM order_detail \
             WHERE order_id={}))".format(order.value("id")))
     details = {}
     while query.next():
         details[query.value("name")] = query.value("id")
     if not details:
         return QMessageBox.warning(None, "Ошибка добавления",
             "Не удалось добавить новый товар к заказу: все возможные товары уже добавлены.")
     choice, ok = QInputDialog.getItem(None, "Товар", "Укажите товар:",
         list(details.keys()), 0, False)
     if not ok: return
     qnt, ok = QInputDialog.getInt(None, "Количество", "Укажите количество товара:", 1, 1)
     if not ok: return
     detail_id = details[choice]
     order_id = order.value("id")
     query = QSqlQuery("INSERT INTO order_detail (order_id, detail_id, quantity) \
         VALUES ({}, {}, {})".format(order_id, detail_id, qnt))
     if not query.isActive():
         print(query.lastError().text())
     self.form.update()
Beispiel #55
0
 def hgQueuePushPopPatches(self, name, operation, all=False, named=False,
                           force=False):
     """
     Public method to push patches onto the stack or pop patches off the
     stack.
     
     @param name file/directory name (string)
     @param operation operation type to be performed (Queues.POP,
         Queues.PUSH, Queues.GOTO)
     @keyparam all flag indicating to push/pop all (boolean)
     @keyparam named flag indicating to push/pop until a named patch
         is at the top of the stack (boolean)
     @keyparam force flag indicating a forceful pop (boolean)
     @return flag indicating that the project should be reread (boolean)
     @exception ValueError raised to indicate an invalid operation
     """
     # find the root of the repo
     repodir = self.vcs.splitPath(name)[0]
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return False
     
     if operation == Queues.POP:
         args = self.vcs.initCommand("qpop")
         title = self.tr("Pop Patches")
         listType = Queues.APPLIED_LIST
     elif operation == Queues.PUSH:
         args = self.vcs.initCommand("qpush")
         title = self.tr("Push Patches")
         listType = Queues.UNAPPLIED_LIST
     elif operation == Queues.GOTO:
         args = self.vcs.initCommand("qgoto")
         title = self.tr("Go to Patch")
         listType = Queues.SERIES_LIST
     else:
         raise ValueError("illegal value for operation")
     args.append("-v")
     if force:
         args.append("--force")
     if all and operation in (Queues.POP, Queues.PUSH):
         args.append("--all")
     elif named or operation == Queues.GOTO:
         patchnames = self.__getPatchesList(repodir, listType)
         if patchnames:
             patch, ok = QInputDialog.getItem(
                 None,
                 self.tr("Select Patch"),
                 self.tr("Select the target patch name:"),
                 patchnames,
                 0, False)
             if ok and patch:
                 args.append(patch)
             else:
                 return False
         else:
             E5MessageBox.information(
                 None,
                 self.tr("Select Patch"),
                 self.tr("""No patches to select from."""))
             return False
     
     dia = HgDialog(title, self.vcs)
     res = dia.startProcess(args, repodir)
     if res:
         dia.exec_()
         res = dia.hasAddOrDelete()
         self.vcs.checkVCSStatus()
     return res
Beispiel #56
0
def get_or_set_config():
    """Get config if exist else Set config if not exist."""
    global config
    log.debug("Vacap Config File: {}.".format(CONFIG_FILENAME))
    days = ["Lunes", "Martes", "Miercoles",
            "Jueves", "Viernes", "Sabado", "Domingo"]
    # if config does not exist or cant be read then try to create it, ask user.
    if not os.path.isfile(CONFIG_FILENAME):
        log.warning("Vacap Config File does not exist; Will try to create it.")
        QMessageBox.information(None, __doc__, "<b>Vamos a Configurar Vacap!.")
        msg = "<b>Hacer un Backup Copia de Seguridad al Iniciar la compu ?."
        _st = QMessageBox.question(
            None, __doc__, msg, QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No) == QMessageBox.Yes
        msg = "<b>Hacer Backup Copia de Seguridad si la compu esta a Bateria ?"
        _bt = QMessageBox.question(
            None, __doc__, msg, QMessageBox.Yes | QMessageBox.No,
            QMessageBox.Yes) == QMessageBox.Yes
        msg = "<b>Que Dia de la Semana Hacer Backup Copia de Seguridad ?."
        _day = str(QInputDialog.getItem(
            None, __doc__, msg, days, 4, False)[0]).lower()
        msg = "<b>A que Hora del Dia hacer Hacer Backup Copia de Seguridad ?."
        _hour = int(QInputDialog.getInt(None, __doc__, msg, 12, 1, 23)[0])
        msg = "<b>Donde Guardar el Backup Copia de Seguridad ?."
        QMessageBox.information(None, __doc__, msg)
        _trg = QFileDialog.getExistingDirectory(None, __doc__, gettempdir())
        msg = "<b>Agregar 1 Carpeta para hacer Backup Copia de Seguridad ?."
        _backup_from = []
        while QMessageBox.question(
            None, __doc__, msg, QMessageBox.Yes | QMessageBox.No,
                QMessageBox.Yes) == QMessageBox.Yes:
            _backup_from.append(str(QFileDialog.getExistingDirectory(
                None, __doc__, os.path.expanduser("~"))))
        configura = {
            "MAKE_BACKUP_FROM": _backup_from,
            "SAVE_BACKUP_TO": _trg,
            "MAKE_BACKUP_ON_STARTUP": _st,
            "MAKE_BACKUP_WHEN_RUNNING_ON_BATTERY": _bt,
            "MAKE_BACKUP_ON_WEEK_DAY": _day,
            "MAKE_BACKUP_AT_THIS_HOUR": _hour,
        }
        config = dumps(configura, ensure_ascii=False, indent=4, sort_keys=True)
        log.debug("Configuration: {}.".format(config))
        confirm = QInputDialog.getMultiLineText(
            None, __doc__, "<b>Resumen Final de la Configuracion:", config)[1]
        if confirm:
            with open(CONFIG_FILENAME, "w", encoding="utf-8") as _config:
                _config.write(config)
            try:
                log.info("Making Config {} Hidden".format(CONFIG_FILENAME))
                ctypes.windll.kernel32.SetFileAttributesW(CONFIG_FILENAME,
                                                          0x02)  # hidden file
                log.info("Making Config {} ReadOnly.".format(CONFIG_FILENAME))
                os.chmod(CONFIG_FILENAME, S_IREAD)  # make read-only
            except Exception as reason:
                log.critical(reason)
        else:
            return get_or_set_config()
    else:
        log.debug("Reading/Parsing Config File: {}.".format(CONFIG_FILENAME))
        with open(CONFIG_FILENAME, "r", encoding="utf-8") as _config:
            config = loads(_config.read())
    return config
Beispiel #57
0
 def _vcsCheckout(self, export=False):
     """
     Protected slot used to create a local project from the repository.
     
     @param export flag indicating whether an export or a checkout
             should be performed
     """
     if not self.project.checkDirty():
         return
     
     vcsSystemsDict = e5App().getObject("PluginManager")\
         .getPluginDisplayStrings("version_control")
     if not vcsSystemsDict:
         # no version control system found
         return
     
     vcsSystemsDisplay = []
     keys = sorted(vcsSystemsDict.keys())
     for key in keys:
         vcsSystemsDisplay.append(vcsSystemsDict[key])
     vcsSelected, ok = QInputDialog.getItem(
         None,
         self.tr("New Project"),
         self.tr("Select version control system for the project"),
         vcsSystemsDisplay,
         0, False)
     if not ok:
         return
     for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()):
         if vcsSystemDisplay == vcsSelected:
             break
     
     if not self.project.closeProject():
         return
     
     self.project.pdata["VCS"] = [vcsSystem]
     self.project.vcs = self.project.initVCS(vcsSystem)
     if self.project.vcs is not None:
         vcsdlg = self.project.vcs.vcsNewProjectOptionsDialog()
         if vcsdlg.exec_() == QDialog.Accepted:
             projectdir, vcsDataDict = vcsdlg.getData()
             self.project.pdata["VCS"] = [vcsSystem]
             self.project.vcs = self.project.initVCS(vcsSystem)
             # edit VCS command options
             if self.project.vcs.vcsSupportCommandOptions():
                 vcores = E5MessageBox.yesNo(
                     self.parent(),
                     self.tr("New Project"),
                     self.tr(
                         """Would you like to edit the VCS command"""
                         """ options?"""))
             else:
                 vcores = False
             if vcores:
                 from .CommandOptionsDialog import VcsCommandOptionsDialog
                 codlg = VcsCommandOptionsDialog(self.project.vcs)
                 if codlg.exec_() == QDialog.Accepted:
                     self.project.vcs.vcsSetOptions(codlg.getOptions())
             
             # create the project directory if it doesn't exist already
             if not os.path.isdir(projectdir):
                 try:
                     os.makedirs(projectdir)
                 except EnvironmentError:
                     E5MessageBox.critical(
                         self.parent(),
                         self.tr("Create project directory"),
                         self.tr(
                             "<p>The project directory <b>{0}</b> could not"
                             " be created.</p>").format(projectdir))
                     self.project.pdata["VCS"] = ['None']
                     self.project.vcs = self.project.initVCS()
                     return
             
             # create the project from the VCS
             self.project.vcs.vcsSetDataFromDict(vcsDataDict)
             if export:
                 ok = self.project.vcs.vcsExport(vcsDataDict, projectdir)
             else:
                 ok = self.project.vcs.vcsCheckout(vcsDataDict, projectdir,
                                                   False)
             if ok:
                 projectdir = os.path.normpath(projectdir)
                 filters = ["*.e4p"]
                 d = QDir(projectdir)
                 plist = d.entryInfoList(filters)
                 if len(plist):
                     if len(plist) == 1:
                         self.project.openProject(
                             plist[0].absoluteFilePath())
                         self.project.newProject.emit()
                     else:
                         pfilenamelist = d.entryList(filters)
                         pfilename, ok = QInputDialog.getItem(
                             None,
                             self.tr("New project from repository"),
                             self.tr("Select a project file to open."),
                             pfilenamelist, 0, False)
                         if ok:
                             self.project.openProject(
                                 QFileInfo(d, pfilename).absoluteFilePath())
                             self.project.newProject.emit()
                     if export:
                         self.project.pdata["VCS"] = ['None']
                         self.project.vcs = self.project.initVCS()
                         self.project.setDirty(True)
                         self.project.saveProject()
                 else:
                     res = E5MessageBox.yesNo(
                         self.parent(),
                         self.tr("New project from repository"),
                         self.tr(
                             "The project retrieved from the repository"
                             " does not contain an eric project file"
                             " (*.e4p). Create it?"),
                         yesDefault=True)
                     if res:
                         self.project.ppath = projectdir
                         self.project.opened = True
                         
                         from Project.PropertiesDialog import \
                             PropertiesDialog
                         dlg = PropertiesDialog(self.project, False)
                         if dlg.exec_() == QDialog.Accepted:
                             dlg.storeData()
                             self.project.initFileTypes()
                             self.project.setDirty(True)
                             try:
                                 ms = os.path.join(
                                     self.project.ppath,
                                     self.project.pdata["MAINSCRIPT"][0])
                                 if os.path.exists(ms):
                                     self.project.appendFile(ms)
                             except IndexError:
                                 ms = ""
                             self.project.newProjectAddFiles(ms)
                             self.project.createProjectManagementDir()
                             self.project.saveProject()
                             self.project.openProject(self.project.pfile)
                             if not export:
                                 res = E5MessageBox.yesNo(
                                     self.parent(),
                                     self.tr(
                                         "New project from repository"),
                                     self.tr(
                                         "Shall the project file be added"
                                         " to the repository?"),
                                     yesDefault=True)
                                 if res:
                                     self.project.vcs.vcsAdd(
                                         self.project.pfile)
             else:
                 E5MessageBox.critical(
                     self.parent(),
                     self.tr("New project from repository"),
                     self.tr(
                         """The project could not be retrieved from"""
                         """ the repository."""))
                 self.project.pdata["VCS"] = ['None']
                 self.project.vcs = self.project.initVCS()
         else:
             self.project.pdata["VCS"] = ['None']
             self.project.vcs = self.project.initVCS()
Beispiel #58
0
 def _vcsImport(self):
     """
     Protected slot used to import the local project into the repository.
     
     <b>NOTE</b>:
         This does not necessarily make the local project a vcs controlled
         project. You may have to checkout the project from the repository
         in order to accomplish that.
     """
     def revertChanges():
         """
         Local function to revert the changes made to the project object.
         """
         self.project.pdata["VCS"] = pdata_vcs[:]
         self.project.pdata["VCSOPTIONS"] = copy.deepcopy(pdata_vcsoptions)
         self.project.pdata["VCSOTHERDATA"] = copy.deepcopy(pdata_vcsother)
         self.project.vcs = vcs
         self.project.vcsProjectHelper = vcsHelper
         self.project.vcsBasicHelper = vcs is None
         self.initMenu(self.project.vcsMenu)
         self.project.setDirty(True)
         self.project.saveProject()
     
     pdata_vcs = self.project.pdata["VCS"][:]
     pdata_vcsoptions = copy.deepcopy(self.project.pdata["VCSOPTIONS"])
     pdata_vcsother = copy.deepcopy(self.project.pdata["VCSOTHERDATA"])
     vcs = self.project.vcs
     vcsHelper = self.project.vcsProjectHelper
     vcsSystemsDict = e5App().getObject("PluginManager")\
         .getPluginDisplayStrings("version_control")
     if not vcsSystemsDict:
         # no version control system found
         return
     
     vcsSystemsDisplay = []
     keys = sorted(list(vcsSystemsDict.keys()))
     for key in keys:
         vcsSystemsDisplay.append(vcsSystemsDict[key])
     vcsSelected, ok = QInputDialog.getItem(
         None,
         self.tr("Import Project"),
         self.tr("Select version control system for the project"),
         vcsSystemsDisplay,
         0, False)
     if not ok:
         return
     for vcsSystem, vcsSystemDisplay in list(vcsSystemsDict.items()):
         if vcsSystemDisplay == vcsSelected:
             break
     
     self.project.pdata["VCS"] = [vcsSystem]
     self.project.vcs = self.project.initVCS(vcsSystem)
     if self.project.vcs is not None:
         vcsdlg = self.project.vcs.vcsOptionsDialog(self.project,
                                                    self.project.name, 1)
         if vcsdlg.exec_() == QDialog.Accepted:
             vcsDataDict = vcsdlg.getData()
             # edit VCS command options
             if self.project.vcs.vcsSupportCommandOptions():
                 vcores = E5MessageBox.yesNo(
                     self.parent(),
                     self.tr("Import Project"),
                     self.tr(
                         """Would you like to edit the VCS command"""
                         """ options?"""))
             else:
                 vcores = False
             if vcores:
                 from .CommandOptionsDialog import VcsCommandOptionsDialog
                 codlg = VcsCommandOptionsDialog(self.project.vcs)
                 if codlg.exec_() == QDialog.Accepted:
                     self.project.vcs.vcsSetOptions(codlg.getOptions())
             self.project.setDirty(True)
             self.project.vcs.vcsSetDataFromDict(vcsDataDict)
             self.project.saveProject()
             isVcsControlled = self.project.vcs.vcsImport(
                 vcsDataDict, self.project.ppath)[0]
             if isVcsControlled:
                 # reopen the project
                 self.project.openProject(self.project.pfile)
             else:
                 # revert the changes to the local project
                 # because the project dir is not a VCS directory
                 revertChanges()
         else:
             # revert the changes because user cancelled
             revertChanges()
Beispiel #59
0
    def etiquette(self):
        select = self.canvas.select
        etiquette = select.etiquette if select.etiquette is not None else select
        old = {'mode': etiquette.style("mode"), 'texte': etiquette.texte}

        # ----------------
        # Cas particuliers
        # ----------------

        if isinstance(select, Champ):
            if select.style('choix'):
                choix = select.style('choix')
                try:
                    index = choix.index(select.texte)
                except ValueError:
                    index = 0
                text, ok = QInputDialog.getItem(self.canvas, "Choisir une valeur",
                                "Réponse :", choix, index, False)
            else:
                text, ok = QInputDialog.getText(self.canvas, "Éditer le champ",
                            "Réponse :", QLineEdit.Normal, select.texte)
            if ok:
                select.label(text)
            return

        # -----------
        # Cas général
        # -----------

        dlg = QDialog(self.canvas)
        dlg.setWindowTitle("Changer la légende de l'objet (texte quelconque)")

        sizer = QVBoxLayout()
        sizer.addWidget(QLabel("Note: le code LATEX doit etre entre $$. Ex: $\\alpha$"))

        dlg.text = QTextEdit(dlg)
        dlg.text.setPlainText(etiquette.texte)
        dlg.setMinimumSize(300, 50)
        sizer.addWidget(dlg.text)

        dlg.cb = QCheckBox("Interpréter la formule", dlg)
        dlg.cb.setChecked(select.mode_affichage == 'formule')
        sizer.addWidget(dlg.cb)

        line = QFrame(self)
        line.setFrameStyle(QFrame.HLine)
        sizer.addWidget(line)

        box = QHBoxLayout()
        btn = QPushButton('OK')
        btn.clicked.connect(dlg.accept)
        box.addWidget(btn)
        box.addStretch(1)
        btn = QPushButton("Annuler")
        btn.clicked.connect(dlg.reject)
        box.addWidget(btn)
        sizer.addLayout(box)

        dlg.setLayout(sizer)
        dlg.setWindowModality(Qt.WindowModal)

        while True:
            ok = dlg.exec_()
            if ok:
                try:
                    nom = select.nom
                    txt = repr(dlg.text.toPlainText())
                    mode = repr('formule' if dlg.cb.isChecked() else 'texte')
                    self.executer("%s.label(%s, %s)" %(nom, txt, mode))
                except:
                    # Au cas où une formule incorrecte fasse buguer l'affichage (?)
                    etiquette.texte = old['texte']
                    etiquette.style(mode=old['mode'])
                    print_error()
                    continue
            else:
                etiquette.texte = old['texte']
                etiquette.style(mode=old['mode'])
            break
 def __newUiForm(self, path):
     """
     Private slot to handle the New Form menu action for Qt-related
     projects.
     
     @param path full directory path for the new form file (string)
     """
     selectedForm, ok = QInputDialog.getItem(
         None,
         self.tr("New Form"),
         self.tr("Select a form type:"),
         self.templateTypes4,
         0, False)
     if not ok or not selectedForm:
         # user pressed cancel
         return
     
     templateIndex = self.templateTypes4.index(selectedForm)
     templateFile = os.path.join(
         getConfig('ericTemplatesDir'), self.templates4[templateIndex])
     
     fname, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
         self,
         self.tr("New Form"),
         path,
         self.tr("Qt User-Interface Files (*.ui);;All Files (*)"),
         "",
         E5FileDialog.Options(E5FileDialog.DontConfirmOverwrite))
     
     if not fname:
         # user aborted or didn't enter a filename
         return
     
     ext = QFileInfo(fname).suffix()
     if not ext:
         ex = selectedFilter.split("(*")[1].split(")")[0]
         if ex:
             fname += ex
     
     if os.path.exists(fname):
         res = E5MessageBox.yesNo(
             self,
             self.tr("New Form"),
             self.tr("The file already exists! Overwrite it?"),
             icon=E5MessageBox.Warning)
         if not res:
             # user selected to not overwrite
             return
     
     try:
         shutil.copy(templateFile, fname)
     except IOError as e:
         E5MessageBox.critical(
             self,
             self.tr("New Form"),
             self.tr(
                 "<p>The new form file <b>{0}</b> could not be created.<br>"
                 "Problem: {1}</p>").format(fname, str(e)))
         return
     
     self.project.appendFile(fname)
     self.designerFile.emit(fname)