Exemplo n.º 1
0
 def __filterSignatures(self):
     """
     Private method to filter the log entries.
     """
     searchRxText = self.rxEdit.text()
     filterTop = self.categoryCombo.currentText() == self.tr("Revision")
     if filterTop and searchRxText.startswith("^"):
         searchRx = QRegExp(
             "^\s*{0}".format(searchRxText[1:]), Qt.CaseInsensitive)
     else:
         searchRx = QRegExp(searchRxText, Qt.CaseInsensitive)
     for topIndex in range(self.signaturesList.topLevelItemCount()):
         topLevelItem = self.signaturesList.topLevelItem(topIndex)
         if filterTop:
             topLevelItem.setHidden(
                 searchRx.indexIn(topLevelItem.text(0)) == -1)
         else:
             visibleChildren = topLevelItem.childCount()
             for childIndex in range(topLevelItem.childCount()):
                 childItem = topLevelItem.child(childIndex)
                 if searchRx.indexIn(childItem.text(0)) == -1:
                     childItem.setHidden(True)
                     visibleChildren -= 1
                 else:
                     childItem.setHidden(False)
             topLevelItem.setHidden(visibleChildren == 0)
Exemplo n.º 2
0
    def run(self):
        """Execute this rules in another thread to avoid blocking the ui."""
        styles = {}
        self.msleep(300)
        block = self._highlighter.document().begin()
        while block.blockNumber() != -1:
            text = block.text()
            formats = []

            for expression, nth, char_format in self._highlighter.rules:
                index = expression.indexIn(text, 0)

                while index >= 0:
                    # We actually want the index of the nth match
                    index = expression.pos(nth)
                    length = len(expression.cap(nth))

                    formats.append((index, length, char_format))
                    index = expression.indexIn(text, index + length)

            #Spaces
            expression = QRegExp('\s+')
            index = expression.indexIn(text, 0)
            while index >= 0:
                index = expression.pos(0)
                length = len(expression.cap(0))
                formats.append((index, length, STYLES['spaces']))
                index = expression.indexIn(text, index + length)

            styles[block.blockNumber()] = formats
            block = block.next()# block = next(block)
        self.highlightingDetected.emit(styles)
Exemplo n.º 3
0
    def findCodecs(self):
        codecMap = []
        iso8859RegExp = QRegExp('ISO[- ]8859-([0-9]+).*')

        for mib in QTextCodec.availableMibs():
            codec = QTextCodec.codecForMib(mib)
            sortKey = codec_name(codec).upper()
            rank = 0

            if sortKey.startswith('UTF-8'):
                rank = 1
            elif sortKey.startswith('UTF-16'):
                rank = 2
            elif iso8859RegExp.exactMatch(sortKey):
                if len(iso8859RegExp.cap(1)) == 1:
                    rank = 3
                else:
                    rank = 4
            else:
                rank = 5

            codecMap.append((str(rank) + sortKey, codec))

        codecMap.sort()
        self.codecs = [item[-1] for item in codecMap]
Exemplo n.º 4
0
    def highlightBlock(self, text):
        for pattern, format in self.highlightingRules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)

        startIndex = 0
        if self.previousBlockState() != 1:
            startIndex = self.commentStartExpression.indexIn(text)

        while startIndex >= 0:
            endIndex = self.commentEndExpression.indexIn(text, startIndex)

            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLength = len(text) - startIndex
            else:
                commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()

            self.setFormat(startIndex, commentLength,
                    self.multiLineCommentFormat)
            startIndex = self.commentStartExpression.indexIn(text,
                    startIndex + commentLength);
Exemplo n.º 5
0
 def __init__(self, mergelist1, mergelist2, targetlist, force=False,
              parent=None):
     """
     Constructor
     
     @param mergelist1 list of previously entered URLs/revisions
         (list of strings)
     @param mergelist2 list of previously entered URLs/revisions
         (list of strings)
     @param targetlist list of previously entered targets (list of strings)
     @param force flag indicating a forced merge (boolean)
     @param parent parent widget (QWidget)
     """
     super(SvnMergeDialog, self).__init__(parent)
     self.setupUi(self)
    
     self.forceCheckBox.setChecked(force)
     
     self.rx_url = QRegExp('(?:file:|svn:|svn+ssh:|http:|https:)//.+')
     self.rx_rev = QRegExp('\\d+')
     
     self.tag1Combo.clear()
     self.tag1Combo.addItems(mergelist1)
     self.tag2Combo.clear()
     self.tag2Combo.addItems(mergelist2)
     self.targetCombo.clear()
     self.targetCombo.addItems(targetlist)
     
     self.okButton = self.buttonBox.button(QDialogButtonBox.Ok)
     self.okButton.setEnabled(False)
     
     msh = self.minimumSizeHint()
     self.resize(max(self.width(), msh.width()), msh.height())
Exemplo n.º 6
0
 def __init__(self, vcs, parent=None):
     """
     Constructor
     
     @param vcs reference to the vcs object
     @param parent parent widget (QWidget)
     """
     super(SvnPropListDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)
     
     self.process = QProcess()
     env = QProcessEnvironment.systemEnvironment()
     env.insert("LANG", "C")
     self.process.setProcessEnvironment(env)
     self.vcs = vcs
     
     self.propsList.headerItem().setText(self.propsList.columnCount(), "")
     self.propsList.header().setSortIndicator(0, Qt.AscendingOrder)
     
     self.process.finished.connect(self.__procFinished)
     self.process.readyReadStandardOutput.connect(self.__readStdout)
     self.process.readyReadStandardError.connect(self.__readStderr)
     
     self.rx_path = QRegExp(r"Properties on '([^']+)':\s*")
     self.rx_prop = QRegExp(r"  (.*) *: *(.*)[\r\n]")
     self.lastPath = None
     self.lastProp = None
     self.propBuffer = ""
Exemplo n.º 7
0
 def __autoIncFilename(self):
     """
     Private method to auto-increment the file name.
     """
     # Extract the file name
     name = os.path.basename(self.__filename)
     
     # If the name contains a number, then increment it.
     numSearch = QRegExp("(^|[^\\d])(\\d+)")
     # We want to match as far left as possible, and when the number is
     # at the start of the name.
     
     # Does it have a number?
     start = numSearch.lastIndexIn(name)
     if start != -1:
         # It has a number, increment it.
         start = numSearch.pos(2)    # Only the second group is of interest.
         numAsStr = numSearch.capturedTexts()[2]
         number = "{0:0{width}d}".format(
             int(numAsStr) + 1, width=len(numAsStr))
         name = name[:start] + number + name[start + len(numAsStr):]
     else:
         # no number
         start = name.rfind('.')
         if start != -1:
             # has a '.' somewhere, e.g. it has an extension
             name = name[:start] + '1' + name[start:]
         else:
             # no extension, just tack it on to the end
             name += '1'
     
     self.__filename = os.path.join(os.path.dirname(self.__filename), name)
     self.__updateCaption()
Exemplo n.º 8
0
    def __init__(self, parent=None):
        super(XmlSyntaxHighlighter, self).__init__(parent)

        self.highlightingRules = []

        # Tag format.
        format = QTextCharFormat()
        format.setForeground(Qt.darkBlue)
        format.setFontWeight(QFont.Bold)
        pattern = QRegExp("(<[a-zA-Z:]+\\b|<\\?[a-zA-Z:]+\\b|\\?>|>|/>|</[a-zA-Z:]+>)")
        self.highlightingRules.append((pattern, format))

        # Attribute format.
        format = QTextCharFormat()
        format.setForeground(Qt.darkGreen)
        pattern = QRegExp("[a-zA-Z:]+=")
        self.highlightingRules.append((pattern, format))

        # Attribute content format.
        format = QTextCharFormat()
        format.setForeground(Qt.red)
        pattern = QRegExp("(\"[^\"]*\"|'[^']*')")
        self.highlightingRules.append((pattern, format))

        # Comment format.
        self.commentFormat = QTextCharFormat()
        self.commentFormat.setForeground(Qt.lightGray)
        self.commentFormat.setFontItalic(True)

        self.commentStartExpression = QRegExp("<!--")
        self.commentEndExpression = QRegExp("-->")
Exemplo n.º 9
0
 def validate(self, inpt: str, pos: int):
     if self.suffix().upper() in ("", "K", "M", "G"):
         rx = QRegExp("^(-?[0-9]+)[.]?[0-9]*[kKmMgG]?$")
     else:
         rx = QRegExp("^(-?[0-9]+)[.]?[0-9]*[{}]?$".format(self.suffix()))
     result = QValidator.Acceptable if rx.exactMatch(inpt.replace(",", ".")) else QValidator.Invalid
     return result, inpt, pos
Exemplo n.º 10
0
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(Qt.darkBlue)
        keywordFormat.setFontWeight(QFont.Bold)

        keywordPatterns = ["""</?\w+\s+[^>]*>""","<[/]?(html|body|head|title|div|a|br|form|input|b|p|i|center|span|font|table|tr|td|h[1-6])[/]?>"]

        self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                for pattern in keywordPatterns]


        self.multiLineCommentFormat = QTextCharFormat()
        self.multiLineCommentFormat.setForeground(Qt.red)

        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""),
                quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(Qt.blue)
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
                functionFormat))
        
        moreKeyWords = QTextCharFormat()
        moreKeyWords.setForeground(Qt.darkMagenta)
        moreKeyWords.setFontWeight(QFont.Bold)
        self.highlightingRules.append((QRegExp("(id|class|src|border|width|height|style|name|type|value)="),moreKeyWords))

        self.commentStartExpression = QRegExp("<!--")
        self.commentEndExpression = QRegExp("-->")
Exemplo n.º 11
0
 def __init__(self, vcs, parent=None):
     """
     Constructor
     
     @param vcs reference to the vcs object
     @param parent parent widget (QWidget)
     """
     super(SvnChangeListsDialog, self).__init__(parent)
     self.setupUi(self)
     self.setWindowFlags(Qt.Window)
     
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)
     
     self.process = None
     self.vcs = vcs
     
     self.rx_status = QRegExp(
         '(.{8,9})\\s+([0-9-]+)\\s+([0-9?]+)\\s+(\\S+)\\s+(.+)\\s*')
     # flags (8 or 9 anything), revision, changed rev, author, path
     self.rx_status2 = \
         QRegExp('(.{8,9})\\s+(.+)\\s*')
     # flags (8 or 9 anything), path
     self.rx_changelist = \
         QRegExp('--- \\S+ .([\\w\\s]+).:\\s+')
Exemplo n.º 12
0
    def valueFromText(text):
        regExp = QRegExp("(\\d+)(\\s*[xx]\\s*\\d+)?")

        if regExp.exactMatch(text):
            return int(regExp.cap(1))
        else:
            return 0
Exemplo n.º 13
0
Arquivo: item.py Projeto: dani-l/PaPI
    def setData(self, index, value, role):
        """
        This function is called when a content in a row is edited by the user.

        :param index: Current selected index.
        :param value: New value from user
        :param role:
        :return:
        """

        if not index.isValid():
            return None

        row = index.row()
        col = index.column()

        if role == Qt.EditRole:
            if col == 1:
                index_sibling = index.sibling(row, col-1)
                dparameter = super(DParameterTreeModel, self).data(index_sibling, Qt.UserRole)

                if dparameter.regex is not None:
                    rx = QRegExp(dparameter.regex)
                    if rx.exactMatch(value):
                        dparameter.value = value
                        self.dataChanged.emit(index_sibling, index_sibling)
                else:
                    dparameter.value = value
                    self.dataChanged.emit(index_sibling, index_sibling)

                return True

        return False
Exemplo n.º 14
0
 def data_changed(self, index1, index2, roles):
     if index1.column() in (1, 3):
         regexp1 = QRegExp("^-?\d+(\.\d+)?$")
         regexp2 = QRegExp("^\d+$")
         if len(str(index1.data())) == 0:
             QMessageBox.critical(None,
                                  "Invalid data",
                                  "Field cannot be empty.",
                                  QMessageBox.Ok)
             self.model.revertRow(index1.row())
         elif len(str(index1.data())) != len(str(index1.data()).strip()):
             QMessageBox.critical(None,
                                  "Invalid data",
                                  "Unwanted whitespace character.",
                                  QMessageBox.Ok)
             self.model.revertRow(index1.row())
         elif index1.column() == 1 and not regexp1.exactMatch(str(index1.data())):
             QMessageBox.critical(None,
                                  "Invalid data",
                                  "Field must be numeric.",
                                  QMessageBox.Ok)
             self.model.revertRow(index1.row())
         elif index1.column() == 3 and not regexp2.exactMatch(str(index1.data())):
             QMessageBox.critical(None,
                                  "Invalid data",
                                  "Field must be numeric.",
                                  QMessageBox.Ok)
             self.model.revertRow(index1.row())
Exemplo n.º 15
0
class XmlSyntaxHighlighter(QSyntaxHighlighter):

    def __init__(self, parent=None):
        super(XmlSyntaxHighlighter, self).__init__(parent)

        self.highlightingRules = []

        # Tag format.
        format = QTextCharFormat()
        format.setForeground(Qt.darkBlue)
        format.setFontWeight(QFont.Bold)
        pattern = QRegExp("(<[a-zA-Z:]+\\b|<\\?[a-zA-Z:]+\\b|\\?>|>|/>|</[a-zA-Z:]+>)")
        self.highlightingRules.append((pattern, format))

        # Attribute format.
        format = QTextCharFormat()
        format.setForeground(Qt.darkGreen)
        pattern = QRegExp("[a-zA-Z:]+=")
        self.highlightingRules.append((pattern, format))

        # Attribute content format.
        format = QTextCharFormat()
        format.setForeground(Qt.red)
        pattern = QRegExp("(\"[^\"]*\"|'[^']*')")
        self.highlightingRules.append((pattern, format))

        # Comment format.
        self.commentFormat = QTextCharFormat()
        self.commentFormat.setForeground(Qt.lightGray)
        self.commentFormat.setFontItalic(True)

        self.commentStartExpression = QRegExp("<!--")
        self.commentEndExpression = QRegExp("-->")

    def highlightBlock(self, text):
        for pattern, format in self.highlightingRules:
            expression = QRegExp(pattern)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)

        startIndex = 0
        if self.previousBlockState() != 1:
            startIndex = self.commentStartExpression.indexIn(text)

        while startIndex >= 0:
            endIndex = self.commentEndExpression.indexIn(text, startIndex)
            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLength = text.length() - startIndex
            else:
                commentLength = endIndex - startIndex + self.commentEndExpression.matchedLength()

            self.setFormat(startIndex, commentLength, self.commentFormat)
            startIndex = self.commentStartExpression.indexIn(text,
                    startIndex + commentLength)
Exemplo n.º 16
0
 def __init__(self):
     """
     Constructor
     """
     super(NsHtmlReader, self).__init__()
     
     self.__folderRx = QRegExp("<DT><H3(.*)>(.*)</H3>", Qt.CaseInsensitive)
     self.__folderRx.setMinimal(True)
     
     self.__endFolderRx = QRegExp("</DL>", Qt.CaseInsensitive)
     
     self.__bookmarkRx = QRegExp("<DT><A(.*)>(.*)</A>", Qt.CaseInsensitive)
     self.__bookmarkRx.setMinimal(True)
     
     self.__descRx = QRegExp("<DD>(.*)", Qt.CaseInsensitive)
     
     self.__separatorRx = QRegExp("<HR>", Qt.CaseInsensitive)
     
     self.__urlRx = QRegExp('HREF="(.*)"', Qt.CaseInsensitive)
     self.__urlRx.setMinimal(True)
     
     self.__addedRx = QRegExp('ADD_DATE="(\d*)"', Qt.CaseInsensitive)
     self.__addedRx.setMinimal(True)
     
     self.__modifiedRx = QRegExp(
         'LAST_MODIFIED="(\d*)"', Qt.CaseInsensitive)
     self.__modifiedRx.setMinimal(True)
     
     self.__visitedRx = QRegExp('LAST_VISIT="(\d*)"', Qt.CaseInsensitive)
     self.__visitedRx.setMinimal(True)
     
     self.__foldedRx = QRegExp("FOLDED", Qt.CaseInsensitive)
Exemplo n.º 17
0
 def __parsePattern(self, pattern):
     """
     Private method to parse the match pattern.
     
     @param pattern match pattern to be used (string)
     """
     if pattern.startswith("/") and pattern.endswith("/"):
         pattern = pattern[1:-1]
         
         self.__regExp = QRegExp(pattern, Qt.CaseInsensitive)
         self.__useRegExp = True
     elif ".tld" in pattern:
         # escape special symbols
         pattern = re.sub(r"(\W)", r"\\\1", pattern)
         # remove multiple wildcards
         pattern = re.sub(r"\*+", "*", pattern)
         # process anchor at expression start
         pattern = re.sub(r"^\\\|", "^", pattern)
         # process anchor at expression end
         pattern = re.sub(r"\\\|$", "$", pattern)
         # replace wildcards by .*
         pattern = re.sub(r"\\\*", ".*", pattern)
         # replace domain pattern
         pattern = re.sub(r"\.tld", r"\.[a-z.]{2,6}")
         
         self.__useRegExp = True
         self.__regExp = QRegExp(pattern, Qt.CaseInsensitive)
     else:
         self.__matchString = pattern
Exemplo n.º 18
0
    def highlightBlock(self, text):
        for pattern, format in self.rules:
            exp = QRegExp(pattern)
            index = exp.indexIn(text)
            while index >= 0:
                length = exp.matchedLength()
                if exp.numCaptures() > 0:
                    self.setFormat(exp.pos(1), len(str(exp.cap(1))), format)
                else:
                    self.setFormat(exp.pos(0), len(str(exp.cap(0))), format)
                index = exp.indexIn(text, index + length)

        # Multi line strings
        start = self.multilineStart
        end = self.multilineEnd

        self.setCurrentBlockState(0)
        startIndex, skip = 0, 0
        if self.previousBlockState() != 1:
            startIndex, skip = start.indexIn(text), 3
        while startIndex >= 0:
            endIndex = end.indexIn(text, startIndex + skip)
            if endIndex == -1:
                self.setCurrentBlockState(1)
                commentLen = len(text) - startIndex
            else:
                commentLen = endIndex - startIndex + 3
            self.setFormat(startIndex, commentLen, self.stringFormat)
            startIndex, skip = (start.indexIn(text,
                                              startIndex + commentLen + 3),
                                3)
Exemplo n.º 19
0
def hasEnvironmentEntry(key):
    """
    Module function to check, if the environment contains an entry.
    
    @param key key of the requested environment entry (string)
    @return flag indicating the presence of the requested entry (boolean)
    """
    filter = QRegExp("^%s[ \t]*=" % key)
    if isWindowsPlatform():
        filter.setCaseSensitivity(Qt.CaseInsensitive)
    
    entries = QProcess.systemEnvironment().filter(filter)
    return entries.count() > 0
