def __init__(self): #self.host = socket.gethostbyaddr('211.255.132.121')[2][0] self.host = socket.gethostbyname(socket.gethostname()) print "HOST: ", self.host #print socket.gethostbyaddr('211.255.132.121') #Make sure the host exists! self.port = 1900 #NOTE: PORT MAY LEAD TO socket errno 10048; in which case, switch the sockets being used for the Arduino. self.address = (self.host, self.port) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind((self.address)) self.server.listen(1) print "Looking for Client to talk to...." self.conn, self.address = self.server.accept() output = self.conn.recv(2048) print "Message received from client:" print output self.count = 0 self.y = pyqtSignal(int) self.z = pyqtSignal(int) self.u = pyqtSignal(int) self.r = pyqtSignal(int) self.v = pyqtSignal(int) self.count = 0 super(Server, self).__init__() print "FINISHED INITIALIZING"
def __init__(self, parent = None): """ MainWindow constructor """ # Text messages for the class are set here self.genericMsg = "WARNING -- Your changes have NOT been saved.\nAre you sure you want to %s\nand lose all of your changes?" self.quit_msg = self.genericMsg %"exit the program" self.new_msg = self.genericMsg %"start a new file" self.open_msg = self.genericMsg %"open a new file" self.close_msg = self.genericMsg %"close this file" self.testcases = [] # \ self.testsuitefolder = "" # \__ Start with a clean slate. # Read the confuration file data into the local class namespace as the # class will need this information. try: self.configs = {} self.configs = configFile2dictionary(CONFIG_FILE) # print self.configs if len(self.configs) == 0: raise Exception ("Failed to read configurations from \"%s\"" %CONFIG_FILE) self.configs['testcasefolder'] = os.path.join(MY_PATH, self.configs['testcasefolder']) self.configs['resultshome'] = os.path.join(MY_PATH, self.configs['resultshome']) except Exception as e: # TODO: SHow this as a message box as well print e print "Using default configurations" self.configs['testcasefolder'] = "/tmp/testcases" self.configs['resultshome'] = "/var/www/html/results" # Call to the Super Class for QT MainWindow super(MainWindow, self).__init__() # Don't ask, just do it. # Set up a way to write to the Console Area in from a separate thread. This # allows for real-time output to the consoleArea. self.consoleMessage = pyqtSignal(str) self.connect(self, SIGNAL("self.consoleMessage"), self.updateConsole) # Set up a way to write to the Debug Area from a separate thread. This # allows for real-time output to the consoleArea. self.debugMessage = pyqtSignal(str) self.connect(self, SIGNAL("self.debugMessage"), self.updateDebug) # Set up a way to write to the Results Area from a separate thread. This # allows for real-time output to the resultsArea. self.resultsMessage = pyqtSignal(str) self.connect(self, SIGNAL("self.resultsMessage"), self.updateResults) # The Steps for creating the main windows self.create_menubarActions() self.create_menubar() self.create_toolbarActions() self.create_toolbar() self.createWidgets() self.paint_mainWindow() self.setState(0) # This needs fixed, see setState()
def __init__(self, parent=None): """Class Constructor.""" super(GeoODKConverter, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-aut o-connect self.connect_action = pyqtSignal(str) self.setupUi(self) self.chk_all.setCheckState(Qt.Checked) self.entity_model = EntitiesModel() self.set_entity_model_view(self.entity_model) self.stdm_config = None self.parent = parent self.load_profiles() self.check_state_on() self.check_geoODK_path_exist() self.chk_all.stateChanged.connect(self.check_state_on) self.btnShowOutputFolder.clicked.connect(self.onShowOutputFolder) #self.btn_upload.clicked.connect(self.upload_generated_form) self._notif_bar_str = NotificationBar(self.vlnotification)
def prop_sig(type, name, default=None, doc=None): """ Creates a pyqtProperty/pyqtSignal pair from the given name and type. The signal is assumed to have the name of the property plus a "_changed" suffix; the member variable is stored as the name of the property. Example: class cls(object): length, length_changed = prop_sig(int, "length", 20) """ # """ # The new method should take one argument, the object that is assigned # to the property. It acts as a filter before the assigned object is # actually set. # # The delete method should take one argument, the object that is # to be deleted. It will be called on the property value when it is # about to be replaced by another value. # """ sig = name + "_changed" mem = "_" + name # Make sure that the type passed in was a python class, not # a C++ type-string. if (isinstance(type, basestring) or isinstance(type, QString) ) and default is None: raise PropertyException, "must give a default when type is a C++ type-string" fget = get_fget(mem, type, sig, default) fset = get_fset(mem, type, sig) return pyqtProperty(type, fget, fset, doc=doc), pyqtSignal(type)
def __init__(self, parent = None): ''' @type parent: QWidget ''' QWidget.__init__(self, parent) self.ui = uic.loadUi(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ui/showtab.ui'), self) self.connect(self.ui.closebutton, SIGNAL('pressed()'), self.closetab) self.connect(self.ui.seasonlist, SIGNAL('doubleClicked(QModelIndex)'), self.openseason) self.episodestatuschanged = pyqtSignal('QString', 'QDateTime', name = 'episodestatuschanged')
def __init__(self, backend, seasonid, data = []): ''' @type backend: L{src.backends.backend.backend} @type seasonid: str @type data: dict ''' QAbstractTableModel.__init__(self, parent = None) self.__backend = backend self.__seasonid = seasonid self.__data = data self.__episodestatuschanged = pyqtSignal('QString', 'QDateTime', name = 'episodestatuschanged')
def setupUi(self, RadialBand): RadialBand.setObjectName(_fromUtf8("RadialBand")) RadialBand.resize(374, 325) self.buttonBox = QtGui.QDialogButtonBox(RadialBand) self.buttonBox.setGeometry(QtCore.QRect(20, 290, 341, 32)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) self.BandLine = QtGui.QLineEdit(RadialBand) self.BandLine.setGeometry(QtCore.QRect(10, 50, 131, 21)) self.BandLine.setInputMethodHints(QtCore.Qt.ImhDigitsOnly) self.BandLine.setText(_fromUtf8("")) self.BandLine.setObjectName(_fromUtf8("BandLine")) self.AddBand = QtGui.QPushButton(RadialBand) self.AddBand.setGeometry(QtCore.QRect(10, 80, 131, 23)) self.AddBand.setObjectName(_fromUtf8("AddBand")) self.listWidget = QtGui.QListWidget(RadialBand) self.listWidget.setGeometry(QtCore.QRect(155, 50, 211, 192)) self.listWidget.setInputMethodHints(QtCore.Qt.ImhFormattedNumbersOnly) self.listWidget.setObjectName(_fromUtf8("listWidget")) self.DeleteBand = QtGui.QPushButton(RadialBand) self.DeleteBand.setGeometry(QtCore.QRect(10, 110, 131, 21)) self.DeleteBand.setObjectName(_fromUtf8("DeleteBand")) self.ClearBand = QtGui.QPushButton(RadialBand) self.ClearBand.setGeometry(QtCore.QRect(10, 140, 131, 21)) self.ClearBand.setObjectName(_fromUtf8("ClearBand")) self.label = QtGui.QLabel(RadialBand) self.label.setGeometry(QtCore.QRect(10, 30, 131, 16)) self.label.setFrameShape(QtGui.QFrame.NoFrame) self.label.setObjectName(_fromUtf8("label")) self.label_2 = QtGui.QLabel(RadialBand) self.label_2.setGeometry(QtCore.QRect(160, 30, 201, 16)) self.label_2.setObjectName(_fromUtf8("label_2")) self.label_3 = QtGui.QLabel(RadialBand) self.label_3.setGeometry(QtCore.QRect(20, 250, 121, 61)) self.label_3.setFrameShape(QtGui.QFrame.NoFrame) self.label_3.setTextFormat(QtCore.Qt.AutoText) self.label_3.setScaledContents(False) self.label_3.setWordWrap(True) self.label_3.setObjectName(_fromUtf8("label_3")) self.retranslateUi(RadialBand) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), RadialBand.reject) QtCore.QObject.connect(self.AddBand, QtCore.SIGNAL(_fromUtf8("clicked()")), RadialBand.AddData) QtCore.QObject.connect(self.DeleteBand, QtCore.SIGNAL(_fromUtf8("clicked()")), RadialBand.DeleteData) QtCore.QObject.connect(self.ClearBand, QtCore.SIGNAL(_fromUtf8("clicked()")), RadialBand.ClearBands) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), RadialBand.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), RadialBand.pass_radius) QtCore.QMetaObject.connectSlotsByName(RadialBand) list_values=pyqtSignal()
def __init__(self, parent = None): ''' @type parent: QWidget ''' QWidget.__init__(self, parent) self.ui = uic.loadUi(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ui/seasontab.ui'), self) self.connect(self.ui.closebutton, SIGNAL('pressed()'), self.closetab) self.connect(self.ui.checkselectedbutton, SIGNAL('pressed()'), self.checkselected) self.connect(self.ui.uncheckselectedbutton, SIGNAL('pressed()'), self.uncheckselected) self.episodestatuschanged = pyqtSignal('QString', 'QDateTime', name = 'episodestatuschanged')
def main(): def callback(name, address): print("Name=%s and address=%s" % (name, address)) signal = pyqtSignal() signal.connect(callback) # Mistake the first argument for a tuple. signal.emit(names=('marcus', 'ottosson'), address='earth') # TypeError: callback() got an unexpected keyword argument 'names' # When actually, its a single string value. signal.emit(name='marcus ottosson', address='earth') # Name=marcus ottosson and address=earth # Of course, non-keyword arguments works too. signal.emit('marcus ottosson', 'earth')
def __init__(self, parent=None): super(Login, self).__init__(parent) self.setWindowTitle(u"NENRA 2016 20180901 Kullanıcı Girişi ") self.labelname = QtGui.QLabel(self) self.labelpass = QtGui.QLabel(self) self.textName = QtGui.QLineEdit(self) self.textPass = QtGui.QLineEdit(self) self.labelname.setText(u"Kullanıcı Adı") self.labelpass.setText(u"Parola") self.buttonLogin = QtGui.QPushButton(u'Giriş', self) self.buttonLogin.clicked.connect(self.handleLogin) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.labelname) layout.addWidget(self.textName) layout.addWidget(self.labelpass) layout.addWidget(self.textPass) layout.addWidget(self.buttonLogin) self.acac1 = pyqtSignal(int)
def __init__(self, parent=None, tray_icon=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.tray_icon = tray_icon self.request = pyqtSignal() # background threads self.trigger_thread = TriggerWorker() # signal connection self.connect(self.trigger_thread, QtCore.SIGNAL("triggers_update(QString)"), self.triggers_update) #self.trigger_table.setRowCount(10) self.trigger_table.setColumnCount(7) self.trigger_table.setHorizontalHeaderLabels(['Level', 'Status', 'Info', 'Last change', 'Duration', 'Host', 'Description']) self.trigger_table.verticalHeader().setVisible(False) self.trigger_table.setSelectionBehavior(QAbstractItemView.SelectRows) #self.trigger_table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.trigger_table.horizontalHeader().setStretchLastSection(True)
class dlyWorkerSignals(QObject): result = pyqtSignal(object)
class MinMaxSource(QObject): """ A datasource that serves as a normalizing decorator for other datasources. """ isDirty = pyqtSignal(object) boundsChanged = pyqtSignal( object ) # When a new min/max is discovered in the result of a request, this signal is fired with the new (dmin, dmax) numberOfChannelsChanged = pyqtSignal(int) _delayedBoundsChange = pyqtSignal( ) # Internal use only. Allows non-main threads to start the delayedDirtySignal timer. def __init__(self, rawSource, parent=None): """ rawSource: The original datasource whose data will be normalized """ super(MinMaxSource, self).__init__(parent) self._rawSource = rawSource self._rawSource.isDirty.connect(self.isDirty) self._rawSource.numberOfChannelsChanged.connect( self.numberOfChannelsChanged) self._bounds = [1e9, -1e9] self._delayedDirtySignal = QTimer() self._delayedDirtySignal.setSingleShot(True) self._delayedDirtySignal.setInterval(10) self._delayedDirtySignal.timeout.connect( partial(self.setDirty, sl[:, :, :, :, :])) self._delayedBoundsChange.connect(self._delayedDirtySignal.start) @property def numberOfChannels(self): return self._rawSource.numberOfChannels def clean_up(self): self._rawSource.clean_up() @property def dataSlot(self): if hasattr(self._rawSource, "_orig_outslot"): return self._rawSource._orig_outslot else: return None def dtype(self): return self._rawSource.dtype() def request(self, slicing): rawRequest = self._rawSource.request(slicing) return MinMaxUpdateRequest(rawRequest, self._getMinMax) def setDirty(self, slicing): self.isDirty.emit(slicing) def __eq__(self, other): equal = True if other is None: return False equal &= isinstance(other, MinMaxSource) equal &= (self._rawSource == other._rawSource) return equal def __ne__(self, other): return not (self == other) def _getMinMax(self, data): dmin = np.min(data) dmax = np.max(data) dmin = min(self._bounds[0], dmin) dmax = max(self._bounds[1], dmax) dirty = False if (self._bounds[0] - dmin) > 1e-2: dirty = True if (dmax - self._bounds[1]) > 1e-2: dirty = True if dirty: self._bounds[0] = dmin self._bounds[1] = dmax self.boundsChanged.emit(self._bounds) # Our min/max have changed, which means we must force the TileProvider to re-request all tiles. # If we simply mark everything dirty now, then nothing changes for the tile we just rendered. # (It was already dirty. That's why we are rendering it right now.) # And when this data gets back to the TileProvider that requested it, the TileProvider will mark this tile clean again. # To ENSURE that the current tile is marked dirty AFTER the TileProvider has stored this data (and marked the tile clean), # we'll use a timer to set everything dirty. # This fixes ilastik issue #418 # Finally, note that before this timer was added, the problem described above occurred at random due to a race condition: # Sometimes the 'dirty' signal was processed BEFORE the data (bad) and sometimes it was processed after the data (good), # due to the fact that the Qt signals are always delivered in the main thread. # Perhaps a better way to fix this would be to store a timestamp in the TileProvider for dirty notifications, which # could be compared with the request timestamp before clearing the dirty state for each tile. # Signal everything dirty with a timer, as described above. self._delayedBoundsChange.emit() # Now, that said, we can still give a slightly more snappy response to the OTHER tiles (not this one) # if we immediately tell the TileProvider we are dirty. This duplicates some requests, but that shouldn't be a big deal. self.setDirty(sl[:, :, :, :, :])
class _ExpandableTextEdit(QTextEdit): """ Class implements edit line, which expands themselves automatically """ historyNext = pyqtSignal() historyPrev = pyqtSignal() def __init__(self, termWidget, *args): QTextEdit.__init__(self, *args) self.setStyleSheet("font: 9pt \"Courier\";") self._fittedHeight = 1 self.textChanged.connect(self._fit_to_document) self._fit_to_document() self._termWidget = termWidget def sizeHint(self): """ QWidget sizeHint impelemtation """ hint = QTextEdit.sizeHint(self) hint.setHeight(self._fittedHeight) return hint def _fit_to_document(self): """ Update widget height to fit all text """ documentSize = self.document().size().toSize() self._fittedHeight = documentSize.height() + (self.height() - self.viewport().height()) self.setMaximumHeight(self._fittedHeight) self.updateGeometry() def keyPressEvent(self, event): """ Catch keyboard events. Process Enter, Up, Down """ if event.matches(QKeySequence.InsertParagraphSeparator): text = self.toPlainText() if self._termWidget.is_command_complete(text): self._termWidget.exec_current_command() return elif event.matches(QKeySequence.MoveToNextLine): text = self.toPlainText() cursorPos = self.textCursor().position() textBeforeEnd = text[cursorPos:] # if len(textBeforeEnd.splitlines()) <= 1: if len(textBeforeEnd.split('\n')) <= 1: self.historyNext.emit() return elif event.matches(QKeySequence.MoveToPreviousLine): text = self.toPlainText() cursorPos = self.textCursor().position() textBeforeStart = text[:cursorPos] # lineCount = len(textBeforeStart.splitlines()) lineCount = len(textBeforeStart.split('\n')) if len(textBeforeStart) > 0 and \ (textBeforeStart[-1] == '\n' or textBeforeStart[-1] == '\r'): lineCount += 1 if lineCount <= 1: self.historyPrev.emit() return elif event.matches(QKeySequence.MoveToNextPage) or \ event.matches(QKeySequence.MoveToPreviousPage): return self._termWidget.browser().keyPressEvent(event) QTextEdit.keyPressEvent(self, event)
class FindReplace(QWidget): """ Find replace widget bar """ NbReplaced = pyqtSignal(int) def __init__(self, parent=None): """ This class provides an graphical interface to find and replace text @param parent: @type parent: """ QWidget.__init__(self, parent) self.editor = None self.styleEdit = { False: "background-color:rgb(255, 175, 90);", True: "" } self.createButton() self.createWidgets() self.createConnections() def showEnhanced(self, textSelected=''): """ Show enhanced (focus and text selected) """ self.show() if len(textSelected): self.edit.setEditText(textSelected) self.edit.setFocus() self.edit.lineEdit().selectAll() def createButton(self): """ create qt buttons Buttons defined: * Previous * Next * Replace """ self.previousButton = QtHelper.createButton( self, text=self.tr("Find Previous"), triggered=self.findPrevious, icon=QIcon(":/find_previous.png")) self.nextButton = QtHelper.createButton(self, text=self.tr("Find Next"), triggered=self.findNext, icon=QIcon(":/find_next.png")) self.replaceButton = QtHelper.createButton(self, text=self.tr("Replace..."), triggered=self.replaceFind, icon=QIcon(":/replace.png")) def createWidgets(self): """ QtWidgets creation QHBoxLayout -------------------------------------------..... | QLabel: QLineEdit QButton QButton QCheckBox | -------------------------------------------..... ....-------------------------------------- QLabel: QLineEdit QButton QCheckBox | ....-------------------------------------- """ glayout = QGridLayout() self.edit = QLineEditMore(parent=self) self.edit.setEditable(1) self.edit.setMaxCount(10) self.edit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.edit.lineEdit().setPlaceholderText("Search text in your test?") self.edit.setMinimumWidth(200) self.replaceEdit = QComboBox(self) self.replaceEdit.setEditable(1) self.replaceEdit.setMaxCount(10) self.replaceEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.replaceEdit.lineEdit().setPlaceholderText( "Replace the text with?") self.replaceEdit.setMinimumWidth(200) self.caseCheck = QCheckBox(self.tr("Case Sensitive")) self.caseCheck.setChecked( QtHelper.str2bool(Settings.instance().readValue( key='Editor/find-case-sensitive'))) self.caseWordCheck = QCheckBox(self.tr("Whole word only")) self.caseWordCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/find-whole-word'))) self.allCheck = QCheckBox(self.tr("All occurences")) self.allCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/replace-all'))) self.caseRegexpCheck = QCheckBox(self.tr("Regular expression")) self.caseRegexpCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/find-regexp'))) self.caseWrapCheck = QCheckBox(self.tr("Wrap at the end")) self.caseWrapCheck.setChecked( QtHelper.str2bool( Settings.instance().readValue(key='Editor/find-wrap'))) glayout.addWidget(self.edit, 0, 1) glayout.addWidget(self.nextButton, 0, 3) glayout.addWidget(self.previousButton, 0, 2) glayout.addWidget(self.caseCheck, 2, 2) glayout.addWidget(self.caseWrapCheck, 2, 3) glayout.addWidget(self.caseWordCheck, 3, 2) glayout.addWidget(self.caseRegexpCheck, 3, 3) glayout.addWidget(self.replaceEdit, 1, 1) glayout.addWidget(self.replaceButton, 1, 2) glayout.addWidget(self.allCheck, 1, 3) self.previousButton.setDisabled(True) self.nextButton.setDisabled(True) self.setLayout(glayout) flags = Qt.WindowFlags() flags |= Qt.Window flags |= Qt.WindowTitleHint flags |= Qt.WindowCloseButtonHint flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags) self.setWindowIcon(QIcon(":/main.png")) self.setWindowTitle("Find And Replace") def createConnections(self): """ create qt connection """ self.edit.editTextChanged.connect(self.textHasChanged) self.edit.EnterPressed.connect(self.returnPressed) self.caseCheck.stateChanged.connect(self.find) def returnPressed(self): """ Return key pressed Find next in this case """ self.findNext() def setEditor(self, editor): """ Set the target to find the text @param editor: @type editor: """ self.editor = editor def textHasChanged(self, txt): """ Find text has changed """ text = self.edit.currentText() if len(text) > 0: self.previousButton.setEnabled(True) self.nextButton.setEnabled(True) self.find(changed=True, forward=True) else: self.previousButton.setDisabled(True) self.nextButton.setDisabled(True) def updateComboBox(self): """ Update combobox """ comboUpdated = False for i in range(self.edit.count()): if self.edit.itemText(i) == self.edit.currentText(): comboUpdated = True if not comboUpdated: self.edit.addItem(self.edit.currentText()) comboUpdated = False for i in range(self.replaceEdit.count()): if self.replaceEdit.itemText(i) == self.replaceEdit.currentText(): comboUpdated = True if not comboUpdated: self.replaceEdit.addItem(self.replaceEdit.currentText()) def clearText(self): """ Clear all QlineEdit """ self.edit.setStyleSheet("") self.edit.clearEditText() self.replaceEdit.clearEditText() def findPrevious(self): """ Find previous occurence """ # update combobox self.updateComboBox() # find previous self.find(changed=False, forward=False) def findNext(self, line=-1, index=-1): """ Find next occurence """ # update combobox self.updateComboBox() return self.find(changed=False, forward=True, line=line, index=index) def find(self, changed=True, forward=True, line=-1, index=-1): """ Call the find function @param changed: @type changed: boolean @param forward: @type forward: boolean """ text = self.edit.currentText() if len(text) == 0: self.edit.setStyleSheet("") return None else: found = self.editor.findText( text, changed, forward, case=self.caseCheck.isChecked(), words=self.caseWordCheck.isChecked(), regexp=self.caseRegexpCheck.isChecked(), wraps=self.caseWrapCheck.isChecked(), line=line, index=index) self.edit.setStyleSheet(self.styleEdit[found]) return found def replaceFind(self): """ Replace and find """ if (self.editor is None): return replaceText = self.replaceEdit.currentText() searchText = self.edit.currentText() if not self.caseCheck.isChecked(): searchText = searchText.lower() current = -1 nbReplaced = 0 # find the first occurence from the beginning of the doc or not if not self.allCheck.isChecked(): detected = self.findNext() else: detected = self.findNext(line=0, index=0) (line, _) = self.editor.getCursorPosition() while detected: previous = current selectedText = self.editor.selectedText() # normalize the text in lower case if the case sensitive is not activated if not self.caseCheck.isChecked(): selectedText = selectedText.lower() # replace the selection if self.editor.hasSelectedText() and selectedText == searchText: self.editor.replace(replaceText) nbReplaced += 1 # find the next occurence of the word detected = self.findNext() (current, _) = self.editor.getCursorPosition() # all doc readed ? break the loop if previous > current: break if current == line and previous != -1: break # just execute one replace if not self.allCheck.isChecked(): break self.allCheck.setCheckState(Qt.Unchecked) self.NbReplaced.emit(nbReplaced)
class Beamshutter(QObject): throwMessage = pyqtSignal(str, int, name='throwMessage') CtrlStarted = pyqtSignal(bool, name="ControlStarted") enableShutter = pyqtSignal(int, name='EnableShutter') disableShutter = pyqtSignal(int, name='DisableShutter') setOpMode = pyqtSignal(int, int, name='setOpMode') setCyMode = pyqtSignal(int, float, float, int, name='SetCycleMode') getShutState = pyqtSignal(int, int, name='ShutterState') startControl = pyqtSignal(name='startControl') stopControl = pyqtSignal(name='stopControl') def __init__(self, widget): QObject.__init__(self) self.parent = widget self.beamshutter_not_found = False # gehrlich temporarily connect to another function for testing self.startControl.connect(self.do_something) self.stopControl.connect(self.do_something) self.CtrlStarted.connect(self.do_something) self.enableShutter.connect(self.do_something) self.disableShutter.connect(self.do_something) self.setOpMode.connect(self.do_something) self.setCyMode.connect(self.do_something) self.getShutState.connect(self.do_something) #try: """ self.startControl.connect(self.parent.control.StartCtrl) self.stopControl.connect(self.parent.control.StopCtrl) self.CtrlStarted.connect(self.parent.control.GetCtrlStarted) self.enableShutter.connect(self.parent.control.SC_Enable) self.disableShutter.connect(self.parent.control.SC_Disable) self.setOpMode.connect(self.parent.control.SC_SetOperatingMode) self.setCyMode.connect(self.parent.control.SC_SetCycleParams) self.getShutState.connect(self.parent.control.SC_GetOPState) self.parent.control.MoveComplete.connect(self.stateChanged) """ #except(AttributeError): # self.throwMessage.emit("Beamshutter is not installed",0) # self.beamshutter_not_found=True # gehrlich temporary fn to which to connect, so that I can test the UI def do_something(): print "Beamshutter was told to do something" def initialize(self): self.startControl.emit() self.jobFinished() def finalize(self): self.stopControl.emit() self.jobFinished() def isInitialized(self): #notWorking # print ("test") # a=ctypes.c_bool(True) # started=ctypes.pointer(a) # self.CtrlStarted.emit(bool(ctypes.byref(a))) # print (started) #started = QVariant(1) #args=[started] #self.parent.control.dynamicCall("GetCtrlStarted(bool&)",args) return (True) def stateChanged(self, channelId): #Is this working? print("BeamShutter State Changed?") def enable(self): self.enableShutter.emit(1) self.parent.currentShutterState.emit("Open") self.jobFinished() def disable(self): self.disableShutter.emit(1) self.parent.currentShutterState.emit("Close") self.jobFinished() def getShutterState(self): result = ctypes.c_int(-1) self.getShutState.emit(1, ctypes.byref(result)) self.jobFinished() return result.value def setOperationMode(self, mode): self.setOpMode.emit(mode) self.jobFinished() def setCycleParameters(self, onTime, offTime, numberOfCycles): self.setCyMode.emit(1, onTime, offTime, numberOfCycles) self.jobFinished() def jobFinished(self): lock = QMutexLocker(self.parent.mutex) self.parent.shutterReplied = True
class PluginLoader(QObject): '''PluginLoader. Goes through subfolders of /plugins and searches for plugin files(ending with "plugin.py"). SamplePlugin provides a sample for such plugins. ''' insertPluginAction = pyqtSignal('PyQt_PyObject') def __init__(self, distributedObjects): """CTOR of pluginloader.""" QObject.__init__(self) self.plugin_dir = os.path.dirname(__file__) + '/../plugins' # contains the instances of the loaded modules' classes self.loadedPlugins = {} # all generated actions by their path self.pluginActions = {} # signalproxy for communication with plugins self.signalproxy = distributedObjects.signalProxy # xml file for plugin info self.xmlFile = self.plugin_dir + '/plugins.xml' def addAvailablePlugins(self): """Search in all subfolders of src/plugins for plugin files and add them as menu entries.""" # go through subdirs of pluginfolder and identify pluginfiles (ending with "Plugins.py") for root, _, files in os.walk(self.plugin_dir): for f in files: if root != self.plugin_dir and (f.endswith('Plugin.py') or f.endswith('plugin.py')): # create action and add it to mainwindow path = os.path.join(root, f) pAction = PluginAction(self, path) self.pluginActions[path] = pAction self.insertPluginAction.emit(pAction) # activate all plugins which where active on previous program execution self.getActivePlugins() def loadPlugin(self, plugin): """Load plugin from plugin folder. Name of class and file of plugin must be the same.""" try: pluginmodule = __import__("plugins.%s.%s" % (plugin.modulename, plugin.classname)) except ImportError as e: logging.error( "Error while loading plugin " + plugin.modulename + ". Error: %s", e) return False try: module = getattr(getattr(pluginmodule, plugin.modulename), plugin.classname) class_ = getattr(module, plugin.classname) self.loadedPlugins[plugin] = class_() except AttributeError: logging.error("Error while loading plugin " + plugin.modulename + ". Class " + plugin.classname + " not found") return False if hasattr(self.loadedPlugins[plugin], "initPlugin"): self.loadedPlugins[plugin].initPlugin( self.signalproxy) # init plugin with signal interface return True else: logging.error("Error while loading plugin " + plugin.classname + ". Function initPlugin() not found") return False def unloadPlugin(self, plugin): '''Called when user unloads plugin from menu''' try: self.loadedPlugins[plugin].deInitPlugin() except AttributeError: logging.error("Error while unloading " + plugin.modulename + ". No deInitPlugin() function found") except KeyError: # the plugin was not loaded, no need to fail pass else: del self.loadedPlugins[plugin] def getActivePlugins(self, filename=None): ''' Function checks xml and returns if plugin was active on previous program execution xmlfile: specifies alternative path to xml file with plugin information ''' if not filename: filename = self.xmlFile if os.path.exists(filename): fileObject = QFile(filename) Xml = QDomDocument("xmldoc") Xml.clear() if (fileObject.open(QIODevice.ReadOnly)): Xml.setContent(fileObject.readAll()) fileObject.close() rootNode = Xml.documentElement() nodeList = rootNode.elementsByTagName("plugin") for i in range(nodeList.length()): bpNode = nodeList.at(i).toElement() path = str(bpNode.attribute("path")) if path in self.pluginActions: self.pluginActions[path].setLoaded( bpNode.attribute("active") == "y") else: logging.warning( "No plugin for %s found, maybe it was moved/deleted?", path) def savePluginInfo(self, filename=None): ''' write plugin info to xml (plugin active/inactive ...) xmlfile: specifies alternative path to xml file with plugin information ''' if not filename: filename = self.xmlFile # create xml Xml = QDomDocument("xmldoc") rootNode = Xml.createElement("SysCDbgActivePlugins") Xml.appendChild(rootNode) for i in iter(self.pluginActions.values()): pluginNode = Xml.createElement("plugin") pluginNode.setAttribute("path", i.path) if i.isChecked(): pluginNode.setAttribute("active", "y") else: pluginNode.setAttribute("active", "n") rootNode.appendChild(pluginNode) # create and write xml file with open(filename, "w") as f: f.write(Xml.toString())
class LayerSnappingAction(LayerSnappingEnabledAction): """Action to change snapping settings for a QGIS vector layer.""" snapSettingsChanged = pyqtSignal(str) def __init__(self, snapLayer, parent=None): super(LayerSnappingAction, self).__init__(snapLayer, parent) self._toleranceAction = None # LayerSnappingToleranceAction() self._avoidAction = None # LayerSnappingAvoidIntersectionsAction() self._vertexAction = LayerSnappingTypeAction(snapLayer, Snapping.Vertex, self) self._segmentAction = LayerSnappingTypeAction(snapLayer, Snapping.Segment, self) self._vertexSegmentAction = LayerSnappingTypeAction( snapLayer, Snapping.VertexAndSegment, self) self._snappingTypeActionGroup = QActionGroup(self) self._snappingTypeActionGroup.addAction(self._vertexAction) self._snappingTypeActionGroup.addAction(self._segmentAction) self._snappingTypeActionGroup.addAction(self._vertexSegmentAction) self._toleranceAction = LayerSnappingToleranceAction(snapLayer, parent) self._pixelUnitsAction = LayerSnappingUnitAction( snapLayer, Snapping.Pixels, self) self._layerUnitsAction = LayerSnappingUnitAction( snapLayer, Snapping.LayerUnits, self) self._projectUnitsAction = LayerSnappingUnitAction( snapLayer, Snapping.ProjectUnits, self) self._unitTypeActionGroup = QActionGroup(self) self._unitTypeActionGroup.addAction(self._pixelUnitsAction) self._unitTypeActionGroup.addAction(self._layerUnitsAction) self._unitTypeActionGroup.addAction(self._projectUnitsAction) menu = ControlMenu(parent) menu.addActions(self._snappingTypeActionGroup.actions()) menu.addSeparator() menu.addAction(self._toleranceAction) menu.addActions(self._unitTypeActionGroup.actions()) if (isinstance(snapLayer, QgisInterface) or (isinstance(snapLayer, QgsVectorLayer) and snapLayer.geometryType() == QGis.Polygon)): self._avoidAction = LayerSnappingAvoidIntersectionsAction( snapLayer, self) menu.addSeparator() menu.addAction(self._avoidAction) self.setMenu(menu) self._refreshAction() # Make sure we catch changes in the main snapping dialog QgsProject.instance().snapSettingsChanged.connect(self._refreshAction) # If using current layer, make sure we update when it changes if self._iface: self._iface.legendInterface().currentLayerChanged.connect( self._refreshAction) # If any of the settings change then signal, but don't tell project as actions already have self.snappingEnabledChanged.connect(self.snapSettingsChanged) self._vertexAction.snappingTypeChanged.connect( self.snapSettingsChanged) self._segmentAction.snappingTypeChanged.connect( self.snapSettingsChanged) self._vertexSegmentAction.snappingTypeChanged.connect( self.snapSettingsChanged) self._toleranceAction.snappingToleranceChanged.connect( self.snapSettingsChanged) self._pixelUnitsAction.snappingUnitChanged.connect( self.snapSettingsChanged) self._layerUnitsAction.snappingUnitChanged.connect( self.snapSettingsChanged) self._projectUnitsAction.snappingUnitChanged.connect( self.snapSettingsChanged) if self._avoidAction: self._avoidAction.avoidIntersectionsChanged.connect( self.snapSettingsChanged) def setInterface(self, iface): self._toleranceAction.setInterface(iface) def unload(self): if not self._layerId: return super(LayerSnappingAction, self).unload() QgsProject.instance().snapSettingsChanged.disconnect( self._refreshAction) self.snappingEnabledChanged.disconnect(self.snapSettingsChanged) self._vertexAction.snappingTypeChanged.disconnect( self.snapSettingsChanged) self._segmentAction.snappingTypeChanged.disconnect( self.snapSettingsChanged) self._vertexSegmentAction.snappingTypeChanged.disconnect( self.snapSettingsChanged) self._toleranceAction.snappingToleranceChanged.disconnect( self.snapSettingsChanged) self._pixelUnitsAction.snappingUnitChanged.disconnect( self.snapSettingsChanged) self._layerUnitsAction.snappingUnitChanged.disconnect( self.snapSettingsChanged) self._projectUnitsAction.snappingUnitChanged.disconnect( self.snapSettingsChanged) if self._avoidAction: self._avoidAction.avoidIntersectionsChanged.disconnect( self.snapSettingsChanged) self._vertexAction.unload() self._segmentAction.unload() self._vertexSegmentAction.unload() self._toleranceAction.unload() self._pixelUnitsAction.unload() self._layerUnitsAction.unload() self._projectUnitsAction.unload() # Private API def _refreshAction(self): if (self._segmentAction.isChecked()): self.setIcon(self._segmentAction.icon()) elif (self._vertexSegmentAction.isChecked()): self.setIcon(self._vertexSegmentAction.icon()) else: # Snapping.Vertex or undefined self.setIcon(self._vertexAction.icon()) if self._iface and self._avoidAction: layer = QgsMapLayerRegistry.instance().mapLayer(self.layerId()) isPolygon = (layer is not None and layer.type() == QgsMapLayer.VectorLayer and layer.geometryType() == QGis.Polygon) self._avoidAction.setEnabled(isPolygon)
class IVSweepMeasurement(QThread): readingAvailable = pyqtSignal(float, float, float, float, float) sweepComplete = pyqtSignal(float, float, float, float, float, float, np.ndarray, np.ndarray, np.ndarray) '''T, Vo, VcDrive, VcMeas, tStart, tEnd, Vdrives, Vmeas''' def __init__(self, ao, ai, parent=None): QThread.__init__(self, parent) self.ao = ao self.ai = ai self.paused = False self.threshold = 10 self.bipolar = False self.T = np.nan self.interSweepDelay = 0 self.samplesPerPoint = 1 self.adaptiveSweep = False self.adaptiveLower = 0.6 self.adaptiveUpper = 1.3 self.reverseSweep = False def enableReverseSweep(self, enable=True): self.reverseSweep = enable def enableAdaptiveSweep(self, enable=True): self.adaptiveSweep = enable def setAdaptiveUpper(self, fraction): self.adaptiveUpper = fraction def setAdaptiveLower(self, fraction): self.adaptiveLower = fraction def setFileName(self, fileName): self.fileName = fileName def setVoltages(self, voltages): self.voltages = voltages def enableBipolar(self, enable=True): self.bipolar = enable def setThreshold(self, threshold): self.threshold = threshold def setInterSweepDelay(self, delay): self.interSweepDelay = delay def stop(self): self.stopRequested = True def pause(self, pause=True): self.paused = pause def unpause(self): self.pause(False) def updateTemperature(self, T): self.T = T def setMaximumVoltage(self, Vmax): self.VmaxP = limit(Vmax, 0, 10) self.VmaxN = -self.VmaxP def setMinimumVoltage(self, Vmin): self.VminP = limit(Vmin, 0, 10) self.VminN = -self.VminP def setPositiveRange(self, Vmin, Vmax): self.VmaxP = limit(Vmax, 0, 10) self.VminP = limit(Vmin, 0, Vmax) def setNegativeRange(self, Vmin, Vmax): self.VmaxN = -limit(Vmax, 0, 10) self.VminN = -limit(Vmin, 0, Vmax) def setSteps(self, steps): self.steps = steps def interruptibleSleep(self, seconds, condition=False): t0 = time.time() while (time.time() - t0 < self.interSweepDelay): if self.stopRequested or condition: break self.msleep(10) def run(self): self.stopRequested = False print "Thread running" daqRes = 20. / 65535. bipolarToggle = 1. VcritOldP = None # Keep track of positive and negative critical drive for adaptive sweeping VcritOldN = None try: while not self.stopRequested: self.ao.setDcDrive(0) self.interruptibleSleep(10. * self.interSweepDelay) Vo = self.ai.measureDc() print "Offset voltage Vo=", Vo if bipolarToggle < 0: Vmax = self.VmaxN Vmin = self.VminN else: Vmax = self.VmaxP Vmin = self.VminP maxSteps = int(abs(Vmax - Vmin) / daqRes) steps = min(self.steps, maxSteps) Vdrives = np.linspace(Vmin, Vmax, steps) if self.reverseSweep: Vdrives = np.append(Vdrives, Vdrives[::-1]) self.ao.setDcDrive(Vdrives[0]) self.interruptibleSleep(self.interSweepDelay) Vmeas = [] print "Starting sweep from %f to %f V (%d steps)" % ( Vmin, Vmax, steps) ts = np.ones_like(Vdrives) * np.nan Vmeas = np.ones_like(Vdrives) * np.nan for i, Vdrive in enumerate(Vdrives): self.ao.setDcDrive(Vdrive) t = time.time() V = self.ai.measureDc() Vmeas[i] = V ts[i] = t self.readingAvailable.emit(t, Vdrive, V, Vo, self.T) if self.stopRequested: break Vcrit, Icrit = determineCriticalCurrent(Vdrives, Vmeas) print "Vcrit, Icrit", Vcrit, Icrit #Vcrit = bipolarToggle; Icrit = bipolarToggle # if np.sign(slope) == np.sign(bipolarToggle): # iCrit = np.argmax(Vmeas) # else: # iCrit = np.argmin(Vmeas) # Vcrit = Vdrives[iCrit] # Icrit = Vmeas[iCrit] # Not really a current... #print "iCrit, Vcrit, Icrit:", iCrit, Vcrit, 'V', Icrit, 'V' self.ao.setDcDrive(0) print "Sweep complete" '''T, Vo, Vcrit, Icrit, tStart, tEnd, Vdrives, Vmeas, ts''' self.sweepComplete.emit(self.T, Vo, Vcrit, Icrit, ts[0], ts[-1], np.asarray(Vdrives, dtype=np.float32), np.asarray(Vmeas, dtype=np.float32), np.asarray(ts, dtype=np.float)) if self.adaptiveSweep and not np.isnan(Vcrit): Vmin = self.adaptiveLower * abs(Vcrit) Vmax = self.adaptiveUpper * abs(Vcrit) if Vcrit < 0: if VcritOldN is not None: error = abs(Vcrit - VcritOldN) / VcritOldN else: error = 0 if error < 0.25: VcritOldN = Vcrit self.setNegativeRange(Vmin, Vmax) else: print "Rejected new negative critical drive because the error was too large:", error else: if VcritOldP is not None: error = abs(Vcrit - VcritOldP) / VcritOldP else: error = 0 if error < 0.1: VcritOldP = Vcrit self.setPositiveRange(Vmin, Vmax) else: print "Rejected new positive critical drive because the error was too large:", error if self.bipolar: bipolarToggle = -bipolarToggle if self.stopRequested: break except Exception, e: print "Exception:", e print "Thread finished"
class ProcessorThread(QThread): """Thread processes text with ctags and returns tags """ resultsReady = pyqtSignal(tuple) # Document, dict _Task = collections.namedtuple("Task", ["document", "language", "filePath"]) _MSG_ID_CONVERTOR = {# Note that most of the PEP8 "errors" listed in http://pep8.readthedocs.org/en/latest/intro.html#error-codes aren't syntax errors. So, mark most of these as warnings instead. Later in the code, E9 errors are actually marked as errors. See https://github.com/hlamer/enki/issues/349. 'E': Qutepart.LINT_WARNING, 'W': Qutepart.LINT_WARNING, 'F': Qutepart.LINT_ERROR, 'C': Qutepart.LINT_NOTE, 'N': Qutepart.LINT_NOTE, } _PARSER_REG_EXP = re.compile('^(.+):(\d+):(\d+): ([A-Z]\d\d\d .+)$') def __init__(self): QThread.__init__(self) self._queue = Queue.Queue() self.start(QThread.LowPriority) def process(self, document): """Parse text and emit results """ self._queue.put( self._Task(document, document.qutepart.language(), document.filePath())) def stopAsync(self): self._queue.put(None) def run(self): """Thread function """ while True: # exits with break # wait task task = self._queue.get() # take the last task # get the last task while not self._queue.empty(): task = self._queue.get() if task is None: # None is a quit command break results = self._processSync(task.language, task.filePath) if results is not None: self.resultsReady.emit(( task.document, results, )) def _processSync(self, language, filePath): conf = core.config()['Lint']['Python'] ignored = ','.join(conf['IgnoredMessages'].split()) try: stdout = get_console_output([ conf['Path'], '--max-line-length={}'.format(conf['MaxLineLength']), '--ignore={}'.format(ignored), filePath ])[0] except OSError: return result = {} for line in stdout.splitlines(): match = self._PARSER_REG_EXP.match(line) if match: filePath = match.group(1) lineNumber = match.group(2) columnNumber = match.group(3) rest = match.group(4) msgId, msgText = rest.lstrip().split(' ', 1) lineIndex = int(lineNumber) - 1 # Per comments on _MSG_ID_CONVERTOR, mark PEP8 E9 errors as errors. All other PEP8 errors are shown as warnings. if msgId.startswith('E9'): msgType = Qutepart.LINT_ERROR else: msgType = self._MSG_ID_CONVERTOR[msgId[0]] if msgType is not None: # not ignored if lineIndex not in result: result[lineIndex] = (msgType, rest) return result
class CalibrateGyroscopeGain(QWidget, Ui_calibrate_gyroscope_gain): TYPE_GYR_GAIN = 4 NUM_AVG = 5000 qtcb_callback = pyqtSignal(int, int, int) def __init__(self, parent): QWidget.__init__(self) self.setupUi(self) self.parent = parent self.imu = parent.parent.imu self.set_default() self.start_button.clicked.connect(self.next_state) self.i = 0 self.t = 0 self.state = 0 self.gyr = [0, 0, 0] self.gyr_sum = [0, 0, 0] self.gyr_gain_mult = [0, 0, 0] self.gyr_gain_div = [0, 0, 0] self.qtcb_callback.connect(self.callback) def start(self): self.imu.register_callback(self.imu.CALLBACK_ANGULAR_VELOCITY, self.qtcb_callback.emit) def stop(self): self.imu.set_angular_velocity_period(0) def set_default(self): self.i = 0 self.t = 0 self.gyr = [0, 0, 0] self.gyr_sum = [0, 0, 0] self.gyr_gain_mult = [0, 0, 0] self.gyr_gain_div = [0, 0, 0] self.text_label.setText("""<p>To calibrate the \ gyroscope gain you need to rotate the IMU Brick with precise speeds, this is \ only possible with suitable machinery. <font color="red">We highly recommend \ hat you keep the factory calibration here.</font></p> Note: As soon as you click "Start Calibration", the current calibration \ will be deleted. You can make a backup of the old calibration \ in the Im/Export tab.""") self.start_button.setText("Start Calibration") def calc(self, i): self.gyr_gain_mult[i] = 647 # 45*14.375 self.gyr_gain_div[i] = abs(self.gyr[i]) if i == 0: self.gain_x.setText( str(self.gyr_gain_mult[i]) + '/' + str(self.gyr_gain_div[i])) elif i == 1: self.gain_y.setText( str(self.gyr_gain_mult[i]) + '/' + str(self.gyr_gain_div[i])) elif i == 2: self.gain_z.setText( str(self.gyr_gain_mult[i]) + '/' + str(self.gyr_gain_div[i])) def next_state(self): self.state += 1 if self.state == 8: self.state = 0 if self.state == 0: gain = [ self.gyr_gain_mult[0], self.gyr_gain_mult[1], self.gyr_gain_mult[2], self.gyr_gain_div[0], self.gyr_gain_div[1], self.gyr_gain_div[2], 0, 0, 0, 0 ] self.imu.set_calibration(self.TYPE_GYR_GAIN, gain) self.parent.refresh_values() self.gain_x.setText("?") self.gain_y.setText("?") self.gain_z.setText("?") self.set_default() if self.state == 1: gain = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] self.imu.set_calibration(self.TYPE_GYR_GAIN, gain) self.parent.refresh_values() self.text_label.setText("Turn IMU Brick 45%c/s around X-axis." % 0xB0) self.start_button.setText("Start X Calibration") if self.state == 2: self.i = 0 self.imu.set_angular_velocity_period(1) self.start_button.setEnabled(False) if self.state == 3: self.gyr[0] = self.gyr_sum[0] / self.NUM_AVG self.calc(0) self.text_label.setText("Turn IMU Brick 45%c/s around Y-axis." % 0xB0) self.start_button.setText("Start Y Calibration") if self.state == 4: self.i = 0 self.imu.set_angular_velocity_period(1) self.start_button.setEnabled(False) if self.state == 5: self.gyr[1] = self.gyr_sum[1] / self.NUM_AVG self.calc(1) self.text_label.setText("Turn IMU Brick 45%c/s around Z-axis." % 0xB0) self.start_button.setText("Start Z Calibration") if self.state == 6: self.i = 0 self.imu.set_angular_velocity_period(1) self.start_button.setEnabled(False) if self.state == 7: self.gyr[2] = self.gyr_sum[2] / self.NUM_AVG self.calc(2) self.text_label.setText("""Ready. Press "Save Calibration" to \ upload the new calibration.""") self.start_button.setText("Save Calibration") def callback(self, gyr_x, gyr_y, gyr_z): if self.i == 0: self.t = time.time() self.gyr_sum = [0, 0, 0] if not self.start_button.isEnabled(): self.text_label.setText("Calibrating: " + str(self.i) + '/' + str(self.NUM_AVG)) else: return self.gyr_sum[0] += gyr_x self.gyr_sum[1] += gyr_y self.gyr_sum[2] += gyr_z self.i += 1 if self.i == self.NUM_AVG: self.imu.set_angular_velocity_period(0) self.start_button.setEnabled(True) self.next_state() self.i = 0
class SettingsPage(QWidget): """ """ ReloadSettings = pyqtSignal() TestSettings = pyqtSignal(dict) def __init__(self, parent): """ """ super(SettingsPage, self).__init__() self.__core = parent self.config = None self.createWidgets() self.createConnections() self.loadCfg() def core(self): """ """ return self.__core def createConnections(self): """ """ self.saveButton.clicked.connect(self.__saveCfg) self.testButton.clicked.connect(self.testConnection) def createWidgets(self): """ """ qcCredGroup = QGroupBox(self.tr("HP ALM server credentials")) self.hpCredLogin = QLineEdit() self.hpCredPwd = QLineEdit() self.hpCredPwd.setEchoMode(QLineEdit.Password) qcCredLayout = QGridLayout() qcCredLayout.addWidget(QLabel("Login"), 0, 0) qcCredLayout.addWidget(self.hpCredLogin, 0, 1) qcCredLayout.addWidget(QLabel("Password"), 1, 0) qcCredLayout.addWidget(self.hpCredPwd, 1, 1) qcCredGroup.setLayout(qcCredLayout) qcSvrGroup = QGroupBox(self.tr("HP ALM server informations")) self.hpSvrURL = QLineEdit() self.hpSvrDomain = QLineEdit() self.hpSvrProject = QLineEdit() self.comAPI = QRadioButton("COM") self.comAPI.setChecked(False) self.comAPI.setEnabled(False) self.restAPI = QRadioButton("REST") self.restAPI.setChecked(True) layoutApi = QHBoxLayout() layoutApi.addWidget(self.comAPI) layoutApi.addWidget(self.restAPI) qcSvrLayout = QGridLayout() qcSvrLayout.addWidget(QLabel("URL"), 0, 0) qcSvrLayout.addWidget(self.hpSvrURL, 0, 1) qcSvrLayout.addWidget(QLabel("Domain"), 1, 0) qcSvrLayout.addWidget(self.hpSvrDomain, 1, 1) qcSvrLayout.addWidget(QLabel("Project"), 2, 0) qcSvrLayout.addWidget(self.hpSvrProject, 2, 1) qcSvrLayout.addWidget(QLabel("API"), 3, 0) qcSvrLayout.addLayout(layoutApi, 3, 1) qcSvrGroup.setLayout(qcSvrLayout) # begin export result settings qcExportResultGroup = QGroupBox(self.tr("Export results")) self.ignoreTcCheckBox = QCheckBox(self.tr("Ignore testcase(s)")) self.ignoreUncompleteCheckBox = QCheckBox( self.tr("Ignore uncomplete test(s)")) self.addFoldersTlCheckBox = QCheckBox( self.tr("Create missing folders in test lab")) self.addTestsetCheckBox = QCheckBox( self.tr("Create testset if missing in test lab")) self.addTestinstanceCheckBox = QCheckBox( self.tr("Create test instance in test set")) self.cfgsTestsetTable = DesignPage.ConfigsTableView(self, core=self.core()) qcExportResultLayout = QVBoxLayout() qcExportResultLayout.addWidget(self.ignoreTcCheckBox) qcExportResultLayout.addWidget(self.ignoreUncompleteCheckBox) qcExportResultLayout.addWidget(self.addFoldersTlCheckBox) qcExportResultLayout.addWidget(self.addTestsetCheckBox) qcExportResultLayout.addWidget(self.addTestinstanceCheckBox) qcExportResultLayout.addWidget(QLabel("Custom TestSet Fields")) qcExportResultLayout.addWidget(self.cfgsTestsetTable) qcExportResultLayout.addStretch(1) qcExportResultGroup.setLayout(qcExportResultLayout) # end # begin export test settings qcExportGroup = QGroupBox(self.tr("Export tests")) self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one")) self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one")) self.showTcNameCheckBox = QCheckBox( self.tr("Load with original test name")) self.replaceTcCheckBox = QCheckBox( self.tr("Replace testcase with testname")) self.addFoldersTpCheckBox = QCheckBox( self.tr("Create missing folders in test plan")) self.overwriteTcCheckBox = QCheckBox( self.tr("Overwrite testcases in test plan")) self.cfgsTable = DesignPage.ConfigsTableView(self, core=self.core()) qcExportLayout = QGridLayout() qcExportLayout.addWidget(self.mergeCheckBox, 0, 0) qcExportLayout.addWidget(self.mergeStepsCheckBox, 1, 0) qcExportLayout.addWidget(self.showTcNameCheckBox, 2, 0) qcExportLayout.addWidget(self.replaceTcCheckBox, 3, 0) qcExportLayout.addWidget(self.addFoldersTpCheckBox, 4, 0) qcExportLayout.addWidget(self.overwriteTcCheckBox, 5, 0) qcExportLayout.addWidget(QLabel("Custom Test Fields"), 6, 0) qcExportLayout.addWidget(self.cfgsTable, 7, 0) qcExportGroup.setLayout(qcExportLayout) # end layoutCtrls = QHBoxLayout() self.saveButton = QPushButton(self.tr("Save Settings"), self) self.testButton = QPushButton(self.tr("Test Connection"), self) layoutCtrls.addWidget(self.saveButton) layoutCtrls.addWidget(self.testButton) mainLayout = QGridLayout() mainLayout.addWidget(qcSvrGroup, 0, 0) mainLayout.addWidget(qcCredGroup, 0, 1) mainLayout.addWidget(qcExportGroup, 2, 0) mainLayout.addWidget(qcExportResultGroup, 2, 1) mainLayout.addLayout(layoutCtrls, 3, 1) self.setLayout(mainLayout) def loadCfg(self): """ """ with open("%s/config.json" % (QtHelper.dirExec())) as f: CONFIG_RAW = f.read() self.config = json.loads(CONFIG_RAW) self.hpCredLogin.setText(self.config["credentials"]["login"]) self.hpSvrURL.setText(self.config["qc-server"]["url"]) self.hpSvrDomain.setText(self.config["qc-server"]["domain"]) self.hpSvrProject.setText(self.config["qc-server"]["project"]) self.restAPI.setChecked(True) if self.config["export-tests"]["merge-all-tests"]: self.mergeCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["merge-all-steps"]: self.mergeStepsCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["original-test"]: self.showTcNameCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["replace-testcase"]: self.replaceTcCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["add-folders"]: self.addFoldersTpCheckBox.setCheckState(Qt.Checked) if self.config["export-tests"]["overwrite-tests"]: self.overwriteTcCheckBox.setCheckState(Qt.Checked) self.cfgsTable.loadTable(data=self.config["custom-test-fields"]) if self.config["export-results"]["ignore-testcase"]: self.ignoreTcCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["ignore-uncomplete"]: self.ignoreUncompleteCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["add-folders"]: self.addFoldersTlCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["add-testset"]: self.addTestsetCheckBox.setCheckState(Qt.Checked) if self.config["export-results"]["add-testinstance"]: self.addTestinstanceCheckBox.setCheckState(Qt.Checked) self.cfgsTestsetTable.loadTable( data=self.config["custom-testset-fields"]) # decrypt password if len(self.config["credentials"]["password"]): decrypted = self.decryptPwd( key=bytes(self.config["credentials"]["login"], "utf8"), ciphertext=bytes(self.config["credentials"]["password"], "utf8")) self.config["credentials"]["password"] = decrypted self.hpCredPwd.setText(decrypted) def __saveCfg(self): """ """ self.saveCfg(successMsg=True) def saveCfg(self, successMsg=True): """ """ # if successMsg: if not len(self.hpSvrURL.text()): QMessageBox.warning(self, self.tr("Save Settings"), self.tr("Please to set the server url")) return if not len(self.hpSvrDomain.text()): QMessageBox.warning(self, self.tr("Save Settings"), self.tr("Please to set the server domain")) return if not len(self.hpSvrProject.text()): QMessageBox.warning(self, self.tr("Save Settings"), self.tr("Please to set the server project")) return if not len(self.hpCredLogin.text()): QMessageBox.warning(self, self.tr("Save Settings"), self.tr("Please to set a login")) return if not len(self.hpCredPwd.text()): QMessageBox.warning(self, self.tr("Save Settings"), self.tr("Please to set a password")) return self.config["credentials"]["login"] = self.hpCredLogin.text() # encrypt password encryptPwd = self.encryptPwd(key=self.hpCredLogin.text(), plaintext=self.hpCredPwd.text()) self.config["credentials"]["password"] = str(encryptPwd, "utf8") self.config["qc-server"]["url"] = self.hpSvrURL.text() self.config["qc-server"]["domain"] = self.hpSvrDomain.text() self.config["qc-server"]["project"] = self.hpSvrProject.text() self.config["qc-server"]["use-rest"] = False if self.restAPI.isChecked(): self.config["qc-server"]["use-rest"] = True self.config["export-tests"]["merge-all-tests"] = False self.config["export-tests"]["merge-all-steps"] = False self.config["export-tests"]["original-test"] = False self.config["export-tests"]["replace-testcase"] = False self.config["export-tests"]["add-folders"] = False self.config["export-tests"]["overwrite-tests"] = False if self.mergeCheckBox.isChecked(): self.config["export-tests"]["merge-all-tests"] = True if self.mergeStepsCheckBox.isChecked(): self.config["export-tests"]["merge-all-steps"] = True if self.showTcNameCheckBox.isChecked(): self.config["export-tests"]["original-test"] = True if self.replaceTcCheckBox.isChecked(): self.config["export-tests"]["replace-testcase"] = True if self.addFoldersTpCheckBox.isChecked(): self.config["export-tests"]["add-folders"] = True if self.overwriteTcCheckBox.isChecked(): self.config["export-tests"]["overwrite-tests"] = True self.config["custom-test-fields"] = self.cfgsTable.model.getData() self.config["export-results"]["add-folders"] = False self.config["export-results"]["ignore-testcase"] = False self.config["export-results"]["ignore-uncomplete"] = False self.config["export-results"]["add-testset"] = False self.config["export-results"]["add-testinstance"] = False if self.ignoreTcCheckBox.isChecked(): self.config["export-results"]["ignore-testcase"] = True if self.ignoreUncompleteCheckBox.isChecked(): self.config["export-results"]["ignore-uncomplete"] = True if self.addFoldersTlCheckBox.isChecked(): self.config["export-results"]["add-folders"] = True if self.addTestsetCheckBox.isChecked(): self.config["export-results"]["add-testset"] = True if self.addTestinstanceCheckBox.isChecked(): self.config["export-results"]["add-testinstance"] = True self.config[ "custom-testset-fields"] = self.cfgsTestsetTable.model.getData() with open("%s/config.json" % (QtHelper.dirExec()), "w") as f: f.write(json.dumps(self.config)) if len(self.config["credentials"]["password"]): self.config["credentials"]["password"] = self.decryptPwd( key=bytes(self.config["credentials"]["login"], "utf8"), ciphertext=bytes(self.config["credentials"]["password"], "utf8")) self.ReloadSettings.emit() if successMsg: QMessageBox.information(self, self.tr("Save Settings"), self.tr("Settings saved.")) def cfg(self): """ """ return self.config def encryptPwd(self, key, plaintext): """ """ return base64.b64encode(bytes(plaintext, "utf8")) def decryptPwd(self, key, ciphertext): """ """ return str(base64.b64decode(ciphertext), "utf8") def testConnection(self): """ """ self.TestSettings.emit(self.config)
class QMashupAppMainWindow(QtGui.QMainWindow): #signals appWasClosed = pyqtSignal(QtGui.QMainWindow) def __init__(self, parent=None, vistrail_view=None, dumpcells=False, controller=None, version=-1): """ QMashupAppMainWindow() Initialize an app window from a mashup. """ # Constructing the main widget QtGui.QMainWindow.__init__(self, parent) self.vtkCells = [] self.setStatusBar(QtGui.QStatusBar(self)) # Central widget centralWidget = QtGui.QWidget() self.mainLayout = QtGui.QVBoxLayout() self.mainLayout.setMargin(0) self.mainLayout.setSpacing(5) centralWidget.setLayout(self.mainLayout) self.setCentralWidget(centralWidget) self.numberOfCells = 0 self.is_executing = False self.sequenceOption = False self.steps = [] self.isLooping = False #self.resize(100,100) self.dumpcells = dumpcells self.view = vistrail_view if controller: self.controller = controller self.mshptrail = controller.mshptrail if version == -1: self.currentMashup = self.controller.currentMashup else: self.currentMashup = self.mshptrail.getMashup(version) self.setWindowTitle('%s Mashup' % self.controller.getMashupName(version)) else: self.setWindowTitle('Mashup') # Assign "hidden" shortcut self.editingModeAct = QtGui.QAction( "Chang&e Layout", self, shortcut="Ctrl+E", statusTip="Change the layout of the widgets", triggered=self.toggleEditingMode) #self.editingModeShortcut = QtGui.QShortcut(QtGui.QKeySequence('Ctrl+E'), self) #self.connect(self.editingModeShortcut, QtCore.SIGNAL('activated()'), # self.toggleEditingMode) self.editing = False # Constructing alias controls self.controlDocks = [] # Show here to make sure XDisplay info is correct (for VTKCell) self.show() spreadsheetController.setEchoMode(True) #will run to get Spreadsheet Cell events (cellEvents, errors) = self.runAndGetCellEvents(useDefaultValues=True) if cellEvents: self.numberOfCells = len(cellEvents) self.initCells(cellEvents) if len(errors) > 0: show_warning( "VisTrails::Mashup Preview", "There was a problem executing the pipeline: %s." % errors) # Construct the controllers for aliases self.controlDocks = {} self.cellControls = {} self.aliasWidgets = {} self.initControls() if self.currentMashup.layout is not None: self.restoreState( QtCore.QByteArray.fromPercentEncoding( QtCore.QByteArray(self.currentMashup.layout))) if self.currentMashup.geometry is not None: self.restoreGeometry( QtCore.QByteArray.fromPercentEncoding( QtCore.QByteArray(self.currentMashup.geometry))) else: self.resize(self.sizeHint()) # Constructing buttons buttonDock = QCustomDockWidget('Control Buttons', self) buttonWidget = QtGui.QWidget(buttonDock) buttonWidget.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred) buttonLayout = QtGui.QGridLayout() buttonWidget.setLayout(buttonLayout) buttonLayout.setMargin(5) self.cb_auto_update = QtGui.QCheckBox("Turn on auto-update", self.centralWidget()) self.cb_auto_update.setChecked(False) self.cb_loop_sequence = QtGui.QCheckBox("Render all steps in '%s'" % \ (self.sequenceOption.alias.name if self.sequenceOption else 'None'), self.centralWidget()) self.cb_loop_sequence.setChecked(False) self.cb_loop_sequence.setVisible(self.sequenceOption is not False) self.cb_loop_sequence.setToolTip( "Render each step of this stepper for fast switching") self.cb_loop_int = QtGui.QCheckBox("Interactive Steps", self.centralWidget()) self.cb_loop_int.setChecked(False) self.cb_loop_int.setVisible(False) self.cb_loop_int.setToolTip( "Show complete result of each step instead of static images") self.cb_loop_sequence.clicked.connect(self.cb_loop_int.setVisible) self.cb_keep_camera = QtGui.QCheckBox("Keep camera position", self.centralWidget()) self.cb_keep_camera.setChecked(True) self.connect(self.cb_auto_update, QtCore.SIGNAL("stateChanged(int)"), self.auto_update_changed) self.connect(self.cb_loop_int, QtCore.SIGNAL("stateChanged(int)"), self.loop_int_changed) self.loopButton = QtGui.QPushButton("&Loop", self.centralWidget()) self.loopButton.setToolTip("Loop automatically through steps") self.loopButton.setCheckable(True) self.loopButton.setVisible(self.sequenceOption is not False) self.updateButton = QtGui.QPushButton("&Update", self.centralWidget()) if self.dumpcells: self.quitButton = QtGui.QPushButton("&Save", self.centralWidget()) self.connect(self.quitButton, QtCore.SIGNAL('clicked(bool)'), self.saveAndExport) else: self.quitButton = QtGui.QPushButton("&Quit", self.centralWidget()) self.connect(self.quitButton, QtCore.SIGNAL('clicked(bool)'), self.close) buttonLayout.setColumnStretch(0, 1) if self.sequenceOption: sequenceLayout = QtGui.QHBoxLayout() sequenceLayout.setMargin(5) sequenceLayout.addWidget(self.cb_loop_int) sequenceLayout.addWidget(self.cb_loop_sequence) buttonLayout.addLayout(sequenceLayout, 0, 0, QtCore.Qt.AlignRight) buttonLayout.addWidget(self.cb_auto_update, 0, 1, QtCore.Qt.AlignLeft) buttonLayout.addWidget(self.cb_keep_camera, 0, 2, 1, 2, QtCore.Qt.AlignLeft) if self.sequenceOption: buttonLayout.addWidget(self.loopButton, 1, 1, QtCore.Qt.AlignRight) self.loopButton.setEnabled(False) buttonLayout.addWidget(self.updateButton, 1, 2, QtCore.Qt.AlignRight) buttonLayout.addWidget(self.quitButton, 1, 3, QtCore.Qt.AlignRight) self.connect(self.updateButton, QtCore.SIGNAL('clicked(bool)'), self.updateButtonClick) if self.sequenceOption: self.connect(self.loopButton, QtCore.SIGNAL('clicked(bool)'), self.loopButtonClick) buttonDock.setWidget(buttonWidget) self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, buttonDock) self.controlDocks["__buttons__"] = buttonDock self.saveAllAct = QtGui.QAction( "S&ave Combined", self, shortcut=QtGui.QKeySequence.SelectAll, statusTip="Save combined images to disk", triggered=self.saveAllEvent) self.saveAct = QtGui.QAction("&Save Each", self, shortcut=QtGui.QKeySequence.Save, statusTip="Save separate images to disk", triggered=self.saveEventAction) self.showBuilderAct = QtGui.QAction( "VisTrails Main Window", self, statusTip="Show VisTrails Main Window", triggered=self.showBuilderWindow) self.createMenus() self.lastExportPath = '' def createMenus(self): self.fileMenu = self.menuBar().addMenu("&File") self.fileMenu.addAction(self.saveAct) self.fileMenu.addAction(self.saveAllAct) self.viewMenu = self.menuBar().addMenu("&View") self.viewMenu.addAction(self.editingModeAct) self.windowMenu = self.menuBar().addMenu("&Window") self.windowMenu.addAction(self.showBuilderAct) def runAndGetCellEvents(self, useDefaultValues=False): spreadsheetController.setEchoMode(True) #will run to get Spreadsheet Cell events cellEvents = [] errors = [] try: (res, errors) = self.run(useDefaultValues) if res: cellEvents = spreadsheetController.getEchoCellEvents() except Exception, e: debug.unexpected_exception(e) print "Executing pipeline failed:", debug.format_exc() finally:
class QAliasParameterTreeWidget(QSearchTreeWidget): """ QAliasParameterTreeWidget is a subclass of QSearchTreeWidget to display all Vistrails Module """ #signals aliasChanged = pyqtSignal(InstanceObject) def __init__(self, parent=None): """ QAliasParameterTreeWidget(parent: QWidget) -> QParameterTreeWidget Set up size policy and header """ QSearchTreeWidget.__init__(self, parent) self.header().hide() self.setRootIsDecorated(False) self.delegate = QAliasParameterTreeWidgetItemDelegate(self, self) self.setItemDelegate(self.delegate) self.aliasNames = [] self.itemDoubleClicked.connect(self.changeAlias) def updateFromPipeline(self, pipeline): """ updateFromPipeline(pipeline: Pipeline) -> None Read the list of aliases and parameters from the pipeline """ self.clear() if not pipeline: return # Update the aliases # if len(pipeline.aliases)>0: # aliasRoot = QParameterTreeWidgetItem(None, self, # QtCore.QStringList('Aliases')) # aliasRoot.setFlags(QtCore.Qt.ItemIsEnabled, # ) # for (alias, info) in pipeline.aliases.iteritems(): # ptype, pId, parentType, parentId, _ = info # parameter = pipeline.db_get_object(ptype, pId) # v = parameter.strValue # aType = parameter.type # aIdentifier = parameter.identifier # aNamespace = parameter.namespace # label = QtCore.QStringList('%s = %s' % (alias, v)) # pInfo = InstanceObject(type=aType, # identifier=aIdentifier, # namespace=aNamespace, # value=v, # id=pId, # dbtype=ptype, # parent_dbtype=parentType, # parent_id=parentId, # is_alias=True) # aliasItem = QParameterTreeWidgetItem((alias, [pInfo]), # aliasRoot, label) # aliasRoot.setExpanded(True) # Now go through all modules and functions self.aliasNames = pipeline.aliases.keys() inspector = PipelineInspector() inspector.inspect_ambiguous_modules(pipeline) sortedModules = sorted(pipeline.modules.iteritems(), key=lambda item: item[1].name) for mId, module in sortedModules: if len(module.functions) > 0: mLabel = QtCore.QStringList(module.name) moduleItem = None for fId in xrange(len(module.functions)): function = module.functions[fId] if len(function.params) == 0: continue if moduleItem == None: if inspector.annotated_modules.has_key(mId): annotatedId = inspector.annotated_modules[mId] moduleItem = QAliasParameterTreeWidgetItem( annotatedId, self, mLabel) else: moduleItem = QAliasParameterTreeWidgetItem( None, self, mLabel) #v = ', '.join([p.strValue for p in function.params]) label = QtCore.QStringList('%s' % function.name) pList = [ InstanceObject( type=function.params[pId].type, identifier=function.params[pId].identifier, namespace=function.params[pId].namespace, value=function.params[pId].strValue, id=function.params[pId].real_id, dbtype=ModuleParam.vtType, parent_dbtype=function.vtType, parent_id=function.real_id, alias=function.params[pId].alias, mId=mId) for pId in xrange(len(function.params)) ] mName = module.name if moduleItem.parameter != None: mName += '(%d)' % moduleItem.parameter fName = '%s :: %s' % (mName, function.name) mItem = QAliasParameterTreeWidgetItem((fName, pList), moduleItem, label) if moduleItem: moduleItem.setExpanded(True) @pyqtSlot(QtGui.QTreeWidgetItem, int) def changeAlias(self, item, column): """ itemClicked(item: , column: int) -> None If mouse click on the item, show up a dialog to change/add the alias name """ if type(item.parameter) == InstanceObject: (text, ok) = QtGui.QInputDialog.getText( self, 'Set Parameter Alias', 'Enter the parameter alias', QtGui.QLineEdit.Normal, item.parameter.alias) while ok and str(text) in self.aliasNames: msg = " This alias is already being used.\ Please enter a different parameter alias " (text, ok) = QtGui.QInputDialog.getText(self, 'Set Parameter Alias', msg, QtGui.QLineEdit.Normal, text) if ok and item.parameter.alias != str(text): item.parameter.alias = str(text) item.updateAlias() self.aliasChanged.emit(item.parameter)
class DrawMonoLineMapTool(QgsMapToolEmitPoint): azimuth_calcul = pyqtSignal(QgsPoint, QgsPoint) def __init__(self, canvas): self.canvas = canvas s = QSettings() s.beginGroup('Qgis') color = QColor( int(s.value('default_measure_color_red')), int(s.value('default_measure_color_green')), int(s.value('default_measure_color_blue')) ) s.endGroup() QgsMapToolEmitPoint.__init__(self, self.canvas) self.rubberBand = QgsRubberBand(self.canvas, QGis.Line) self.rubberBandDraw = QgsRubberBand(self.canvas, QGis.Line) self.rubberBandDraw.setColor(color) self.rubberBandDraw.setWidth(1) self.rubberBand.setColor(color) self.rubberBand.setWidth(1) # self.rubberBand.setLineStyle(Qt.DashLine) self.points = [] self.reset() def reset(self): self.startPoint = self.endPoint = None self.isEmittingPoint = False self.rubberBand.reset(QGis.Line) self.rubberBandDraw.reset(QGis.Line) def canvasPressEvent(self, e): self.isEmittingPoint = False def canvasReleaseEvent(self, e): self.isEmittingPoint = True self.startPoint = self.toMapCoordinates(e.pos()) if len(self.points) < 2: self.rubberBandDraw.reset(QGis.Line) self.rubberBand.reset(QGis.Line) self.points.append(self.startPoint) if len(self.points) == 2: self.rubberBandDraw.setToGeometry( QgsGeometry.fromPolyline([ self.points[0], self.points[1] ]), None ) self.points = [] self.isEmittingPoint = False def canvasMoveEvent(self, e): if not self.isEmittingPoint: return self.endPoint = self.toMapCoordinates(e.pos()) if len(self.points) > 0: self.rubberBand.setToGeometry( QgsGeometry.fromPolyline([ self.startPoint, self.endPoint ]), None ) if ((self.startPoint is not None and self.endPoint is not None and self.startPoint != self.endPoint)): self.azimuth_calcul.emit(self.startPoint, self.endPoint) def activate(self): self.reset() super(DrawMonoLineMapTool, self).activate() self.emit(SIGNAL("activated()")) def deactivate(self): self.reset() super(DrawMonoLineMapTool, self).deactivate() self.emit(SIGNAL("deactivated()"))
class BeamshutterWidget(QWidget): currentShutterState = pyqtSignal(str, name='currentShutterState') def __init__(self, parent=None): QWidget.__init__(self, parent) self.ui = uic.loadUi("Beamshutter.ui", self) self.control = QAxContainer.QAxWidget(self) self.control.setControl('{3CE35BF3-1E13-4D2C-8C0B-DEF6314420B3}') self.control.setProperty("HWSerialNum", 85845031) self.control.setGeometry(0, 0, 600, 400) self.mutex = QMutex(mode=QMutex.Recursive) self.shutterReplied = False self.shut = Beamshutter(self) self.worker = WorkerThread() self.ui.mainLayout.addWidget(self.control) self.layout().setAlignment(Qt.AlignCenter) sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sizePolicy.setHeightForWidth(True) self.setSizePolicy(sizePolicy) def heightForWidth(self, width): return width * 0.75 @pyqtSlot() def on_BInitializeShutter_clicked(self): if not self.LEDShutter.isChecked(): self.initialize() else: self.finalize() def initialize(self): with self.check(timeOut=10): self.worker.executeFunction(self.shut.initialize) self.ui.LEDShutter.setChecked(True) def finalize(self): with self.check(): self.worker.executeFunction(self.shut.finalize) self.LEDShutter.setChecked(False) def enable(self): with self.check(): self.worker.executeFunction(self.shut.enable) def disable(self): with self.check(): self.worker.executeFunction(self.shut.disable) def _del(self): if self.ui.LEDShutter.isChecked(): self.finalize() def heightForWidth(self, w): return (w) @contextmanager def check(self, timeOut=2): out = datetime.datetime.now() + datetime.timedelta(seconds=timeOut) self.shutterReplied = shutterReplied = False yield while datetime.datetime.now() < out and shutterReplied == False: self.mutex.lock() shutterReplied = self.shutterReplied self.mutex.unlock() if shutterReplied == False: raise Exception("ThorlabsShutter timed out and might be Crashed")
class RestHpAlmClient(QObject): """ Rest HP ALM client """ Error = pyqtSignal(object) ConnectionOk = pyqtSignal() TestsExported = pyqtSignal(list, dict) ResultsExported = pyqtSignal(list, dict) LogAuthStatus = pyqtSignal(str) LogTestsStatus = pyqtSignal(str) LogResultsStatus = pyqtSignal(str) def __init__(self, parent, core, proxies={}): """ """ QObject.__init__(self, parent) self.__core = core self.WsProxies = proxies self.WsLwssoCookie = None self.WsQcSession = None self.WsXsrfToken = None self.loadConfig() def loadConfig(self): """ """ self.WsUsername = self.core().settings().cfg()["credentials"]["login"] self.WsPassword = self.core().settings().cfg( )["credentials"]["password"] self.WsCheckSsl = self.core().settings().cfg( )["qc-server"]["check-ssl"] # self.WsDomain = self.core().settings().cfg()["qc-server"]["domain"] self.WsProject = self.core().settings().cfg()["qc-server"]["project"] self.WsUrl = self.core().settings().cfg()["qc-server"]["url"] if self.WsUrl.endswith("/"): self.WsUrl = self.WsUrl[:-1] def core(self): """ """ return self.__core def RestFindTest(self, logger, testName): """ """ logger("Finding test (%s) in test plan..." % testName) r = requests.get( "%s/rest/raven/1.0/api/test?jql=%s" % (self.WsUrl, urllib.parse.quote('summary ~ "%s"' % testName)), auth=requests.auth.HTTPBasicAuth(self.WsUsername, self.WsPassword), headers={'content-type': 'application/json; charset=utf-8'}, proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 200: raise Exception("Unable to get tests from testplan - %s - %s" % (r.status_code, r.text)) response = json.loads(r.text) ret = None if len(response) > 0: if "key" in response[0].keys(): testId = response[0]["id"] testKey = response[0]["key"] ret = testKey return ret def RestCreateTest(self, logger, testName, testDescription): """ """ logger("Creating test (%s) in test plan" % testName) ret = None data = { "fields": { "project": { "key": "%s" % self.WsProject }, "summary": "%s" % testName, "description": "%s" % testDescription, "issuetype": { "name": "Test" } } } payload_data = json.dumps(data) r = requests.post( "%s/rest/api/2/issue" % (self.WsUrl), auth=requests.auth.HTTPBasicAuth(self.WsUsername, self.WsPassword), headers={'content-type': 'application/json; charset=utf-8'}, data=payload_data, proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 201: raise Exception("Unable to add test in JIRA - %s - %s" % (r.status_code, r.text.encode("utf8"))) # response = ET.fromstring( r.text.encode("utf8") ) # testId = response.find("./Fields/Field[@Name='id']/Value") response = json.loads(r.text) logger("Response when creating test (%s) in test plan : %s" % (testName, response)) ret = None if "key" in response.keys(): testId = response["id"] testKey = response["key"] ret = testKey return ret def RestCreateRun(self, logger, testId, testStatus, testName): """ """ logger("Creating run") data = { "info": { "summary": "%s" % testName, "description": "This execution is automatically created by Extensive Automation", "user": "******" % self.WsUsername }, "tests": [{ "testKey": "%s" % testId, "status": "%s" % testStatus }] } payload_data = json.dumps(data) r = requests.post( "%s/rest/raven/1.0/import/execution" % (self.WsUrl), auth=requests.auth.HTTPBasicAuth(self.WsUsername, self.WsPassword), headers={'content-type': 'application/json; charset=utf-8'}, data=payload_data, proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 200: raise Exception("Unable to add test in JIRA - %s - %s" % (r.status_code, r.text.encode("utf8"))) # response = ET.fromstring( r.text.encode("utf8") ) # testId = response.find("./Fields/Field[@Name='id']/Value") response = json.loads(r.text) # logger("response for creating run : %s" % response) # if len(response) > 0: testKey = None if "key" in response['testExecIssue'].keys(): testId = response['testExecIssue']["id"] testKey = response['testExecIssue']["key"] ret = testKey # testId = response["id"] # testKey = response["key"] ret = testKey return ret def RestGetTestInstanceSteps(self, logger, runId): """ """ logger("Get steps from test instance") r = requests.get("%s/rest/domains/%s/projects/%s/runs/%s/run-steps" % (self.WsUrl, self.WsDomain, self.WsProject, runId), cookies={ 'LWSSO_COOKIE_KEY': self.WsLwssoCookie, 'QCSession': self.WsQcSession }, proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 200: raise Exception( "Unable to get steps according to the test instances - %s - %s" % (r.status_code, r.text)) oXml = ET.fromstring(r.text.encode("utf8")) steps = self.__findSteps(xml=oXml) return steps def RestUpdateRun(self, logger, runId, runStatus): """ """ logger("Updating run") data = ["<?xml version=\"1.0\" encoding=\"utf-8\"?>"] data.append("<Entity Type=\"run\">") data.append("<Fields>") data.append("<Field Name=\"status\"><Value>%s</Value></Field>" % runStatus) data.append("</Fields>") data.append("</Entity>") r = requests.put( "%s/rest/domains/%s/projects/%s/runs/%s" % (self.WsUrl, self.WsDomain, self.WsProject, runId), cookies={ 'LWSSO_COOKIE_KEY': self.WsLwssoCookie, 'QCSession': self.WsQcSession }, headers={'Content-Type': 'application/xml;charset=utf-8'}, data="\n".join(data).encode("utf8"), proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 200: raise Exception("Unable to update run - %s - %s" % (r.status_code, r.text)) return True def RestUpdateRunStep(self, logger, stepId, runId, stepStatus, stepActual): """ """ logger("Running steps") data = ["<?xml version=\"1.0\" encoding=\"utf-8\"?>"] data.append("<Entity Type=\"run-step\">") data.append("<Fields>") data.append("<Field Name=\"status\"><Value>%s</Value></Field>" % stepStatus) data.append("<Field Name=\"actual\"><Value>%s</Value></Field>" % self.__gethtml(stepActual)) data.append("</Fields>") data.append("</Entity>") r = requests.put( "%s/rest/domains/%s/projects/%s/runs/%s/run-steps/%s" % (self.WsUrl, self.WsDomain, self.WsProject, runId, stepId), cookies={ 'LWSSO_COOKIE_KEY': self.WsLwssoCookie, 'QCSession': self.WsQcSession }, headers={'Content-Type': 'application/xml;charset=utf-8'}, data="\n".join(data).encode("utf8"), proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 200: raise Exception("Unable to update run step - %s - %s" % (r.status_code, r.text)) return True def RestAuthenticate(self, logger): """ """ self.WsLwssoCookie = None self.WsQcSession = None self.WsXsrfToken = None almAuth = "<alm-authentication><user>%s</user><password>%s</password></alm-authentication>" "" % ( self.WsUsername, escape(self.WsPassword)) logger("Connection to the REST API...") r = requests.post( "%s/authentication-point/alm-authenticate" % self.WsUrl, headers={'Content-Type': 'application/xml;charset=utf-8'}, data=almAuth.encode("utf8"), proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 200: raise Exception('Unable to connect to the rest api: %s - %s' % (r.status_code, r.text)) cookies = r.headers["set-cookie"] self.WsLwssoCookie = cookies.split("LWSSO_COOKIE_KEY=")[1].split( ";", 1)[0] logger("Creating session...") r = requests.post("%s/rest/site-session" % self.WsUrl, cookies={'LWSSO_COOKIE_KEY': self.WsLwssoCookie}, proxies=self.WsProxies, verify=self.WsCheckSsl) if r.status_code != 201: raise Exception( 'Unable to create the session to the rest api: %s - %s' % (r.status_code, r.text)) logger("Session ready") cookies = r.headers["set-cookie"] self.WsQcSession = cookies.split("QCSession=")[1].split(";", 1)[0] self.WsXsrfToken = cookies.split("XSRF-TOKEN=")[1].split(";", 1)[0] logger("Successfully connected") def RestLogout(self, logger): """ """ logger("Disconnection from the REST API...") r = requests.get("%s/authentication-point/logout" % self.WsUrl, proxies=self.WsProxies, verify=self.WsCheckSsl, cookies={'LWSSO_COOKIE_KEY': self.WsLwssoCookie}) if r.status_code != 200: raise Exception('Unable to disconnect from the rest api: %s - %s' % (r.status_code, r.text)) logger("Disconnected") def testConnection(self, config={}): """ """ try: # connect r = requests.get( "%s/rest/raven/1.0/api/settings/teststatuses" % self.WsUrl, headers={'content-type': 'application/json; charset=utf-8'}, verify=self.WsCheckSsl, auth=requests.auth.HTTPBasicAuth(self.WsUsername, self.WsPassword)) if r.status_code == 200: self.ConnectionOk.emit() else: self.Error.emit("Problem with connection\n%s %s" % (r.status_code, r.text)) except Exception as e: self.logAuthStatus("Error on HP connection") self.Error.emit("%s" % e) def addTestsInTestPlan(self, testcases, config={}): """ """ try: # export one testcase for tc in testcases: funcParams = { 'logger': self.logTestsStatus, 'testName': tc['testcase'], 'testDescription': tc['purpose'] } funcParams.update(config) testId = self.RestFindTest(self.logTestsStatus, tc['testcase']) if testId is None: testId = self.RestCreateTest(self.logTestsStatus, tc['testcase'], tc['purpose']) # # create steps # i = 1 # for stp in tc["steps"]: # self.RestCreateStep(logger=self.logTestsStatus, testId=testId, # stepName="Step%s" % i, stepDescription=stp["action"], # stepExpected=stp["expected"]) # i += 1 self.TestsExported.emit(testcases, config) except Exception as e: self.logTestsStatus("Error on test(s) export") self.Error.emit("%s" % e) def addResultsInTestLab(self, testcases, config={}): """ """ try: self.logResultsStatus("Exporting tests") for tc in testcases: # self.logResultsStatus("tc = %s"% tc) # Search for an existing test with the same test name and create it if needed testId = self.RestFindTest(self.logTestsStatus, tc['testname']) # self.logResultsStatus("testId = %s"% testId) if testId is None: # funcParams = { 'logger': self.logTestsStatus, # 'testName': tc['testcase'], # 'testDescription': tc['purpose'] } testId = self.RestCreateTest(self.logTestsStatus, tc['testname'], "") # self.logResultsStatus("testId2 = %s"% testId) # self.logResultsStatus("testId3 = %s"% testId) # self.logResultsStatus("tc[result] = %s"% tc["result"]) # create an execution with the status of the test self.RestCreateRun(self.logResultsStatus, testId, tc["result"], tc['testname']) self.ResultsExported.emit(testcases, config) except Exception as e: self.logResultsStatus("Error on result(s) export") self.Error.emit("%s" % e) def logAuthStatus(self, status): """ """ self.LogAuthStatus.emit("Status: %s" % status) def logTestsStatus(self, status): """ """ self.LogTestsStatus.emit("Status: %s" % status) def logResultsStatus(self, status): """ """ self.LogResultsStatus.emit("Status: %s" % status)
class QSwitch(QSlider): """ Custom Switch Widget, inspired from some QML desktop components """ style_knob, style_off, style_on = qss_knob, qss_off, qss_on clicked, animationOk = pyqtSignal(), pyqtSignal() def __init__(self, parent=None): """ Init Custom Switch Widget, set Animation and Glow effects """ QSlider.__init__(self, parent) self.setOrientation(Qt.Horizontal) self.animationType = QEasingCurve.OutExpo self.animation = QPropertyAnimation(self, "value") self.animation.setDuration(1000) self.animation.finished.connect(self.animationDone) self.clicked.connect(self.changeValue) self.setStyleSheet(self.style_knob + self.style_off) self.glow = QGraphicsDropShadowEffect(self) self.glow.setOffset(0) self.glow.setBlurRadius(99) self.glow.setColor(QColor(99, 255, 255)) self.setGraphicsEffect(self.glow) self.glow.setEnabled(False) def changeValue(self): """ method to change the actual state ON <--> OFF """ self.animation.setEasingCurve(self.animationType) if self.value() == self.maximum(): self.animation.setStartValue(self.maximum()) self.animation.setEndValue(self.minimum()) self.animation.start() self.setStyleSheet(self.style_knob + self.style_off) self.glow.setEnabled(False) return else: self.animation.setStartValue(self.minimum()) self.animation.setEndValue(self.maximum()) self.setStyleSheet(self.style_knob + self.style_on) self.glow.setEnabled(True) self.animation.start() @pyqtSignature("setAtMax()") def setAtMax(self): """ method to set at Maximum, aka ON """ if self.value() == self.minimum(): self.animation.setEasingCurve(self.animationType) self.animation.setStartValue(self.minimum()) self.animation.setEndValue(self.maximum()) self.animation.start() self.setStyleSheet(self.style_knob + self.style_on) @pyqtSignature("setAtMin()") def setAtMin(self): """ method to set at Minimum, aka OFF """ if self.value() == self.maximum(): self.animation.setEasingCurve(self.animationType) self.animation.setStartValue(self.maximum()) self.animation.setEndValue(self.minimum()) self.animation.start() self.setStyleSheet(self.style_knob + self.style_off) def mousePressEvent(self, event): """ method to respond a signal to mouse pointer clicks """ self.clicked.emit() def isChecked(self): """ method to return a bool based on actual state """ return self.value() == self.maximum() def wheelEvent(self, event): """ dumb method, its not a bug leave it alone """ return def animationDone(self): """ method to respond a signal to animation effects """ self.animationOk.emit()
class ResourceTreeWidgetDecorator(QObject): branch_resource_double_clicked = pyqtSignal(object) leaf_resource_double_clicked = pyqtSignal(object) def __init__(self, decorated): super(ResourceTreeWidgetDecorator, self).__init__() self._decorated = decorated self.itemDoubleClicked.connect(self._itemDoubleClicked_event) def __getattr__(self, name): return getattr(self._decorated, name) def _itemDoubleClicked_event(self, item): iri = item.text(1) item_has_children = item.childCount() > 0 if item_has_children: return resource = ResourceManager.load(iri) if resource.error: MessageBox.critical( u'Link está indisponível ou fora do ar.\n {}'.format( resource.iri), u'Link indisponível') return # Verifica se é um entrypoint com layers ainda não carregadas if resource.is_entry_point(): item.set_icon_entry_point() self.add(resource, item) self.branch_resource_double_clicked.emit(item) return self.leaf_resource_double_clicked.emit(item) def add(self, resource, parent_item=None): if resource.is_entry_point(): item = self._add_entry_point(resource, parent_item) else: item = self._add_simple_resource(resource, parent_item) if resource.error: item.set_icon_error() return item def _add_simple_resource(self, resource, parent_item=None): widget = ComponentFactory.create_list_resource_element(resource) return self._append(widget, parent_item) def _add_entry_point(self, resource, parent_item=None): entry_point_list = resource.as_json() order_alphabetically = lambda i: sorted(i, key=lambda t: t[0]) entry_point_list = OrderedDict( order_alphabetically(entry_point_list.items())) return self._append_entry_point(resource, entry_point_list, parent_item) def _append(self, item, parent=None): if parent: parent.addChild(item) return parent self.addTopLevelItem(item) return item # Cria um entry point na lista de recursos # name: nome do entry point # elements: dict contendo chave:valor dos recursos do entry point def _append_entry_point(self, resource, entry_point_elements, parent_item=None): create_item = ComponentFactory.create_list_resource_element parent_item = parent_item or create_item(resource) parent_item.set_icon_entry_point() for name, url in entry_point_elements.items(): new_res = ResourceManager.load(url, name) item = create_item(new_res) self._append(item, parent_item) self._append(parent_item) return parent_item
class PyEditor(QsciScintilla, Logger.ClassLogger): """ Python editor """ FocusChanged = pyqtSignal() __indicator_word = 0 def __init__(self, editorId, parent=None, activePyLexer=True, activePropertiesLexer=False, wrappingText=False): """ Python editor based on QsciScintilla @param editorId: @type editorId: @param parent: @type parent: """ QsciScintilla.__init__(self, parent) self.editorId = editorId self.activePyLexer = activePyLexer self.activePropertiesLexer = activePropertiesLexer self.setAcceptDrops(True) self.wrappingText = wrappingText self.opening = ['(', '{', '[', "'", '"'] self.closing = [')', '}', ']', "'", '"'] self.createActions() self.createWidgets() self.createConnections() self.setupContextMenu() def enterEvent(self, event): """ On mouse move event """ event.accept() def leaveEvent(self, event): """ On mouse move event """ event.accept() def activeXmlLexer(self): """ Active Xml Lexer """ self.setLexer(QsciLexerXML(self)) def activeIniLexer(self): """ Deactive Xml Lexer """ self.setLexer(QsciLexerProperties(self)) def dragEnterEvent(self, event): """ Drag enter event """ if event.mimeData().hasFormat( 'application/x-%s-help-item' % Settings.instance().readValue(key='Common/acronym').lower()): event.accept() elif event.mimeData().hasFormat( 'application/x-%s-parameter-item' % Settings.instance().readValue(key='Common/acronym').lower()): event.accept() elif event.mimeData().hasFormat( 'application/x-%s-agent-item' % Settings.instance().readValue(key='Common/acronym').lower()): event.accept() elif event.mimeData().hasFormat( 'application/x-%s-description-item' % Settings.instance().readValue(key='Common/acronym').lower()): event.accept() else: QsciScintilla.dragEnterEvent(self, event) def dragMoveEvent(self, event): """ Drag move event """ if event.mimeData().hasFormat( "application/x-%s-help-item" % Settings.instance().readValue(key='Common/acronym').lower()): event.setDropAction(Qt.CopyAction) event.accept() elif event.mimeData().hasFormat( "application/x-%s-parameter-item" % Settings.instance().readValue(key='Common/acronym').lower()): event.setDropAction(Qt.CopyAction) event.accept() elif event.mimeData().hasFormat( "application/x-%s-agent-item" % Settings.instance().readValue(key='Common/acronym').lower()): event.setDropAction(Qt.CopyAction) event.accept() elif event.mimeData().hasFormat( "application/x-%s-description-item" % Settings.instance().readValue(key='Common/acronym').lower()): event.setDropAction(Qt.CopyAction) event.accept() else: QsciScintilla.dragMoveEvent(self, event) def dropEvent(self, event): """ Drop event """ # drag and drop from assistant if (event.mimeData().hasFormat( 'application/x-%s-help-item' % Settings.instance().readValue(key='Common/acronym').lower())): event.acceptProposedAction() if sys.version_info > (3, ): # python 3 support data = event.mimeData().data("application/x-%s-help-item" % Settings.instance().readValue( key='Common/acronym').lower()) else: data = QString( event.mimeData().data("application/x-%s-help-item" % Settings.instance().readValue( key='Common/acronym').lower())) if sys.version_info > (3, ): # python 3 support d = eval(data) else: d = eval(str(data)) self.beginUndoAction() if self.editorId == 2: # testunit try: self.insert(d[2]) except IndexError as e: self.insert(d[0]) else: # testsuite if self.editorId == 0: self.insert(d[0]) else: self.insert(d[1]) self.endUndoAction() # drag and drop from test parameters elif (event.mimeData().hasFormat( 'application/x-%s-parameter-item' % Settings.instance().readValue(key='Common/acronym').lower())): event.acceptProposedAction() if sys.version_info > (3, ): # python 3 support data = event.mimeData().data( "application/x-%s-parameter-item" % Settings.instance().readValue( key='Common/acronym').lower()) else: data = QString( event.mimeData().data("application/x-%s-parameter-item" % Settings.instance().readValue( key='Common/acronym').lower())) if sys.version_info > (3, ): # python 3 support data = str(data, 'utf8') self.beginUndoAction() if self.editorId == 0: self.insert(data) else: self.insert(data) self.endUndoAction() # drag and drop from test agents elif (event.mimeData().hasFormat( 'application/x-%s-agent-item' % Settings.instance().readValue(key='Common/acronym').lower())): event.acceptProposedAction() if sys.version_info > (3, ): # python 3 support data = event.mimeData().data("application/x-%s-agent-item" % Settings.instance().readValue( key='Common/acronym').lower()) else: data = QString( event.mimeData().data("application/x-%s-agent-item" % Settings.instance().readValue( key='Common/acronym').lower())) if sys.version_info > (3, ): # python 3 support data = str(data, 'utf8') self.beginUndoAction() if self.editorId == 0: self.insert(data) else: self.insert(data) self.endUndoAction() # drag and drop from test description elif (event.mimeData().hasFormat( 'application/x-%s-description-item' % Settings.instance().readValue(key='Common/acronym').lower())): event.acceptProposedAction() if sys.version_info > (3, ): # python 3 support data = event.mimeData().data( "application/x-%s-description-item" % Settings.instance().readValue( key='Common/acronym').lower()) else: data = QString( event.mimeData().data("application/x-%s-description-item" % Settings.instance().readValue( key='Common/acronym').lower())) if sys.version_info > (3, ): # python 3 support data = str(data, 'utf8') self.beginUndoAction() if self.editorId == 0: self.insert(data) else: self.insert(data) self.endUndoAction() else: QsciScintilla.dropEvent(self, event) def createWidgets(self): """ QsciScintilla widget creation """ self.setFrameShape(QFrame.NoFrame) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) # Lexer/Highlighter settings lexer = CustomPythonLexer(self) fontSettings = Settings.instance().readValue( key='Editor/font').split(",") font = fontSettings[0] fontSize = fontSettings[1] defaultFont = QFont(font, int(fontSize)) defaultFont.setFixedPitch(True) lexer.setDefaultFont(defaultFont) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) lexer.setIndentationWarning(QsciLexerPython.Inconsistent) if self.activePyLexer: self.setLexer(lexer) # api = QsciAPIs(lexer) # api.add('aLongString') # api.add('aLongerString') # api.add('aDifferentString') # api.add('sOmethingElse') # api.prepare() # self.setAutoCompletionThreshold(1) # self.setAutoCompletionSource(QsciScintilla.AcsAPIs) lexerProperties = QsciLexerProperties(self) if self.activePropertiesLexer: self.setLexer(lexerProperties) ## Editing line color self.setCaretLineVisible(True) self.setCaretLineBackgroundColor( QColor(Settings.instance().readValue( key='Editor/color-current-line'))) self.setUtf8(True) self.setAutoIndent(True) self.setTabWidth(2) self.setIndentationsUseTabs(True) self.setEolMode(QsciScintilla.EolUnix) self.activeFolding(False) self.setIndentationGuidesVisible(False) self.setTabIndents(True) # margins self.setMarginLineNumbers(1, False) self.setMarginWidth(1, 0) self.setMarginsBackgroundColor(Qt.gray) marginFont = QFont() marginFont.setBold(False) self.setMarginsFont(marginFont) self.setMarginsForegroundColor(Qt.white) # text wrapping if self.wrappingText: self.setWrappingMode(wrap=True) # folding self.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf')) # indicators if sys.version_info > (3, ): self.matchIndicator = self.indicatorDefine( QsciScintilla.INDIC_FULLBOX, 9) self.setIndicatorForegroundColor( QColor(Settings.instance().readValue( key='Editor/color-indicator')), self.matchIndicator) self.setIndicatorDrawUnder(True, self.matchIndicator) self.findOccurenceThread = FindOccurenceThread() self.findOccurenceThread.markOccurrence.connect(self.markOccurence) # selection self.setSelectionBackgroundColor( QColor(Settings.instance().readValue( key='Editor/color-selection-background'))) def setWrappingMode(self, wrap): """ Set wrap mode """ if wrap: self.setWrapMode(QsciScintilla.WrapCharacter) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) else: self.setWrapMode(QsciScintilla.WrapNone) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) def setIndentationGuidesVisible(self, state): """ Show/hide guides @param state: @type state: boolean """ if state: self.setIndentationGuides(state) else: self.setIndentationGuides(state) def setWhitespaceVisible(self, state): """ Show/hide whitespace @param state: @type state: boolean """ if state: self.setWhitespaceVisibility(QsciScintilla.WsVisible) else: self.setWhitespaceVisibility(QsciScintilla.WsInvisible) def activeFolding(self, fold): """ Active folding @param fold: @type fold: boolean """ if fold: self.foldAllAction.setEnabled(True) self.setFolding(QsciScintilla.PlainFoldStyle) self.SendScintilla(QsciScintilla.SCI_SETFOLDFLAGS, 0) else: self.foldAllAction.setEnabled(False) self.unfoldAll() self.setFolding(QsciScintilla.NoFoldStyle) def foldHeader(self, line): """ Is it a fold header line? @param line: @type line: """ lvl = self.SendScintilla(QsciScintilla.SCI_GETFOLDLEVEL, line) return lvl & QsciScintilla.SC_FOLDLEVELHEADERFLAG def foldExpanded(self, line): """ Is fold expanded? @param line: @type line: """ return self.SendScintilla(QsciScintilla.SCI_GETFOLDEXPANDED, line) def getFoldedLines(self): """ Return the list of folded line numbers """ return [line for line in xrange(self.lines()) \ if self.foldHeader(line) and not self.foldExpanded(line) ] def unfoldAll(self): """ Unfold all folded lines """ for line in self.getFoldedLines(): self.foldLine(line) def foldAllLines(self): """ Fold all lines """ if sys.platform == "win32": self.foldAll(children=True) else: self.foldAll() def createConnections(self): """ create qt connections """ self.linesChanged.connect(self.onLinesChanged) self.copyAvailable.connect(self.copyAction.setEnabled) self.copyAvailable.connect(self.cutAction.setEnabled) self.copyAvailable.connect(self.deleteAction.setEnabled) def createActions(self): """ QtActions creation Actions defined: * undo * redo * cut * copy * paste * delete * comment * uncomment """ self.undoAction = QtHelper.createAction(self, "Undo", callback=self.undo, icon=QIcon(":/undo.png"), shortcut="Ctrl+Z", tip='Undoes the last action') self.redoAction = QtHelper.createAction( self, "Redo", callback=self.redo, icon=QIcon(":/redo.png"), shortcut="Ctrl+Y", tip='Redoes the previously undone action') self.cutAction = QtHelper.createAction( self, "Cut", callback=self.cut, shortcut=QKeySequence.Cut, icon=QIcon(":/cut.png"), tip='Cuts the selection and puts it on the clipboard') self.copyAction = QtHelper.createAction( self, "Copy", callback=self.copy, shortcut=QKeySequence.Copy, icon=QIcon(":/copy.png"), tip='Copies the selection and puts it on the clipboard') self.pasteAction = QtHelper.createAction( self, "Paste", callback=self.paste, shortcut=QKeySequence.Paste, icon=QIcon(":/paste.png"), tip='Inserts clipboard contents') self.deleteAction = QtHelper.createAction( self, "Delete Selection", callback=self.removeSelectedText, tip='Deletes the selection') self.commentAction = QtHelper.createAction( self, "Comment", callback=self.comment, icon=QIcon(":/comment.png"), tip='Insert comment sign at the begining of line') self.uncommentAction = QtHelper.createAction( self, "Uncomment", callback=self.uncomment, icon=QIcon(":/uncomment.png"), tip='Remove comment sign at the begining of line') self.foldAllAction = QtHelper.createAction(self, "Fold\nUnfold", callback=self.foldAllLines, icon=QIcon(":/folding.png"), tip='Fold/Unfold all lines') def setupContextMenu(self): """ Setup context menu """ self.menu = QMenu() self.menu.addAction(self.undoAction) self.menu.addAction(self.redoAction) self.menu.addSeparator() self.menu.addAction(self.commentAction) self.menu.addAction(self.uncommentAction) self.menu.addSeparator() self.menu.addAction(self.cutAction) self.menu.addAction(self.copyAction) self.menu.addAction(self.pasteAction) self.menu.addAction(self.deleteAction) self.menu.addAction("Select All", self.selectAll) self.menu.addSeparator() self.menu.addAction(self.foldAllAction) def onLinesChanged(self): """ Update the line counter margin's width. """ width = math.log(self.lines(), 10) + 2 if sys.version_info > (3, ): # for python3 support self.setMarginWidth(1, '0' * int(width)) else: self.setMarginWidth(1, QString('0' * int(width))) def comment(self): """ Comment current line or selection """ self.addPrefix('#') def uncomment(self): """ Uncomment current line or selection """ self.removePrefix('#') def indent(self): """ Indent current line or selection """ self.addPrefix("\t") def unindent(self): """ Unindent current line or selection """ self.removePrefix("\t") def keyPressEvent(self, event): """ Reimplement Qt method @param event: @type event: """ key = event.key() startLine, startPos, endLine, endPos = self.getSelection() line, index = self.getCursorPosition() cmd = self.text(line) if (key == Qt.Key_Tab): self.indent() event.accept() elif key == Qt.Key_Backtab: self.unindent() event.accept() else: # new in v13.1 t = event.text() # extract option from settings file autoCloseBracket = QtHelper.str2bool( Settings.instance().readValue(key='Editor/auto-close-bracket')) txt = cmd[:index].replace('>>> ', '').replace('... ', '') # new in v16 afterTxt = cmd[index:] if len(afterTxt): afterTxt = afterTxt.splitlines()[0] # end of new if t in self.opening and autoCloseBracket: i = self.opening.index(t) if self.hasSelectedText(): selText = self.selectedText() self.removeSelectedText() self.insert(self.opening[i] + selText + self.closing[i]) self.setCursorPosition(endLine, endPos + 2) return else: if len(afterTxt): pass elif t == '(' and (re.match(r'^[ \t]*def \w+$', txt) or re.match(r'^[ \t]*class \w+$', txt)): self.insert('):') else: self.insert(self.closing[i]) elif t in [')', ']', '}'] and autoCloseBracket: txt = self.text(line) try: if txt[index - 1] in self.opening and t == txt[index]: self.setCursorPosition(line, index + 1) self.SendScintilla(QsciScintilla.SCI_DELETEBACK) except IndexError: pass else: pass # end new in v13.1 QsciScintilla.keyPressEvent(self, event) def addPrefix(self, prefix): """ Add prefix to current line or selected line(s) @param prefix: @type prefix: """ if self.hasSelectedText(): # Add prefix to selected line(s) lineFrom, indexFrom, lineTo, indexTo = self.getSelection() if indexTo == 0: lineTo -= 1 self.beginUndoAction() for line in range(lineFrom, lineTo + 1): self.insertAt(prefix, line, 0) self.endUndoAction() if indexTo == 0: lineTo += 1 else: indexTo += len(prefix) self.setSelection(lineFrom, indexFrom + len(prefix), lineTo, indexTo) else: # Add prefix to current line line, index = self.getCursorPosition() self.beginUndoAction() self.insertAt(prefix, line, 0) self.endUndoAction() self.setCursorPosition(line, index + len(prefix)) def removePrefix(self, prefix): """ Remove prefix from current line or selected line(s) @param prefix: @type prefix: """ if self.hasSelectedText(): # Remove prefix from selected line(s) lineFrom, indexFrom, lineTo, indexTo = self.getSelection() if indexTo == 0: lineTo -= 1 self.beginUndoAction() for line in range(lineFrom, lineTo + 1): if sys.version_info > (3, ): # python3 support if not self.text(line).startswith(prefix): continue else: if not self.text(line).startsWith(prefix): continue self.setSelection(line, 0, line, len(prefix)) self.removeSelectedText() if line == lineFrom: indexFrom = max([0, indexFrom - len(prefix)]) if line == lineTo and indexTo != 0: indexTo = max([0, indexTo - len(prefix)]) if indexTo == 0: lineTo += 1 self.setSelection(lineFrom, indexFrom, lineTo, indexTo) self.endUndoAction() else: # Remove prefix from current line line, index = self.getCursorPosition() if sys.version_info > (3, ): # python3 support if not self.text(line).startswith(prefix): return else: if not self.text(line).startsWith(prefix): return self.beginUndoAction() self.setSelection(line, 0, line, len(prefix)) self.removeSelectedText() self.setCursorPosition(line, index - len(prefix)) self.endUndoAction() self.setCursorPosition(line, max([0, index - len(prefix)])) def contextMenuEvent(self, event): """ Reimplement Qt method Menu on right click @param event: @type event: """ self.undoAction.setEnabled(self.isUndoAvailable()) self.redoAction.setEnabled(self.isRedoAvailable()) self.menu.popup(event.globalPos()) event.accept() def findText(self, text, changed=True, forward=True, wraps=True, case=False, words=False, regexp=False, line=-1, index=-1):
class MessageBoxDialog(QDialog): """ Message box dialog """ Download = pyqtSignal(str) DownloadCanceled = pyqtSignal() def __init__(self, dialogName, parent = None): """ Constructor @param dialogName: @type dialogName: @param parent: @type parent: """ QDialog.__init__(self, parent) self.setWindowIcon( QIcon(":/main.png") ) self.name = dialogName self.url = None self.createDialog() def closeEvent(self, event): """ Close event @param event: @type event: """ pass def setDownload(self, title, txt, url): """ Set dialog for download purpose @param title: @type title: @param txt: @type txt: @param url: @type url: """ self.url = url self.setWindowTitle( title ) self.progressBar.hide() self.imageLabel.setPixmap(QPixmap(':/information.png')) self.loadingLabel.setText( txt ) self.downloadButton.show() self.cancelButton.show() self.okButton.hide() self.imageLabel.show() def setTxt (self, title, txt, error=False): """ Set dialog with text @param title: @type title: @param txt: @type txt: """ self.setWindowTitle( title ) self.progressBar.hide() self.loadingLabel.setText( txt ) self.imageLabel.show() if error: self.imageLabel.setPixmap(QPixmap(':/warning.png')) else: self.imageLabel.setPixmap(QPixmap(':/information.png')) self.okButton.show() self.downloadButton.hide() self.cancelButton.hide() def setLoading (self, msg='Loading data...' ): """ Set dialog for loading @param msg: @type msg: """ self.setWindowTitle( "%s" % self.name ) self.progressBar.setMaximum(0) self.progressBar.setProperty("value", 0) self.progressBar.show() self.loadingLabel.setText( msg ) self.loadingLabel.show() self.okButton.hide() self.downloadButton.hide() self.cancelButton.hide() self.imageLabel.hide() def setConnection (self ): """ Set connection message """ self.loadingLabel.setText( "Connection..." ) def setInitialization (self ): """ Set init message """ self.loadingLabel.setText( "Initialization..." ) self.show() def download (self): """ Emit download signla """ self.Download.emit(self.url) def onReject(self): """ On cancel """ self.DownloadCanceled.emit() self.reject() def updateDataReadProgress(self, bytesRead, totalBytes): """ Update progress bar @param bytesRead: @type bytesRead: @param totalBytes: @type totalBytes: """ self.progressBar.setMaximum(totalBytes) self.progressBar.setValue(bytesRead) def createDialog(self): """ Create qt dialog """ self.setWindowTitle( "%s" % self.name ) layout = QVBoxLayout() self.loadingLabel = QLabel("Loading...") self.imageLabel = QLabel() layout2 = QHBoxLayout() layout2.addWidget( self.imageLabel ) layout2.addWidget( self.loadingLabel ) self.progressBar = QProgressBar(self) self.progressBar.setMaximum(0) self.progressBar.setProperty("value", 0) self.progressBar.setAlignment(Qt.AlignCenter) self.progressBar.setObjectName("progressBar") buttonLayout = QHBoxLayout() buttonLayout.addStretch() self.okButton = QPushButton("Ok", self) self.downloadButton = QPushButton("Download", self) self.cancelButton = QPushButton("Cancel", self) buttonLayout.addWidget(self.okButton) buttonLayout.addWidget(self.downloadButton) buttonLayout.addWidget(self.cancelButton) self.okButton.clicked.connect(self.accept) self.downloadButton.clicked.connect(self.download) self.cancelButton.clicked.connect(self.onReject) self.okButton.hide() layout.addLayout(layout2) layout.addWidget( self.progressBar ) layout.addLayout(buttonLayout) self.setLayout(layout) flags = Qt.WindowFlags() flags |= Qt.WindowCloseButtonHint flags |= Qt.MSWindowsFixedSizeDialogHint self.setWindowFlags(flags)
class LazyflowSource(QObject): isDirty = pyqtSignal(object) numberOfChannelsChanged = pyqtSignal(int) @property def dataSlot(self): return self._orig_outslot def __init__(self, outslot, priority=0): super(LazyflowSource, self).__init__() assert _has_lazyflow, "Can't instantiate a LazyflowSource: Wasn't able to import lazyflow." self._orig_outslot = outslot # Attach an OpReorderAxes to ensure the data will display correctly # (We include the graph parameter, too, since tests sometimes provide an operator with no parent.) self._op5 = lazyflow.operators.opReorderAxes.OpReorderAxes( parent=outslot.getRealOperator().parent, graph=outslot.getRealOperator().graph) self._op5.Input.connect(outslot) self._priority = priority self._dirtyCallback = partial(weakref_setDirtyLF, weakref.ref(self)) self._op5.Output.notifyDirty(self._dirtyCallback) self._op5.externally_managed = True self.additional_owned_ops = [] self._shape = self._op5.Output.meta.shape self._op5.Output.notifyMetaChanged(self._checkForNumChannelsChanged) @property def numberOfChannels(self): return self._shape[-1] def _checkForNumChannelsChanged(self, *args): if self._op5 and self._op5.Output.ready( ) and self._shape[-1] != self._op5.Output.meta.shape[-1]: self._shape = tuple(self._op5.Output.meta.shape) self.numberOfChannelsChanged.emit(self._shape[-1]) def clean_up(self): self._op5.cleanUp() self._op5 = None for op in reversed(self.additional_owned_ops): op.cleanUp() def dtype(self): dtype = self._orig_outslot.meta.dtype assert dtype is not None, "Your LazyflowSource doesn't have a dtype! Is your lazyflow slot properly configured in setupOutputs()?" return dtype @translate_lf_exceptions def request(self, slicing): if cfg.getboolean('pixelpipeline', 'verbose'): volumina.printLock.acquire() print " LazyflowSource '%s' requests %s" % ( self.objectName(), volumina.strSlicing(slicing)) volumina.printLock.release() if not is_pure_slicing(slicing): raise Exception('LazyflowSource: slicing is not pure') assert self._op5 is not None, "Underlying operator is None. Are you requesting from a datasource that has been cleaned up already?" return LazyflowRequest(self._op5, slicing, self._priority, objectName=self.objectName()) def _setDirtyLF(self, slot, roi): self.setDirty(roi.toSlice()) def setDirty(self, slicing): if not is_pure_slicing(slicing): raise Exception('dirty region: slicing is not pure') self.isDirty.emit(slicing) def __eq__(self, other): if other is None: return False return self._orig_outslot is other._orig_outslot def __ne__(self, other): return not (self == other)
KlpC = (ktable[round(G, 1)] - pow( ( pow(ktable[round(G,1)], 2) - a*( pow(ktable[round(G,1)], 2) - b )), 0.5))/a KlpC.name = 'K_lower' confidence = pd.concat([KupC, KlpC], axis=1) qprint("Conf\n"+confidence.to_string()) confidence['LogQ_U'] = Xbar + confidence['K_upper']*S confidence['LogQ_L'] = Xbar + confidence['K_lower']*S confidence['Q_U'] = confidence['LogQ_U'].apply(lambda x: pow(10,x)) confidence['Q_L'] = confidence['LogQ_L'].apply(lambda x: pow(10,x)) qprint("Conf\n"+confidence.to_string()) #final_freq['Q'].plot() #Calculate Expected Probability #expected_p = final_freq.loc[[.0001, .001, .01, .05, .10, .30, .5, .7, .9, .95, .99, .999, .9999]] self.results[site]={'curve' : final_freq['Q'], 'positions':ranked_df, 'confidence':confidence} #Finished processing all sites, return results self.finished.emit(True, self.results) except Exception, e: import traceback self.error.emit(e, traceback.format_exc()) self.status.emit("Error in flood peak parser thread") #print e, traceback.format_exc() self.finished.emit(False, self.results) status = pyqtSignal(str) error = pyqtSignal(Exception, basestring) finished = pyqtSignal(bool, dict) plot_and_save = pyqtSignal(dict) #additional threaded utilities go here???
class CreateProfile(QObject): def __init__(self, interface, settings): QObject.__init__(self) self.iface = interface self.settings = settings self.stop = False self.util = Util(self.iface) self.intersections = [] def abort(self): self.stop = True finished = pyqtSignal(object, object) error = pyqtSignal(basestring) progress = pyqtSignal(basestring) def create(self): profiles = [] try: #Line aus den Textboxwerten erstellen if self.settings.modeLine == enumModeLine.straightLine: profiles.append( self.processFeature(None, 1, 1, self.settings.mapData.customLine)) self.finished.emit(profiles, self.intersections) return #Line aus gezeichneter Linie erstellen if self.settings.modeLine == enumModeLine.customLine: profiles.append( self.processFeature(None, 1, 1, self.settings.mapData.customLine)) self.finished.emit(profiles, self.intersections) return #Shapefile Geometrien abarbeiten if self.settings.modeLine == enumModeLine.line: provider = self.settings.mapData.selectedLineLyr.line.dataProvider( ) feats = [] #Alle Attribute holen if QGis.QGIS_VERSION_INT < 10900: provider.select(provider.attributeIndexes()) if self.settings.onlySelectedFeatures is True: feats = self.settings.mapData.selectedLineLyr.line.selectedFeatures( ) else: if QGis.QGIS_VERSION_INT < 10900: attrib_indices = provider.attributeIndexes() provider.select(attrib_indices) feat = QgsFeature() while provider.nextFeature(feat): feats.append(feat) #neues Feature verwenden, weil sonst die Multiparts #nicht als solche erkannt werden feat = QgsFeature() else: #processing.getfeatures: This will iterate over all the features in the layer, in case there is no selection, or over the selected features otherwise. #obviously not available with windows standalone installer #features = processing.getfeatures(self.settings.mapData.selectedLineLyr.line) features = self.settings.mapData.selectedLineLyr.line.getFeatures( ) for feat in features: feats.append(feat) feats, err_msg = self.util.prepareFeatures( self.settings, provider, feats) if not err_msg is None: #QMessageBox.critical(self.iface.mainWindow(), 'PREPARE ERROR', err_msg) self.error.emit(err_msg) self.finished.emit([], []) return for feat in feats: geom = feat.geometry() if geom.isMultipart(): msg = QApplication.translate( 'code', 'Multipart Feature vorhanden! Option zum Explodieren verwenden.', None, QApplication.UnicodeUTF8) self.error.emit(msg) self.finished.emit([], []) return feat_cnt = len(feats) for idx, feat in enumerate(feats): if self.stop is True: profiles = [] break if idx == 0 or idx % 5 == 0: msg = 'Profil {0}/{1}'.format(idx + 1, feat_cnt) self.progress.emit(msg) profiles.append( self.processFeature( provider.fields(), len(profiles) + 1, self.settings.mapData.selectedLineLyr.line.id(), feat)) msg = 'Profil {0}/{1}'.format(idx + 1, feat_cnt) self.progress.emit(msg) self.finished.emit(profiles, self.intersections) except Exception, ex: self.error.emit(traceback.format_exc()) self.finished.emit([], [])
def on_actionCARGAR_triggered(self): self.loadGamesWindow.loadData() self.loadGamesWindow.show() # Signals cellValueChanged = pyqtSignal(int, int) def __init__(self): QMainWindow.__init__(self) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.initBoard() self.ui.actionJUEGO_NUEVO.triggered.connect(self.onActionJuegoNuevoTriggered) self.ui.actionSALIR.triggered.connect(self.onActionSalirTriggered) self.ui.actionATRAS.triggered.connect(self.onActionAtrasTriggered) self.loadGamesWindow = LoadGames(self) def initTimer(self, elapsedSeconds): self.timer = QTimer() self.timer.setInterval(1000) self.timer.start() self.h = elapsedSeconds / 3600 self.m = (elapsedSeconds - 3600*self.h) / 60 self.s = (elapsedSeconds - 3600*self.h) % 60 self.timer.timeout.connect(self.timerTimeout) def stopTimer(self): self.timer.stop() def timerTimeout(self): self.s = self.s + 1 if self.s > 59: self.s = 0 self.m=self.m + 1 elif self.m > 59: self.m = 0 self.h= self.h + 1 elif self.h > 23: self.h = 0 # Write time in a pushButton self.ui.btnTiempo.setText(QString ("%1:%2:%3") .arg (self.h) .arg (self.m) .arg (self.s) ) def initBoard(self): self.board = [] self.keyboard = Keyboard(self) for i in range(9*9): x = i % 9 y = i / 9 c = Cell() self.board.append(c) self.ui.board.addWidget(c, y, x) c.setKeyboard(self.keyboard) #self.setStyleSheet("font: italic 13pt Courier 50 Pitch; background-color: rgb(82, 163, 53);"#) # Change cell value when user change cell value c.valueChanged.connect(self.setCellValueFromView) def newGame(self, name, elapsedSeconds = 0, sudoku = None): if sudoku == None: # Generate new sudoku board self.sudoku = Sudoku() self.sudoku.shuffle(self.difficulty*9 + 3*9) else: self.sudoku = sudoku self.sudoku.cellValueChanged.connect(self.setCellValue) self.sudoku.triggerChanges() self.sudoku.cellValueChanged.disconnect(self.setCellValue) # Update the model when the view is changed self.cellValueChanged.connect(self.sudoku.setCellValue) self.initTimer(elapsedSeconds) self.ui.btnJugador.setText(name) def endGame(self): self.stopTimer() userName = str(self.ui.btnJugador.text()) seconds = int(self.s) + int(self.m) * 60 + int(self.h) * 60 * 60 difficulty = ['Easy', 'Medium', 'Hard'][self.difficulty - 1] # Check if current score is a high scores highscores = HighScore.loadFromFile() highscores.reverse() if seconds < highscores[0].seconds: msj = QMessageBox() msj.setText( "Puntaje alto" ) msj.exec_() # Put score in highscore highscores.append( HighScore(userName, seconds, difficulty) ) highscores.sort() highscores.pop() HighScore.saveToFile(highscores) def setCellValue(self, index, value): self.board[index].setValue(value) # TODO change color to indicate that it's precalculated def setCellValueFromView(self, value): c = self.sender() self.cellValueChanged.emit( self.board.index(c), value ) def onActionSalirTriggered(self): self.close() def setHomeWindow(self, homeWindow): self.homeWindow = homeWindow def setDifficulty(self,value): self.difficulty = value def onActionJuegoNuevoTriggered(self): name = self.ui.btnJugador.text() self.newGame(name) def onActionAtrasTriggered(self): self.hide() self.homeWindow.show() def on_endGameButton_triggered(self): msj = QMessageBox() valid = self.sudoku.validate() msj.setText( "Valido" if valid else "No valido" ) msj.exec_() if valid: self.endGame() def on_actionGUARDAR_triggered(self): userName = str(self.ui.btnJugador.text()) seconds = int(self.s) + int(self.m) * 60 + int(self.h) * 60 * 60 games = Game.loadFromFile() games.append( Game(userName, seconds, self.sudoku) ) Game.saveToFile(games) def on_actionCARGAR_triggered(self): self.loadGamesWindow.loadData() self.loadGamesWindow.show()
class GPSService(QObject): gpsfixed = pyqtSignal(bool, object) gpsfailed = pyqtSignal() gpsdisconnected = pyqtSignal() # Connect to listen to GPS status updates. gpspostion = pyqtSignal(QgsPoint, object) firstfix = pyqtSignal(QgsPoint, object) def __init__(self): super(GPSService, self).__init__() self.isConnected = False self.currentport = None self.postion = None self.elevation = None self.wgs84CRS = QgsCoordinateReferenceSystem(4326) self.crs = None def connectGPS(self, portname): if not self.isConnected: self.currentport = portname if portname == 'scan' or portname == '': log("Auto scanning for GPS port") portname = '' self.detector = QgsGPSDetector(portname) log("Connecting to:{}".format(portname or 'scan')) self.detector.detected.connect(self._gpsfound) self.detector.detectionFailed.connect(self.gpsfailed) self.isConnectFailed = False self.detector.advance() def disconnectGPS(self): if self.isConnected: self.gpsConn.stateChanged.disconnect(self.gpsStateChanged) self.gpsConn.close() log("GPS disconnect") self.isConnected = False self.postion = None QgsGPSConnectionRegistry.instance().unregisterConnection(self.gpsConn) self.gpsdisconnected.emit() def _gpsfound(self, gpsConnection): log("GPS found") self.gpsConn = gpsConnection self.gpsConn.stateChanged.connect(self.gpsStateChanged) self.isConnected = True QgsGPSConnectionRegistry.instance().registerConnection(self.gpsConn) def gpsStateChanged(self, gpsInfo): if gpsInfo.fixType == NMEA_FIX_BAD or gpsInfo.status == 0 or gpsInfo.quality == 0: self.gpsfixed.emit(False, gpsInfo) return elif gpsInfo.fixType == NMEA_FIX_3D or NMEA_FIX_2D: self.gpsfixed.emit(True, gpsInfo) map_pos = QgsPoint(gpsInfo.longitude, gpsInfo.latitude) if self.crs: transform = QgsCoordinateTransform(self.wgs84CRS, self.crs) try: map_pos = transform.transform(map_pos) except QgsCsException: log("Transform exception") return if self.postion is None: self.firstfix.emit(map_pos, gpsInfo) self.gpspostion.emit(map_pos, gpsInfo) self.postion = map_pos self.elevation = gpsInfo.elevation
class FlightTab(Tab, flight_tab_class): uiSetupReadySignal = pyqtSignal() _motor_data_signal = pyqtSignal(int, object, object) _imu_data_signal = pyqtSignal(int, object, object) _althold_data_signal = pyqtSignal(int, object, object) _baro_data_signal = pyqtSignal(int, object, object) _input_updated_signal = pyqtSignal(float, float, float, float) _rp_trim_updated_signal = pyqtSignal(float, float) _emergency_stop_updated_signal = pyqtSignal(bool) _log_error_signal = pyqtSignal(object, str) # UI_DATA_UPDATE_FPS = 10 connectionFinishedSignal = pyqtSignal(str) disconnectedSignal = pyqtSignal(str) _limiting_updated = pyqtSignal(bool, bool, bool) def __init__(self, tabWidget, helper, *args): super(FlightTab, self).__init__(*args) self.setupUi(self) self.tabName = "Flight Control" self.menuName = "Flight Control" self.tabWidget = tabWidget self.helper = helper self.disconnectedSignal.connect(self.disconnected) self.connectionFinishedSignal.connect(self.connected) # Incomming signals self.helper.cf.connected.add_callback( self.connectionFinishedSignal.emit) self.helper.cf.disconnected.add_callback(self.disconnectedSignal.emit) self._input_updated_signal.connect(self.updateInputControl) self.helper.inputDeviceReader.input_updated.add_callback( self._input_updated_signal.emit) self._rp_trim_updated_signal.connect(self.calUpdateFromInput) self.helper.inputDeviceReader.rp_trim_updated.add_callback( self._rp_trim_updated_signal.emit) self._emergency_stop_updated_signal.connect(self.updateEmergencyStop) self.helper.inputDeviceReader.emergency_stop_updated.add_callback( self._emergency_stop_updated_signal.emit) self.helper.inputDeviceReader.althold_updated.add_callback( lambda enabled: self.helper.cf.param.set_value( "flightmode.althold", enabled)) self._imu_data_signal.connect(self._imu_data_received) self._baro_data_signal.connect(self._baro_data_received) self._althold_data_signal.connect(self._althold_data_received) self._motor_data_signal.connect(self._motor_data_received) self._log_error_signal.connect(self._logging_error) # Connect UI signals that are in this tab self.flightModeCombo.currentIndexChanged.connect(self.flightmodeChange) self.minThrust.valueChanged.connect(self.minMaxThrustChanged) self.maxThrust.valueChanged.connect(self.minMaxThrustChanged) self.thrustLoweringSlewRateLimit.valueChanged.connect( self.thrustLoweringSlewRateLimitChanged) self.slewEnableLimit.valueChanged.connect( self.thrustLoweringSlewRateLimitChanged) self.targetCalRoll.valueChanged.connect(self._trim_roll_changed) self.targetCalPitch.valueChanged.connect(self._trim_pitch_changed) self.maxAngle.valueChanged.connect(self.maxAngleChanged) self.maxYawRate.valueChanged.connect(self.maxYawRateChanged) self.uiSetupReadySignal.connect(self.uiSetupReady) self.clientXModeCheckbox.toggled.connect(self.changeXmode) self.isInCrazyFlightmode = False self.uiSetupReady() self.clientXModeCheckbox.setChecked(Config().get("client_side_xmode")) self.crazyflieXModeCheckbox.clicked.connect( lambda enabled: self.helper.cf.param.set_value( "flightmode.x", str(enabled))) self.helper.cf.param.add_update_callback( group="flightmode", name="xmode", cb=(lambda name, checked: self.crazyflieXModeCheckbox.setChecked( eval(checked)))) self.ratePidRadioButton.clicked.connect( lambda enabled: self.helper.cf.param.set_value( "flightmode.ratepid", str(enabled))) self.angularPidRadioButton.clicked.connect( lambda enabled: self.helper.cf.param.set_value( "flightmode.ratepid", str(not enabled))) self._led_ring_headlight.clicked.connect( lambda enabled: self.helper.cf.param.set_value( "ring.headlightEnable", str(enabled))) self.helper.cf.param.add_update_callback( group="flightmode", name="ratepid", cb=(lambda name, checked: self.ratePidRadioButton.setChecked( eval(checked)))) self.helper.cf.param.add_update_callback( group="cpu", name="flash", cb=self._set_enable_client_xmode) self.helper.cf.param.add_update_callback( group="ring", name="headlightEnable", cb=(lambda name, checked: self._led_ring_headlight.setChecked( eval(checked)))) self.helper.cf.param.add_update_callback( group="flightmode", name="althold", cb=(lambda name, enabled: self.helper.inputDeviceReader. enable_alt_hold(eval(enabled)))) self._ledring_nbr_effects = 0 self.helper.cf.param.add_update_callback(group="ring", name="effect", cb=self._ring_effect_updated) self.helper.cf.param.add_update_callback( group="imu_sensors", cb=self._set_available_sensors) self.helper.cf.param.all_updated.add_callback( self._ring_populate_dropdown) self.logBaro = None self.logAltHold = None self.ai = AttitudeIndicator() self.verticalLayout_4.addWidget(self.ai) self.splitter.setSizes([1000, 1]) self.targetCalPitch.setValue(Config().get("trim_pitch")) self.targetCalRoll.setValue(Config().get("trim_roll")) self.helper.inputDeviceReader.alt1_updated.add_callback( self.alt1_updated) self.helper.inputDeviceReader.alt2_updated.add_callback( self.alt2_updated) self._tf_state = 0 self._ring_effect = 0 # Connect callbacks for input device limiting of rpöö/pitch/yaw/thust self.helper.inputDeviceReader.limiting_updated.add_callback( self._limiting_updated.emit) self._limiting_updated.connect(self._set_limiting_enabled) def _set_enable_client_xmode(self, name, value): if eval(value) <= 128: self.clientXModeCheckbox.setEnabled(True) else: self.clientXModeCheckbox.setEnabled(False) self.clientXModeCheckbox.setChecked(False) def _set_limiting_enabled(self, rp_limiting_enabled, yaw_limiting_enabled, thrust_limiting_enabled): self.maxAngle.setEnabled(rp_limiting_enabled) self.targetCalRoll.setEnabled(rp_limiting_enabled) self.targetCalPitch.setEnabled(rp_limiting_enabled) self.maxYawRate.setEnabled(yaw_limiting_enabled) self.maxThrust.setEnabled(thrust_limiting_enabled) self.minThrust.setEnabled(thrust_limiting_enabled) self.slewEnableLimit.setEnabled(thrust_limiting_enabled) self.thrustLoweringSlewRateLimit.setEnabled(thrust_limiting_enabled) def thrustToPercentage(self, thrust): return ((thrust / MAX_THRUST) * 100.0) def uiSetupReady(self): flightComboIndex = self.flightModeCombo.findText( Config().get("flightmode"), Qt.MatchFixedString) if (flightComboIndex < 0): self.flightModeCombo.setCurrentIndex(0) self.flightModeCombo.currentIndexChanged.emit(0) else: self.flightModeCombo.setCurrentIndex(flightComboIndex) self.flightModeCombo.currentIndexChanged.emit(flightComboIndex) def _logging_error(self, log_conf, msg): QMessageBox.about( self, "Log error", "Error when starting log config [%s]: %s" % (log_conf.name, msg)) def _motor_data_received(self, timestamp, data, logconf): if self.isVisible(): self.actualM1.setValue(data["motor.m1"]) self.actualM2.setValue(data["motor.m2"]) self.actualM3.setValue(data["motor.m3"]) self.actualM4.setValue(data["motor.m4"]) def _baro_data_received(self, timestamp, data, logconf): if self.isVisible(): estimated_z = data[PARAM_NAME_ESTIMATED_Z] self.actualASL.setText(("%.2f" % estimated_z)) self.ai.setBaro(estimated_z) def _althold_data_received(self, timestamp, data, logconf): if self.isVisible(): target = data[PARAM_NAME_ALT_HOLD_TARGET] if target > 0: if not self.targetASL.isEnabled(): self.targetASL.setEnabled(True) self.targetASL.setText(("%.2f" % target)) self.ai.setHover(target) elif self.targetASL.isEnabled(): self.targetASL.setEnabled(False) self.targetASL.setText("Not set") self.ai.setHover(0) def _imu_data_received(self, timestamp, data, logconf): if self.isVisible(): self.actualRoll.setText(("%.2f" % data["stabilizer.roll"])) self.actualPitch.setText(("%.2f" % data["stabilizer.pitch"])) self.actualYaw.setText(("%.2f" % data["stabilizer.yaw"])) self.actualThrust.setText( "%.2f%%" % self.thrustToPercentage(data["stabilizer.thrust"])) self.ai.setRollPitch(-data["stabilizer.roll"], data["stabilizer.pitch"]) def connected(self, linkURI): # IMU & THRUST lg = LogConfig("Stabilizer", Config().get("ui_update_period")) lg.add_variable("stabilizer.roll", "float") lg.add_variable("stabilizer.pitch", "float") lg.add_variable("stabilizer.yaw", "float") lg.add_variable("stabilizer.thrust", "uint16_t") try: self.helper.cf.log.add_config(lg) lg.data_received_cb.add_callback(self._imu_data_signal.emit) lg.error_cb.add_callback(self._log_error_signal.emit) lg.start() except KeyError as e: logger.warning(str(e)) except AttributeError as e: logger.warning(str(e)) # MOTOR lg = LogConfig("Motors", Config().get("ui_update_period")) lg.add_variable("motor.m1") lg.add_variable("motor.m2") lg.add_variable("motor.m3") lg.add_variable("motor.m4") try: self.helper.cf.log.add_config(lg) lg.data_received_cb.add_callback(self._motor_data_signal.emit) lg.error_cb.add_callback(self._log_error_signal.emit) lg.start() except KeyError as e: logger.warning(str(e)) except AttributeError as e: logger.warning(str(e)) def _set_available_sensors(self, name, available): logger.info("[%s]: %s", name, available) available = eval(available) if ("HMC5883L" in name): if (not available): self.actualASL.setText("N/A") self.actualASL.setEnabled(False) else: self.actualASL.setEnabled(True) self.helper.inputDeviceReader.set_alt_hold_available(available) if (not self.logBaro and not self.logAltHold): # The sensor is available, set up the logging self.logBaro = LogConfig("Baro", 200) self.logBaro.add_variable(PARAM_NAME_ESTIMATED_Z, "float") try: self.helper.cf.log.add_config(self.logBaro) self.logBaro.data_received_cb.add_callback( self._baro_data_signal.emit) self.logBaro.error_cb.add_callback( self._log_error_signal.emit) self.logBaro.start() except KeyError as e: logger.warning(str(e)) except AttributeError as e: logger.warning(str(e)) self.logAltHold = LogConfig("AltHold", 200) self.logAltHold.add_variable(PARAM_NAME_ALT_HOLD_TARGET, "float") try: self.helper.cf.log.add_config(self.logAltHold) self.logAltHold.data_received_cb.add_callback( self._althold_data_signal.emit) self.logAltHold.error_cb.add_callback( self._log_error_signal.emit) self.logAltHold.start() except KeyError as e: logger.warning(str(e)) except AttributeError: logger.warning(str(e)) def disconnected(self, linkURI): self.ai.setRollPitch(0, 0) self.actualM1.setValue(0) self.actualM2.setValue(0) self.actualM3.setValue(0) self.actualM4.setValue(0) self.actualRoll.setText("") self.actualPitch.setText("") self.actualYaw.setText("") self.actualThrust.setText("") self.actualASL.setText("") self.targetASL.setText("Not Set") self.targetASL.setEnabled(False) self.actualASL.setEnabled(False) self.clientXModeCheckbox.setEnabled(False) self.logBaro = None self.logAltHold = None self._led_ring_effect.setEnabled(False) self._led_ring_effect.clear() try: self._led_ring_effect.currentIndexChanged.disconnect( self._ring_effect_changed) except TypeError: # Signal was not connected pass self._led_ring_effect.setCurrentIndex(-1) self._led_ring_headlight.setEnabled(False) def minMaxThrustChanged(self): self.helper.inputDeviceReader.min_thrust = self.minThrust.value() self.helper.inputDeviceReader.max_thrust = self.maxThrust.value() if (self.isInCrazyFlightmode is True): Config().set("min_thrust", self.minThrust.value()) Config().set("max_thrust", self.maxThrust.value()) def thrustLoweringSlewRateLimitChanged(self): self.helper.inputDeviceReader.thrust_slew_rate = ( self.thrustLoweringSlewRateLimit.value()) self.helper.inputDeviceReader.thrust_slew_limit = ( self.slewEnableLimit.value()) if (self.isInCrazyFlightmode is True): Config().set("slew_limit", self.slewEnableLimit.value()) Config().set("slew_rate", self.thrustLoweringSlewRateLimit.value()) def maxYawRateChanged(self): logger.debug("MaxYawrate changed to %d", self.maxYawRate.value()) self.helper.inputDeviceReader.max_yaw_rate = self.maxYawRate.value() if (self.isInCrazyFlightmode is True): Config().set("max_yaw", self.maxYawRate.value()) def maxAngleChanged(self): logger.debug("MaxAngle changed to %d", self.maxAngle.value()) self.helper.inputDeviceReader.max_rp_angle = self.maxAngle.value() if (self.isInCrazyFlightmode is True): Config().set("max_rp", self.maxAngle.value()) def _trim_pitch_changed(self, value): logger.debug("Pitch trim updated to [%f]" % value) self.helper.inputDeviceReader.trim_pitch = value Config().set("trim_pitch", value) def _trim_roll_changed(self, value): logger.debug("Roll trim updated to [%f]" % value) self.helper.inputDeviceReader.trim_roll = value Config().set("trim_roll", value) def calUpdateFromInput(self, rollCal, pitchCal): logger.debug("Trim changed on joystick: roll=%.2f, pitch=%.2f", rollCal, pitchCal) self.targetCalRoll.setValue(rollCal) self.targetCalPitch.setValue(pitchCal) def updateInputControl(self, roll, pitch, yaw, thrust): self.targetRoll.setText(("%0.2f" % roll)) self.targetPitch.setText(("%0.2f" % pitch)) self.targetYaw.setText(("%0.2f" % yaw)) self.targetThrust.setText( ("%0.2f %%" % self.thrustToPercentage(thrust))) self.thrustProgress.setValue(thrust) def setMotorLabelsEnabled(self, enabled): self.M1label.setEnabled(enabled) self.M2label.setEnabled(enabled) self.M3label.setEnabled(enabled) self.M4label.setEnabled(enabled) def emergencyStopStringWithText(self, text): return ("<html><head/><body><p>" "<span style='font-weight:600; color:#7b0005;'>{}</span>" "</p></body></html>".format(text)) def updateEmergencyStop(self, emergencyStop): if emergencyStop: self.setMotorLabelsEnabled(False) self.emergency_stop_label.setText( self.emergencyStopStringWithText("Kill switch active")) else: self.setMotorLabelsEnabled(True) self.emergency_stop_label.setText("") def flightmodeChange(self, item): Config().set("flightmode", str(self.flightModeCombo.itemText(item))) logger.debug("Changed flightmode to %s", self.flightModeCombo.itemText(item)) self.isInCrazyFlightmode = False if (item == 0): # Normal self.maxAngle.setValue(Config().get("normal_max_rp")) self.maxThrust.setValue(Config().get("normal_max_thrust")) self.minThrust.setValue(Config().get("normal_min_thrust")) self.slewEnableLimit.setValue(Config().get("normal_slew_limit")) self.thrustLoweringSlewRateLimit.setValue( Config().get("normal_slew_rate")) self.maxYawRate.setValue(Config().get("normal_max_yaw")) if (item == 1): # Advanced self.maxAngle.setValue(Config().get("max_rp")) self.maxThrust.setValue(Config().get("max_thrust")) self.minThrust.setValue(Config().get("min_thrust")) self.slewEnableLimit.setValue(Config().get("slew_limit")) self.thrustLoweringSlewRateLimit.setValue( Config().get("slew_rate")) self.maxYawRate.setValue(Config().get("max_yaw")) self.isInCrazyFlightmode = True if (item == 0): newState = False else: newState = True self.maxThrust.setEnabled(newState) self.maxAngle.setEnabled(newState) self.minThrust.setEnabled(newState) self.thrustLoweringSlewRateLimit.setEnabled(newState) self.slewEnableLimit.setEnabled(newState) self.maxYawRate.setEnabled(newState) @pyqtSlot(bool) def changeXmode(self, checked): self.helper.cf.commander.set_client_xmode(checked) Config().set("client_side_xmode", checked) logger.info("Clientside X-mode enabled: %s", checked) def alt1_updated(self, state): if state: new_index = (self._ring_effect + 1) % (self._ledring_nbr_effects + 1) self.helper.cf.param.set_value("ring.effect", str(new_index)) def alt2_updated(self, state): self.helper.cf.param.set_value("ring.headlightEnable", str(state)) def _ring_populate_dropdown(self): try: nbr = int(self.helper.cf.param.values["ring"]["neffect"]) current = int(self.helper.cf.param.values["ring"]["effect"]) except KeyError: return # Used only in alt1_updated function self._ring_effect = current self._ledring_nbr_effects = nbr hardcoded_names = { 0: "Off", 1: "White spinner", 2: "Color spinner", 3: "Tilt effect", 4: "Brightness effect", 5: "Color spinner 2", 6: "Double spinner", 7: "Solid color effect", 8: "Factory test", 9: "Battery status", 10: "Boat lights", 11: "Alert", 12: "Gravity", 13: "LED tab" } for i in range(nbr + 1): name = "{}: ".format(i) if i in hardcoded_names: name += hardcoded_names[i] else: name += "N/A" self._led_ring_effect.addItem(name, i) self._led_ring_effect.currentIndexChanged.connect( self._ring_effect_changed) self._led_ring_effect.setCurrentIndex(current) if self.helper.cf.mem.ow_search(vid=0xBC, pid=0x01): self._led_ring_effect.setEnabled(True) self._led_ring_headlight.setEnabled(True) def _ring_effect_changed(self, index): self._ring_effect = index if index > -1: i = self._led_ring_effect.itemData(index) logger.info("Changed effect to {}".format(i)) if i != int(self.helper.cf.param.values["ring"]["effect"]): self.helper.cf.param.set_value("ring.effect", str(i)) def _ring_effect_updated(self, name, value): if self.helper.cf.param.is_updated: self._led_ring_effect.setCurrentIndex(int(value))
def __init__( self, serverPath ): self.serverPath = serverPath self.data = None self.peoplesList = []; ready = pyqtSignal()
sip.setapi('QDate', 2) sip.setapi('QDateTime', 2) sip.setapi('QString', 2) sip.setapi('QTextStream', 2) sip.setapi('QTime', 2) sip.setapi('QUrl', 2) sip.setapi('QWidget', 2) sip.setapi('QComboBox', 2) sip.setapi('QFormLayout', 2) sip.setapi('QVBoxLayout', 2) sip.setapi('QLineEdit', 2) sip.setapi('QPushButton', 2) from PyQt4.Qt import * from PyQt4.QtCore import pyqtSignal tapped = pyqtSignal() # Create a Qt application app = QApplication(sys.argv) # Our main window will be a QListView list = QListView() list.setWindowTitle('Honey-Do List') list.setMinimumSize(600, 400) # Create an empty model for the list's data model = QStandardItemModel(list) # Add some textual items foods = [
else: # calculate the force exerted on points close to the # centroid of this polygon xF = distance / feature.radius # distance ** 2 / feature.radius ** 2 instead of xF force = feature.mass * (xF ** 2) * (4 - (3 * xF)) force = force * force_reduction_factor / distance x = (x0 - cx) * force + x y = (y0 - cy) * force + y new_line.append(QgsPoint(x, y)) new_polygon.append(new_line) new_line = [] return new_polygon finished = pyqtSignal(object) error = pyqtSignal(Exception, basestring) progress = pyqtSignal(float) def get_step(self): """Determine how often the progress bar should be updated.""" feature_count = self.layer.featureCount() # update the progress bar at each .1% increment step = feature_count // 1000 # because we use modulo to determine if we should emit the progress # signal, the step needs to be greater than 1 if step < 2: step = 2
class testermain(QDialog, Ui_Dialog): """ Class documentation goes here. """ #用于上传线程中的测试结果 updateSignal = pyqtSignal(object) def __init__(self, parent=None): """ Constructor @param parent reference to the parent widget @type QWidget """ QDialog.__init__(self, parent) self.setupUi(self) self.setFixedSize(331, 229) self.showWindow = showDataWindow() self.status = TEST_STATUS.IDLE self.testTimeList = [] #保存测试时间 str self.testSpeedList = [] #保存测试速度 int self.updateSignal.connect(self.receiveTestData) self.tester = None self.gapTime = 0 #int(timer seconds) self.timer = QTimer() #计时器QTimer self.timer.timeout.connect(self.doPlanWork) self.remoteIp = 'localhost' def Confirm(self, intArg, strArg=None): """ 确认窗口 :param intArg: :return:确定返回True, 取消返回False """ noticeWindow = NoticeWindow() noticeWindow.Confirm(intArg, strArg) return noticeWindow.status def verifyIp(self, ipStr): ip = str(ipStr).split('.') result = (len(ip) == 4 and len( filter(lambda x: x >= 0 and x <= 255, map(int, filter(lambda x: x.isdigit(), ip)))) == 4 and ip[0] != '0') if result is True: self.remoteIp = str(ipStr) return self.Confirm(1) else: self.Confirm(2) self.remoteIp = 'localhost' return False def doPlanWork(self): """ 定时器触发动作 :return: """ if self.status is TEST_STATUS.PLANNED_TEST: if self.tester is None: self.startOneTest() pass print(time.asctime() + ':on time test') else: self.timer.stop() print('timer stop') @pyqtSignature("") def on_startOneTestBtn_clicked(self): """ Slot documentation goes here. """ # TODO: not implemented yet if self.status is TEST_STATUS.IDLE: if self.verifyIp(self.remoteIpInput.text()): #todo:需要输入ip和port self.startOneTest(ip=self.remoteIp) self.status = TEST_STATUS.SINGLE_TEST else: self.Confirm(2001) @pyqtSignature("") def on_startAutoTestBtn_clicked(self): """ Slot documentation goes here. """ # TODO: not implemented yet if self.status is TEST_STATUS.IDLE: if self.verifyIp(self.remoteIpInput.text()): #空闲状态,开始测试并改变UI、status if self.Confirm(3001): self.startOneTestBtn.setDisabled(True) self.clearResultBtn.setDisabled(True) self.gapTimeEdit.setDisabled(True) self.remoteIpInput.setDisabled(True) self.startAutoTestBtn.setText( _translate("Dialog", "关闭定时测试", None)) self.startOneTest(ip=self.remoteIp) self.status = TEST_STATUS.PLANNED_TEST self.timer.start( self.getSec(self.gapTimeEdit.time()) * 1000) elif self.status is TEST_STATUS.PLANNED_TEST: if self.Confirm(3002): self.startOneTestBtn.setDisabled(False) self.clearResultBtn.setDisabled(False) self.gapTimeEdit.setDisabled(False) self.remoteIpInput.setDisabled(False) self.timer.stop() self.startAutoTestBtn.setText( _translate("Dialog", "开始定时测试", None)) self.status = TEST_STATUS.IDLE @pyqtSignature("") def on_clearResultBtn_clicked(self): """ Slot documentation goes here. """ if self.status is TEST_STATUS.IDLE: if self.Confirm(4001): self.testSpeedList = [] self.testTimeList = [] else: self.Confirm(2001) @pyqtSignature("") def on_showResultBtn_clicked(self): """ Slot documentation goes here. """ # self.showWindow.webView.reload() self.showWindow.show() @pyqtSignature("") def on_remoteIpInput_returnPressed(self): """ Slot documentation goes here. """ pass @pyqtSignature("") def on_gapTimeEdit_editingFinished(self): """ Slot documentation goes here. """ # TODO: not implemented yet if self.status is TEST_STATUS.IDLE: print('time edit finished') if self.Confirm(5001, self.getGap(self.gapTimeEdit.time())): print(self.gapTimeEdit.time()) self.gapTime = self.getSec(self.gapTimeEdit.time()) else: self.Confirm(2001) @pyqtSignature("QTime") def on_gapTimeEdit_timeChanged(self, date): """ Slot documentation goes here. @param date DESCRIPTION @type QTime """ # TODO: not implemented yet print('time changed') print(self.gapTimeEdit.time(), self.getSec(self.gapTimeEdit.time())) def startOneTest(self, ip='localhost', port=10230): # todo:需要输入ip和port self.tester = UdpTestManager(updateSignal=self.updateSignal, remoteIP=ip, remotePort=port) self.tester.start() time.sleep(0.5) def receiveTestData(self, dataTuple): print('main window recv: ', dataTuple) if self.status is not TEST_STATUS.PLANNED_TEST: self.status = TEST_STATUS.IDLE del self.tester self.tester = None if dataTuple[0] is True: self.testTimeList.append(dataTuple[1]) self.testSpeedList.append(int(dataTuple[2])) self.updateChart(self.testTimeList, self.testSpeedList) else: self.Confirm(2002) def updateChart(self, timeStrList, speedIntList): """ 用于更新数据至本地图表 :param timeList: 时间列表,eg. ['1:10','1:20','1:30','1:40'] :param speedList: 速度列表, eg. [20,100,30,10] :return: """ try: timeList = ['\'' + str(c) + '\'' for c in timeStrList] timeStr = ','.join(timeList) speedStr = ','.join([str(c) for c in speedIntList]) content = """ <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="static/echarts.js"></script> </head> <body> <div id="main" style="width: 690px;height:430px;"></div> <script type="text/javascript"> var myChart = echarts.init(document.getElementById('main')); option = { title: { text: '网速测试结果', subtext: '@heyu' }, tooltip: { trigger: 'axis' }, legend: { data:['网速测试'] }, toolbox: { show: true, feature: { dataZoom: { yAxisIndex: 'none' }, dataView: {readOnly: false}, magicType: {type: ['line', 'bar']}, restore: {}, } }, xAxis: { type: 'category', boundaryGap: false, data: [%s] }, yAxis: { type: 'value', axisLabel: { formatter: '{value} Kbps' } }, series: [ { name:'网速测试', type:'line', data:[%s], markPoint: { data: [ {type: 'max', name: '最大值'}, {type: 'min', name: '最小值'} ] }, markLine: { data: [ {type: 'average', name: '平均值'} ] } } ] }; myChart.setOption(option); </script> </body> </html> """ % (timeStr, speedStr) with open('echart/show.html', 'w') as file: file.writelines(content) self.showWindow.webView.reload() print timeStr, speedStr except Exception as e: print('error in updateChart', e) def getSec(self, QTimeObj): return (QTimeObj.hour() * 24 + QTimeObj.minute()) * 60 + QTimeObj.second() def getGap(self, QTimeObj): return ':'.join( str(i) for i in [QTimeObj.hour(), QTimeObj.minute(), QTimeObj.second()]) def mockManagerUpdate(self): """ 用于测试来自manager的datatuple上报/singal的emit和recv正常,updateChart功能正常 :return: """ ts = str(int(time.time())) dataTest = (True, ts[-4:], int(ts[-1:]) * 12) print('test btn:', dataTest) self.updateSignal.emit(dataTest)
hiResFilters = [i + '_???.' + ext for ext in self.hiResFormats] for hr in hiResEntryList: if self.killed is True: # kill request received, exit loop early break hrDir = QDir(iDir.path() + '\\' + hr) hrEntryList = hrDir.entryList(hiResFilters, QDir.Files) self.hiResRegistry = self.hiResRegistry + hrEntryList if self.killed is False: self.imageRegistryNE = [img[:14].replace('_','.') for img in self.imageRegistry] self.hiResRegistryNE = [img[:14].replace('_','.') for img in self.hiResRegistry] def updateOrthoRegistry(self): import glob, os self.orthoRegistryNE = [] self.orthoRegistry = [] self.orthoEntryList = self.orthoDir.entryList(['??????????'], QDir.Dirs) for o in self.orthoEntryList: if self.killed is True: # kill request received, exit loop early break orthoFilters = [o + '_???_op*.' + ext for ext in self.orthoFormats] oDir = QDir(self.orthoDir.path() +'\\' + o) oEntryList = oDir.entryList(orthoFilters, QDir.Files) self.orthoRegistry = self.orthoRegistry + oEntryList if self.killed is False: self.orthoRegistryNE = [img[:14].replace('_','.') for img in self.orthoRegistry] finished = pyqtSignal(object) error = pyqtSignal(Exception, basestring)
def __init__(self, parent): QLabel.__init__(self, parent) self.outside = pyqtSignal(str) self.setStyleSheet(self.default_style)
class SR830(VisaInstrument, InstrumentWithSettings, QObject): #adcReadingAvailable = pyqtSignal(float, float) #resistanceReadingAvailable = pyqtSignal(float, float) auxInRead = pyqtSignal(int, float) inputOverloadRead = pyqtSignal(bool) filterOverloadRead = pyqtSignal(bool) outputOverloadRead = pyqtSignal(bool) readingAvailable = pyqtSignal(float, float, float) '''Emitted whenever a new reading is taken with snapSignal, provides X, Y, and f''' OffsetQuantityCodes = {'X': 1, 'Y': 2, 'R': 3} OffsetExpandCodes = {1:0, 10:1, 100:2} Channel1DisplayItems = {'X': 0, 'R':1, 'Xn':2,'AUX In 1':3, 'AUX In 2':4} Channel2DisplayItems = {'Y': 0, 'Theta':1, 'Yn':2,'AUX In 3':3, 'AUX In 4':4} def __init__(self, visaResource): QObject.__init__(self) InstrumentWithSettings.__init__(self) VisaInstrument.__init__(self, visaResource) self._x = None self._y = None self._f = None self._auxIn = [np.nan, np.nan, np.nan, np.nan] self.model = 'SR830' self.serial = '000000' if visaResource is not None: try: visaId = self.visaId() d = visaId.split(',') self.model = d[1] self.serial = d[2][3:] if not self.model in ['SR810', 'SR830', 'SR850']: raise Exception('Unknown model %s' % self.model) except Exception as e: warnings.warn("Unable to obtain VISA ID: %s" % e) self.inputSource = EnumSetting('ISRC', 'input source', [(0, 'A (single ended)'), (1, 'A-B (differential)'), (2, 'I (1 MOhm)'), (3, 'I (100 MOhm)')], self) self.inputCoupling = EnumSetting('ICPL', 'input coupling', [(0, 'AC'), (1, 'DC')], self) self.inputGrounding = EnumSetting('IGND', 'input shield ground', [(0, 'FLOAT'), (1, 'GND')], self) self.inputFilters = EnumSetting('ILIN', 'input filters', [(0, 'None'), (1, '60 Hz'), (2, '120Hz'), (3, '60 & 120 Hz')], self) self.reserve = EnumSetting('RMOD', 'reserve', [(0, 'high reserve'), (1, 'normal'), (2, 'low noise')], self) self.syncDemodulator = OnOffSetting('SYNC', 'synchronous demodulator', self) self.auxOut = [] for i in range(4): self.auxOut.append(FloatSetting('AUXV %i,' % (i+1), 'auxilliary output', -10.,+10., 'V', 1E-3, 3, self, queryString='AUXV? %i' % (i+1))) self.sineOut = FloatSetting('SLVL', 'sine out amplitude', 0.004, 5.000, 'V', step=0.002, decimals=3, instrument=self) self.referenceFrequency = FloatSetting('FREQ', 'reference frequency', 1E-3, 102E3, 'Hz', step=1E-4, decimals=4, instrument=self) #self.referencePhase = AngleSetting('PHAS', 'reference phase', self) self.referenceTrigger = EnumSetting('RSLP', 'reference trigger', [(0, 'sine'), (1, 'positive edge'),(2,'negative edge')], instrument=self) if self.model in ['SR810', 'SR830']: self.referenceSource = EnumSetting('FMOD', 'reference source', [(0, 'external'), (1, 'internal')], self) elif self.model == 'SR850': self.referenceSource = EnumSetting('FMOD', 'reference source', [(0, 'internal'), (1, 'sweep'), (2, 'external')], self) self.harmonic = IntegerSetting('HARM', 'harmonic', 1, 100, unit='', instrument=self) self.filterTc = NumericEnumSetting('OFLT', 'filter time constant', [(0,10E-6), (1, 30E-6), (2, 100E-6), (3, 300E-6), (4, 1E-3), (5, 3E-3), (6, 10E-3), (7, 30E-3), (8, 100E-3), (9,300E-3), (10, 1.), (11, 3.), (12, 10.), (13, 30.), (14, 100.), (15, 300.), (16, 1E3), (17, 3E3), (18, 10E3), (19, 30E3)], self, 's') self.filterSlope = NumericEnumSetting('OFSL', 'filter roll-off', [(0, 6), (1, 12), (2, 18), (3,24)], self, 'dB/oct.') self.sensitivity = NumericEnumSetting('SENS', 'sensitivity', [(0, 2E-9), (1, 5E-9), (2, 1E-8), (3, 2E-8), (4, 5E-8), (5, 1E-7), (6, 2E-7), (7, 5E-7), (8, 1E-6), (9, 2E-6), (10, 5E-6), (11,1E-5), (12,2E-5), (13, 5E-5), (14, 1E-4), (15, 2E-4), (16, 5E-4), (17, 1E-3), (18, 2E-3), (19, 5E-3), (20, 1E-2), (21, 2E-2), (22, 5E-2), (23,0.1), (24, 0.2), (25, 0.5), (26, 1.0)], self, unit='V') self.traceLoop = EnumSetting('SEND', 'buffer mode', [(0, 'single shot'), (1, 'loop')], self) self.traceRate = NumericEnumSetting('SRAT', 'sample data rate', [(0, 62.5E-3), (1, 125E-3), (2, 250E-3), (3, 500E-3), (4, 1.0), (5, 2.0), (6, 4.0), (7, 8.0), (8, 16.0), (9, 32.0), (10, 64.0), (11, 128.0), (12, 256.0), (13, 512.0)], self, 'Hz') @pyqtSlot() def readAll(self): self.inputSource.code self.inputCoupling.code self.inputGrounding.code self.inputFilters.code self.reserve.code self.syncDemodulator.enabled self.sineOut.value self.referenceFrequency.value self.referenceTrigger.code self.referenceSource.code self.harmonic.value self.filterTc.code self.filterSlope.code self.sensitivity.code for i in range(4): self.auxOut[i].value @pyqtSlot(int) def snapSignal(self, auxIn=None): '''Snap X,Y, and f and optionally one of the AUX inputs from the lock-in. Returns X,Y,f. Data are also cached in the LockIn instance and can be read as any combination of X,Y, R and Theta + the AUX values. ''' items = ['1','2','9'] #X,Y,f if auxIn is not None: items.append(str(auxIn+5)) items = ','.join(items) result = self.queryString("SNAP ? %s" % items) d = result.split(',') self._x = float(d[0]) self._y = float(d[1]) self._f = float(d[2]) self.readingAvailable.emit(self._x,self._y,self._f) if auxIn is not None: Vaux = float(d[3]) self._auxIn[auxIn] = Vaux self.auxInRead.emit(auxIn, Vaux) return (self._x, self._y, self._f) @pyqtSlot(int) def snapSignalR(self, auxIn=None): '''Like snapSignal, but instead of X,Y this transfers R and theta. This was to test the idea that since R is always positive we may gain additional resolution by loosing the sign bit. In practice, this does not pan out. Deprecated.''' items = ['3', '4', '9'] # R, theta, f if auxIn is not None: items.append(str(auxIn+5)) items = ','.join(items) result = self.queryString("SNAP ? %s" % items) d = result.split(',') r = float(d[0]) theta = np.deg2rad(float(d[1])) self._x = r * np.cos(theta) self._y = r * np.sin(theta) self._f = float(d[2]) self.readingAvailable.emit(self._x,self._y,self._f) if auxIn is not None: Vaux = float(d[3]) self._auxIn[auxIn] = Vaux self.auxInRead.emit(auxIn, Vaux) return (self._x, self._y, self._f) def checkStatus(self): '''Query the staus register of the lock-in Returns: SR830LiaStatus Emits: inputOverloadRead(bool), filterOverloadRead(bool), outputOverloadRead(bool) ''' lias = SR830LiaStatus(self.queryInteger('LIAS?')) self._lockinStatus = lias self.inputOverloadRead.emit(lias.inputOverload) self.filterOverloadRead.emit(lias.filterOverload) self.outputOverloadRead.emit(lias.outputOverload) return lias @property def overload(self): '''Return if any overload (input, filter or output) has occured. Need to call checkStatus first. Deprecated.''' return self._lockinStatus.anyOverload @property def R(self): return np.sqrt(self._x**2+self._y**2) @property def theta(self): return np.arctan2(self._y, self._x) @property def thetaDegree(self): return np.rad2deg(self.theta) @property def X(self): return self._x @property def Y(self): return self._y @property def f(self): return self._f @f.setter def f(self, newFrequency): self.referenceFrequency.value = newFrequency def auxIn(self, channel): '''Read one of the auxillary inputs channel (int): specify channel to be read (0-3)''' V = self.queryFloat('OAUX? %i' % channel+1) self.auxInRead.emit(channel, V) return V def autoGain(self, block=True): '''Execute instrument internal auto-gain. block (bool): wait for operation to complete if True (default) ''' self.commandString('AGAN') self.sensitivity._value = None if block: self.waitForOpc() def autoPhase(self, block=True): self.commandString('APHS') if block: self.waitForOpc() def autoReserve(self, block=True): self.commandString('ARSV') if block: self.waitForOpc() def waitForOpc(self): warnings.warn('waitForOpc not implemented/does not work!') pass #while self.queryInteger('*STB?') & 2 == 0: # pass def verifyPresence(self): '''Check if instrument is actually present and responding.''' visaId = self.visaId() return 'SR830' in visaId def startTrace(self): '''Start recording trace data. Make sure to resetTrace first (as needed).''' self.commandString('STRT') def pauseTrace(self): '''Pause recording of trace data. Do this before reading when LOOP mode is on.''' self.commandString('PAUS') def resetTrace(self): '''Clear past trace data''' self.commandString('REST') def traceNumberOfPoints(self): '''Returns number of points in the trace buffer.''' return self.queryInteger('SPTS?') def readTraceAscii(self, display, start=0, count=None): '''Read trace buffer, transmitting data as ASCII *display*: 1 or 2 *start* : index of first point to transmit *count* : number of points to transmit (if None, transmit all points) Returns the data as a numpy array ''' if count is None: count = self.traceNumberOfPoints() buff = self.queryString('TRCA? %d,%d,%d' % (display,start,count)) d = buff.split(',')[:-1] data = np.asarray([float(v) for v in d]) return data def autoOffset(self, quantity): '''Automatically offset specified quantity quantity (str): 'X', 'Y', or 'Z' ''' code = self.OffsetQuantityCodes[quantity] self.commandInteger('AOFF', code) def offsetExpand(self, quantity='X'): '''Returns the offset/expand settings for the specified quantity. quantity (str): 'X', 'Y', or 'R' returns: percentage, expandFactor (1, 10, or 100)''' code = self.OffsetQuantityCodes[quantity] r = self.queryString('OEXP? %d' % code) d = r.split(',') offsetPercent, expandCode = float(d[0]), int(d[1]) expand = [k for k, v in self.OffsetExpandCodes.items() if v==expandCode] return offsetPercent, expand[0] def disableOffsetExpand(self, quantity = None): '''Disable offset/expand for specified quantity. quantity (str): 'X', 'Y', 'R', or None for all.''' if quantity is None: self.disableOffsetExpand('X') self.disableOffsetExpand('Y') self.disableOffsetExpand('R') else: self.setOffsetExpand(quantity, 0, 1) def setOffsetExpand(self, quantity, percent, expand): '''Set offset and expand parameters quantity (str) : 'X', 'Y', or 'R' percent (float): percentage of full scale sensitivity (from -105 to +105%) expand (int) : expand factor 1, 10, or 100''' quantityCode = self.OffsetQuantityCodes[quantity] expandCode = self.OffsetExpandCodes[expand] self.commandString('OEXP %d,%.2f,%d' % (quantityCode, percent, expandCode)) def setDisplay(self, channel, item, ratio = 0): '''Select the item displayed for specified channel. channel (int): Channel 1 or 2 item : one of Channel1DisplayItem or Channel2DisplayItem ratio (int) : 0 for no ratio (default), 1 for ratio with first aux-in channel, 2 for ratio with second aux-in channel ''' if channel == 1: itemCode = self.Channel1DisplayItems[item] elif channel == 2: itemCode = self.Channel2DisplayItems[item] else: raise IndexError self.commandString('DDEF %d,%d,%d' % (channel, itemCode, ratio))
class UdpTestManager(QThread): """ 测速管理员,用于管理单次测速,格式化结果 """ innerSignal = pyqtSignal(object) def __init__(self, repeatTime=5, remoteIP='localhost', remotePort=10230, updateSignal=None, parent=None): super(UdpTestManager, self).__init__(parent) self.updateSignal = updateSignal self.remoteIP = remoteIP self.remotePort = remotePort self.repeatTime = repeatTime self.testTime = '' self.avrSpeed = 0 self.resultList = [] #用于存储上报结果 self.singleTester = None #用于传递至单次测速类 self.innerSignal.connect(self.processTestData) def run(self): """ 运行类,根据repeatTime,重复测速,汇总测试数据 :return: """ #todo:循环测试类 print('test manager start.') ts = time.gmtime() ts = map( lambda x: ('00' + x)[-2:], [str(i) for i in [(ts.tm_hour + 8) % 24, ts.tm_min, ts.tm_sec]]) self.testTime = ':'.join(ts) for i in range(self.repeatTime): self.singleTester = UdpClientQThread(self.remoteIP, self.remotePort, updateSignal=self.innerSignal) self.singleTester.start() while self.singleTester.isRunning(): time.sleep(0.5) del self.singleTester print('test finish, no.' + str(i + 1)) self.sendToParent() def processTestData(self, dataTuple): """ 处理来自UdpThread的测试结果 :param dataTuple: (FlagBool, timeStr, speedInt) :return: """ #todo:处理类 print('manager rec from client:', dataTuple) if dataTuple[0] is True: self.resultList.append(dataTuple[2]) def sendToParent(self): """ 将处理结果发送给上层窗口类 :param dataTuple: (FlagBool, timeStr, speedInt) :return: """ #todo:发送类 if len(self.resultList) >= 3: self.avrSpeed = sum(self.resultList) / len(self.resultList) self.updateSignal.emit((True, self.testTime, self.avrSpeed)) print('manager: test success.') else: self.updateSignal.emit((False, '-', '0')) print('manager: test fail.')
class GorgLineEdit(QtGui.QLineEdit): # the framing and content class for the minibuffer, which contains the GorgLineEdit object and the buffer that populates it. constructor takes a buffer. gorg_key_event_signal = pyqtSignal(str, int, int, QtGui.QWidget) def __init__(self): super(GorgMiniBuffer, self).__init__() def insertPlainText(self, QString): self.insert(QString) def _select_text(self, start, end): self._cursor.setPosition(start) self._cursor.setPosition(end, mode = 1) def _update_selected_text_properties(self, prop_dict): # sets color colors = {"black": Qt.black, "white": Qt.white, "red": Qt.red, "blue": Qt.blue, "cyan": Qt.cyan, "magenta": Qt.magenta, "yellow": Qt.yellow, "green": Qt.green} text_color = QtGui.QColor(colors[prop_dict["color"]]) self.setTextColor(text_color) # sets bold if prop_dict["bold"] == True: self.setFontWeight(75) else: self.setFontWeight(50) # sets italic if prop_dict["italics"] == True: self.setFontItalic(True) else: self.setFontItalic(False) #sets underline if prop_dict["underline"] == True: self.setFontUnderline(True) else: self.setFontUnderline(False) def update_view(self): self.clear() text_list = self._gate.get_text() for i in text_list: length = len(i[0]) self.insertPlainText(i[0]) self._select_text(self, self._cursor.position() - length, self._cursor.position()) self._update_selected_text_properties(i[1]) def keyPressEvent(self, e): self.gorg_key_event_signal.emit("p", e.key(), self._cursor.position(), self) def keyReleaseEvent(self, e): self.gorg_key_event_signal.emit("r", e.key(), self._cursor.position(), self)
class ExtentSelectorDialog(QDialog, FORM_CLASS): """Dialog for letting user determine analysis extents. """ extent_defined = pyqtSignal(QgsRectangle, QgsCoordinateReferenceSystem) clear_extent = pyqtSignal() extent_selector_closed = pyqtSignal() def __init__(self, iface, parent=None, extent=None, crs=None): """Constructor for the dialog. :param iface: A Quantum GIS QGisAppInterface instance. :type iface: QGisAppInterface :param parent: Parent widget of this dialog :type parent: QWidget :param extent: Extent of the user's preferred analysis area. :type extent: QgsRectangle :param crs: Coordinate reference system for user defined analysis extent. :type crs: QgsCoordinateReferenceSystem """ QDialog.__init__(self, parent) self.setupUi(self) self.iface = iface self.parent = parent self.canvas = iface.mapCanvas() self.previous_map_tool = None self.show_info() # Prepare the map tool self.tool = RectangleMapTool(self.canvas) self.previous_map_tool = self.canvas.mapTool() if extent is None and crs is None: # Use the current map canvas extents as a starting point self.tool.set_rectangle(self.canvas.extent()) else: # Ensure supplied extent is in current canvas crs transform = QgsCoordinateTransform( crs, self.canvas.mapRenderer().destinationCrs()) transformed_extent = transform.transformBoundingBox(extent) self.tool.set_rectangle(transformed_extent) self._populate_coordinates() # Observe inputs for changes self.x_minimum.valueChanged.connect(self._coordinates_changed) self.y_minimum.valueChanged.connect(self._coordinates_changed) self.x_maximum.valueChanged.connect(self._coordinates_changed) self.y_maximum.valueChanged.connect(self._coordinates_changed) # Draw the rubberband self._coordinates_changed() # Wire up button events self.capture_button.clicked.connect(self.start_capture) # Handle cancel cancel_button = self.button_box.button(QtGui.QDialogButtonBox.Cancel) cancel_button.clicked.connect(self.reject) # Make sure to reshow this dialog when rectangle is captured self.tool.rectangle_created.connect(self.stop_capture) # Setup ok button self.ok_button = self.button_box.button(QtGui.QDialogButtonBox.Ok) self.ok_button.clicked.connect(self.accept) # Set up context help self.help_context = 'user_extents' help_button = self.button_box.button(QtGui.QDialogButtonBox.Help) help_button.clicked.connect(self.show_help) # Reset / Clear button clear_button = self.button_box.button(QtGui.QDialogButtonBox.Reset) clear_button.setText(self.tr('Clear')) clear_button.clicked.connect(self.clear) # Populate the bookmarks list and connect the combobox self._populate_bookmarks_list() self.comboBox_bookmarks_list.currentIndexChanged.connect( self.bookmarks_index_changed) def show_help(self): """Load the help text for the dialog.""" show_context_help(self.help_context) def show_info(self): """Show usage info to the user.""" # Read the header and footer html snippets header = html_header() footer = html_footer() string = header heading = m.Heading(self.tr('User Extents Tool'), **INFO_STYLE) body = self.tr( 'This tool allows you to specify exactly which geographical ' 'region should be used for your analysis. You can either ' 'enter the coordinates directly into the input boxes below ' '(using the same CRS as the canvas is currently set to), or ' 'you can interactively select the area by using the \'select ' 'on map\' button - which will temporarily hide this window and ' 'allow you to drag a rectangle on the map. After you have ' 'finished dragging the rectangle, this window will reappear. ' 'You can also use one of your bookmarks to set the region. ' 'If you enable the \'Toggle scenario outlines\' tool on the ' 'InaSAFE toolbar, your user defined extent will be shown on ' 'the map as a blue rectangle. Please note that when running ' 'your analysis, the effective analysis extent will be the ' 'intersection of the hazard extent, exposure extent and user ' 'extent - thus the entire user extent area may not be used for ' 'analysis.' ) message = m.Message() message.add(heading) message.add(body) string += message.to_html() string += footer self.web_view.setHtml(string) def start_capture(self): """Start capturing the rectangle.""" previous_map_tool = self.canvas.mapTool() if previous_map_tool != self.tool: self.previous_map_tool = previous_map_tool self.canvas.setMapTool(self.tool) self.hide() def stop_capture(self): """Stop capturing the rectangle and reshow the dialog.""" self._populate_coordinates() self.canvas.setMapTool(self.previous_map_tool) self.show() def clear(self): """Clear the currently set extent. """ self.tool.reset() self._populate_coordinates() def reject(self): """User rejected the rectangle. """ self.canvas.unsetMapTool(self.tool) if self.previous_map_tool != self.tool: self.canvas.setMapTool(self.previous_map_tool) self.tool.reset() self.extent_selector_closed.emit() super(ExtentSelectorDialog, self).reject() def accept(self): """User accepted the rectangle. """ self.canvas.unsetMapTool(self.tool) if self.previous_map_tool != self.tool: self.canvas.setMapTool(self.previous_map_tool) if self.tool.rectangle() is not None: LOGGER.info( 'Extent selector setting user extents to %s' % self.tool.rectangle().toString()) self.extent_defined.emit( self.tool.rectangle(), self.canvas.mapRenderer().destinationCrs() ) else: LOGGER.info( 'Extent selector setting user extents to nothing') self.clear_extent.emit() self.tool.reset() self.extent_selector_closed.emit() super(ExtentSelectorDialog, self).accept() def _are_coordinates_valid(self): """ Check if the coordinates are valid. :return: True if coordinates are valid otherwise False. :type: bool """ try: QgsPoint( self.x_minimum.value(), self.y_maximum.value()) QgsPoint( self.x_maximum.value(), self.y_minimum.value()) except ValueError: return False return True def _coordinates_changed(self): """ Handle a change in the coordinate input boxes. """ if self._are_coordinates_valid(): point1 = QgsPoint( self.x_minimum.value(), self.y_maximum.value()) point2 = QgsPoint( self.x_maximum.value(), self.y_minimum.value()) rect = QgsRectangle(point1, point2) self.tool.set_rectangle(rect) def _populate_coordinates(self): """ Update the UI with the current active coordinates. """ rect = self.tool.rectangle() self.blockSignals(True) if rect is not None: self.x_minimum.setValue(rect.xMinimum()) self.y_minimum.setValue(rect.yMinimum()) self.x_maximum.setValue(rect.xMaximum()) self.y_maximum.setValue(rect.yMaximum()) else: self.x_minimum.clear() self.y_minimum.clear() self.x_maximum.clear() self.y_maximum.clear() self.blockSignals(False) def bookmarks_index_changed(self): """Update the UI when the bookmarks combobox has changed. """ index = self.comboBox_bookmarks_list.currentIndex() if index >= 0: self.tool.reset() rectangle = self.comboBox_bookmarks_list.itemData(index) self.tool.set_rectangle(rectangle) self.canvas.setExtent(rectangle) self.ok_button.setEnabled(True) else: self.ok_button.setDisabled(True) def on_checkBox_use_bookmark_toggled(self, use_bookmark): """Update the UI when the user toggles the bookmarks checkbox. :param use_bookmark: The status of the checkbox. :type use_bookmark: bool """ if use_bookmark: self.bookmarks_index_changed() self.groupBox_coordinates.setDisabled(True) else: self.groupBox_coordinates.setEnabled(True) self.ok_button.setEnabled(True) self._populate_coordinates() def _populate_bookmarks_list(self): """Read the sqlite database and populate the bookmarks list. Every bookmark are reprojected to mapcanvas crs. """ # Connect to the QGIS sqlite database and check if the table exists. db_file_path = QgsApplication.qgisUserDbFilePath() db = sqlite3.connect(db_file_path) cursor = db.cursor() cursor.execute( 'SELECT COUNT(*) ' 'FROM sqlite_master ' 'WHERE type=\'table\' ' 'AND name=\'tbl_bookmarks\';') number_of_rows = cursor.fetchone()[0] if number_of_rows > 0: cursor.execute( 'SELECT * ' 'FROM tbl_bookmarks;') bookmarks = cursor.fetchall() canvas_srid = self.canvas.mapRenderer().destinationCrs().srsid() for bookmark in bookmarks: name = bookmark[1] srid = bookmark[7] rectangle = QgsRectangle( bookmark[3], bookmark[4], bookmark[5], bookmark[6]) if srid != canvas_srid: transform = QgsCoordinateTransform( srid, canvas_srid) rectangle = transform.transform(rectangle) if rectangle.isEmpty(): pass self.comboBox_bookmarks_list.addItem(name, rectangle)
+"&pPointIndexingMaxDist=25"\ +"&pOutputPathFlag=FALSE"\ +"&pReturnFlowlineGeomFlag=FALSE"\ +"&optNHDPlusDataset=2.1" #Call the EPA Waters point service using the qgis lat long coordinates clicked #print url response = json.loads(urllib2.urlopen(url).read()) if response['output']: results = response['output']['ary_flowlines'] showText = x+' , '+y + '\nFound %d results:\n'%len(results) showText = showText+'comid = %d\nfmeasure = %d'%(results[0]['comid'],results[0]['fmeasure']) #Return the comid and fmeasure found by the point service ret = (results[0]['comid'], results[0]['fmeasure']) self.finished.emit(True, ret) else: showText = 'No features found at %s, %s'%(x,y) self.finished.emit(False, ret) #Send out status message self.status.emit(showText) except Exception, e: import traceback self.error.emit(e, traceback.format_exc()) self.status.emit("Error in Point Service Thread") #print e, traceback.format_exc() self.finished.emit(False, ret) status = pyqtSignal(str) error = pyqtSignal(Exception, basestring) finished = pyqtSignal(bool, tuple)
def getSignalQuality(self): linkQualityValue = None linkQualitySignal = pyqtSignal(int) # Connect link quality feedback self.cf.linkQuality.add_callback(self.linkQualitySignal.emit)