Exemplo n.º 20
0
    def lessThan(self, left, right):
        leftData = self.sourceModel().data(left)
        rightData = self.sourceModel().data(right)

        if not isinstance(leftData, QDate):
            emailPattern = QRegExp("([\\w\\.]*@[\\w\\.]*)")

            if left.column() == 1 and emailPattern.indexIn(leftData) != -1:
                leftData = emailPattern.cap(1)

            if right.column() == 1 and emailPattern.indexIn(rightData) != -1:
                rightData = emailPattern.cap(1)

        return leftData < rightData
Exemplo n.º 21
0
    def parseInDocRules(self):
        oldRules = self.inDocRules
        self.inDocRules = []

        t = self.thisDocument.toPlainText()

        # Get all conf files
        confs = []
        lines = t.split("\n")
        for l in lines:
            r = QRegExp(r'^%!includeconf:\s*([^\s]*)\s*')
            if r.indexIn(l) != -1:
                confs.append(r.cap(1))

        # Try to load conf files
        for c in confs:
            try:
                import codecs
                f = self.editor.fileWidget.file
                d = QDir.cleanPath(QFileInfo(f).absoluteDir().absolutePath() + "/" + c)
                file = codecs.open(d, 'r', "utf-8")
            except:
                print(("Error: cannot open {}.".format(c)))
                continue
                # We add the content to the current lines of the current document
            lines += file.readlines()  # lines.extend(file.readlines())

        # b = self.thisDocument.firstBlock()
        lastColor = ""

        # while b.isValid():
        for l in lines:
            text = l  # b.text()
            r = QRegExp(r'^%!p[or][se]t?proc[^\s]*\s*:\s*(\'[^\']*\'|\"[^\"]*\")\s*(\'[^\']*\'|\"[^\"]*\")')
            if r.indexIn(text) != -1:
                rule = r.cap(1)[1:-1]
                # Check if there was a color-comment above that post/preproc bloc
                if lastColor:
                    self.inDocRules.append((str(rule), lastColor))
                # Check if previous block is a comment like it should
                else:
                    previousText = lines[lines.indexOf(l) - 1]  # b.previous().text()
                    r = QRegExp(r'^%.*\s\((.*)\)')
                    if r.indexIn(previousText) != -1:
                        lastColor = r.cap(1)
                        self.inDocRules.append((str(rule), lastColor))
            else:
                lastColor = ""
                # b = b.next()

        if oldRules != self.inDocRules:
            # Rules have changed, we need to rehighlight
            # print("Rules have changed.", len(self.inDocRules))
            # self.rehighlight()  # Doesn't work (seg fault), why?
            pass
Exemplo n.º 22
0
    def __init__(self, editor, parent=None):
        """
        Constructor
        
        @param editor reference to the editor object (QScintilla.Editor)
        @param parent reference to the parent object (QObject)
        """
        CompleterBase.__init__(self, editor, parent)

        self.__beginRX = QRegExp(r"""^=begin """)
        self.__beginNlRX = QRegExp(r"""^=begin\r?\n""")
        self.__hereRX = QRegExp(r"""<<-?['"]?(\w*)['"]?\r?\n""")

        self.readSettings()
Exemplo n.º 23
0
    def slotCursorPositionChanged(self):
        """Called whenever the cursor position changes.
        
        Highlights matching characters if the cursor is at one of them.
        
        """
        cursor = self.edit().textCursor()
        block = cursor.block()
        text = block.text()

        # try both characters at the cursor
        col = cursor.position() - block.position()
        end = col + 1
        col = max(0, col - 1)
        for c in text[col:end]:
            if c in self.matchPairs:
                break
            col += 1
        else:
            self.clear()
            return

        # the cursor is at a character from matchPairs
        i = self.matchPairs.index(c)
        cursor.setPosition(block.position() + col)

        # find the matching character
        new = QTextCursor(cursor)
        if i & 1:
            # look backward
            match = self.matchPairs[i - 1]
            flags = QTextDocument.FindBackward
        else:
            # look forward
            match = self.matchPairs[i + 1]
            flags = QTextDocument.FindFlags()
            new.movePosition(QTextCursor.Right)

        # search, also nesting
        rx = QRegExp(QRegExp.escape(c) + "|" + QRegExp.escape(match))
        nest = 0
        while nest >= 0:
            new = cursor.document().find(rx, new, flags)
            if new.isNull():
                self.clear()
                return
            nest += 1 if new.selectedText() == c else -1
        cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
        self.highlight([cursor, new])
Exemplo n.º 24
0
 def __init__(self, parent=None):
     """
     Constructor
     
     @param parent reference to the parent object (QObject)
     """
     super(HistoryCompletionModel, self).__init__(parent)
     
     self.__searchString = ""
     self.__searchMatcher = QRegExp(
         "", Qt.CaseInsensitive, QRegExp.FixedString)
     self.__wordMatcher = QRegExp("", Qt.CaseInsensitive)
     self.__isValid = False
     
     self.setDynamicSortFilter(True)
Exemplo n.º 25
0
Arquivo: item.py Projeto: dani-l/PaPI
    def mark_visibility_by_name(self, value):

        all_items_are_hidden = True

        for row in range(self.rowCount()):
            treeItem = self.child(row)
            regex = QRegExp(value, Qt.CaseInsensitive, QRegExp.Wildcard)

            if regex.exactMatch(treeItem.name):
                treeItem.visible = True
                all_items_are_hidden = False
            else:
                treeItem.visible = False

        self.visible = not all_items_are_hidden
Exemplo n.º 26
0
 def __init__(self, vcs, parent=None):
     """
     Constructor
     
     @param vcs reference to the vcs object
     @param parent parent widget (QWidget)
     """
     super(SvnTagBranchListDialog, self).__init__(parent)
     self.setupUi(self)
     self.setWindowFlags(Qt.Window)
     
     self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
     self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)
     
     self.vcs = vcs
     self.tagsList = None
     self.allTagsList = None
     
     self.tagList.headerItem().setText(self.tagList.columnCount(), "")
     self.tagList.header().setSortIndicator(3, Qt.AscendingOrder)
     
     self.process = QProcess()
     self.process.finished.connect(self.__procFinished)
     self.process.readyReadStandardOutput.connect(self.__readStdout)
     self.process.readyReadStandardError.connect(self.__readStderr)
     
     self.rx_list = QRegExp(
         r"""\w*\s*(\d+)\s+(\w+)\s+\d*\s*"""
         r"""((?:\w+\s+\d+|[0-9.]+\s+\w+)\s+[0-9:]+)\s+(.+)/\s*""")
Exemplo n.º 27
0
    def set_selected_word(self, word, partial=True):
        """Set the word to highlight."""
        # partial = True for new highlighter compatibility
        hl_worthy = len(word) > 2
        if hl_worthy:
            self.selected_word_pattern = QRegExp(
                r'\b%s\b' % self.sanitize(word))
        else:
            self.selected_word_pattern = None

        suffix = "(?![A-Za-z_\d])"
        prefix = "(?<![A-Za-z_\d])"
        word = re.escape(word)
        if not partial:
            word = "%s%s%s" % (prefix, word, suffix)
        lines = []
        pat_find = re.compile(word)
        document = self.document()
        for lineno, text in enumerate(document.toPlainText().splitlines()):
            if hl_worthy and pat_find.search(text):
                lines.append(lineno)
            elif self._old_search and self._old_search.search(text):
                lines.append(lineno)
        # Ask perrito if i don't know what the next line does:
        self._old_search = hl_worthy and pat_find
        self.rehighlight_lines(lines)
Exemplo n.º 28
0
    def getSize(self):
        text, ok = QInputDialog.getText(self, "Grabber",
                "Enter pixmap size:", QLineEdit.Normal,
                "%d x %d" % (self.glWidget.width(), self.glWidget.height()))

        if not ok:
            return QSize()

        regExp = QRegExp(r'([0-9]+) *x *([0-9]+)')

        if regExp.exactMatch(text):
            width = int(regExp.cap(1))
            height = int(regExp.cap(2))
            if width > 0 and width < 2048 and height > 0 and height < 2048:
                return QSize(width, height)

        return self.glWidget.size()
Exemplo n.º 29
0
    def __init__(self, parent=None):
        super(Highlighter, self).__init__(parent)

        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(Qt.darkBlue)
        keywordFormat.setFontWeight(QFont.Bold)

        keywordPatterns = ["\\bchar\\b", "\\bclass\\b", "\\bconst\\b",
                "\\bdouble\\b", "\\benum\\b", "\\bexplicit\\b", "\\bfriend\\b",
                "\\binline\\b", "\\bint\\b", "\\blong\\b", "\\bnamespace\\b",
                "\\boperator\\b", "\\bprivate\\b", "\\bprotected\\b",
                "\\bpublic\\b", "\\bshort\\b", "\\bsignals\\b", "\\bsigned\\b",
                "\\bslots\\b", "\\bstatic\\b", "\\bstruct\\b",
                "\\btemplate\\b", "\\btypedef\\b", "\\btypename\\b",
                "\\bunion\\b", "\\bunsigned\\b", "\\bvirtual\\b", "\\bvoid\\b",
                "\\bvolatile\\b"]

        self.highlightingRules = [(QRegExp(pattern), keywordFormat)
                for pattern in keywordPatterns]

        classFormat = QTextCharFormat()
        classFormat.setFontWeight(QFont.Bold)
        classFormat.setForeground(Qt.darkMagenta)
        self.highlightingRules.append((QRegExp("\\bQ[A-Za-z]+\\b"),
                classFormat))

        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(Qt.red)
        self.highlightingRules.append((QRegExp("//[^\n]*"),
                singleLineCommentFormat))

        self.multiLineCommentFormat = QTextCharFormat()
        self.multiLineCommentFormat.setForeground(Qt.red)

        quotationFormat = QTextCharFormat()
        quotationFormat.setForeground(Qt.darkGreen)
        self.highlightingRules.append((QRegExp("\".*\""), quotationFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setFontItalic(True)
        functionFormat.setForeground(Qt.blue)
        self.highlightingRules.append((QRegExp("\\b[A-Za-z0-9_]+(?=\\()"),
                functionFormat))

        self.commentStartExpression = QRegExp("/\\*")
        self.commentEndExpression = QRegExp("\\*/")
Exemplo n.º 30
0
 def __init__(self, interval, project, vcs, parent=None):
     """
     Constructor
     
     @param interval new interval in seconds (integer)
     @param project reference to the project object (Project)
     @param vcs reference to the version control object
     @param parent reference to the parent object (QObject)
     """
     VcsStatusMonitorThread.__init__(self, interval, project, vcs, parent)
     
     self.__ioEncoding = Preferences.getSystem("IOEncoding")
     
     self.rx_status1 = \
         QRegExp('(.{8,9})\\s+([0-9-]+)\\s+(.+)\\s*')
     self.rx_status2 = QRegExp(
         '(.{8,9})\\s+([0-9-]+)\\s+([0-9?]+)\\s+(\\S+)\\s+(.+)\\s*')
Exemplo n.º 31
0
 def textFiltering(self):
     reg_num = QRegExp('^[0-9]{5}$')
     validator_num = QRegExpValidator(self)
     validator_num.setRegExp(reg_num)
     self.setValidator(validator_num)
Exemplo n.º 32
0
 def mainWin(self):
     # Filtra l'input per il tempo
     self.delayTimer.setValidator(QRegExpValidator(QRegExp(r"[0-9]+")))
     # Collega i puldanti per le rispettive funzioni
     self.startTimer.clicked.connect(lambda: self.startTime())
     self.stopTimer.clicked.connect(lambda: self.stopTime())
    def __init__(self, mode=RegExpMode, parent=None):
        """
        Constructor
        
        @param mode mode of the dialog (one of RegExpMode, WildcardMode,
            W3CMode)
        @param parent parent widget (QWidget)
        """
        super(QRegExpWizardCharactersDialog, self).__init__(parent)
        self.setupUi(self)

        self.__mode = mode

        if mode == QRegExpWizardCharactersDialog.WildcardMode:
            self.predefinedBox.setEnabled(False)
            self.predefinedBox.hide()
        elif mode == QRegExpWizardCharactersDialog.RegExpMode:
            self.w3cInitialIdentifierCheckBox.hide()
            self.w3cNonInitialIdentifierCheckBox.hide()
            self.w3cNmtokenCheckBox.hide()
            self.w3cNonNmtokenCheckBox.hide()
        elif mode == QRegExpWizardCharactersDialog.W3CMode:
            self.__initCharacterSelectors()

        self.comboItems = []
        self.singleComboItems = []  # these are in addition to the above
        self.comboItems.append((self.tr("Normal character"), "-c"))
        if mode == QRegExpWizardCharactersDialog.RegExpMode:
            self.comboItems.append(
                (self.tr("Unicode character in hexadecimal notation"), "-h"))
            self.comboItems.append(
                (self.tr("ASCII/Latin1 character in octal notation"), "-o"))
            self.singleComboItems.append(("---", "-i"))
            self.singleComboItems.append(
                (self.tr("Bell character (\\a)"), "\\a"))
            self.singleComboItems.append((self.tr("Page break (\\f)"), "\\f"))
            self.singleComboItems.append((self.tr("Line feed (\\n)"), "\\n"))
            self.singleComboItems.append(
                (self.tr("Carriage return (\\r)"), "\\r"))
            self.singleComboItems.append(
                (self.tr("Horizontal tabulator (\\t)"), "\\t"))
            self.singleComboItems.append(
                (self.tr("Vertical tabulator (\\v)"), "\\v"))
        elif mode == QRegExpWizardCharactersDialog.W3CMode:
            self.comboItems.append(
                (self.tr("Unicode character in hexadecimal notation"), "-h"))
            self.comboItems.append(
                (self.tr("ASCII/Latin1 character in octal notation"), "-o"))
            self.singleComboItems.append(("---", "-i"))
            self.singleComboItems.append((self.tr("Line feed (\\n)"), "\\n"))
            self.singleComboItems.append(
                (self.tr("Carriage return (\\r)"), "\\r"))
            self.singleComboItems.append(
                (self.tr("Horizontal tabulator (\\t)"), "\\t"))
            self.singleComboItems.append(("---", "-i"))
            self.singleComboItems.append(
                (self.tr("Character Category"), "-ccp"))
            self.singleComboItems.append((self.tr("Character Block"), "-cbp"))
            self.singleComboItems.append(
                (self.tr("Not Character Category"), "-ccn"))
            self.singleComboItems.append(
                (self.tr("Not Character Block"), "-cbn"))

        self.charValidator = QRegExpValidator(QRegExp(".{0,1}"), self)
        self.hexValidator = QRegExpValidator(QRegExp("[0-9a-fA-F]{0,4}"), self)
        self.octValidator = QRegExpValidator(QRegExp("[0-3]?[0-7]{0,2}"), self)

        # generate dialog part for single characters
        self.singlesBoxLayout = QVBoxLayout(self.singlesBox)
        self.singlesBoxLayout.setObjectName("singlesBoxLayout")
        self.singlesBoxLayout.setSpacing(6)
        self.singlesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesBox.setLayout(self.singlesBoxLayout)
        self.singlesView = QScrollArea(self.singlesBox)
        self.singlesView.setObjectName("singlesView")
        self.singlesBoxLayout.addWidget(self.singlesView)

        self.singlesItemsBox = QWidget(self)
        self.singlesView.setWidget(self.singlesItemsBox)
        self.singlesItemsBox.setObjectName("singlesItemsBox")
        self.singlesItemsBox.setMinimumWidth(1000)
        self.singlesItemsBoxLayout = QVBoxLayout(self.singlesItemsBox)
        self.singlesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.singlesItemsBoxLayout.setSpacing(6)
        self.singlesItemsBox.setLayout(self.singlesItemsBoxLayout)
        self.singlesEntries = []
        self.__addSinglesLine()

        hlayout0 = QHBoxLayout()
        hlayout0.setContentsMargins(0, 0, 0, 0)
        hlayout0.setSpacing(6)
        hlayout0.setObjectName("hlayout0")
        self.moreSinglesButton = QPushButton(self.tr("Additional Entries"),
                                             self.singlesBox)
        self.moreSinglesButton.setObjectName("moreSinglesButton")
        hlayout0.addWidget(self.moreSinglesButton)
        hspacer0 = QSpacerItem(30, 20, QSizePolicy.Expanding,
                               QSizePolicy.Minimum)
        hlayout0.addItem(hspacer0)
        self.singlesBoxLayout.addLayout(hlayout0)
        self.moreSinglesButton.clicked.connect(self.__addSinglesLine)

        # generate dialog part for character ranges
        self.rangesBoxLayout = QVBoxLayout(self.rangesBox)
        self.rangesBoxLayout.setObjectName("rangesBoxLayout")
        self.rangesBoxLayout.setSpacing(6)
        self.rangesBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesBox.setLayout(self.rangesBoxLayout)
        self.rangesView = QScrollArea(self.rangesBox)
        self.rangesView.setObjectName("rangesView")
        self.rangesBoxLayout.addWidget(self.rangesView)

        self.rangesItemsBox = QWidget(self)
        self.rangesView.setWidget(self.rangesItemsBox)
        self.rangesItemsBox.setObjectName("rangesItemsBox")
        self.rangesItemsBox.setMinimumWidth(1000)
        self.rangesItemsBoxLayout = QVBoxLayout(self.rangesItemsBox)
        self.rangesItemsBoxLayout.setContentsMargins(6, 6, 6, 6)
        self.rangesItemsBoxLayout.setSpacing(6)
        self.rangesItemsBox.setLayout(self.rangesItemsBoxLayout)
        self.rangesEntries = []
        self.__addRangesLine()

        hlayout1 = QHBoxLayout()
        hlayout1.setContentsMargins(0, 0, 0, 0)
        hlayout1.setSpacing(6)
        hlayout1.setObjectName("hlayout1")
        self.moreRangesButton = QPushButton(self.tr("Additional Entries"),
                                            self.rangesBox)
        self.moreSinglesButton.setObjectName("moreRangesButton")
        hlayout1.addWidget(self.moreRangesButton)
        hspacer1 = QSpacerItem(30, 20, QSizePolicy.Expanding,
                               QSizePolicy.Minimum)
        hlayout1.addItem(hspacer1)
        self.rangesBoxLayout.addLayout(hlayout1)
        self.moreRangesButton.clicked.connect(self.__addRangesLine)
Exemplo n.º 34
0
class SvnMergeDialog(QDialog, Ui_SvnMergeDialog):
    """
    Class implementing a dialog to enter the data for a merge operation.
    """
    def __init__(self,
                 mergelist1,
                 mergelist2,
                 targetlist,
                 force=False,
                 parent=None):
        """
        Constructor
        
        @param mergelist1 list of previously entered URLs/revisions
            (list of strings)
        @param mergelist2 list of previously entered URLs/revisions
            (list of strings)
        @param targetlist list of previously entered targets (list of strings)
        @param force flag indicating a forced merge (boolean)
        @param parent parent widget (QWidget)
        """
        super(SvnMergeDialog, self).__init__(parent)
        self.setupUi(self)

        self.forceCheckBox.setChecked(force)

        self.rx_url = QRegExp('(?:file:|svn:|svn+ssh:|http:|https:)//.+')
        self.rx_rev = QRegExp('\\d+')

        self.tag1Combo.clear()
        self.tag1Combo.addItems(mergelist1)
        self.tag2Combo.clear()
        self.tag2Combo.addItems(mergelist2)
        self.targetCombo.clear()
        self.targetCombo.addItems(targetlist)

        self.okButton = self.buttonBox.button(QDialogButtonBox.Ok)
        self.okButton.setEnabled(False)

        msh = self.minimumSizeHint()
        self.resize(max(self.width(), msh.width()), msh.height())

    def __enableOkButton(self):
        """
        Private method used to enable/disable the OK-button.
        """
        self.okButton.setDisabled(
            self.tag1Combo.currentText() != ""
            or self.tag2Combo.currentText() != "" or
            not ((self.rx_url.exactMatch(self.tag1Combo.currentText())
                  and self.rx_url.exactMatch(self.tag2Combo.currentText())) or
                 (self.rx_rev.exactMatch(self.tag1Combo.currentText())
                  and self.rx_rev.exactMatch(self.tag2Combo.currentText()))))

    def on_tag1Combo_editTextChanged(self, text):
        """
        Private slot to handle the tag1Combo editTextChanged signal.
        
        @param text text of the combo (string)
        """
        self.__enableOkButton()

    def on_tag2Combo_editTextChanged(self, text):
        """
        Private slot to handle the tag2Combo editTextChanged signal.
        
        @param text text of the combo (string)
        """
        self.__enableOkButton()

    def getParameters(self):
        """
        Public method to retrieve the merge data.
        
        @return tuple naming two tag names or two revisions, a target and
            a flag indicating a forced merge (string, string, string, boolean)
        """
        return (self.tag1Combo.currentText(), self.tag2Combo.currentText(),
                self.targetCombo.currentText(), self.forceCheckBox.isChecked())
Exemplo n.º 35
0
class SvnChangeListsDialog(QDialog, Ui_SvnChangeListsDialog):
    """
    Class implementing a dialog to browse the change lists.
    """
    def __init__(self, vcs, parent=None):
        """
        Constructor
        
        @param vcs reference to the vcs object
        @param parent parent widget (QWidget)
        """
        super(SvnChangeListsDialog, self).__init__(parent)
        self.setupUi(self)

        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Cancel).setDefault(True)

        self.process = None
        self.vcs = vcs

        self.rx_status = QRegExp(
            '(.{8,9})\\s+([0-9-]+)\\s+([0-9?]+)\\s+(\\S+)\\s+(.+)\\s*')
        # flags (8 or 9 anything), revision, changed rev, author, path
        self.rx_status2 = \
            QRegExp('(.{8,9})\\s+(.+)\\s*')
        # flags (8 or 9 anything), path
        self.rx_changelist = \
            QRegExp('--- \\S+ .([\\w\\s]+).:\\s+')
        # three dashes, Changelist (translated), quote,
        # changelist name, quote, :

    @pyqtSlot(QListWidgetItem, QListWidgetItem)
    def on_changeLists_currentItemChanged(self, current, previous):
        """
        Private slot to handle the selection of a new item.
        
        @param current current item (QListWidgetItem)
        @param previous previous current item (QListWidgetItem)
        """
        self.filesList.clear()
        if current is not None:
            changelist = current.text()
            if changelist in self.changeListsDict:
                self.filesList.addItems(
                    sorted(self.changeListsDict[changelist]))

    def start(self, path):
        """
        Public slot to populate the data.
        
        @param path directory name to show change lists for (string)
        """
        self.changeListsDict = {}

        self.filesLabel.setText(
            self.tr("Files (relative to {0}):").format(path))

        self.errorGroup.hide()
        self.intercept = False

        self.path = path
        self.currentChangelist = ""

        self.process = QProcess()
        self.process.finished.connect(self.__procFinished)
        self.process.readyReadStandardOutput.connect(self.__readStdout)
        self.process.readyReadStandardError.connect(self.__readStderr)

        args = []
        args.append('status')
        self.vcs.addArguments(args, self.vcs.options['global'])
        self.vcs.addArguments(args, self.vcs.options['status'])
        if '--verbose' not in self.vcs.options['global'] and \
           '--verbose' not in self.vcs.options['status']:
            args.append('--verbose')
        if isinstance(path, list):
            self.dname, fnames = self.vcs.splitPathList(path)
            self.vcs.addArguments(args, fnames)
        else:
            self.dname, fname = self.vcs.splitPath(path)
            args.append(fname)

        self.process.setWorkingDirectory(self.dname)

        self.process.start('svn', args)
        procStarted = self.process.waitForStarted(5000)
        if not procStarted:
            self.inputGroup.setEnabled(False)
            self.inputGroup.hide()
            E5MessageBox.critical(
                self, self.tr('Process Generation Error'),
                self.tr(
                    'The process {0} could not be started. '
                    'Ensure, that it is in the search path.').format('svn'))
        else:
            self.inputGroup.setEnabled(True)
            self.inputGroup.show()

    def __finish(self):
        """
        Private slot called when the process finished or the user pressed
        the button.
        """
        if self.process is not None and \
           self.process.state() != QProcess.NotRunning:
            self.process.terminate()
            QTimer.singleShot(2000, self.process.kill)
            self.process.waitForFinished(3000)

        self.buttonBox.button(QDialogButtonBox.Close).setEnabled(True)
        self.buttonBox.button(QDialogButtonBox.Cancel).setEnabled(False)
        self.buttonBox.button(QDialogButtonBox.Close).setDefault(True)

        self.inputGroup.setEnabled(False)
        self.inputGroup.hide()

        if len(self.changeListsDict) == 0:
            self.changeLists.addItem(self.tr("No changelists found"))
            self.buttonBox.button(QDialogButtonBox.Close).setFocus(
                Qt.OtherFocusReason)
        else:
            self.changeLists.addItems(sorted(self.changeListsDict.keys()))
            self.changeLists.setCurrentRow(0)
            self.changeLists.setFocus(Qt.OtherFocusReason)

    def on_buttonBox_clicked(self, button):
        """
        Private slot called by a button of the button box clicked.
        
        @param button button that was clicked (QAbstractButton)
        """
        if button == self.buttonBox.button(QDialogButtonBox.Close):
            self.close()
        elif button == self.buttonBox.button(QDialogButtonBox.Cancel):
            self.__finish()

    def __procFinished(self, exitCode, exitStatus):
        """
        Private slot connected to the finished signal.
        
        @param exitCode exit code of the process (integer)
        @param exitStatus exit status of the process (QProcess.ExitStatus)
        """
        self.__finish()

    def __readStdout(self):
        """
        Private slot to handle the readyReadStandardOutput signal.
        
        It reads the output of the process, formats it and inserts it into
        the contents pane.
        """
        if self.process is not None:
            self.process.setReadChannel(QProcess.StandardOutput)

            while self.process.canReadLine():
                s = str(self.process.readLine(),
                        Preferences.getSystem("IOEncoding"), 'replace')
                if self.currentChangelist != "" and \
                        self.rx_status.exactMatch(s):
                    file = self.rx_status.cap(5).strip()
                    filename = file.replace(self.path + os.sep, "")
                    if filename not in \
                            self.changeListsDict[self.currentChangelist]:
                        self.changeListsDict[self.currentChangelist].append(
                            filename)
                elif self.currentChangelist != "" and \
                        self.rx_status2.exactMatch(s):
                    file = self.rx_status2.cap(2).strip()
                    filename = file.replace(self.path + os.sep, "")
                    if filename not in \
                            self.changeListsDict[self.currentChangelist]:
                        self.changeListsDict[self.currentChangelist].append(
                            filename)
                elif self.rx_changelist.exactMatch(s):
                    self.currentChangelist = self.rx_changelist.cap(1)
                    if self.currentChangelist not in self.changeListsDict:
                        self.changeListsDict[self.currentChangelist] = []

    def __readStderr(self):
        """
        Private slot to handle the readyReadStandardError signal.
        
        It reads the error output of the process and inserts it into the
        error pane.
        """
        if self.process is not None:
            self.errorGroup.show()
            s = str(self.process.readAllStandardError(),
                    Preferences.getSystem("IOEncoding"), 'replace')
            self.errors.insertPlainText(s)
            self.errors.ensureCursorVisible()

    def on_passwordCheckBox_toggled(self, isOn):
        """
        Private slot to handle the password checkbox toggled.
        
        @param isOn flag indicating the status of the check box (boolean)
        """
        if isOn:
            self.input.setEchoMode(QLineEdit.Password)
        else:
            self.input.setEchoMode(QLineEdit.Normal)

    @pyqtSlot()
    def on_sendButton_clicked(self):
        """
        Private slot to send the input to the subversion process.
        """
        input = self.input.text()
        input += os.linesep

        if self.passwordCheckBox.isChecked():
            self.errors.insertPlainText(os.linesep)
            self.errors.ensureCursorVisible()
        else:
            self.errors.insertPlainText(input)
            self.errors.ensureCursorVisible()

        self.process.write(input)

        self.passwordCheckBox.setChecked(False)
        self.input.clear()

    def on_input_returnPressed(self):
        """
        Private slot to handle the press of the return key in the input field.
        """
        self.intercept = True
        self.on_sendButton_clicked()

    def keyPressEvent(self, evt):
        """
        Protected slot to handle a key press event.
        
        @param evt the key press event (QKeyEvent)
        """
        if self.intercept:
            self.intercept = False
            evt.accept()
            return
        super(SvnChangeListsDialog, self).keyPressEvent(evt)
                def __init__(self):
                    QDialog.__init__(self)

                    grid = QGridLayout()
                    grid.setSpacing(20)

                    self.lbl = QLabel()
                    self.pixmap = QPixmap('./images/logos/verbinding.jpg')
                    self.lbl.setPixmap(self.pixmap)
                    grid.addWidget(self.lbl, 0, 1, 1, 2)

                    self.logo = QLabel()
                    self.pixmap = QPixmap('./images/logos/logo.jpg')
                    self.logo.setPixmap(self.pixmap)
                    grid.addWidget(self.logo, 0, 2, 1, 1, Qt.AlignRight)

                    grid.addWidget(QLabel('Clusternummer               '+clusternr+\
                                        '\n'+momschr[:35]), 1, 1, 1, 3)

                    self.setFont(QFont('Arial', 10))
                    grid.addWidget(
                        QLabel('Artikelnummer               ' +
                               str(artikelnr)), 3, 1, 1, 3)

                    self.setWindowTitle("Clusters Samenstellen")
                    self.setWindowIcon(QIcon('./images/logos/logo.jpg'))
                    self.setFont(QFont('Arial', 10))

                    self.Hoeveelheid = QLabel(self)
                    self.Hoeveelheid.setText('Hoeveelheid ')
                    self.hoev = QLineEdit(self)
                    self.hoev.setFixedWidth(210)
                    reg_ex = QRegExp("^[-+]?[0-9]*\.?[0-9]+$")
                    input_validator = QRegExpValidator(reg_ex, self.hoev)
                    self.hoev.setValidator(input_validator)

                    grid.addWidget(self.Hoeveelheid, 4, 1)
                    grid.addWidget(self.hoev, 4, 2)

                    grid.addWidget(
                        QLabel(
                            '\u00A9 2017 all rights reserved\n     [email protected]'
                        ), 6, 0, 1, 3, Qt.AlignCenter)

                    self.applyBtn = QPushButton('Invoeren', self)
                    self.applyBtn.clicked.connect(self.clickMethod)
                    grid.addWidget(self.applyBtn, 5, 2, 1, 1, Qt.AlignRight)
                    self.applyBtn.setFont(QFont("Arial", 10))
                    self.applyBtn.setFixedWidth(100)
                    self.applyBtn.setStyleSheet(
                        "color: black;  background-color: gainsboro")

                    self.cancelBtn = QPushButton('Sluiten')
                    self.cancelBtn.clicked.connect(self.close)
                    grid.addWidget(self.cancelBtn, 5, 1, 1, 2, Qt.AlignCenter)
                    self.cancelBtn.setFont(QFont("Arial", 10))
                    self.cancelBtn.setFixedWidth(100)
                    self.cancelBtn.setStyleSheet(
                        "color: black;  background-color: gainsboro")

                    self.setLayout(grid)
                    self.setGeometry(500, 100, 150, 150)
Exemplo n.º 37
0
 def __init__(self, *args):
     self.prefix = 'COM'
     super().__init__(QRegExp('[1-9]{1}[0-9]{0,2}'), *args)
Exemplo n.º 38
0
 def start(self, path, tags=True):
     """
     Public slot to start the svn status command.
     
     @param path name of directory to be listed (string)
     @param tags flag indicating a list of tags is requested
             (False = branches, True = tags)
     @return flag indicating success (boolean)
     """
     self.errorGroup.hide()
     
     if not tags:
         self.setWindowTitle(self.tr("Subversion Branches List"))
     self.activateWindow()
     QApplication.processEvents()
     
     dname, fname = self.vcs.splitPath(path)
     
     reposURL = self.vcs.svnGetReposName(dname)
     if reposURL is None:
         E5MessageBox.critical(
             self,
             self.tr("Subversion Error"),
             self.tr(
                 """The URL of the project repository could not be"""
                 """ retrieved from the working copy. The list operation"""
                 """ will be aborted"""))
         self.close()
         return False
     
     if self.vcs.otherData["standardLayout"]:
         # determine the base path of the project in the repository
         rx_base = QRegExp('(.+)/(trunk|tags|branches).*')
         if not rx_base.exactMatch(reposURL):
             E5MessageBox.critical(
                 self,
                 self.tr("Subversion Error"),
                 self.tr(
                     """The URL of the project repository has an"""
                     """ invalid format. The list operation will"""
                     """ be aborted"""))
             return False
         
         reposRoot = rx_base.cap(1)
         
         if tags:
             path = "{0}/tags".format(reposRoot)
         else:
             path = "{0}/branches".format(reposRoot)
     else:
         reposPath, ok = QInputDialog.getText(
             self,
             self.tr("Subversion List"),
             self.tr("Enter the repository URL containing the"
                     " tags or branches"),
             QLineEdit.Normal,
             self.vcs.svnNormalizeURL(reposURL))
         if not ok:
             self.close()
             return False
         if not reposPath:
             E5MessageBox.critical(
                 self,
                 self.tr("Subversion List"),
                 self.tr(
                     """The repository URL is empty. Aborting..."""))
             self.close()
             return False
         path = reposPath
     
     locker = QMutexLocker(self.vcs.vcsExecutionMutex)
     self.tagsList = []
     cwd = os.getcwd()
     os.chdir(dname)
     try:
         entries = self.client.list(path, recurse=False)
         # dirent, lock already unicode in Python 2
         for dirent, lock in entries:
             if dirent["path"] != path:
                 name = dirent["path"].replace(path + '/', "")
                 self.__generateItem(dirent["created_rev"].number,
                                     dirent["last_author"],
                                     formatTime(dirent["time"]),
                                     name)
                 if self.vcs.otherData["standardLayout"]:
                     self.tagsList.append(name)
                 else:
                     self.tagsList.append(path + '/' + name)
                 if self._clientCancelCallback():
                     break
         res = True
     except pysvn.ClientError as e:
         self.__showError(e.args[0])
         res = False
     except AttributeError:
         self.__showError(
             self.tr("The installed version of PySvn should be"
                     " 1.4.0 or better."))
         res = False
     locker.unlock()
     self.__finish()
     os.chdir(cwd)
     return res
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowTitle("Cluster -> Artikelen bereik")
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))

            self.setFont(QFont('Arial', 10))

            self.Clusternummer = QLabel()
            clEdit = QLineEdit()
            clEdit.setFixedWidth(210)
            font = QFont("Arial", 10)
            font.setCapitalization(QFont.AllUppercase)
            clEdit.setFont(font)
            reg_ex = QRegExp('^[L-Tl-t]{1}[A-Za-z]{1}[0-9]{5}')
            input_validator = QRegExpValidator(reg_ex, clEdit)
            clEdit.setValidator(input_validator)
            clEdit.textChanged.connect(self.clChanged)

            self.Keuze = QLabel()
            k0Edit = QComboBox()
            k0Edit.setFixedWidth(320)
            k0Edit.setFont(QFont("Arial", 10))
            k0Edit.setStyleSheet("color: black;  background-color: #F8F7EE")
            k0Edit.addItem('                  Zoeken Artikelen')
            k0Edit.addItem('1. Alle Artikelen')
            k0Edit.addItem('2. Filter op artikelnummers')
            k0Edit.addItem('3. Filter op artikelomschrijving')
            k0Edit.activated[str].connect(self.k0Changed)

            self.Zoekterm = QLabel()
            zktermEdit = QLineEdit()
            zktermEdit.setFixedWidth(210)
            zktermEdit.setFont(QFont("Arial", 10))
            reg_ex = QRegExp('^.{0,20}$')
            input_validator = QRegExpValidator(reg_ex, zktermEdit)
            zktermEdit.setValidator(input_validator)
            zktermEdit.textChanged.connect(self.zktermChanged)

            grid = QGridLayout()
            grid.setSpacing(20)

            lbl = QLabel()
            pixmap = QPixmap('./images/logos/verbinding.jpg')
            lbl.setPixmap(pixmap)
            grid.addWidget(lbl, 1, 0, 1, 2)

            lbl2 = QLabel('Clusternummer')
            lbl2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl2, 2, 0)
            grid.addWidget(clEdit, 2, 1)

            grid.addWidget(k0Edit, 3, 0, 1, 2, Qt.AlignRight)
            lbl1 = QLabel('Zoekterm')
            lbl1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl1, 4, 0)
            grid.addWidget(zktermEdit, 4, 1)

            self.setLayout(grid)
            self.setGeometry(500, 300, 150, 150)

            grid.addWidget(
                QLabel('\u00A9 2017 all rights reserved [email protected]'),
                6, 0, 1, 3)

            logo = QLabel()
            pixmap = QPixmap('./images/logos/logo.jpg')
            logo.setPixmap(pixmap)
            grid.addWidget(logo, 1, 1, 1, 1, Qt.AlignRight)

            applyBtn = QPushButton('Zoeken')
            applyBtn.clicked.connect(self.accept)

            grid.addWidget(applyBtn, 5, 1, 1, 1, Qt.AlignRight)
            applyBtn.setFont(QFont("Arial", 10))
            applyBtn.setFixedWidth(100)
            applyBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            cancelBtn = QPushButton('Sluiten')
            cancelBtn.clicked.connect(lambda: windowSluit(self, m_email))

            grid.addWidget(cancelBtn, 5, 1, 1, 2)
            cancelBtn.setFont(QFont("Arial", 10))
            cancelBtn.setFixedWidth(100)
            cancelBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")
Exemplo n.º 40
0
    def initUI(self, pos_offset):

        self.setWindowTitle(f"DataViewer - {self.df.name}")
        self.setGeometry(80 + pos_offset, 300 + pos_offset, 900, 650)

        # for the status bar
        main_widget = QWidget()
        self.statusBar()

        self.tsCanvas = mkTimeSeriesCanvas()
        main_frame = QWidget()
        self.tsCanvas.setParent(main_frame)
        ntb = NavigationToolbar(self.tsCanvas, main_frame)  # full toolbar

        # the table instance,
        DataTable = QTableView()
        model = PandasModel(self.df)
        DataTable.setModel(model)
        DataTable.setSelectionBehavior(2)  # columns only
        DataTable.clicked.connect(
            self.Table_select)  # magically transports QModelIndex
        # so that it also works for header selection
        header = DataTable.horizontalHeader()  # returns QHeaderView
        header.sectionClicked.connect(
            self.Header_select)  # magically transports QModelIndex

        # size policy for DataTable, not needed..?!
        # size_pol= QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        # DataTable.setSizePolicy(size_pol)

        # the signal selection box
        SignalBox = QComboBox(self)
        SignalBox.setStatusTip(
            "..or just click directly on a signal in the table!")

        main_layout_v = QVBoxLayout()  # The whole Layout
        # Data selction drop-down
        dataLabel = QLabel("Select Signal", self)

        dt_label = QLabel("Sampling Interval:")
        self.dt_edit = QLineEdit()
        self.dt_edit.setStatusTip("How much time in between two recordings?")
        self.dt_edit.setMinimumSize(70, 0)  # no effect :/
        self.dt_edit.setValidator(posfloatV)

        unit_label = QLabel("Time Unit:")
        self.unit_edit = QLineEdit(self)
        self.unit_edit.setStatusTip("Changes only the axis labels..")
        self.unit_edit.setMinimumSize(70, 0)

        top_bar_box = QWidget()
        top_bar_layout = QHBoxLayout()

        top_bar_layout.addWidget(dataLabel)
        top_bar_layout.addWidget(SignalBox)
        top_bar_layout.addStretch(0)
        top_bar_layout.addWidget(dt_label)
        top_bar_layout.addWidget(self.dt_edit)
        top_bar_layout.addStretch(0)
        top_bar_layout.addWidget(unit_label)
        top_bar_layout.addWidget(self.unit_edit)
        top_bar_layout.addStretch(0)
        top_bar_box.setLayout(top_bar_layout)

        top_and_table = QGroupBox("Settings and Data")
        top_and_table_layout = QVBoxLayout()
        top_and_table_layout.addWidget(top_bar_box)
        top_and_table_layout.addWidget(DataTable)
        top_and_table.setLayout(top_and_table_layout)
        main_layout_v.addWidget(top_and_table)

        ## detrending parameter

        self.T_c_edit = QLineEdit()
        self.T_c_edit.setMaximumWidth(70)
        self.T_c_edit.setValidator(posfloatV)
        self.T_c_edit.setStatusTip("..in time units, e.g. 120min")

        sinc_options_box = QGroupBox("Sinc Detrending")
        sinc_options_layout = QGridLayout()
        sinc_options_layout.addWidget(QLabel("Cut-off Period:"), 0, 0)
        sinc_options_layout.addWidget(self.T_c_edit, 0, 1)
        sinc_options_box.setLayout(sinc_options_layout)

        ## Amplitude envelope parameter
        self.wsize_edit = QLineEdit()
        self.wsize_edit.setMaximumWidth(70)
        self.wsize_edit.setValidator(self.envelopeV)
        self.wsize_edit.setStatusTip("..in time units, e.g. 120min")

        envelope_options_box = QGroupBox("Amplitude Envelope")
        envelope_options_layout = QGridLayout()
        envelope_options_layout.addWidget(QLabel("Window Size:"), 0, 0)
        envelope_options_layout.addWidget(self.wsize_edit, 0, 1)
        envelope_options_box.setLayout(envelope_options_layout)

        # plot options box
        plot_options_box = QGroupBox("Plotting Options")
        plot_options_layout = QGridLayout()

        self.cb_raw = QCheckBox("Raw Signal", self)
        self.cb_raw.setStatusTip("Plots the raw unfiltered signal")

        self.cb_trend = QCheckBox("Trend", self)
        self.cb_trend.setStatusTip("Plots the sinc filtered signal")

        self.cb_detrend = QCheckBox("Detrended Signal", self)
        self.cb_detrend.setStatusTip(
            "Plots the signal after trend subtraction (detrending)")

        self.cb_envelope = QCheckBox("Envelope", self)
        self.cb_envelope.setStatusTip("Plots the estimated amplitude envelope")

        plotButton = QPushButton("Refresh Plot", self)
        plotButton.setStatusTip(
            "Updates the plot with the new filter parameter values")
        plotButton.clicked.connect(self.doPlot)

        saveButton = QPushButton("Save Filter Results", self)
        saveButton.clicked.connect(self.save_out_trend)
        saveButton.setStatusTip(
            "Writes the trend and the detrended signal into a file")

        ## checkbox layout
        plot_options_layout.addWidget(self.cb_raw, 0, 0)
        plot_options_layout.addWidget(self.cb_trend, 0, 1)
        plot_options_layout.addWidget(self.cb_detrend, 1, 0)
        plot_options_layout.addWidget(self.cb_envelope, 1, 1)
        plot_options_layout.addWidget(plotButton, 2, 0)
        plot_options_layout.addWidget(saveButton, 2, 1, 1, 1)
        plot_options_box.setLayout(plot_options_layout)

        ## checkbox signal set and change
        self.cb_raw.toggle()

        self.cb_raw.stateChanged.connect(self.toggle_raw)
        self.cb_trend.stateChanged.connect(self.toggle_trend)
        self.cb_detrend.stateChanged.connect(self.toggle_trend)
        self.cb_envelope.stateChanged.connect(self.toggle_envelope)

        # Ploting box/Canvas area
        plot_box = QGroupBox("Signal and Trend")
        plot_layout = QVBoxLayout()
        plot_layout.addWidget(self.tsCanvas)
        plot_layout.addWidget(ntb)
        plot_box.setLayout(plot_layout)

        # Analyzer box with tabs
        ana_widget = QGroupBox("Analysis")
        ana_box = QVBoxLayout()

        ## Initialize tab scresen
        tabs = QTabWidget()
        tab1 = QWidget()
        tab2 = QWidget()

        ## Add tabs
        tabs.addTab(tab1, "Wavelet Analysis")
        tabs.addTab(tab2, "Fourier Transform")

        ## Create first tab
        tab1.parameter_box = QFormLayout()

        ## for wavlet params, button, etc.
        self.Tmin_edit = QLineEdit()
        self.Tmin_edit.setStatusTip("This is the lower period limit")
        self.nT_edit = QLineEdit()
        self.nT_edit.setValidator(QRegExpValidator(QRegExp('[0-9]+')))
        self.nT_edit.setStatusTip(
            "Increase this number for more spectral resolution")
        self.Tmax_edit = QLineEdit()
        self.Tmax_edit.setStatusTip("This is the upper period limit")

        self.pow_max_edit = QLineEdit()
        self.pow_max_edit.setStatusTip(
            "Enter a fixed value or leave blank for automatic wavelet power scaling"
        )

        Tmin_lab = QLabel("Lowest period")
        step_lab = QLabel("Number of periods")
        Tmax_lab = QLabel("Highest  period")
        pow_max_lab = QLabel("Expected maximal power")

        Tmin_lab.setWordWrap(True)
        step_lab.setWordWrap(True)
        Tmax_lab.setWordWrap(True)
        pow_max_lab.setWordWrap(True)

        wletButton = QPushButton("Analyze Signal", self)
        wletButton.setStyleSheet("background-color: lightblue")
        wletButton.setStatusTip("Opens the wavelet analysis..")
        wletButton.clicked.connect(self.run_wavelet_ana)

        batchButton = QPushButton("Analyze All..", self)
        batchButton.clicked.connect(self.run_batch)
        batchButton.setStatusTip("Starts the batch processing")

        ## add  button to layout
        wlet_button_layout_h = QHBoxLayout()

        wlet_button_layout_h.addStretch(0)
        wlet_button_layout_h.addWidget(wletButton)
        wlet_button_layout_h.addStretch(0)
        wlet_button_layout_h.addWidget(batchButton)
        wlet_button_layout_h.addStretch(0)

        self.cb_use_detrended = QCheckBox("Use Detrended Signal", self)
        # self.cb_use_detrended.stateChanged.connect(self.toggle_trend)
        self.cb_use_detrended.setChecked(True)  # detrend by default

        self.cb_use_envelope = QCheckBox("Normalize with Envelope", self)
        self.cb_use_envelope.stateChanged.connect(self.toggle_envelope)
        self.cb_use_envelope.setChecked(False)  # no envelope by default

        ## Add Wavelet analyzer options to tab1.parameter_box layout

        tab1.parameter_box.addRow(Tmin_lab, self.Tmin_edit)
        tab1.parameter_box.addRow(Tmax_lab, self.Tmax_edit)
        tab1.parameter_box.addRow(step_lab, self.nT_edit)
        tab1.parameter_box.addRow(pow_max_lab, self.pow_max_edit)
        tab1.parameter_box.addRow(self.cb_use_detrended)
        tab1.parameter_box.addRow(self.cb_use_envelope)
        tab1.parameter_box.addRow(wlet_button_layout_h)

        tab1.setLayout(tab1.parameter_box)

        # fourier button
        fButton = QPushButton("Analyze Signal", self)
        ## add  button to layout
        f_button_layout_h = QHBoxLayout()
        fButton.clicked.connect(self.run_fourier_ana)
        f_button_layout_h.addStretch(0)
        f_button_layout_h.addWidget(fButton)

        # fourier detrended switch
        self.cb_use_detrended2 = QCheckBox("Use Detrended Signal", self)
        self.cb_use_detrended2.setChecked(True)  # detrend by default

        self.cb_use_envelope2 = QCheckBox("Normalize with Envelope", self)
        self.cb_use_envelope2.setChecked(False)

        # fourier period or frequency view
        self.cb_FourierT = QCheckBox("Show Frequencies", self)
        self.cb_FourierT.setChecked(False)  # show periods per default

        ## Create second tab
        tab2.parameter_box = QFormLayout()
        # tab2.parameter_box.addRow(Tmin_lab,self.Tmin)
        # tab2.parameter_box.addRow(Tmax_lab,self.Tmax)
        tab2.parameter_box.addRow(self.cb_use_detrended2)
        tab2.parameter_box.addRow(self.cb_use_envelope2)
        tab2.parameter_box.addRow(self.cb_FourierT)
        tab2.parameter_box.addRow(f_button_layout_h)
        tab2.setLayout(tab2.parameter_box)

        # Add tabs to Vbox
        ana_box.addWidget(tabs)
        # set layout of ana_widget (will be added to options layout)
        # as ana_box (containing actual layout)
        ana_widget.setLayout(ana_box)

        # Fix size of table_widget containing parameter boxes
        # -> it's all done via column stretches of
        # the GridLayout below
        # size_pol= QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        # ana_widget.setSizePolicy(size_pol)

        # ==========Plot and Options Layout=================================
        # Merge Plotting canvas and options
        plot_and_options = QWidget()
        layout = QGridLayout()
        plot_and_options.setLayout(layout)

        layout.addWidget(plot_box, 0, 0, 4, 1)
        layout.addWidget(sinc_options_box, 0, 5, 1, 1)
        layout.addWidget(envelope_options_box, 0, 6, 1, 1)
        layout.addWidget(plot_options_box, 1, 5, 1, 2)
        layout.addWidget(ana_widget, 2, 5, 2, 2)

        # plotting-canvas column stretch <-> 1st (0th) column
        layout.setColumnStretch(0, 1)  # plot should stretch
        layout.setColumnMinimumWidth(0, 360)  # plot should not get too small

        layout.setColumnStretch(1, 0)  # options shouldn't stretch
        layout.setColumnStretch(2, 0)  # options shouldn't stretch

        # ==========Main Layout=======================================
        main_layout_v.addWidget(plot_and_options)  # is a VBox

        # populate signal selection box
        SignalBox.addItem("")  # empty initial selector

        for col in self.df.columns:
            SignalBox.addItem(col)

        # connect to plotting machinery
        SignalBox.activated[str].connect(self.select_signal_and_Plot)
        # to modify current index by table selections
        self.SignalBox = SignalBox

        # --- connect some parameter fields ---

        self.dt_edit.textChanged[str].connect(self.qset_dt)
        self.unit_edit.textChanged[str].connect(self.qset_time_unit)

        # --- initialize parameter fields from settings ---

        self.load_settings()

        main_widget.setLayout(main_layout_v)
        self.setCentralWidget(main_widget)
        self.show()
Exemplo n.º 41
0
from configparser import ConfigParser
from datetime import datetime
from functools import partial
from smtplib import SMTPAuthenticationError, SMTPConnectError, SMTPServerDisconnected, SMTPNotSupportedError, \
    SMTPSenderRefused, SMTPDataError, SMTPRecipientsRefused, SMTPException
from threading import Thread, Lock

from PyQt5.QtCore import pyqtSignal, QRegExp
from PyQt5.QtGui import QFont, QRegExpValidator
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QTableWidgetItem, QFileDialog, QMessageBox, QPushButton

from GUI import Ui_MainWindow
from email_dialog import Ui_AddEmailDialog
from scheduling import TimedEmailMessage, SendingTimeMonitor

EMAIL_REGEXP = QRegExp(r'.+@[\w-]+\.\w+')

# Workaround for thread exceptions bug
old_run = Thread.run


def run(*args, **kwargs):
    try:
        old_run(*args, **kwargs)
    except Exception:
        sys.excepthook(*sys.exc_info())


Thread.run = run
#####################################
Exemplo n.º 42
0
    def __init__(self, project_manager: ProjectManager, is_tx: bool, parent=None, testing_mode=False):
        super().__init__(parent)
        self.is_tx = is_tx
        self.update_interval = 25

        self.setWindowFlags(Qt.Window)
        self.testing_mode = testing_mode

        self.ui = Ui_SendRecvDialog()
        self.ui.setupUi(self)
        self.ui.splitter.setHandleWidth(6)

        self.set_sniff_ui_items_visible(False)

        self.graphics_view = None  # type: QGraphicsView
        self.__device = None  # type: VirtualDevice

        self.backend_handler = BackendHandler()

        self.ui.btnStop.setEnabled(False)
        self.ui.btnClear.setEnabled(False)
        self.ui.btnSave.setEnabled(False)

        self.start = 0

        self.bw_sr_are_locked = constants.SETTINGS.value("lock_bandwidth_sample_rate", True, bool)

        self.ui.spinBoxFreq.setValue(project_manager.device_conf["frequency"])
        self.ui.spinBoxSampleRate.setValue(project_manager.device_conf["sample_rate"])
        self.ui.spinBoxBandwidth.setValue(project_manager.device_conf["bandwidth"])
        self.ui.spinBoxGain.setValue(project_manager.device_conf["gain"])
        try:
            if_gain = project_manager.device_conf["if_gain"]
        except KeyError:
            if_gain = config.DEFAULT_IF_GAIN
        self.ui.spinBoxIFGain.setValue(if_gain)

        try:
            baseband_gain = project_manager.device_conf["baseband_gain"]
        except KeyError:
            baseband_gain = config.DEFAULT_BB_GAIN
        self.ui.spinBoxBasebandGain.setValue(baseband_gain)

        try:
            freq_correction = project_manager.device_conf["freq_correction"]
        except KeyError:
            freq_correction = config.DEFAULT_FREQ_CORRECTION
        self.ui.spinBoxFreqCorrection.setValue(freq_correction)

        self.ui.spinBoxNRepeat.setValue(constants.SETTINGS.value('num_sending_repeats', 1, type=int))
        device = project_manager.device

        self.ui.cbDevice.clear()
        items = self.get_devices_for_combobox()
        self.ui.cbDevice.addItems(items)

        if device in items:
            self.ui.cbDevice.setCurrentIndex(items.index(device))

        if testing_mode:
            self.ui.cbDevice.setCurrentText(NetworkSDRInterfacePlugin.NETWORK_SDR_NAME)

        self.timer = QTimer(self)

        dev_name = self.ui.cbDevice.currentText()
        self.set_device_ui_items_visibility(dev_name, adjust_gains=False)

        self.ui.btnLockBWSR.setChecked(self.bw_sr_are_locked)
        self.on_btn_lock_bw_sr_clicked()

        ip_range = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])"
        ip_regex = QRegExp("^" + ip_range
                          + "\\." + ip_range
                          + "\\." + ip_range
                          + "\\." + ip_range + "$")
        self.ui.lineEditIP.setValidator(QRegExpValidator(ip_regex))

        try:
            self.restoreGeometry(constants.SETTINGS.value("{}/geometry".format(self.__class__.__name__)))
        except TypeError:
            pass

        self.ui.splitter.setSizes([0.4 * self.width(), 0.6 * self.width()])
Exemplo n.º 43
0
    def __init__(self):
        """
        Constructor
        """
        super(NsHtmlReader, self).__init__()

        self.__folderRx = QRegExp("<DT><H3(.*)>(.*)</H3>", Qt.CaseInsensitive)
        self.__folderRx.setMinimal(True)

        self.__endFolderRx = QRegExp("</DL>", Qt.CaseInsensitive)

        self.__bookmarkRx = QRegExp("<DT><A(.*)>(.*)</A>", Qt.CaseInsensitive)
        self.__bookmarkRx.setMinimal(True)

        self.__descRx = QRegExp("<DD>(.*)", Qt.CaseInsensitive)

        self.__separatorRx = QRegExp("<HR>", Qt.CaseInsensitive)

        self.__urlRx = QRegExp('HREF="(.*)"', Qt.CaseInsensitive)
        self.__urlRx.setMinimal(True)

        self.__addedRx = QRegExp('ADD_DATE="(\d*)"', Qt.CaseInsensitive)
        self.__addedRx.setMinimal(True)

        self.__modifiedRx = QRegExp('LAST_MODIFIED="(\d*)"',
                                    Qt.CaseInsensitive)
        self.__modifiedRx.setMinimal(True)

        self.__visitedRx = QRegExp('LAST_VISIT="(\d*)"', Qt.CaseInsensitive)
        self.__visitedRx.setMinimal(True)

        self.__foldedRx = QRegExp("FOLDED", Qt.CaseInsensitive)
Exemplo n.º 44
0
    def initUI(self):

        self.dict_gen = Dictionary_generator('merriam webster',
                                             ['noun', 'verb', 'adjective'],
                                             'random')

        self.setWindowTitle('Dictionary Text Generator')

        screen_rect = QDesktopWidget().availableGeometry(self)
        screen_w, screen_h = screen_rect.width(), screen_rect.height()
        app_w = screen_w * .25
        app_h = screen_h * .75
        self.resize(app_w, app_h)

        selectDictionaryLabel = QLabel('Select dictionary to use:')
        selectDictionaryLabel.setAlignment(Qt.AlignTop)
        self.selectDictionaryDropdown = QComboBox()
        self.selectDictionaryDropdown.addItems(
            Dictionary_generator.dictionaries)

        selectMethodLabel = QLabel('Select method to use:')
        self.selectMethodDropdown = QComboBox()
        self.selectMethodDropdown.addItems(Dictionary_generator.methods)

        originWordLabel = QLabel(
            'Choose origin word(s) (if multiple, use a comma separated list):')
        self.originWord = QLineEdit()
        regexp = QRegExp('^[a-zA-Z]+(,[ ][a-zA-Z]+)*')
        self.validator = QRegExpValidator(regexp)
        self.originWord.setValidator(self.validator)

        numberOfWordsLabel = QLabel('Choose number of words used per output:')
        self.numberOfWords = QSpinBox()
        self.numberOfWords.setMinimum(1)

        numberOfLoopsLabel = QLabel('Choose number of times to loop output:')
        self.numberOfLoops = QSpinBox()
        self.numberOfLoops.setMinimum(1)

        generateButton = QPushButton('Generate text')
        #generateButton.clicked.connect(self.generate_text)
        generateButton.clicked.connect(self.start_generation)

        noteText = QLabel(
            'Note: Parts of speech used are noun, verb, and adjective')

        self.output = QLabel('')
        self.output.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        self.output.setWordWrap(True)
        self.output.setAlignment(Qt.AlignTop)

        outputScrollArea = QScrollArea()
        outputScrollArea.setWidget(self.output)
        outputScrollArea.setWidgetResizable(True)

        clearTextButton = QPushButton('Clear output')
        clearTextButton.clicked.connect(self.clear_text)

        parametersGroup = QGroupBox('Input Parameters:')
        outputGroup = QGroupBox('Output:')

        parametersLayout = QVBoxLayout()
        outputLayout = QVBoxLayout()

        parametersLayout.addWidget(selectDictionaryLabel)
        parametersLayout.addWidget(self.selectDictionaryDropdown)
        parametersLayout.addWidget(selectMethodLabel)
        parametersLayout.addWidget(self.selectMethodDropdown)
        parametersLayout.addWidget(originWordLabel)
        parametersLayout.addWidget(self.originWord)
        parametersLayout.addWidget(numberOfWordsLabel)
        parametersLayout.addWidget(self.numberOfWords)
        parametersLayout.addWidget(numberOfLoopsLabel)
        parametersLayout.addWidget(self.numberOfLoops)
        parametersLayout.addWidget(generateButton)
        parametersLayout.setAlignment(generateButton, Qt.AlignCenter)
        parametersLayout.addWidget(noteText)

        outputLayout.addWidget(outputScrollArea)
        outputLayout.addWidget(clearTextButton)
        outputLayout.setAlignment(clearTextButton, Qt.AlignCenter)

        parametersGroup.setLayout(parametersLayout)
        parametersGroup.setMaximumHeight(app_h * .4)
        outputGroup.setLayout(outputLayout)

        mainLayout = QVBoxLayout(self)
        mainLayout.addWidget(parametersGroup)
        mainLayout.addWidget(outputGroup)

        self.setLayout(mainLayout)
Exemplo n.º 45
0
class NsHtmlReader(QObject):
    """
    Class implementing a reader object for Netscape HTML bookmark files.
    """
    indentSize = 4

    def __init__(self):
        """
        Constructor
        """
        super(NsHtmlReader, self).__init__()

        self.__folderRx = QRegExp("<DT><H3(.*)>(.*)</H3>", Qt.CaseInsensitive)
        self.__folderRx.setMinimal(True)

        self.__endFolderRx = QRegExp("</DL>", Qt.CaseInsensitive)

        self.__bookmarkRx = QRegExp("<DT><A(.*)>(.*)</A>", Qt.CaseInsensitive)
        self.__bookmarkRx.setMinimal(True)

        self.__descRx = QRegExp("<DD>(.*)", Qt.CaseInsensitive)

        self.__separatorRx = QRegExp("<HR>", Qt.CaseInsensitive)

        self.__urlRx = QRegExp('HREF="(.*)"', Qt.CaseInsensitive)
        self.__urlRx.setMinimal(True)

        self.__addedRx = QRegExp('ADD_DATE="(\d*)"', Qt.CaseInsensitive)
        self.__addedRx.setMinimal(True)

        self.__modifiedRx = QRegExp('LAST_MODIFIED="(\d*)"',
                                    Qt.CaseInsensitive)
        self.__modifiedRx.setMinimal(True)

        self.__visitedRx = QRegExp('LAST_VISIT="(\d*)"', Qt.CaseInsensitive)
        self.__visitedRx.setMinimal(True)

        self.__foldedRx = QRegExp("FOLDED", Qt.CaseInsensitive)

    def read(self, fileNameOrDevice):
        """
        Public method to read a Netscape HTML bookmark file.
        
        @param fileNameOrDevice name of the file to read (string)
            or reference to the device to read (QIODevice)
        @return reference to the root node (BookmarkNode)
        """
        if isinstance(fileNameOrDevice, QIODevice):
            dev = fileNameOrDevice
        else:
            f = QFile(fileNameOrDevice)
            if not f.exists():
                return BookmarkNode(BookmarkNode.Root)
            f.open(QFile.ReadOnly)
            dev = f

        folders = []
        lastNode = None

        root = BookmarkNode(BookmarkNode.Root)
        folders.append(root)

        while not dev.atEnd():
            line = str(dev.readLine(), encoding="utf-8").rstrip()
            if self.__folderRx.indexIn(line) != -1:
                # folder definition
                arguments = self.__folderRx.cap(1)
                name = self.__folderRx.cap(2)
                node = BookmarkNode(BookmarkNode.Folder, folders[-1])
                node.title = Utilities.html_udecode(name)
                node.expanded = self.__foldedRx.indexIn(arguments) == -1
                if self.__addedRx.indexIn(arguments) != -1:
                    node.added = QDateTime.fromTime_t(
                        int(self.__addedRx.cap(1)))
                folders.append(node)
                lastNode = node

            elif self.__endFolderRx.indexIn(line) != -1:
                # end of folder definition
                folders.pop()

            elif self.__bookmarkRx.indexIn(line) != -1:
                # bookmark definition
                arguments = self.__bookmarkRx.cap(1)
                name = self.__bookmarkRx.cap(2)
                node = BookmarkNode(BookmarkNode.Bookmark, folders[-1])
                node.title = Utilities.html_udecode(name)
                if self.__urlRx.indexIn(arguments) != -1:
                    node.url = self.__urlRx.cap(1)
                if self.__addedRx.indexIn(arguments) != -1:
                    node.added = QDateTime.fromTime_t(
                        int(self.__addedRx.cap(1)))
                if self.__modifiedRx.indexIn(arguments) != -1:
                    node.modified = QDateTime.fromTime_t(
                        int(self.__modifiedRx.cap(1)))
                if self.__visitedRx.indexIn(arguments) != -1:
                    node.visited = QDateTime.fromTime_t(
                        int(self.__visitedRx.cap(1)))
                lastNode = node

            elif self.__descRx.indexIn(line) != -1:
                # description
                if lastNode:
                    lastNode.desc = Utilities.html_udecode(
                        self.__descRx.cap(1))

            elif self.__separatorRx.indexIn(line) != -1:
                # separator definition
                BookmarkNode(BookmarkNode.Separator, folders[-1])

        return root
Exemplo n.º 46
0
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowTitle('Bestelregels inkooporder materialen invoeren')
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))

            self.setFont(QFont('Arial', 10))

            self.Inkoopordernummer = QLabel()
            inkorderEdit = QLineEdit(str(minkordnr))
            inkorderEdit.setDisabled(True)
            inkorderEdit.setFixedWidth(130)
            inkorderEdit.setFont(QFont("Arial", 10))
            inkorderEdit.textChanged.connect(self.inkorderChanged)

            self.BestelregelArtikel = QLabel()
            artEdit = QLineEdit()
            artEdit.setFixedWidth(130)
            artEdit.setFont(QFont("Arial", 10))
            artEdit.textChanged.connect(self.artChanged)
            reg_ex = QRegExp("^[2#]{1}[0-9]{8}$")
            input_validator = QRegExpValidator(reg_ex, artEdit)
            artEdit.setValidator(input_validator)

            self.BestelHoeveelheid = QLabel()
            hoevEdit = QLineEdit()
            hoevEdit.setFixedWidth(130)
            hoevEdit.setFont(QFont("Arial", 10))
            hoevEdit.textChanged.connect(self.hoevChanged)
            reg_ex = QRegExp("^[0-9.]{0,12}$")
            input_validator = QRegExpValidator(reg_ex, hoevEdit)
            hoevEdit.setValidator(input_validator)

            self.Inkoopeenheidsprijs = QLabel()
            prijsEdit = QLineEdit()
            prijsEdit.setFixedWidth(130)
            prijsEdit.setFont(QFont("Arial", 10))
            prijsEdit.textChanged.connect(self.prijsChanged)
            reg_ex = QRegExp("^[0-9.]{0,12}$")
            input_validator = QRegExpValidator(reg_ex, prijsEdit)
            prijsEdit.setValidator(input_validator)

            self.Levering_start = QLabel()
            #levertEdit = QDateEdit(datetime.date)
            startEdit = QLineEdit('')
            startEdit.setCursorPosition(0)
            startEdit.setFixedWidth(130)
            startEdit.setFont(QFont("Arial", 10))
            startEdit.textChanged.connect(self.startChanged)
            reg_ex = QRegExp(
                '^[2]{1}[0]{1}[0-9]{2}[-]{1}[0-1]{1}[0-9]{1}[-]{1}[0-3]{1}[0-9]{1}$'
            )
            input_validator = QRegExpValidator(reg_ex, startEdit)
            startEdit.setValidator(input_validator)

            self.Levering_end = QLabel()
            #levertEdit = QDateEdit(datetime.date)
            endEdit = QLineEdit('')
            endEdit.setCursorPosition(0)
            endEdit.setFixedWidth(130)
            endEdit.setFont(QFont("Arial", 10))
            endEdit.textChanged.connect(self.endChanged)
            reg_ex = QRegExp(
                '^[2]{1}[0]{1}[0-9]{2}[-]{1}[0-1]{1}[0-9]{1}[-]{1}[0-3]{1}[0-9]{1}$'
            )
            input_validator = QRegExpValidator(reg_ex, endEdit)
            endEdit.setValidator(input_validator)

            grid = QGridLayout()
            grid.setSpacing(20)

            lbl = QLabel()
            pixmap = QPixmap('./images/logos/verbinding.jpg')
            lbl.setPixmap(pixmap)
            grid.addWidget(lbl, 1, 0)

            self.setFont(QFont('Arial', 10))
            grid.addWidget(QLabel('Bestelling voor\nLeverancier: '+str(minkgeg[1])+\
              ',\n'+minkgeg[2]+' '+minkgeg[3]+',\n'+minkgeg[4]+' '+str(minkgeg[5])+\
              minkgeg[6]+',\n'+minkgeg[7]+' '+minkgeg[8]+'.\nOrderregel '+str(mregel)), 1, 1, 1, 2)

            lbl1 = QLabel('Ordernummer')
            lbl1.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl1, 5, 0)
            grid.addWidget(inkorderEdit, 5, 1)

            lbl2 = QLabel('Artikelnummer')
            lbl2.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl2, 6, 0)
            grid.addWidget(artEdit, 6, 1)

            lbl3 = QLabel('Bestelhoeveelheid')
            lbl3.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl3, 7, 0)
            grid.addWidget(hoevEdit, 7, 1)

            lbl4 = QLabel('Inkoopeenheidsprijs')
            lbl4.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl4, 8, 0)
            grid.addWidget(prijsEdit, 8, 1)

            lbl5 = QLabel('Levering start jjjj-mm-dd')
            lbl5.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl5, 9, 0)
            grid.addWidget(startEdit, 9, 1)

            lbl6 = QLabel('Levering eind jjjj-mm-dd')
            lbl6.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            grid.addWidget(lbl6, 10, 0)
            grid.addWidget(endEdit, 10, 1)

            logo = QLabel()
            pixmap = QPixmap('./images/logos/logo.jpg')
            logo.setPixmap(pixmap)
            grid.addWidget(logo, 5, 2, 1, 1, Qt.AlignRight)

            self.setLayout(grid)
            self.setGeometry(100, 100, 150, 150)

            applyBtn = QPushButton('Invoeren')
            applyBtn.clicked.connect(self.accept)

            grid.addWidget(applyBtn, 11, 2, 1, 1, Qt.AlignRight)
            applyBtn.setFont(QFont("Arial", 10))
            applyBtn.setFixedWidth(100)
            applyBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            sluitBtn = QPushButton('Sluiten')
            sluitBtn.clicked.connect(self.close)

            grid.addWidget(sluitBtn, 11, 1, 1, 2)
            sluitBtn.setFont(QFont("Arial", 10))
            sluitBtn.setFixedWidth(100)
            sluitBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            grid.addWidget(
                QLabel('\u00A9 2017 all rights reserved [email protected]'),
                12, 0, 1, 3, Qt.AlignCenter)
Exemplo n.º 47
0
 def validate_data(self, reg_exp, field_name):
     field = getattr(self, field_name)
     reg_ex = QRegExp(reg_exp)
     input_validator = QRegExpValidator(reg_ex, field)
     field.setValidator(input_validator)
        def __init__(self, parent=None):
            super(Widget, self).__init__(parent)
            self.setWindowTitle("Opvragen Webverkooporder")
            self.setWindowIcon(QIcon('./images/logos/logo.jpg'))

            self.setFont(QFont('Arial', 10))

            self.Keuze = QLabel()
            k0Edit = QComboBox()
            k0Edit.setFixedWidth(230)
            k0Edit.setFont(QFont("Arial", 10))
            k0Edit.setStyleSheet("color: black;  background-color: #F8F7EE")
            k0Edit.addItem(' Sorteersleutel voor zoeken')
            k0Edit.addItem('1. Alle Orders')
            k0Edit.addItem('2. Gefilterd op postcode')
            k0Edit.addItem('3. Gefilterd op achternaam')
            k0Edit.addItem('4. Gefilterd op ordernummer')
            k0Edit.addItem('5. Gefilterd op besteldatum')
            k0Edit.activated[str].connect(self.k0Changed)

            self.Zoekterm = QLabel()
            zktrmEdit = QLineEdit()
            zktrmEdit.setFixedWidth(220)
            zktrmEdit.setFont(QFont("Arial", 10))
            zktrmEdit.textChanged.connect(self.zktrmChanged)
            reg_ex = QRegExp('.*$')
            input_validator = QRegExpValidator(reg_ex, zktrmEdit)
            zktrmEdit.setValidator(input_validator)

            grid = QGridLayout()
            grid.setSpacing(20)

            lbl = QLabel()
            pixmap = QPixmap('./images/logos/verbinding.jpg')
            lbl.setPixmap(pixmap)
            grid.addWidget(lbl, 1, 0, 1, 2)

            logo = QLabel()
            pixmap = QPixmap('./images/logos/logo.jpg')
            logo.setPixmap(pixmap)
            grid.addWidget(logo, 1, 1, 1, 2, Qt.AlignRight)

            lbl1 = QLabel('Zoekterm')
            grid.addWidget(lbl1, 3, 0, 1, 1, Qt.AlignRight)
            grid.addWidget(zktrmEdit, 3, 1, 1, 2)
            grid.addWidget(k0Edit, 2, 1, 1, 2, Qt.AlignRight)

            self.setLayout(grid)
            self.setGeometry(500, 300, 150, 150)

            grid.addWidget(
                QLabel('\u00A9 2017 all rights reserved [email protected]'),
                5, 0, 1, 3, Qt.AlignCenter)

            applyBtn = QPushButton('Zoeken')
            applyBtn.clicked.connect(self.accept)

            grid.addWidget(applyBtn, 4, 2, 1, 1, Qt.AlignRight)
            applyBtn.setFont(QFont("Arial", 10))
            applyBtn.setFixedWidth(100)
            applyBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")

            closeBtn = QPushButton('Sluiten')
            closeBtn.clicked.connect(lambda: windowSluit(self, m_email))

            grid.addWidget(closeBtn, 4, 1, 1, 1, Qt.AlignRight)
            closeBtn.setFont(QFont("Arial", 10))
            closeBtn.setFixedWidth(100)
            closeBtn.setStyleSheet(
                "color: black;  background-color: gainsboro")
Exemplo n.º 49
0
    def initUi(self):
        self.setFixedSize(400, 200)                      # 创建固定窗口大小         # 窗口标题
        self.setWindowFlags(Qt.FramelessWindowHint)      # 设置窗口无边框
        self.setWindowIcon(QIcon(':/logo.png')) 

        window_pale = QPalette()                           # 创建窗口背景图片对象
        window_pale.setBrush(self.backgroundRole(),\
                QBrush(QPixmap("UI/image/login.jpg")))        # 按指定路径找到图片
        self.setPalette(window_pale)

        pee = QPalette()                                  # 设置程序显示名的颜色
        pee.setColor(QPalette.WindowText,Qt.white)
        colo = QPalette()                                    #设置普通文字的颜色
        colo.setColor(QPalette.WindowText,Qt.red)
        
        if self.error == 'normal':
            self.lbl_main = QLabel('货运信息公共平台', self)    #设置程序的名字
            self.lbl_main.setPalette(pee)
        elif self.error == 'NetworkConnectIonisFailed':
            self.lbl_main = QLabel('*网络连接失败*', self)    #设置程序的名字
            self.lbl_main.setPalette(colo)
        self.lbl_main.move(10, 10)

        pe = QPalette()                                    #设置普通文字的颜色
        pe.setColor(QPalette.WindowText,Qt.gray)
        lucency = "background:transparent;border-width:\
                0;border-style:outset"

        self.lbl_user = QLabel('账号:', self)                 # 创建一个标题用户名标题
        self.lbl_user.move(110, 55)
        self.lbl_user.setPalette(pe)
        
        self.Edit_user = QLineEdit(self)                       # 创建一个用户名输入框对象
        self.Edit_user.setGeometry(150, 45, 140, 30)           # 设置输入框的位置大小
        self.Edit_user.setPlaceholderText('手机号码')           # 悬浮显示提示信息
        self.Edit_user.setStyleSheet(lucency)                  # 透明输入框                      # 无边框设置
        self.Edit_user.setValidator(QRegExpValidator\
                    (QRegExp("[0-9]+"),self))                  # 限制用户输入信息的类型
        self.Edit_user.setMaxLength(11)                        # 输入框中的信息最大长度11
        self.Edit_user.setToolTip('用户名只能为11位的电话号码')  # 输入框的提示语句
        
        self.lbl_password = QLabel('密码:', self)               # 创建密码标签
        self.lbl_password.move(110, 90)
        self.lbl_password.setPalette(pe)

        self.Edit_password = QLineEdit(self)                   # 创建密码输入框
        self.Edit_password.setGeometry(150, 80, 140, 30)
        self.Edit_password.setPlaceholderText('密码')
        self.Edit_password.setStyleSheet(lucency)
        self.Edit_password.setValidator(QRegExpValidator\
                            (QRegExp("[A-Za-z0-9]+"),self))
        self.Edit_password.setEchoMode(QLineEdit.Password)     #隐藏显示密码为圆点
        self.Edit_password.setMaxLength(16)
        self.Edit_password.setToolTip('用户密码最大长度为16位')
        
        # 设置按键背景和悬停的属性变量
        color = "QPushButton{border:none;color:rgb(55, 255, 255);}"\
            "QPushButton:hover{border:none;color:rgb(255, 255, 255);}"
        color2 = "QPushButton{border:none;}"\
                "QPushButton:hover{border-image:\
                url(%s);border:none;}"

        self.button_register = QPushButton('注册', self)      # 创建注册按钮对象
        self.button_register.setGeometry(76, 160, 70, 28)
        self.button_register.setStyleSheet(color)             # 给按钮添加属性

        self.button_lose = QPushButton('忘记密码', self)       # 创建忘记密码按钮对象
        self.button_lose.setGeometry(250, 160, 70, 28)
        self.button_lose.setStyleSheet(color)

        self.button_login = QPushButton(' ', self)             # 创建登陆按钮对象
        self.button_login.setGeometry(88, 130, 230, 26)
        self.button_login.setStyleSheet(color2 % 'UI/image/login1.png')
        
        self.button_little = QPushButton(' ', self)            # 创建最小化按钮对象
        self.button_little.setGeometry(336, 0, 32, 25)
        self.button_little.setToolTip('最小化')
        self.button_little.setStyleSheet(color2 % 'UI/image/login3.png')
        
        self.button_close = QPushButton(' ', self)             # 创建关闭按钮对象
        self.button_close.setGeometry(368, 0, 32, 25)
        self.button_close.setToolTip('关闭')
        self.button_close.setStyleSheet(color2 % 'UI/image/login2.png')
        
        self.centralwidget = QWidget(self)                     # 创建一个QWidget窗口对象
        self.centralwidget.setGeometry(317, 40, 100, 40)       # 设置对象的大小位置
        self.gridLayout = QGridLayout(self.centralwidget)      # 在self.centralwidget窗口中添加一个布局
        self.centralwidget2 = QWidget(self)
        self.centralwidget2.setGeometry(317, 76, 100, 40)
        self.gridLayout2 = QGridLayout(self.centralwidget2)
        
        screen = self.frameGeometry()                           # 窗口居中显示
        wall = QDesktopWidget().availableGeometry().center()
        screen.moveCenter(wall)
        self.move(screen.topLeft())

        self.button_little.clicked.connect(self.showMinimized)   # 为按键添加信号事件
        self.button_close.clicked.connect(self.close_quit)
    
        self.Edit_user.installEventFilter(self)                  # 定义对象获取焦点事件
        self.Edit_password.installEventFilter(self)
Exemplo n.º 50
0
    def __init__(self):
        """

        """
        super(wearTableView, self).__init__()
        self.setupUi(self)
        self.toolbar = QtWidgets.QToolBar("Navigation")
        self.addToolBar(self.toolbar)
        self.refreshAct = QtWidgets.QAction(QtGui.QIcon("refresh1.ico"),
                                            "刷新织轴卡列表")
        self.firstAct = QtWidgets.QAction(QtGui.QIcon("firstPage1.ico"),
                                          "查看第一页织轴卡列表")
        self.prevAct = QtWidgets.QAction(QtGui.QIcon("prevPage2.ico"),
                                         "查看上一页织轴卡列表")
        self.lastAct = QtWidgets.QAction(QtGui.QIcon("lastPage2.ico"),
                                         "查看下一页织轴卡列表")
        self.endAct = QtWidgets.QAction(QtGui.QIcon("endPage1.ico"),
                                        "查看最后一页织轴卡列表")
        self.lookLatestAct = QtWidgets.QAction(QtGui.QIcon("Eye.ico"),
                                               "查看最新织轴卡")

        self.lableFont = QFont("Roman times", 12, QFont.Bold)
        self.timeLable = QtWidgets.QLabel()
        self.timeLable.setSizePolicy(
            QtWidgets.QSizePolicy.Expanding,
            self.timeLable.sizePolicy().verticalPolicy())
        self.nowtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        self.timeLable.setText(str(self.nowtime))
        self.timeLable.setFont(self.lableFont)
        self.timeLable.setStyleSheet("color:blue")
        self.timeLable.setAlignment(Qt.AlignCenter)

        self.curPage = 0
        self.curPageEdit = QLineEdit()
        validator = QRegExpValidator(QRegExp("\d+"))
        self.curPageEdit.setValidator(validator)  # 设置只能输入数字
        self.curPageEdit.setText(str(self.curPage))
        self.curPageEdit.setMaximumSize(QSize(40, 20))
        self.curPageEdit.setFont(self.lableFont)
        self.curPageEdit.setStyleSheet("color:blue")
        self.curPageEdit.setAlignment(Qt.AlignCenter)

        self.totalPage = 0
        self.totalPageLable = QtWidgets.QLabel()
        self.totalPageLable.setText("/" + str(self.totalPage) + "(共" +
                                    str(self.totalPage) + "页)")
        self.totalPageLable.setFont(self.lableFont)
        self.totalPageLable.setStyleSheet("color:blue")
        self.totalPageLable.setAlignment(Qt.AlignCenter)

        self.backAct = QtWidgets.QAction(QtGui.QIcon("Back.ico"), "返回设备列表")

        self.toolbar.addAction(self.refreshAct)
        self.toolbar.addAction(self.firstAct)
        self.toolbar.addAction(self.prevAct)
        self.toolbar.addWidget(self.curPageEdit)
        self.toolbar.addWidget(self.totalPageLable)
        self.toolbar.addAction(self.lastAct)
        self.toolbar.addAction(self.endAct)
        self.toolbar.addAction(self.lookLatestAct)
        self.toolbar.addWidget(self.timeLable)
        self.toolbar.addAction(self.backAct)
        self.wearTable.setHorizontalHeaderLabels(
            ["序号", "设备名称", "所属厂区", "洛轴时间"])
        self.wearTable.verticalHeader().setVisible(False)  # 隐藏纵向表头
        rect = self.wearTable.rect()
        self.wearTable.setColumnWidth(0, 50)
        self.wearTable.setColumnWidth(1, (rect.width() - 50) / 3)
        self.wearTable.setColumnWidth(2, (rect.width() - 50) / 3)
        self.wearTable.setColumnWidth(3, (rect.width() - 50) / 3)
Exemplo n.º 51
0
def get_int_mask() -> QRegExpValidator:
    return QRegExpValidator(QRegExp("[1-9][0-9]*"))
Exemplo n.º 52
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(897, 663)  #设置窗口大小
        self.F = matplot.MyFigure([], [], width=1, height=1, dpi=60)  #轨迹展示图
        # 初始化赋值,(航母的个数等还未初始化)!!
        self.planedata = []  #用于飞机数据保存
        self.shipdata = []  #用于航母数据保存
        self.actionArray = []  #飞机动作序列
        self.shipActionArray = []  #航母动作序列
        self.raddata = []  #飞机电磁数据
        self.num = 1  #计数
        self.savenum = 1  #保存次数计数
        self.formation = 1  #编队标志位
        self.checkedNum = 0  #飞机数量
        self.planeGap = 500  #编队距离
        self.mainShip = 1  #主舰数量默认为1
        self.destroyer = 0  ## 驱逐舰数量
        self.frigate = 0  #护卫舰数量
        self.sig1 = 0  #飞机初始位置是否设置,标志位
        self.sig2 = 0  #航母初始位置是否设置,标志位
        #以下为界面设计,QTdesigner自动生成的代码
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout_4 = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.line_18 = QtWidgets.QFrame(self.centralwidget)
        self.line_18.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_18.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_18.setObjectName("line_18")
        self.gridLayout_4.addWidget(self.line_18, 0, 1, 1, 1)
        self.line_19 = QtWidgets.QFrame(self.centralwidget)
        self.line_19.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_19.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_19.setObjectName("line_19")
        self.gridLayout_4.addWidget(self.line_19, 1, 0, 1, 1)
        self.gridLayout_9 = QtWidgets.QGridLayout()
        self.gridLayout_9.setObjectName("gridLayout_9")
        self.line_15 = QtWidgets.QFrame(self.centralwidget)
        self.line_15.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_15.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_15.setObjectName("line_15")
        self.gridLayout_9.addWidget(self.line_15, 0, 1, 1, 1)
        self.verticalLayout_8 = QtWidgets.QVBoxLayout()
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        self.gridLayout_5 = QtWidgets.QGridLayout()
        self.gridLayout_5.setObjectName("gridLayout_5")
        spacerItem = QtWidgets.QSpacerItem(20, 40,
                                           QtWidgets.QSizePolicy.Minimum,
                                           QtWidgets.QSizePolicy.Expanding)
        self.gridLayout_5.addItem(spacerItem, 7, 0, 1, 1)
        spacerItem1 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.gridLayout_5.addItem(spacerItem1, 0, 0, 1, 1)
        self.line_2 = QtWidgets.QFrame(self.centralwidget)
        self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_2.setObjectName("line_2")
        self.gridLayout_5.addWidget(self.line_2, 4, 0, 1, 3)
        self.line_5 = QtWidgets.QFrame(self.centralwidget)
        self.line_5.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_5.setObjectName("line_5")
        self.gridLayout_5.addWidget(self.line_5, 1, 0, 1, 3)
        self.line_3 = QtWidgets.QFrame(self.centralwidget)
        self.line_3.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_3.setObjectName("line_3")
        self.gridLayout_5.addWidget(self.line_3, 5, 1, 1, 1)
        self.line = QtWidgets.QFrame(self.centralwidget)
        self.line.setFrameShape(QtWidgets.QFrame.HLine)
        self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line.setObjectName("line")
        self.gridLayout_5.addWidget(self.line, 6, 0, 1, 3)
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout.addWidget(self.label_4)
        self.planetype = QtWidgets.QComboBox(self.centralwidget)
        self.planetype.setObjectName("planetype")
        self.planetype.addItem("")
        self.planetype.addItem("")
        self.planetype.addItem("")
        self.horizontalLayout.addWidget(self.planetype)
        spacerItem2 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout.addItem(spacerItem2)
        self.gridLayout_5.addLayout(self.horizontalLayout, 2, 0, 1, 3)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setObjectName("label_5")
        self.verticalLayout_2.addWidget(self.label_5)
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        spacerItem3 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem3)
        self.formation = QtWidgets.QComboBox(self.centralwidget)
        self.formation.setObjectName("formation")
        self.formation.addItem("")
        self.formation.addItem("")
        self.horizontalLayout_3.addWidget(self.formation)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.line_4 = QtWidgets.QFrame(self.centralwidget)
        self.line_4.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_4.setObjectName("line_4")
        self.verticalLayout_2.addWidget(self.line_4)
        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setObjectName("label_9")
        self.verticalLayout_2.addWidget(self.label_9)
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        spacerItem4 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem4)
        self.checkBox = QtWidgets.QCheckBox(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.checkBox.setFont(font)
        self.checkBox.setObjectName("checkBox")
        self.horizontalLayout_5.addWidget(self.checkBox)
        self.verticalLayout_2.addLayout(self.horizontalLayout_5)
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.label_12 = QtWidgets.QLabel(self.centralwidget)
        self.label_12.setObjectName("label_12")
        self.horizontalLayout_4.addWidget(self.label_12)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setObjectName("lineEdit")

        regx = QRegExp("^[0-9]{9}$")  #只允许输入数字
        validator = QRegExpValidator(regx, self.lineEdit)
        self.lineEdit.setValidator(validator)

        self.horizontalLayout_4.addWidget(self.lineEdit)
        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_8 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.label_10 = QtWidgets.QLabel(self.centralwidget)
        self.label_10.setObjectName("label_10")
        self.horizontalLayout_8.addWidget(self.label_10)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_2.setObjectName("lineEdit_2")

        validator = QRegExpValidator(regx, self.lineEdit_2)
        self.lineEdit_2.setValidator(validator)

        self.horizontalLayout_8.addWidget(self.lineEdit_2)
        self.verticalLayout.addLayout(self.horizontalLayout_8)
        self.horizontalLayout_9 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_9.setObjectName("horizontalLayout_9")
        self.label_11 = QtWidgets.QLabel(self.centralwidget)
        self.label_11.setObjectName("label_11")
        self.horizontalLayout_9.addWidget(self.label_11)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_3.setObjectName("lineEdit_3")

        validator = QRegExpValidator(regx, self.lineEdit_3)
        self.lineEdit_3.setValidator(validator)

        self.horizontalLayout_9.addWidget(self.lineEdit_3)
        self.verticalLayout.addLayout(self.horizontalLayout_9)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.gridLayout_5.addLayout(self.verticalLayout_2, 5, 0, 1, 1)
        self.gridLayout = QtWidgets.QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.turn = QtWidgets.QPushButton(self.centralwidget)
        self.turn.setObjectName("turn")
        self.gridLayout.addWidget(self.turn, 3, 0, 1, 1)
        self.falldown = QtWidgets.QPushButton(self.centralwidget)
        self.falldown.setObjectName("falldown")
        self.gridLayout.addWidget(self.falldown, 4, 0, 1, 1)
        self.flying = QtWidgets.QPushButton(self.centralwidget)
        self.flying.setObjectName("flying")
        self.gridLayout.addWidget(self.flying, 1, 0, 1, 1)
        self.climb = QtWidgets.QPushButton(self.centralwidget)
        self.climb.setObjectName("climb")
        self.gridLayout.addWidget(self.climb, 2, 0, 1, 1)
        self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit.setObjectName("textEdit")
        self.gridLayout.addWidget(self.textEdit, 0, 1, 6, 1)
        self.delete1 = QtWidgets.QPushButton(self.centralwidget)
        self.delete1.setStyleSheet("color: rgb(255, 0, 0);")
        self.delete1.setObjectName("delete1")
        self.gridLayout.addWidget(self.delete1, 5, 0, 1, 1)
        self.gridLayout_5.addLayout(self.gridLayout, 5, 2, 1, 1)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_2.addWidget(self.label_3)
        self.spinBox = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBox.setObjectName("spinBox")
        self.horizontalLayout_2.addWidget(self.spinBox)
        self.numchecked = QtWidgets.QPushButton(self.centralwidget)
        self.numchecked.setStyleSheet("color: rgb(255, 0, 0);")
        self.numchecked.setObjectName("numchecked")
        self.horizontalLayout_2.addWidget(self.numchecked)
        spacerItem5 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_2.addItem(spacerItem5)
        self.gridLayout_5.addLayout(self.horizontalLayout_2, 3, 0, 1, 3)
        self.gridLayout_5.setColumnStretch(0, 1)
        self.verticalLayout_8.addLayout(self.gridLayout_5)
        self.line_16 = QtWidgets.QFrame(self.centralwidget)
        self.line_16.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_16.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_16.setObjectName("line_16")
        self.verticalLayout_8.addWidget(self.line_16)
        self.verticalLayout_7 = QtWidgets.QVBoxLayout()
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        self.gridLayout_3 = QtWidgets.QGridLayout()
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.scheck1 = QtWidgets.QPushButton(self.centralwidget)
        self.scheck1.setStyleSheet("color: rgb(255, 0, 0);")
        self.scheck1.setObjectName("scheck1")
        self.gridLayout_3.addWidget(self.scheck1, 1, 2, 1, 1)
        self.label_8 = QtWidgets.QLabel(self.centralwidget)
        self.label_8.setObjectName("label_8")
        self.gridLayout_3.addWidget(self.label_8, 0, 0, 1, 3)
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setObjectName("label_7")
        self.gridLayout_3.addWidget(self.label_7, 1, 0, 1, 1)
        self.scheck2 = QtWidgets.QPushButton(self.centralwidget)
        self.scheck2.setStyleSheet("color: rgb(255, 0, 0);")
        self.scheck2.setObjectName("scheck2")
        self.gridLayout_3.addWidget(self.scheck2, 2, 2, 1, 1)
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setObjectName("label_6")
        self.gridLayout_3.addWidget(self.label_6, 2, 0, 1, 1)
        self.spinBox_2 = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBox_2.setObjectName("spinBox_2")
        self.gridLayout_3.addWidget(self.spinBox_2, 1, 1, 1, 1)
        self.spinBox_4 = QtWidgets.QSpinBox(self.centralwidget)
        self.spinBox_4.setObjectName("spinBox_4")
        self.gridLayout_3.addWidget(self.spinBox_4, 2, 1, 1, 1)
        spacerItem6 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.gridLayout_3.addItem(spacerItem6, 1, 3, 1, 1)
        self.verticalLayout_7.addLayout(self.gridLayout_3)
        self.line_13 = QtWidgets.QFrame(self.centralwidget)
        self.line_13.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_13.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_13.setObjectName("line_13")
        self.verticalLayout_7.addWidget(self.line_13)
        self.horizontalLayout_21 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_21.setObjectName("horizontalLayout_21")
        self.verticalLayout_6 = QtWidgets.QVBoxLayout()
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        self.label_16 = QtWidgets.QLabel(self.centralwidget)
        self.label_16.setObjectName("label_16")
        self.verticalLayout_6.addWidget(self.label_16)
        self.horizontalLayout_7 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        spacerItem7 = QtWidgets.QSpacerItem(40, 20,
                                            QtWidgets.QSizePolicy.Expanding,
                                            QtWidgets.QSizePolicy.Minimum)
        self.horizontalLayout_7.addItem(spacerItem7)
        self.checkBox_2 = QtWidgets.QCheckBox(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(10)
        self.checkBox_2.setFont(font)
        self.checkBox_2.setObjectName("checkBox_2")
        self.horizontalLayout_7.addWidget(self.checkBox_2)
        self.verticalLayout_6.addLayout(self.horizontalLayout_7)
        self.line_6 = QtWidgets.QFrame(self.centralwidget)
        self.line_6.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_6.setObjectName("line_6")
        self.verticalLayout_6.addWidget(self.line_6)
        self.gridLayout_6 = QtWidgets.QGridLayout()
        self.gridLayout_6.setObjectName("gridLayout_6")
        self.label_14 = QtWidgets.QLabel(self.centralwidget)
        self.label_14.setObjectName("label_14")
        self.gridLayout_6.addWidget(self.label_14, 1, 0, 1, 2)
        self.lineEdit_5 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_5.setObjectName("lineEdit_5")
        validator = QRegExpValidator(regx, self.lineEdit_5)
        self.lineEdit_5.setValidator(validator)

        self.gridLayout_6.addWidget(self.lineEdit_5, 1, 2, 1, 1)
        self.lineEdit_6 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_6.setObjectName("lineEdit_6")

        validator = QRegExpValidator(regx, self.lineEdit_6)
        self.lineEdit_6.setValidator(validator)
        self.gridLayout_6.addWidget(self.lineEdit_6, 2, 2, 1, 1)
        self.label_15 = QtWidgets.QLabel(self.centralwidget)
        self.label_15.setObjectName("label_15")
        self.gridLayout_6.addWidget(self.label_15, 2, 0, 1, 2)
        self.label_13 = QtWidgets.QLabel(self.centralwidget)
        self.label_13.setObjectName("label_13")
        self.gridLayout_6.addWidget(self.label_13, 0, 0, 1, 2)
        self.lineEdit_4 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_4.setObjectName("lineEdit_4")

        validator = QRegExpValidator(regx, self.lineEdit_4)
        self.lineEdit_4.setValidator(validator)
        self.gridLayout_6.addWidget(self.lineEdit_4, 0, 2, 1, 1)
        self.verticalLayout_6.addLayout(self.gridLayout_6)
        self.horizontalLayout_21.addLayout(self.verticalLayout_6)
        self.line_12 = QtWidgets.QFrame(self.centralwidget)
        self.line_12.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_12.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_12.setObjectName("line_12")
        self.horizontalLayout_21.addWidget(self.line_12)
        self.gridLayout_7 = QtWidgets.QGridLayout()
        self.gridLayout_7.setObjectName("gridLayout_7")
        self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_5.setObjectName("pushButton_5")
        self.gridLayout_7.addWidget(self.pushButton_5, 1, 1, 1, 1)
        self.pushButton_7 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_7.setObjectName("pushButton_7")
        self.gridLayout_7.addWidget(self.pushButton_7, 2, 1, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setObjectName("label_2")
        self.gridLayout_7.addWidget(self.label_2, 0, 1, 1, 1)
        self.textEdit_2 = QtWidgets.QTextEdit(self.centralwidget)
        self.textEdit_2.setObjectName("textEdit_2")
        self.gridLayout_7.addWidget(self.textEdit_2, 0, 2, 5, 1)
        self.pushButton_8 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_8.setObjectName("pushButton_8")
        self.gridLayout_7.addWidget(self.pushButton_8, 3, 1, 1, 1)
        self.delete2 = QtWidgets.QPushButton(self.centralwidget)
        self.delete2.setStyleSheet("color: rgb(255, 0, 0);")
        self.delete2.setObjectName("delete2")
        self.gridLayout_7.addWidget(self.delete2, 4, 1, 1, 1)
        self.horizontalLayout_21.addLayout(self.gridLayout_7)
        self.verticalLayout_7.addLayout(self.horizontalLayout_21)
        self.verticalLayout_8.addLayout(self.verticalLayout_7)
        self.line_14 = QtWidgets.QFrame(self.centralwidget)
        self.line_14.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_14.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_14.setObjectName("line_14")
        self.verticalLayout_8.addWidget(self.line_14)
        spacerItem8 = QtWidgets.QSpacerItem(20, 40,
                                            QtWidgets.QSizePolicy.Minimum,
                                            QtWidgets.QSizePolicy.Expanding)
        self.verticalLayout_8.addItem(spacerItem8)
        self.horizontalLayout_6 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.start = QtWidgets.QPushButton(self.centralwidget)
        self.start.setObjectName("start")
        self.horizontalLayout_6.addWidget(self.start)
        self.delete3 = QtWidgets.QPushButton(self.centralwidget)
        self.delete3.setStyleSheet("color:rgb(255, 58, 19)")
        self.delete3.setObjectName("delete3")
        self.horizontalLayout_6.addWidget(self.delete3)
        self.verticalLayout_8.addLayout(self.horizontalLayout_6)
        self.gridLayout_9.addLayout(self.verticalLayout_8, 0, 0, 1, 1)
        self.gridLayout_2 = QtWidgets.QGridLayout()
        self.gridLayout_2.setObjectName("gridLayout_2")
        spacerItem9 = QtWidgets.QSpacerItem(20, 13,
                                            QtWidgets.QSizePolicy.Preferred,
                                            QtWidgets.QSizePolicy.Minimum)
        self.gridLayout_2.addItem(spacerItem9, 1, 3, 1, 2)
        spacerItem10 = QtWidgets.QSpacerItem(13, 13,
                                             QtWidgets.QSizePolicy.Minimum,
                                             QtWidgets.QSizePolicy.Minimum)
        self.gridLayout_2.addItem(spacerItem10, 1, 1, 1, 1)
        self.exitbutton = QtWidgets.QPushButton(self.centralwidget)
        self.exitbutton.setObjectName("exitbutton")
        self.gridLayout_2.addWidget(self.exitbutton, 1, 5, 1, 1)
        self.savebutton = QtWidgets.QPushButton(self.centralwidget)
        self.savebutton.setObjectName("savebutton")
        self.gridLayout_2.addWidget(self.savebutton, 1, 3, 1, 1)

        self.display = QtWidgets.QPushButton(self.centralwidget)
        self.display.setObjectName("display")
        self.gridLayout_2.addWidget(self.display, 1, 1, 1, 1)

        # self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        # self.groupBox.setObjectName("groupBox")
        # self.gridLayout_2.addWidget(self.groupBox, 0, 0, 1, 6)

        self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
        self.groupBox.setObjectName("groupBox")
        self.gridLayout_2.addWidget(self.groupBox, 0, 0, 1, 6)

        self.gridLayout_9.addLayout(self.gridLayout_2, 0, 2, 1, 1)
        self.gridLayout_9.setColumnStretch(0, 1)
        self.gridLayout_9.setColumnStretch(2, 3)
        self.gridLayout_4.addLayout(self.gridLayout_9, 1, 1, 1, 1)
        self.line_21 = QtWidgets.QFrame(self.centralwidget)
        self.line_21.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_21.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_21.setObjectName("line_21")
        self.gridLayout_4.addWidget(self.line_21, 2, 1, 1, 1)
        self.line_20 = QtWidgets.QFrame(self.centralwidget)
        self.line_20.setFrameShape(QtWidgets.QFrame.VLine)
        self.line_20.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_20.setObjectName("line_20")
        self.gridLayout_4.addWidget(self.line_20, 3, 0, 1, 1)
        self.line_17 = QtWidgets.QFrame(self.centralwidget)
        self.line_17.setFrameShape(QtWidgets.QFrame.HLine)
        self.line_17.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.line_17.setObjectName("line_17")
        self.gridLayout_4.addWidget(self.line_17, 3, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 897, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.gridlayout2 = QtWidgets.QGridLayout(self.groupBox)  # 继承容器

        self.retranslateUi(MainWindow)
        ##槽函数与按钮关联##
        #飞机四种动作按钮
        self.flying.clicked.connect(self.changeText)
        self.falldown.clicked.connect(self.changeText)
        self.turn.clicked.connect(self.changeText)
        self.climb.clicked.connect(self.changeText)
        #航母三种动作按钮
        self.pushButton_5.clicked.connect(self.changeText1)
        self.pushButton_8.clicked.connect(self.changeText1)
        self.pushButton_7.clicked.connect(self.changeText1)
        # self.pushButton_20.clicked.connect(self.changeText1)
        # self.pushButton_21.clicked.connect(self.changeText1)

        self.start.clicked.connect(self.startPlot)  #生成数据按钮
        # 初始位置是否锁定
        self.checkBox.stateChanged.connect(self.changec1)
        self.checkBox_2.stateChanged.connect(self.changec2)

        # self.pushButton_4.clicked.connect(self.submitNum)
        #self.linearButton.clicked.connect(self.changeStatus)
        #self.diamondButton.clicked.connect(self.changeStatus)
        self.numchecked.clicked.connect(self.submitNum1)
        self.scheck1.clicked.connect(self.submitNum2)
        self.delete3.clicked.connect(self.delt)  #撤销
        self.scheck2.clicked.connect(self.submitNum3)
        self.delete1.clicked.connect(self.deleteItem1)  #删除飞机动作
        self.delete2.clicked.connect(self.deleteItem2)  #删除航母动作
        self.savebutton.clicked.connect(self.save)  #保存按钮
        self.exitbutton.clicked.connect(QCoreApplication.instance().quit)  #退出

        # self.F.fig.canvas.mpl_connect('key_press_event', self.F.on_key_press)
        #self.F.fig.canvas.mpl_connect('motion_notify_event', self.OnMouseMotion)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
    def AddRecord(self):

        ## MODIFY THIS
        print(self.rights, "Rightsss value")

        reg_ex = QRegExp("[1-9]\\d{0,3}")
        self.name_validator = QRegExpValidator(reg_ex)

        if self.ui.textEdit.toPlainText().isalpha():
            name = self.ui.textEdit.toPlainText()
            print("name = letters only")
        else:
            self.ui.textEdit.setFocus()
            name = "wrongvalue"

        job = self.ui.comboBox.currentText()
        access_level = self.ui.label.text()  #Filhal Hardcoded
        try:
            cnic = int(self.ui.textEdit_4.toPlainText())
        except ValueError:
            self.ui.textEdit_4.setFocus()
            cnic = "wrongvalue"
            print("Characters included")

        if self.rights == 1:  #edit mode
            mydata = self.data[0]
            date = mydata[
                8]  #use old arrival date #CHECK THIS INDEX (8 tha tumne 4 rakha huwa tha)

        else:  #new recird hai

            x = datetime.datetime.now()
            date = str(x.day) + "-" + str(x.month) + "-" + str(x.year)

        try:
            sal = int(self.ui.textEdit_5.toPlainText())
        except ValueError:
            self.ui.textEdit_5.setFocus()
            sal = "wrongvalue"
            print("Characters included")

        try:
            contact = int(self.ui.textEdit_6.toPlainText())
        except ValueError:
            self.ui.textEdit_6.setFocus()
            contact = "wrongvalue"
            print("Characters included")
        address = self.ui.textEdit_7.toPlainText()

        password = "******"  #12345
        if name != "wrongvalue" and cnic != "wrongvalue" and contact != "wrongvalue" and sal != "wrongvalue":
            newrr = []
            #rr.append(5)
            self.rr.append(name)
            self.rr.append(password)
            self.rr.append(cnic)
            self.rr.append(job)
            self.rr.append(sal)
            self.rr.append(contact)
            self.rr.append(address)
            print("Date-----------", date)
            self.rr.append(date)
            self.rr.append(access_level)

            cur = self.conn.cursor()

            if (self.rights == 0):

                cur.execute(
                    "Insert into Staff(staff_name,password,cnic,job,contact,salary,address,employment_date,access_level) VALUES (?,?,?,?,?,?,?,?,?)",
                    self.rr)

            else:
                #EditRecord

                iterator = 0

                #newrr.append(self.rr[0]) #ID at end

                for i in self.rr:
                    if (iterator == 0):
                        None
                    else:
                        newrr.append(i)
                    iterator = iterator + 1

                newrr.append(self.rr[0])  #ID at end

                print(self.rr, "Old RR")

                print(newrr, "New RR")

                cur.execute(
                    "Update staff SET staff_name=?, password=?,cnic=?,job=?,contact=?,salary=?,address=?,employment_date=?,access_level=? WHERE staff_id=?",
                    newrr)
            self.conn.commit()
            self.rr.clear()
            newrr.clear()
        else:
            """ Insert Alert HERE"""
            msg = Alert("Invalid input(s)")
Exemplo n.º 54
0
    def __init__(self, max_bytes=-1, digit_group_size=2):
        super().__init__()

        self.max_bytes = max_bytes
        self.digit_group_size = digit_group_size

        if max_bytes == 0:
            self.re_acceptable = QRegExp('')
            self.re_intermediate = QRegExp('')
        elif max_bytes > 0:
            self.re_acceptable = QRegExp(
                '([0-9A-Fa-f]{%d} ){0,%d}[0-9A-Fa-f]{%d}' %
                (digit_group_size, max_bytes - 1, digit_group_size))
            self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*){1,%d}' %
                                           (max_bytes * 2))
        else:
            self.re_acceptable = QRegExp('([0-9A-Fa-f]{%d} )*[0-9A-Fa-f]{%d}' %
                                         (digit_group_size, digit_group_size))
            self.re_intermediate = QRegExp('[ ]*|([ ]*[0-9A-Fa-f][ ]*)+')
Exemplo n.º 55
0
    def highlightBlock(self, text):
        if not self.highLightBlockOn:
            return

        wordFormatDict = self.textFormatManager.getWordFormatDict()
        defaultFormat = self.textFormatManager.getDefaultFormat()
        partOfSpeechFormat = self.textFormatManager.getPartOfSpeechFormat()
        currentBlock = self.currentBlock()

        for textFormat in self.mainWindow.textFormatManager.getFormats():
            textFormat.counterDict[str(currentBlock.blockNumber())] = 0
        self.mainWindow.textFormatManager.getDefaultFormat().counterDict[str(
            currentBlock.blockNumber())] = 0
        self.mainWindow.textFormatManager.getPartOfSpeechFormat().counterDict[
            str(currentBlock.blockNumber())] = 0

        start = currentBlock.position()
        end = start + currentBlock.length()
        wordsToHighlight = self.mainWindow.wordManager.getWords(start, end)

        for word in wordsToHighlight:
            textFormat = wordFormatDict.get(word.content, defaultFormat)

            self.setFormat(word.start - start, word.length, textFormat)

            textFormat.counterDict[str(currentBlock.blockNumber())] += 1

            if word.tagIsOn:
                self.setFormat(word.end - start, word.partOfSpeechLen,
                               partOfSpeechFormat)

        for w in wordsToHighlight:
            w.highlighted = {}

        plainText = getText(wordsToHighlight, 'plainText')
        taggedText = getText(wordsToHighlight, 'taggedText')

        for textFormat in self.textFormatManager.getFormats():
            if textFormat.type == 'level':
                for pattern in textFormat.regexList:
                    expression = QRegExp(pattern)
                    index = expression.indexIn(plainText)
                    while index >= 0:
                        length = expression.matchedLength()
                        for i in range(length):
                            word = getWord(index + i, wordsToHighlight,
                                           'plainText')
                            if word:
                                word.highlighted[index -
                                                 word.plainTextModePosition +
                                                 i] = textFormat
                        index = expression.indexIn(plainText, index + length)
            else:
                for pattern in textFormat.regexList:
                    expression = QRegExp(pattern)
                    index = expression.indexIn(taggedText)
                    while index >= 0:
                        length = expression.matchedLength()
                        for i in range(length):
                            word = getWord(index + i, wordsToHighlight,
                                           'taggedText')
                            if word:
                                word.highlighted[index -
                                                 word.taggedModePosition +
                                                 i] = textFormat
                        index = expression.indexIn(taggedText, index + length)

        for word in wordsToHighlight:
            for index, textFormat in word.highlighted.items():
                if self.mainWindow.modeManager.isTagMode():
                    if index >= word.length + word.partOfSpeechLen:
                        break

                else:
                    if index >= word.length:
                        break

                self.setFormat(word.start - start + index, 1, textFormat)

            textFormat = word.needHighlighted()
            if textFormat:
                self.setFormat(word.start - start, word.length, textFormat)

        self.mainWindow.counterWidget.refresh()
Exemplo n.º 56
0
    def __init__(self, parent=None):
        super(JsHighlighter, self).__init__(parent)

        self.keyword_color = QColor('#C678DD')
        self.comment_color = QColor('#5C6370')
        self.function_color = QColor('#61AFEF')
        self.string_color = QColor('#98C379')
        self.number_color = QColor('#e06c75')
        self.constant_color = QColor('#D19A66')

        self._keywords = [
            "break", "case", "catch", "class", "const", "continue", "debugger",
            "default", "delete", "do", "else", "export", "extends", "false", "finally",
            "for", "function", "if", "import", "in", "instanceof", "new", "null",
            "return", "super", "switch", "this", "throw", "true", "try", "typeof",
            "var", "void", "while", "with", "yield"
        ]

        self._known_m = [
            "Memory", "Process", "MemoryWatcher", "Thread", "Object", "Function", "Interceptor", "Java",
            "JSON", "console"
        ]

        self._known = [
            'log', 'addWatcher', 'deleteHook', 'enumerateJavaClasses',
            'enumerateJavaMethods', 'findExport', 'getAddressTs',
            'hookAllJavaMethods', 'hookJava', 'hookNative',
            'hookNativeOnLoad', 'javaBacktrace', 'isAddressWatched',
            'nativeBacktrace', 'release', 'resume', 'removeWatcher', 'restart',
            'setData', 'startNativeTracer', 'stopNativeTracer',
            "prototype",
            "create",
            "defineProperty",
            "defineProperties",
            "getOwnPropertyDescriptor",
            "keys",
            "getOwnPropertyNames",
            "constructor",
            "__parent__",
            "__proto__",
            "__defineGetter__",
            "__defineSetter__",
            "eval",
            "hasOwnProperty",
            "isPrototypeOf",
            "__lookupGetter__",
            "__lookupSetter__",
            "__noSuchMethod__",
            "propertyIsEnumerable",
            "toSource",
            "toLocaleString",
            "toString",
            "unwatch",
            "valueOf",
            "watch",
            "arguments",
            "arity",
            "caller",
            "constructor",
            "length",
            "name",
            "apply",
            "bind",
            "call",
            "String",
            "fromCharCode",
            "length",
            "charAt",
            "charCodeAt",
            "concat",
            "indexOf",
            "lastIndexOf",
            "localCompare",
            "match",
            "quote",
            "replace",
            "search",
            "slice",
            "split",
            "substr",
            "substring",
            "toLocaleLowerCase",
            "toLocaleUpperCase",
            "toLowerCase",
            "toUpperCase",
            "trim",
            "trimLeft",
            "trimRight",
            "Array",
            "isArray",
            "index",
            "input",
            "pop",
            "push",
            "reverse",
            "shift",
            "sort",
            "splice",
            "unshift",
            "concat",
            "join",
            "filter",
            "forEach",
            "every",
            "map",
            "some",
            "reduce",
            "reduceRight",
            "RegExp",
            "global",
            "ignoreCase",
            "lastIndex",
            "multiline",
            "source",
            "exec",
            "test",
            "parse",
            "stringify",
            "decodeURI",
            "decodeURIComponent",
            "encodeURI",
            "encodeURIComponent",
            "eval",
            "isFinite",
            "isNaN",
            "parseFloat",
            "parseInt",
            "Infinity",
            "NaN",
            "undefined",
            "Math",
            "E",
            "LN2",
            "LN10",
            "LOG2E",
            "LOG10E",
            "PI",
            "SQRT1_2",
            "SQRT2",
            "abs",
            "acos",
            "asin",
            "atan",
            "atan2",
            "ceil",
            "cos",
            "exp",
            "floor",
            "log",
            "max",
            "min",
            "pow",
            "random",
            "round",
            "sin",
            "sqrt",
            "tan",
            "document",
            "window",
            "navigator",
            "userAgent",
        ]

        self.highlightingRules = []

        classFormat = QTextCharFormat()
        classFormat.setFontWeight(QFont.Bold)
        classFormat.setForeground(self.constant_color)
        self.highlightingRules.append((QRegExp("\\bnew [A-Za-z]+\\b"),
                                       classFormat))

        functionFormat = QTextCharFormat()
        functionFormat.setForeground(self.function_color)
        self.highlightingRules.append(
            (QRegExp("(?!function)\\b[A-Za-z0-9_]+(?=\\()"), functionFormat))
Exemplo n.º 57
0
    def setup(self):
        self.trainingLayout = QGridLayout()

        # Bot 1

        leaveButton = QPushButton('Main Menu')
        leaveButton.setStyleSheet('font: bold;background-color: red;font-size: 18px;height: 30px')
        leaveButton.clicked.connect(self.leave)
        self.trainingLayout.addWidget(leaveButton, 0, 0)

        self.botNameLabelForBot1 = QLabel("Bot Name: " + self.env.bot1.name)
        self.botNameLabelForBot1.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.botNameLabelForBot1, 1, 0)

        self.loadStatesForBot1Button = QPushButton("Load States for Bot #1")
        self.trainingLayout.addWidget(self.loadStatesForBot1Button, 1, 1)
        self.loadStatesForBot1Button.clicked.connect(lambda: self.env.bot1.loadStates(self))

        self.learningRateLabelForBot1 = QLabel("Learning rate: ")
        self.learningRateLabelForBot1.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.learningRateLabelForBot1, 2, 0)

        self.learningLineEditForBot1 = QLineEdit()
        floatValidator1 = QRegExpValidator(QRegExp("^[0-0]\\.\\d\\d"), self.learningLineEditForBot1)
        self.learningLineEditForBot1.setValidator(floatValidator1)
        self.learningLineEditForBot1.setText(str(self.env.bot1.learning_rate))
        self.trainingLayout.addWidget(self.learningLineEditForBot1, 2, 1)

        self.discountFactorLabelForBot1 = QLabel("Discount factor: ")
        self.discountFactorLabelForBot1.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.discountFactorLabelForBot1, 3, 0)

        self.discountFactorLineEditForBot1 = QLineEdit()
        floatValidator2 = QRegExpValidator(QRegExp("^[0-0]\\.\\d\\d"), self.discountFactorLineEditForBot1)
        self.discountFactorLineEditForBot1.setValidator(floatValidator2)
        self.discountFactorLineEditForBot1.setText(str(self.env.bot1.discount_factor))
        self.trainingLayout.addWidget(self.discountFactorLineEditForBot1, 3, 1)

        self.explorationRateLabelForBot1 = QLabel("Exploration rate: ")
        self.explorationRateLabelForBot1.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.explorationRateLabelForBot1, 4, 0)

        self.explorationRateLineEditForBot1 = QLineEdit()
        floatValidator3 = QRegExpValidator(QRegExp("^[0-0]\\.\\d\\d"), self.explorationRateLineEditForBot1)
        self.explorationRateLineEditForBot1.setValidator(floatValidator3)
        self.explorationRateLineEditForBot1.setText(str(self.env.bot1.exploration_rate))
        self.trainingLayout.addWidget(self.explorationRateLineEditForBot1, 4, 1)

        self.numberOfGamesLabel= QLabel("Number of Games: ")
        self.numberOfGamesLabel.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.numberOfGamesLabel, 5, 0, 1, 2)

        self.numberOfGamesLineEdit= QLineEdit()
        intValidator = QRegExpValidator(QRegExp("^[1-9]\\d*"), self.numberOfGamesLineEdit)
        self.numberOfGamesLineEdit.setValidator(intValidator)
        self.numberOfGamesLineEdit.setText(str(1000))
        self.trainingLayout.addWidget(self.numberOfGamesLineEdit, 5, 1, 1, 4)

        # Bot 2

        self.botNameLabelForBot2 = QLabel("Bot Name: " + self.env.bot2.name)
        self.botNameLabelForBot2.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.botNameLabelForBot2, 1, 3)

        self.loadStatesForBot2Button = QPushButton("Load States For Bot #2")
        self.trainingLayout.addWidget(self.loadStatesForBot2Button, 1, 4)
        self.loadStatesForBot2Button.clicked.connect(lambda: self.env.bot2.loadStates(self))

        self.learningRateLabelForBot2 = QLabel("Learning rate: ")
        self.learningRateLabelForBot2.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.learningRateLabelForBot2, 2, 3)

        self.learningLineEditForBot2 = QLineEdit()
        floatValidator4 = QRegExpValidator(QRegExp("^[0-0]\\.\\d\\d"), self.learningLineEditForBot2)
        self.learningLineEditForBot2.setValidator(floatValidator4)
        self.learningLineEditForBot2.setText(str(self.env.bot2.learning_rate))
        self.trainingLayout.addWidget(self.learningLineEditForBot2, 2, 4)

        self.discountFactorLabelForBot2 = QLabel("Discount factor: ")
        self.discountFactorLabelForBot2.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.discountFactorLabelForBot2, 3, 3)

        self.discountFactorLineEditForBot2 = QLineEdit()
        floatValidator5 = QRegExpValidator(QRegExp("^[0-0]\\.\\d\\d"), self.discountFactorLineEditForBot2)
        self.discountFactorLineEditForBot2.setValidator(floatValidator5)
        self.discountFactorLineEditForBot2.setText(str(self.env.bot2.discount_factor))
        self.trainingLayout.addWidget(self.discountFactorLineEditForBot2, 3, 4)

        self.explorationRateLabelForBot2 = QLabel("Exploration rate: ")
        self.explorationRateLabelForBot2.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.explorationRateLabelForBot2, 4, 3)

        self.explorationRateLineEditForBot2 = QLineEdit()
        floatValidator6 = QRegExpValidator(QRegExp("^[0-0]\\.\\d\\d"), self.explorationRateLineEditForBot2)
        self.explorationRateLineEditForBot2.setValidator(floatValidator6)
        self.explorationRateLineEditForBot2.setText(str(self.env.bot2.exploration_rate))
        self.trainingLayout.addWidget(self.explorationRateLineEditForBot2, 4, 4)

        self.trainButton = QPushButton('Train')
        self.trainButton.setStyleSheet('font: bold;background-color: blue;font-size: 18px;height: 30px')
        self.trainButton.clicked.connect(self.train)
        self.trainingLayout.addWidget(self.trainButton, 7, 0, 1, 5)

        self.currentTrainingWinsForBot1Label = QLabel(self.env.bot1.name + " Current Wins: " + str(0))
        self.currentTrainingWinsForBot1Label.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.currentTrainingWinsForBot1Label, 8, 0)

        self.currentTrainingDrawsLabel = QLabel("Current Draws: " + str(0))
        self.currentTrainingDrawsLabel.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.currentTrainingDrawsLabel, 8, 2)

        self.currentTrainingWinsForBot2Label = QLabel(self.env.bot2.name + " Current Wins: " + str(0))
        self.currentTrainingWinsForBot2Label.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.currentTrainingWinsForBot2Label, 8, 4)

        self.totalTrainingWinsForBot1Label = QLabel(self.env.bot1.name + " Total Wins: " + str(self.env.totalTrainingWinsForBot1))
        self.totalTrainingWinsForBot1Label.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.totalTrainingWinsForBot1Label, 9, 0)

        self.totalTrainingDrawsLabel = QLabel("Total Draws: " + str(self.env.totalTrainingDraws))
        self.totalTrainingDrawsLabel.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.totalTrainingDrawsLabel, 9, 2)

        self.totalTrainingWinsForBot2Label = QLabel(self.env.bot2.name + " Total Wins: " + str(self.env.totalTrainingWinsForBot2))
        self.totalTrainingWinsForBot2Label.setStyleSheet("font: bold;font-size: 18px;height: 30px")
        self.trainingLayout.addWidget(self.totalTrainingWinsForBot2Label, 9, 4)


        self.setLayout(self.trainingLayout)
Exemplo n.º 58
0
    def highlightBlock(self, text):
        for pattern, format in self.highlightingRules:
            expression = QRegExp(pattern)
            expression.setMinimal(True)
            index = expression.indexIn(text)
            while index >= 0:
                length = expression.matchedLength()
                self.setFormat(index, length, format)
                index = expression.indexIn(text, index + length)

        self.setCurrentBlockState(0)

        blockState = self.previousBlockState()
        bracketLevel = blockState >> 4
        state = blockState & 15

        if blockState < 0:
            bracketLevel = 0
            state = 0

        start = 0
        i = 0
        while i < len(text):
            cur_ch = ''
            next_ch = ''
            if i < len(text):
                cur_ch = text[i]
            if i < len(text) - 1:
                next_ch = text[i + 1]

            if state == 0:  # Start
                start = i

                if cur_ch.isspace():
                    i += 1
                elif cur_ch.isdigit():
                    i += 1
                    state = 1
                elif cur_ch.isalpha() or cur_ch == '_':
                    i += 1
                    state = 2
                elif cur_ch == '\'' or cur_ch == '\"':
                    i += 1
                    state = 3
                elif cur_ch == '/' and next_ch == '*':
                    i += 2
                    state = 4
                elif cur_ch == '/' and next_ch == '/':
                    i = len(text)
                    self.setFormat(start, len(text), self.comment_color)
                elif cur_ch == '/' and next_ch != '*':
                    i += 1
                    state = 5
                else:
                    if cur_ch not in '(){}[],.;':
                        self.setFormat(start, 1, QColor('#099A00'))
                    if cur_ch in '{}':
                        #bracketPositions += i
                        if cur_ch == '{':
                            bracketLevel += 1
                        else:
                            bracketLevel -= 1
                    i += 1
                    state = 0

            elif state == 1:  # Number
                if cur_ch.isspace() or not cur_ch.isdigit():
                    self.setFormat(start, i - start, self.number_color)
                    state = 0
                else:
                    i += 1

            elif state == 2:
                if cur_ch.isspace() or not (cur_ch.isdigit() or cur_ch.isalpha() or cur_ch in '_-'):
                    token = text[start:i].strip()
                    if token in self._keywords:
                        self.setFormat(start, i - start, self.keyword_color)
                    elif token in self._known:
                        self.setFormat(start, i - start, self.function_color)
                    elif token in self._known_m:
                        self.setFormat(start, i - start, self.constant_color)
                    state = 0
                else:
                    i += 1

            elif state == 3:
                if cur_ch == text[start]:
                    prev_ch = ''
                    if i > 0:
                        prev_ch = text[i - 1]

                    if prev_ch != '\\':
                        i += 1
                        self.setFormat(start, i - start, self.string_color)
                        state = 0
                    else:
                        i += 1
                else:
                    i += 1
            elif state == 4:
                if cur_ch == '*' and next_ch == '/':
                    i += 2
                    self.setFormat(start, i - start, self.comment_color)
                    state = 0
                else:
                    i += 1

            elif state == 5:
                if cur_ch == '/':
                    prev_ch = ''
                    if i > 0:
                        prev_ch = text[i - 1]

                    if prev_ch != '\\':
                        i += 1
                        self.setFormat(start, i - start, self.string_color)
                        state = 0
                    else:
                        i += 1
                else:
                    i += 1
            else:
                state = 0

        if state == 4:
            self.setFormat(start, len(text), self.comment_color)
        else:
            state = 0

        blockState = (state & 15) | (bracketLevel << 4)
        self.setCurrentBlockState(blockState)
Exemplo n.º 59
0
    def _interface(self):
        self.layout = QHBoxLayout()
        self.layout.setSpacing(20)
        py_path_layout = QHBoxLayout()
        cy_path_layout = QHBoxLayout()
        samples_layout = QHBoxLayout()
        left_layout = QVBoxLayout()

        py_checkbox = QCheckBox("Run Python", self)
        py_checkbox.stateChanged.connect(self.checkbox_action)
        self._mediator.checks[py_checkbox.text()] = py_checkbox
        py_path_layout.addWidget(py_checkbox)

        self.py_path = QLineEdit(self)
        self.py_path.resize(460, 25)
        self.py_path.setReadOnly(True)
        self.py_path.setEnabled(False)
        py_path_layout.addWidget(self.py_path)

        py_button = QPushButton("Browse (.py)", self)
        py_button.setToolTip("Browse for Python File")
        py_button.clicked.connect(lambda: self.open_file_dialog("py"))
        py_button.setEnabled(False)
        self._mediator.buttons[py_button.text()] = py_button, self.py_path
        py_path_layout.addWidget(py_button)

        left_layout.addLayout(py_path_layout)

        cy_checkbox = QCheckBox("Run Cython", self)
        cy_checkbox.move(20, 60)
        cy_checkbox.stateChanged.connect(self.checkbox_action)
        self._mediator.checks[cy_checkbox.text()] = cy_checkbox
        cy_path_layout.addWidget(cy_checkbox)

        self.cy_path = QLineEdit(self)
        self.cy_path.move(150, 60)
        self.cy_path.resize(460, 25)
        self.cy_path.setReadOnly(True)
        self.cy_path.setEnabled(False)
        cy_path_layout.addWidget(self.cy_path)

        cy_button = QPushButton("Browse (.pyd)", self)
        cy_button.setToolTip("Browse for Cython Extension Module")
        cy_button.move(630, 60)
        cy_button.clicked.connect(lambda: self.open_file_dialog("cy"))
        cy_button.setEnabled(False)
        self._mediator.buttons[cy_button.text()] = cy_button, self.cy_path
        cy_path_layout.addWidget(cy_button)

        left_layout.addLayout(cy_path_layout)

        both_checkbox = QCheckBox("Run Both", self)
        both_checkbox.move(20, 100)
        both_checkbox.stateChanged.connect(self.checkbox_action)
        self._mediator.checks[both_checkbox.text()] = both_checkbox
        left_layout.addWidget(both_checkbox)

        samples_label = QLabel("Samples:")
        self.samples_line = QLineEdit(self)
        validator = QRegExpValidator(QRegExp("([0-9]+,)+"))
        self.samples_line.setValidator(validator)
        # samples = np.geomspace(3, 10000, 20, dtype=int)
        # samples = np.array2string(samples, separator=",")[1:-1].replace(" ", "").replace("\n", "")
        samples = "10, 20, 30, 40, 50, 60, 70, 80, 90, 100"
        self.samples_line.setText(samples)
        samples_increase = QPushButton("*10", self)
        samples_increase.clicked.connect(self.increase_samples)
        samples_decrease = QPushButton("/10", self)
        samples_decrease.clicked.connect(self.decrease_samples)
        samples_layout.addWidget(samples_label)
        samples_layout.addWidget(self.samples_line)
        samples_layout.addWidget(samples_increase)
        samples_layout.addWidget(samples_decrease)
        left_layout.addLayout(samples_layout)

        run_button = QPushButton("Run", self)
        run_button.setToolTip("Run selected tests")
        run_button.move(20, 140)
        run_button.clicked.connect(self.run_action)
        left_layout.addWidget(run_button)

        self.plot = PlotCanvas(self)
        self.plot.move(20, 200)
        left_layout.addWidget(self.plot)

        left_layout.setContentsMargins(5, 5, 5, 5)
        self.layout.addLayout(left_layout)

        self.table_widget = QTableWidget()
        self.table_widget.setRowCount(0)
        self.table_widget.setColumnCount(1)
        self.table_widget.setHorizontalHeaderLabels([""])
        header = self.table_widget.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)

        self.layout.addWidget(self.table_widget)

        self.setLayout(self.layout)

        self.show()
Exemplo n.º 60
0
    def request_trezor_init_settings(self, wizard, method, device):
        vbox = QVBoxLayout()
        next_enabled = True
        label = QLabel(_("Enter a label to name your device:"))
        name = QLineEdit()
        hl = QHBoxLayout()
        hl.addWidget(label)
        hl.addWidget(name)
        hl.addStretch(1)
        vbox.addLayout(hl)

        def clean_text(widget):
            text = widget.toPlainText().strip()
            return ' '.join(text.split())

        if method in [TIM_NEW, TIM_RECOVER]:
            gb = QGroupBox()
            hbox1 = QHBoxLayout()
            gb.setLayout(hbox1)
            # KeepKey recovery doesn't need a word count
            if method == TIM_NEW:
                vbox.addWidget(gb)
            gb.setTitle(_("Select your seed length:"))
            bg = QButtonGroup()
            for i, count in enumerate([12, 18, 24]):
                rb = QRadioButton(gb)
                rb.setText(_("{} words").format(count))
                bg.addButton(rb)
                bg.setId(rb, i)
                hbox1.addWidget(rb)
                rb.setChecked(True)
            cb_pin = QCheckBox(_('Enable PIN protection'))
            cb_pin.setChecked(True)
        else:
            text = QTextEdit()
            text.setMaximumHeight(60)
            if method == TIM_MNEMONIC:
                msg = _("Enter your BIP39 mnemonic:")
            else:
                msg = _("Enter the master private key beginning with xprv:")
                def set_enabled():
                    from electrum_axe.bip32 import is_xprv
                    wizard.next_button.setEnabled(is_xprv(clean_text(text)))
                text.textChanged.connect(set_enabled)
                next_enabled = False

            vbox.addWidget(QLabel(msg))
            vbox.addWidget(text)
            pin = QLineEdit()
            pin.setValidator(QRegExpValidator(QRegExp('[1-9]{0,9}')))
            pin.setMaximumWidth(100)
            hbox_pin = QHBoxLayout()
            hbox_pin.addWidget(QLabel(_("Enter your PIN (digits 1-9):")))
            hbox_pin.addWidget(pin)
            hbox_pin.addStretch(1)

        if method in [TIM_NEW, TIM_RECOVER]:
            vbox.addWidget(WWLabel(RECOMMEND_PIN))
            vbox.addWidget(cb_pin)
        else:
            vbox.addLayout(hbox_pin)

        passphrase_msg = WWLabel(PASSPHRASE_HELP_SHORT)
        passphrase_warning = WWLabel(PASSPHRASE_NOT_PIN)
        passphrase_warning.setStyleSheet("color: red")
        cb_phrase = QCheckBox(_('Enable passphrases'))
        cb_phrase.setChecked(False)
        vbox.addWidget(passphrase_msg)
        vbox.addWidget(passphrase_warning)
        vbox.addWidget(cb_phrase)

        wizard.exec_layout(vbox, next_enabled=next_enabled)

        if method in [TIM_NEW, TIM_RECOVER]:
            item = bg.checkedId()
            pin = cb_pin.isChecked()
        else:
            item = ' '.join(str(clean_text(text)).split())
            pin = str(pin.text())

        return (item, name.text(), pin, cb_phrase.isChecked())