def test_constructor_with_dom(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) qdn.appendChild(kds[-1]) ci = ComponentItem(qdn) self.assertEqual(ci.parent, None) self.assertEqual(ci.node, qdn) self.assertEqual(ci.childNumber(), 0) self.assertEqual(ci.node.nodeName(), nname) for k in range(nkids): self.assertTrue(isinstance(ci.child(k), ComponentItem)) self.assertTrue(isinstance(ci.child(k).parent, ComponentItem)) self.assertEqual(ci.child(k).childNumber(), k) self.assertEqual(ci.child(k).node, kds[k]) self.assertEqual(ci.child(k).parent.node, qdn) self.assertEqual(ci.child(k).node.nodeName(), "kid%s" % k) self.assertEqual(ci.child(k).parent, ci)
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())
def setDataSource( self, newSourceUri): ''' Method to apply a new datasource to a vector Layer ''' layer = self.layer newDS, newUri = self.splitSource(newSourceUri) newDatasourceType = newDS or layer.dataProvider().name() # read layer definition XMLDocument = QDomDocument("style") XMLMapLayers = QDomElement() XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = QDomElement() XMLMapLayer = XMLDocument.createElement("maplayer") layer.writeLayerXML(XMLMapLayer,XMLDocument) # apply layer definition XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue(newUri) XMLMapLayer.firstChildElement("provider").firstChild().setNodeValue(newDatasourceType) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) layer.readLayerXML(XMLMapLayer) # Update layer extent layer.updateExtents() # Update graduated symbol renderer if layer.rendererV2().type() == u'graduatedSymbol': if len(layer.rendererV2().ranges()) == 1: layer.rendererV2().updateClasses( layer, layer.rendererV2().mode(), len(layer.rendererV2().ranges()) ) #Reload layer layer.reload()
def savePluginInfo(self, xmlfile=None): ''' write plugin info to xml (plugin active/inactive ...) xmlfile: specifies alternative path to xml file with plugin information (default: plugins/plugins.xml) ''' #create xml Xml = QDomDocument("xmldoc") rootNode = Xml.createElement("SysCDbgActivePlugins") Xml.appendChild(rootNode) for i in range(self.pluginActions.__len__()): pluginNode = Xml.createElement("plugin") pluginNode.setAttribute("path", self.pluginActions[i].path) if self.pluginActions[i].isChecked(): pluginNode.setAttribute("active", "y") else: pluginNode.setAttribute("active", "n") rootNode.appendChild(pluginNode) #create and write xml file fname = self.xmlFile if xmlfile != None: fname = xmlfile if fname.endswith(".xml") == False: fname += ".xml" fileObject = QFile(fname) fileObject.open(QIODevice.WriteOnly) fileObject.writeData(Xml.toString()) fileObject.close()
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())
def bodystructureToXml(bodystructure): parts = parse_bodystructure(bodystructure) alt_partnum = '.' doc = QDomDocument() root = doc.createElement('body') doc.appendChild(root) for part_num, text in parts: if text.startswith('MULTIPART/'): if text == 'MULTIPART/ALTERNATIVE': alt_part = doc.createElement('alternative') root.appendChild(alt_part) alt_partnum = part_num else: part_type, encoding, size, filename = parse_nonmultipart(text) item = doc.createElement('part') item.setAttribute('PartNum', part_num) item.setAttribute('type', part_type) item.setAttribute('encoding', encoding) if part_num.startswith(alt_partnum) and part_type.startswith('text/'): alt_part.appendChild(item) else: item.setAttribute('filename', filename) item.setAttribute('size', size) root.appendChild(item) return doc
def getDomDef(self, layer): XMLDocument = QDomDocument("undo-layer") XMLMapLayers = QDomElement() XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = QDomElement() XMLMapLayer = XMLDocument.createElement("maplayer") layer.writeLayerXML(XMLMapLayer, XMLDocument) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) return XMLMapLayer
def test_data_name_attr_true(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] tkds = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) kds[-1].setAttribute("name", "myname%s" % n) kds[-1].setAttribute("type", "mytype%s" % n) kds[-1].setAttribute("units", "myunits%s" % n) qdn.appendChild(kds[-1]) tkds.append(doc.createTextNode("\nText\n %s\n" % n)) kds[-1].appendChild(tkds[-1]) # print doc.toString() allAttr = True cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) self.assertEqual(cm.headerData(0, Qt.Vertical), None) ri = cm.rootIndex di = cm.index(0, 0, ri) ci = cd.child(0) for n in range(nkids): kd = ci.child(n) ki0 = cm.index(n, 0, di) dt = cm.data(ki0) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), 'kid%s: myname%s' % (n, n)) ki1 = cm.index(n, 1, di) dt = cm.data(ki1) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual( str(dt.toString()).strip(), 'units="myunits%s" type="mytype%s" name="myname%s"' % (n, n, n)) ki2 = cm.index(n, 2, di) dt = cm.data(ki2) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(str(dt.toString()).strip(), '')
def method_30(self): filePath = define.appPath + "/Resource/settingData/phxtemplates.xml" fileInfo = QFileInfo(filePath) if fileInfo.exists(): QFile.remove(filePath) doc = QDomDocument() rootElem = doc.createElement("Templates") xmlDeclaration = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"utf-8\"") doc.appendChild(xmlDeclaration) for i in range(self.parametersPanel.gridModel.rowCount()): elem = doc.createElement( "Templates" + self.parametersPanel.gridModel.item(i, 0).text()) valueElem = doc.createElement("title") valueElem.appendChild( doc.createTextNode( self.parametersPanel.gridModel.item(i, 0).text())) elem.appendChild(valueElem) valueElem = doc.createElement("space") valueElem.appendChild( doc.createTextNode( self.parametersPanel.gridModel.item(i, 1).text())) elem.appendChild(valueElem) valueElem = doc.createElement("value") valueElem.appendChild( doc.createTextNode( self.parametersPanel.gridModel.item(i, 2).text())) elem.appendChild(valueElem) rootElem.appendChild(elem) doc.appendChild(rootElem) qFile = QFile(filePath) if qFile.open(QFile.WriteOnly): textStream = QTextStream(qFile) doc.save(textStream, 4) qFile.close() # ###CRC file is created. contents = None with open(filePath, 'rb', 0) as tempFile: contents = tempFile.read() tempFile.flush() tempFile.close() bytes = FasDataBlockFile.CRC_Calculation(contents) string_0 = QString(filePath) path = string_0.left(string_0.length() - 3) + "crc" fileStream = open(path, 'wb') fileStream.write(bytes) fileStream.close()
def btnEvaluate_Click(self): #### --------------- Export -------------------### if ProcedureExportDlg.dataBase == None: return filePathDir = QFileDialog.getSaveFileName(self, "Save Data",QCoreApplication.applicationDirPath (),"XML Files (*.xml)") if filePathDir == "": return effectiveDate = ProcedureExportDlg.dataBase.EffectiveDate; resultDlg, effectiveDate = DlgAixmEffectiveDate.smethod_0(effectiveDate) if (not resultDlg): return; xmlDocument = QDomDocument() xmlDeclaration = xmlDocument.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"" ) xmlDocument.appendChild(xmlDeclaration) xmlElement = xmlDocument.createElement("AIXM-update") # xmlAttribute = xmlDocument.createAttribute("xsi") # xmlAttribute.setValue("http://www.w3.org/2001/XMLSchema-instance") xmlElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); xmlElement.setAttribute("xsi:noNamespaceSchemaLocation", "AIXM+Update.xsd"); # xmlAttribute.Value = "AIXM+Update.xsd"; xmlElement.setAttribute("version", "4.5"); xmlElement.setAttribute("origin", "ASAP s.r.o."); strS = QDateTime.currentDateTime().toString("yyyy-MM-dd"); now = QDateTime.currentDateTime(); xmlElement.setAttribute("created", String.Concat([strS, "T", now.toString("hh:mm:ss")])); xmlElement.setAttribute("effective", String.Concat([effectiveDate.toString("yyyy-MM-dd"), "T00:00:00"])); # xmlElement.Attributes.Append(xmlAttribute); xmlDocument.appendChild(xmlElement) xmlElement1 = xmlDocument.createElement("Group"); xmlElement1.setAttribute("Name", "Group 1 of 1"); ProcedureExportDlg.dataBase.ProcedureData.method_61(xmlElement1, self.newProcedurePointsInUse); ProcedureExportDlg.dataBase.ProcedureData.method_62(xmlElement1, ProcedureExportDlg.dataBase.SIDs.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted); ProcedureExportDlg.dataBase.ProcedureData.method_62(xmlElement1, ProcedureExportDlg.dataBase.SIDs.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated); ProcedureExportDlg.dataBase.ProcedureData.method_62(xmlElement1, ProcedureExportDlg.dataBase.SIDs.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created); ProcedureExportDlg.dataBase.ProcedureData.method_63(xmlElement1, ProcedureExportDlg.dataBase.STARs.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted); ProcedureExportDlg.dataBase.ProcedureData.method_63(xmlElement1, ProcedureExportDlg.dataBase.STARs.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated); ProcedureExportDlg.dataBase.ProcedureData.method_63(xmlElement1, ProcedureExportDlg.dataBase.STARs.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created); ProcedureExportDlg.dataBase.ProcedureData.method_64(xmlElement1, ProcedureExportDlg.dataBase.IAPs.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted); ProcedureExportDlg.dataBase.ProcedureData.method_64(xmlElement1, ProcedureExportDlg.dataBase.IAPs.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated); ProcedureExportDlg.dataBase.ProcedureData.method_64(xmlElement1, ProcedureExportDlg.dataBase.IAPs.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created); ProcedureExportDlg.dataBase.ProcedureData.method_65(xmlElement1, ProcedureExportDlg.dataBase.Holdings.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted); ProcedureExportDlg.dataBase.ProcedureData.method_65(xmlElement1, ProcedureExportDlg.dataBase.Holdings.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated); ProcedureExportDlg.dataBase.ProcedureData.method_65(xmlElement1, ProcedureExportDlg.dataBase.Holdings.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created); xmlElement.appendChild(xmlElement1); # xmlDocument.Save(self.sfd.FileName); # base.method_20(string.Format(Messages.X_SUCCESSFULLY_CREATED, self.pnlFile.Value)); qFile = QFile(filePathDir) if qFile.open(QFile.WriteOnly): textStream = QTextStream(qFile) xmlDocument.save(textStream, 4) qFile.close() else: raise UserWarning, "can not open file:" + filePathDir
class TestView(object): def __init__(self): try: self.__seed = long(binascii.hexlify(os.urandom(16)), 16) except NotImplementedError: self.__seed = long(time.time() * 256) # self.__seed = 71366247078680776091931824685320965500 self.__rnd = random.Random(self.__seed) print "VIEW SEED", self.__seed self.sindex = None self.eindex = None self.doc = QDomDocument() self.nname = "definition" self.qdn = self.doc.createElement(self.nname) self.doc.appendChild(self.qdn) self.nkids = self.__rnd.randint(1, 10) # print "NKID", self.nkids self.kds = [] self.tkds = [] for n in range(self.nkids): self.kds.append(self.doc.createElement("kid%s" % n)) self.kds[-1].setAttribute("name", "myname%s" % n) self.kds[-1].setAttribute("type", "mytype%s" % n) self.kds[-1].setAttribute("units", "myunits%s" % n) self.qdn.appendChild(self.kds[-1]) self.tkds.append(self.doc.createTextNode("\nText\n %s\n" % n)) self.kds[-1].appendChild(self.tkds[-1]) # print doc.toString() self.allAttr = False self.testModel = ComponentModel(self.doc, self.allAttr) # self.myindex = self.setIndex(0, 0, self.testModel.rootIndex) self.myindex = QModelIndex() def setIndex(self, row, column, parent): self.myindex = self.testModel.index(row, column, parent) # print self.myindex.column() def currentIndex(self): return self.myindex def model(self): return self.testModel def dataChanged(self, sindex, eindex): self.sindex = sindex self.eindex = eindex
def test_constructor_with_dom_nested_reverse(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] gkds = [] ngks = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) qdn.appendChild(kds[-1]) ngkids = self.__rnd.randint(1, 10) gkds.append([]) ngks.append(ngkids) for g in range(ngkids): gkds[n].append(doc.createElement("grandkid%s" % g)) kds[-1].appendChild(gkds[n][-1]) # print doc.toString() ci = ComponentItem(qdn) self.assertEqual(ci.parent, None) self.assertEqual(ci.node, qdn) self.assertEqual(ci.childNumber(), 0) self.assertEqual(ci.node.nodeName(), nname) for k in reversed(range(nkids)): ks = ci.child(k) self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, kds[k]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "kid%s" % k) self.assertEqual(ks.parent, ci) for g in range(ngks[k]): self.assertTrue(isinstance(ks.child(g), ComponentItem)) self.assertTrue(isinstance(ks.child(g).parent, ComponentItem)) self.assertEqual(ks.child(g).childNumber(), g) self.assertEqual(ks.child(g).node, gkds[k][g]) self.assertEqual(ks.child(g).parent.node, ks.node) self.assertEqual(ks.child(g).node.nodeName(), "grandkid%s" % g) self.assertEqual(ks.child(g).parent, ks) self.assertEqual(ks.child(ngks[k]), None) self.assertEqual(ks.child(-1), None) self.assertEqual(ci.child(nkids), None) self.assertEqual(ci.child(-1), None)
def on_pushButton_4_clicked(self): # 我们先清空显示,然后显示“无法添加!”,这样如果添加失败则会显示“无法添加!” self.listWidget.clear() self.listWidget.addItem(QString("无法添加!")) file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open my.xml Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if not status: file.close() raise Exception(str(rrorMsg)) file.close() root = doc.documentElement() # 获取根元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() # 我们获得了最后一个孩子结点的编号,然后加1,便是新的编号 num = root.lastChild().toElement().attribute(QString("编号")) count = num.toInt() + 1 id.setValue(QString.number(count)) book.setAttributeNode(id) text = doc.createTextNode(self.lineEdit_2.text()) title.appendChild(text) text = doc.createTextNode(self.lineEdit_3.text()) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("file open Err") out = QTextStream(file) doc.save(out, 4) file.close() # 最后更改显示为“添加成功!” self.listWidget.clear() self.listWidget.addItem(QString("添加成功!"))
def getSymbology(source): di = QDomImplementation() documentType = di.createDocumentType('qgis', 'http://mrcc.com/qgis.dtd', 'SYSTEM') doc = QDomDocument(documentType) rootNode = doc.createElement('qgis') rootNode.setAttribute('version', str(QGis.QGIS_VERSION)) doc.appendChild(rootNode) source.writeSymbology(rootNode, doc, '') return rootNode
def getSymbology(source): di = QDomImplementation() documentType = di.createDocumentType('qgis', 'http://mrcc.com/qgis.dtd', 'SYSTEM') doc = QDomDocument(documentType) rootNode = doc.createElement('qgis') rootNode.setAttribute('version', str(QGis.QGIS_VERSION)) doc.appendChild(rootNode) source.writeSymbology(rootNode, doc, '') return rootNode
def ODKout(self, currentLayer): if not currentLayer: if self.iface.legendInterface().currentLayer(): currentLayer = self.iface.legendInterface().currentLayer() self.dlg.setWindowTitle("QGISODK - " + currentLayer.name()) else: return if currentLayer.type() != QgsMapLayer.VectorLayer: return currentFormConfig = currentLayer.editFormConfig() XMLDocument = QDomDocument("QGISFormConfig") XMLFormDef = XMLDocument.createElement("FORM") currentFormConfig.writeXml(XMLFormDef) XMLDocument.appendChild(XMLFormDef) fieldsModel = [] for i in range(0, len(currentLayer.pendingFields())): fieldDef = {} fieldDef['fieldName'] = currentLayer.pendingFields()[i].name() fieldDef['fieldMap'] = currentLayer.pendingFields()[i].name() fieldDef['fieldLabel'] = currentLayer.pendingFields()[i].comment() fieldDef['fieldHint'] = '' fieldDef['fieldType'] = currentLayer.pendingFields()[i].type() fieldDef['fieldEnabled'] = True fieldDef['fieldRequired'] = None fieldDef['fieldDefault'] = '' fieldDef['fieldWidget'] = currentFormConfig.widgetType(i) if fieldDef['fieldWidget'] == 'Hidden': fieldDef['fieldEnabled'] = None else: fieldDef['fieldEnabled'] = True if fieldDef['fieldWidget'] in ('ValueMap', 'ValueRelation', 'CheckBox', 'Photo', 'FileName'): if fieldDef['fieldWidget'] == 'ValueMap': config = { v: k for k, v in currentFormConfig.widgetConfig( i).iteritems() } elif fieldDef['fieldWidget'] == 'ValueRelation': relation_layer = QgsMapLayerRegistry.instance().mapLayer( currentFormConfig.widgetConfig(i)['Layer']) config = {} for feature in relation_layer.getFeatures(): if feature[currentFormConfig.widgetConfig(i)['Key']]: config[feature[currentFormConfig.widgetConfig(i) ['Key']]] = feature[ currentFormConfig.widgetConfig( i)['Value']] or '' else: config = currentFormConfig.widgetConfig(i) fieldDef['fieldChoices'] = config else: fieldDef['fieldChoices'] = {} fieldsModel.append(fieldDef) self.dlg.treeView.setFieldModel(currentLayer, fieldsModel)
def saveMailInfo(self): if self.total_mails != self.mailsTable.rowCount(): return if self.total_mails == 0 : return # Cache mails in xml file doc = QDomDocument() root = doc.createElement('mails') doc.appendChild(root) for i in range(self.mailsTable.rowCount()): item = self.mailsTable.cellWidget(i,0) mail = doc.createElement('mail') mail.setAttribute('UID', item.uid) mail.setAttribute('Message-ID', item.msg_id) mail.setAttribute('Sender', item.sender) mail.setAttribute('Subject', unicode(item.subject).encode('utf8')) mail.setAttribute('Date', item.date) mail.setAttribute('Cached', item.cached) root.appendChild(mail) mailbox_file = ACNT_DIR + self.email_id + '/%s.xml'%self.mailbox[:].replace('/', '_') with open(mailbox_file, 'w') as doc_file: doc_file.write(doc.toString())
def test_data(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) qdn.appendChild(kds[-1]) allAttr = False cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) self.assertEqual(cm.headerData(0, Qt.Vertical), None) dt = cm.data(QModelIndex()) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '') for role in range(1, 5): dt = cm.data(cm.rootIndex, role) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '') dt = cm.data(cm.rootIndex) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '#document') dt = cm.data(cm.rootIndex, Qt.DisplayRole) self.assertTrue(isinstance(dt, QVariant)) self.assertEqual(dt.toString(), '#document')
def test_constructor(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 10) kds = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) qdn.appendChild(kds[-1]) allAttr = False cm = ComponentModel(doc, allAttr) self.assertTrue(isinstance(cm, QAbstractItemModel)) self.assertTrue(isinstance(cm.rootIndex, QModelIndex)) cd = cm.rootIndex.internalPointer() self.assertTrue(isinstance(cd, ComponentItem)) self.assertEqual(cm.rootIndex.row(), 0) self.assertEqual(cm.rootIndex.column(), 0) self.assertEqual(cd.parent, None) self.assertEqual(cd.childNumber(), 0) self.assertEqual(cd.node.nodeName(), "#document") ci = cd.child(0) self.assertEqual(ci.parent, cd) self.assertEqual(ci.node, qdn) self.assertEqual(ci.childNumber(), 0) self.assertEqual(ci.node.nodeName(), nname) for k in range(nkids): self.assertTrue(isinstance(ci.child(k), ComponentItem)) self.assertTrue(isinstance(ci.child(k).parent, ComponentItem)) self.assertEqual(ci.child(k).childNumber(), k) self.assertEqual(ci.child(k).node, kds[k]) self.assertEqual(ci.child(k).parent.node, qdn) self.assertEqual(ci.child(k).node.nodeName(), "kid%s" % k) self.assertEqual(ci.child(k).parent, ci)
def __init__(self): super(MainWindow, self).__init__(None) uic.loadUi("./mainwindow.ui", self) doc = QDomDocument() # 添加处理指令即XML说明 instruction = QDomProcessingInstruction() instruction = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\"") doc.appendChild(instruction) # 添加根元素 root = doc.createElement(QString("书库")) doc.appendChild(root) # 添加根元素 # 添加第一个图书元素及其子元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) text = QDomText() id.setValue(QString("1")) book.setAttributeNode(id) text = doc.createTextNode(QString("Qt")) title.appendChild(text) text = doc.createTextNode(QString("shiming")) author.appendChild(text) book.appendChild(title) # 图书元素 添加 书名元素 book.appendChild(author) # 图书元素 添加 作者元素 root.appendChild(book) # 根元素 添加 图书元素 # 添加第二个图书元素及其子元素 book = doc.createElement(QString("图书")) id = doc.createAttribute(QString("编号")) title = doc.createElement(QString("书名")) author = doc.createElement(QString("作者")) id.setValue(QString("2")) book.setAttributeNode(id) text = doc.createTextNode(QString("Linux")) title.appendChild(text) text = doc.createTextNode(QString("yafei")) author.appendChild(text) book.appendChild(title) book.appendChild(author) root.appendChild(book) file = QFile("my.xml") if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)): raise Exception("open my.xml Err") out = QTextStream(file) doc.save(out, 4) # 将文档保存到文件,4为子元素缩进字符数 file.close()
def layer_style_to_xml(self,qgis_layer): ''' saves qgis style to the setting sheet :param qgis_layer: :return: ''' XMLDocument = QDomDocument("qgis_style") XMLStyleNode = XMLDocument.createElement("style") XMLDocument.appendChild(XMLStyleNode) error = None qgis_layer.writeSymbology(XMLStyleNode, XMLDocument, error) xmldoc = XMLDocument.toString(1) return xmldoc
def updateSqlLayer(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: layer = self._getSqlLayer(self.filter) if layer == None: return #self.layer.dataProvider().setDataSourceUri(layer.dataProvider().dataSourceUri()) #self.layer.dataProvider().reloadData() XMLDocument = QDomDocument("style") XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = XMLDocument.createElement("maplayer") self.layer.writeLayerXML(XMLMapLayer, XMLDocument) XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue(layer.source()) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) self.layer.readLayerXML(XMLMapLayer) self.layer.reload() self.iface.actionDraw().trigger() self.iface.mapCanvas().refresh() self.iface.legendInterface().refreshLayerSymbology(layer) finally: QApplication.restoreOverrideCursor()
def updateSqlLayer(self): QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: layer = self._getSqlLayer(self.filter) if layer == None: return #self.layer.dataProvider().setDataSourceUri(layer.dataProvider().dataSourceUri()) #self.layer.dataProvider().reloadData() XMLDocument = QDomDocument("style") XMLMapLayers = XMLDocument.createElement("maplayers") XMLMapLayer = XMLDocument.createElement("maplayer") self.layer.writeLayerXML(XMLMapLayer, XMLDocument) XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue(layer.source()) XMLMapLayers.appendChild(XMLMapLayer) XMLDocument.appendChild(XMLMapLayers) self.layer.readLayerXML(XMLMapLayer) self.layer.reload() self.iface.actionDraw().trigger() self.iface.mapCanvas().refresh() self.iface.legendInterface().refreshLayerSymbology(layer) finally: QApplication.restoreOverrideCursor()
def updateProperties(self,itemClicked=None): ''' @summary Create and show a widget that contains the currently selected primitive attributes ''' #Clear the current tab widget containing the properties of the last selected item #Need to create a fake dom document, how shitty if itemClicked: domDocument =QDomDocument() newTmpDomElement = domDocument.createElement(itemClicked.doc.getName()) self.primitive = Primitive(None, None,self, newTmpDomElement) self.rightLayout.removeWidget(self.attributeWidget) self.attributeWidget.deleteLater() self.attributeWidget = QtGui.QWidget() self.attributeWidget.setLayout(self.primitive.guiGetAttrLayout()) self.rightLayout.addWidget(self.attributeWidget)
def savePluginInfo(self): ''' write plugin info to xml (plugin active/inactive ...) xmlfile: specifies alternative path to xml file with plugin information ''' # create xml Xml = QDomDocument("xmldoc") rootNode = Xml.createElement("SysCDbgActivePlugins") Xml.appendChild(rootNode) for i in self.pluginActions.itervalues(): 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 fileObject = QFile(self.xmlFile) fileObject.open(QIODevice.WriteOnly) fileObject.writeData(Xml.toString()) fileObject.close()
def mapCanvas_xml(iface, _): """ Return XML configuration used for map rendering. To obtain a JSON specification of the current map canvas settings, see /qgis/mapCanvas Returns: The XML serialisation of the canvas' QgsMapSettings object. """ # TODO implement POST command doc = QDomDocument('xml') root = doc.createElement('mapcanvas') doc.appendChild(root) iface.mapCanvas().mapSettings().writeXML(root, doc) # QDomDocument is automatically processed by server return NetworkAPIResult(doc)
def save(self, filename): doc = QDomDocument() root = doc.createElement("graph") doc.appendChild(root) items = doc.createElement("items") root.appendChild(items) # Items for index, item in enumerate(self.graph.items()): elem = item.save(doc.createElement("item")) elem.setAttribute("id", index) items.appendChild(elem) # Connections connections = doc.createElement("connections") root.appendChild(connections) for edge in self.graph.edges: connection = doc.createElement("connection") # Source source = doc.createElement("source") source.setAttribute( "id", self.graph.items().index(edge[0].parentObject())) source.setAttribute( "port", edge[0].parentObject().providesPorts.index(edge[0])) connection.appendChild(source) # Target target = doc.createElement("target") target.setAttribute( "id", self.graph.items().index(edge[1].parentObject())) target.setAttribute( "port", edge[1].parentObject().requiresPorts.index(edge[1])) connection.appendChild(target) connections.appendChild(connection) # Write f = QFile(filename) f.open(QIODevice.WriteOnly | QIODevice.Text) stream = QTextStream(f) stream << doc.toString() f.close() self.setModified(False)
def mapLayer_xml(_, request): """ Retrieve information about the layer with the given id. HTTP query arguments: id (string): ID of layer whose definition to retrieve or set Returns: The XML definition for the layer with the given ID. """ layer = qgis_layer_by_id(request.args['id']) doc = QDomDocument('xml') root = doc.createElement('maplayer') doc.appendChild(root) layer.writeLayerXML(root, doc, '') # QDomDocument is automatically processed by server return NetworkAPIResult(doc)
def saveqlr(self): layer = self.iface.activeLayer() if not layer: return path = QFileDialog.getSaveFileName(self.iface.mainWindow(), "Save as QGIS Layer Definition", QDir.home().path(), "*.qlr") if not path: return doc = QDomDocument("qgis-layer-definition") mapnode = doc.createElement("maplayer") layer.writeLayerXML(mapnode, doc) mapnode.removeChild(mapnode.firstChildElement("id")) doc.appendChild(mapnode) with open(path, "w") as f: f.write(doc.toString())
def testuniqueId(self): doc = QDomDocument() documentElement = doc.createElement('ComposerItemClipboard') self.mComposition.writeXML(documentElement, doc) self.mComposition.addItemsFromXML(documentElement, doc, 0, False) #test if both composer maps have different ids newMap = QgsComposerMap() mapList = self.mComposition.composerMapItems() for mapIt in mapList: if mapIt != self.mComposerMap: newMap = mapIt break oldId = self.mComposerMap.id() newId = newMap.id() self.mComposition.removeComposerItem(newMap) myMessage = 'old: %s new: %s' % (oldId, newId) assert oldId != newId, myMessage
def testuniqueId(self): doc = QDomDocument() documentElement = doc.createElement('ComposerItemClipboard') self.mComposition.writeXML(documentElement, doc) self.mComposition.addItemsFromXML(documentElement, doc, 0, False) #test if both composer maps have different ids newMap = QgsComposerMap() mapList = self.mComposition.composerMapItems() for mapIt in mapList: if mapIt != self.mComposerMap: newMap = mapIt break oldId = self.mComposerMap.id() newId = newMap.id() self.mComposition.removeComposerItem(newMap) myMessage = 'old: %s new: %s' % (oldId, newId) assert oldId != newId, myMessage
def exportToXml(self, fn): from PyQt4.QtXml import QDomDocument doc = QDomDocument(self.XML_TRANSF_DOC) instr = doc.createProcessingInstruction( "xml", "version=\"1.0\" encoding=\"UTF-8\" ") doc.appendChild(instr) root = doc.createElement(self.XML_TRANSF_LIST_TAG) doc.appendChild(root) for t in Transformation.getAll(): root.appendChild(t._toNode(doc)) f = QFile(fn) if not f.open(QIODevice.WriteOnly): return False xmlStream = QTextStream(f) xmlStream.setCodec(QTextCodec.codecForName("UTF-8")) xmlStream << doc.toString() return True
def save(self): """ Save template list to file. """ self._logger.debug("Saving template list to disk") document = QDomDocument("LumaTemplateFile") root = document.createElement( "LumaTemplates" ) document.appendChild(root) for x in self._templateList: templateNode = document.createElement("template") templateNode.setAttribute("name", x.templateName) templateNode.setAttribute("server", x.server) templateNode.setAttribute("description", x.description) templateClasses = document.createElement("objectClasses") for y in x.objectclasses: classNode = document.createElement(y) templateClasses.appendChild(classNode) templateNode.appendChild(templateClasses) templateAttributes = document.createElement("attributes") for y in x.attributes.keys(): attribute = x.attributes[y] attributeNode = document.createElement(attribute.attributeName) attributeNode.setAttribute("must", str(attribute.must)) attributeNode.setAttribute("customMust", str(attribute.customMust)) attributeNode.setAttribute("single", str(attribute.single)) attributeNode.setAttribute("binary", str(attribute.binary)) if not attribute.defaultValue == None and len(attribute.defaultValue): attributeNode.setAttribute("defaultValue", unicode(attribute.defaultValue)) templateAttributes.appendChild(attributeNode) templateNode.appendChild(templateAttributes) root.appendChild(templateNode) fileHandler = open(self._configFile, "w") fileHandler.write(unicode(document.toString()).encode("utf-8")) fileHandler.close()
class XFORMDocument: """ class to generate an Xml file that is needed for data collection using mobile device. The class creates the file and QDOM sections for holding data once the file is called """ def __init__(self, fname): """ Initalize the class so that we have a new file everytime document generation method is called """ self.dt_text = QDate() self.file_handler = FilePaths() self.doc = QDomDocument() self.form = None self.fname = fname self.doc_with_entities = [] self.supports_doc = self.document() def document(self): """ use the globally defined Document name for supporting document :return: """ global DOCUMENT return DOCUMENT def form_name(self): """ Format the name for the new file to be created. We need to ensure it is .xml file. :return: """ if len(self.fname.split(".")) > 1: return self.fname else: return self.fname+"{}".format(DOCEXTENSION) def set_form_name(self, local_name): """ Allow the user to update the name of the file. This method will be called to return a new file with the local_name given :param local_name: string :return: QFile """ self.fname = local_name+"{}".format(DOCEXTENSION) self.form.setFileName(self.fname) self.create_form() return self.fname def create_form(self): """ Create an XML file that will be our XFORM Document for reading and writing We want a new file when everytime we are creating XForm type: file :return: file """ self.form = QFile(os.path.join(FORM_HOME, self.form_name())) if not QFileInfo(self.form).suffix() == DOCEXTENSION: self.form_name() if not self.form.open(QIODevice.ReadWrite | QIODevice.Truncate | QIODevice.Text): return self.form.OpenError def create_node(self, name): """ Create a XML element node :param name: :return: node :rtype: QelementNode """ return self.doc.createElement(name) def create_text_node(self, text): """ Create an XML text node :param text: :return: """ return self.doc.createTextNode(text) def create_node_attribute(self, node, key, value): """ Create an attribute and attach it to the node :param node: Qnode :param key: Qnode name :param value: Qnode value :return: QNode """ return node.setAttribute(key, value) def xform_document(self): """ :return: QDomDocument """ return self.doc def write_to_form(self): """ Write data to xml file from the base calling class to an output file created earlier :return: """ if isinstance(self.form, QFile): self.form.write(self.doc.toByteArray()) self.form.close() self.doc.clear() else: return None def update_form_data(self): """ Update the xml file with changes that the user has made. Particular section of the document will be deleted or added :return: """ pass
class UiInspector: def __init__(self): self.ui_dir = os.path.abspath ( os.path.join( os.path.dirname(__file__), '../src/ui/*.ui' ) ) self.printMsg ( "Loading UI files " + self.ui_dir ) # list of widget classes we want to follow self.follow = [ QWidget, QDialog, QCheckBox, QComboBox, QDial, QPushButton, QLabel, QLCDNumber, QLineEdit, QRadioButton, QScrollBar, QSlider, QSpinBox, QTextEdit, QDateEdit, QTimeEdit, QDateTimeEdit, QListView, QProgressBar, QTableView, QTabWidget, QTextBrowser, QDialogButtonBox, QScrollArea, QGroupBox, QStackedWidget, ] def printMsg ( self, msg ): sys.stderr.write( msg + "\n" ) def widgetXml(self, element, widget, level=0, label=None ): #print tostring ( element ) #self.printMsg ( "class: " + str( type ( widget ) ) ) #self.printMsg ( "objectName: " + widget.objectName() ) #self.printMsg ( "windowTitle: " + widget.windowTitle() ) if not widget.objectName(): return lab = label if hasattr( widget, 'text' ): lab = widget.text() if widget.windowTitle(): label = widget.windowTitle() if not lab: lab = '' subElement = self.doc.createElement('widget') subElement.setAttribute('class', widget.__class__.__name__ ) subElement.setAttribute('objectName', widget.objectName() ) subElement.setAttribute('label', lab ) element.appendChild( subElement ) #print str ( widget.children () ) # tab widget label is stored in QTabWidget->QTabBarPrivate->tabList->QTab .. if type(widget) in [ QTabWidget ]: children = list ( { 'widget': widget.widget(i), 'label': widget.tabText(i) } for i in range ( 0, widget.count() ) ) else: children = list ( { 'widget': c, 'label': None } for c in widget.children () ) for child in children: w = child['widget'] if w.isWidgetType() and ( type(w) in self.follow ): self.widgetXml( subElement, w, level+1, child['label'] ) def xml(self) : self.doc = QDomDocument() element = self.doc.createElement( "qgiswidgets" ) self.doc.appendChild( element ) for p in glob.glob( self.ui_dir ): self.printMsg ( "Loading " + p ) # qgsrasterlayerpropertiesbase.ui is giving: No module named qwt_plot try: widget = loadUi ( p ) #print dir ( ui ) self.widgetXml( element, widget ) except Exception, e: #except IOError, e: self.printMsg( str(e) ) return self.doc.toString( 2 )
def WriteProjectInfoXml(self): doc = QDomDocument() rootElem = doc.createElement("ProjectListClass") xmlDeclaration = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"") doc.appendChild(xmlDeclaration) elem = doc.createElement("ProjectCount") elem.appendChild(doc.createTextNode(str(len(self.ProjectsList)))) rootElem.appendChild(elem) for i in range(len(self.ProjectsList)): elem = doc.createElement("ProjectInfo") objNameElem = doc.createElement("Name") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Name)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Path") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Path)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Created") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Created)) elem.appendChild(objNameElem) objNameElem = doc.createElement("ProcedureName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].ProcedureName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("ProjName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].ProjName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("Pt") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].Pt)) elem.appendChild(objNameElem) objNameElem = doc.createElement("SubProjName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].SubProjName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("UserName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].UserName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("WorkspaceName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].WorkspaceName)) elem.appendChild(objNameElem) objNameElem = doc.createElement("FullName") objNameElem.appendChild(doc.createTextNode(self.ProjectsList[i].FullName)) elem.appendChild(objNameElem) rootElem.appendChild(elem) doc.appendChild(rootElem) qFile = QFile(self.m_strProjectInfoFullName) if qFile.open(QFile.WriteOnly): textStream = QTextStream(qFile) doc.save(textStream, 4) qFile.close() # ###CRC file is created. with open(self.m_strProjectInfoFullName, 'rb', 0) as tempFile: contents = tempFile.read() tempFile.flush() tempFile.close() bytes = FasDataBlockFile.CRC_Calculation(contents) string_0 = QString(self.m_strProjectInfoFullName) path = string_0.left(string_0.length() - 3) + "crc" fileStream = open(path, 'wb') fileStream.write(bytes) fileStream.close() else: raise UserWarning, "can not open file:" + self.m_strProjectInfoFullName
class demoFileEditor(QtGui.QDialog): ''' This class is an independent dialog used to create and edit demography files ''' def __init__(self, parent,loadFileAtStartup = True ): ''' @summary Constructor @param parent : application's main window @param loadFileAtStartup : Create or open a file at startup ''' QtGui.QDialog.__init__(self,None,QtCore.Qt.Window) self.parent = parent self.setupUi() self.setWindowTitle("Demography File Editor") self.demoFile = None self.domDocument = None if not loadFileAtStartup: self.domDocument = QDomDocument() newDemoElement = self.domDocument.createElement("Demography") self.domDocument.appendChild(newDemoElement) demoPopModel = SimplePopModel(SimpleBaseVarModel(self.parent,self.domDocument.firstChild()),self.parent) self.tableView.setModel(demoPopModel) self.tableView.setItemDelegate(SimpleVarDelegate(self.tableView,self.parent)) else: self.open() def setupUi(self): self.setObjectName("Form") #Dialog buttons self.buttonBox = QtGui.QDialogButtonBox() self.buttonBox.setFixedWidth(200) self.buttonBox.setFixedHeight(30) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok ) self.buttonBox.setObjectName("buttonBox") #Creating and setting the layouts self.mainLayout = QtGui.QVBoxLayout() self.layoutLabel = QtGui.QHBoxLayout() self.layoutButtons = QtGui.QHBoxLayout() self.mainLayout.addLayout(self.layoutLabel) self.tableView = QtGui.QTableView() self.mainLayout.addWidget(self.tableView) self.mainLayout.addLayout(self.layoutButtons) self.mainLayout.addSpacing(50) self.mainLayout.addWidget(self.buttonBox) self.mainLayout.setAlignment(self.buttonBox, QtCore.Qt.AlignRight) #Now that main layout is all set up, populate horizontal layouts self.label = QtGui.QLabel() self.label.setObjectName("label") font = QtGui.QFont() font.setWeight(75) font.setBold(True) self.label.setFont(font) self.label.setText("Demography From File : ") self.label2 = QtGui.QLabel() self.label2.setObjectName("label2") self.label2.setFont(font) self.label2.setText("") self.pushButton_Load= QtGui.QPushButton("Load Demography") self.pushButton_Load.setFixedHeight(26) self.pushButton_Load.setFixedWidth(150) self.layoutLabel.addWidget(self.label) self.layoutLabel.addWidget(self.label2) self.layoutLabel.addWidget(self.pushButton_Load) self.layoutLabel.addItem(QtGui.QSpacerItem(100, 30, QtGui.QSizePolicy.Expanding)) self.pushButton_Add= QtGui.QPushButton("Add variable") self.pushButton_Add.setFixedHeight(26) self.pushButton_Add.setFixedWidth(150) self.pushButton_Delete= QtGui.QPushButton("Delete variable") self.pushButton_Delete.setFixedHeight(26) self.pushButton_Delete.setFixedWidth(150) self.layoutButtons.addWidget(self.pushButton_Add) self.layoutButtons.addWidget(self.pushButton_Delete) self.layoutButtons.addItem(QtGui.QSpacerItem(100, 30, QtGui.QSizePolicy.Expanding)) #Layout look and feel self.mainLayout.setMargin(50) self.layoutLabel.setSpacing(10) self.layoutButtons.setSpacing(10) self.setLayout(self.mainLayout) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), self.lookForAccept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), self.reject) QtCore.QObject.connect(self.pushButton_Load, QtCore.SIGNAL("clicked()"), self.load) QtCore.QObject.connect(self.pushButton_Add, QtCore.SIGNAL("clicked()"), self.addVar) QtCore.QObject.connect(self.pushButton_Delete, QtCore.SIGNAL("clicked()"), self.deleteVar) def load(self): ''' @summary Load a demography file Save before loading if needed ''' reply = QtGui.QMessageBox.warning(self,"Loading Demography", "Save changes made to the previously loaded file?",QtGui.QMessageBox.Yes|QtGui.QMessageBox.No|QtGui.QMessageBox.Cancel) if reply == QtGui.QMessageBox.Cancel: return elif reply == QtGui.QMessageBox.Yes: if not self.demoFile: if not self.saveAs(): return else: self.save() self.open() def lookForAccept(self): ''' @summary Save and quit ''' mBoxSave = QtGui.QMessageBox( QtGui.QMessageBox.Warning, "Leaving demography file editor", "Save changes made to demography file?",QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel|QtGui.QMessageBox.Save) mBoxSave.button(QtGui.QMessageBox.Save).setText("Save as") reply = mBoxSave.exec_() if reply == QtGui.QMessageBox.Cancel: return elif reply == QtGui.QMessageBox.Ok: if not self.demoFile: if self.saveAs(): self.accept() else: self.save() self.accept() elif reply == QtGui.QMessageBox.Save: if self.saveAs(): self.accept() def open(self): ''' summary Open an existing demography file ''' demoPath = QtGui.QFileDialog.getOpenFileName(self, self.tr("Choose a demography to edit"), "./database", self.tr("XML files (*.xml);;All files (*);;")) if not demoPath: #User pressed cancel #If at startup and no model has been created yet if not self.tableView.model(): self.domDocument = QDomDocument() newDemoElement = self.domDocument.createElement("Demography") self.domDocument.appendChild(newDemoElement) demoPopModel = SimplePopModel(SimpleBaseVarModel(self.parent,self.domDocument.firstChild()),self.parent) self.tableView.setModel(demoPopModel) self.tableView.setItemDelegate(SimpleVarDelegate(self.tableView,self.parent)) return if demoPath.split(".")[-1] != "xml": #Non XMl-File edition is not allowed for the moment QtGui.QMessageBox.Warning(self,"Open File", "Non-Xml Files cannot be open for the moment",QtGui.QMessageBox.Ok) return else: f = Opener(demoPath) self.domDocument = f.getDomDocument() root_node = f.getRootNode() if root_node.nodeName() != "Demography": QtGui.QMessageBox.Warning(self,"Open File", "File "+demoPath+" is not a demography file!", QtGui.QMessageBox.Ok) return else: self.demoFile = demoPath demoPopModel = SimplePopModel(SimpleBaseVarModel(self.parent,root_node),self.parent) self.tableView.setModel(demoPopModel) self.tableView.setItemDelegate(SimpleVarDelegate(self.tableView,self.parent)) self.label2.setText(self.demoFile.rsplit("/")[-1]) def save(self): ''' @summary Save a demography file ''' tmpTextStream = QtCore.QTextStream() fileP = QtCore.QFile(self.demoFile) if fileP.open(QtCore.QIODevice.ReadWrite| QtCore.QIODevice.Truncate): tmpTextStream.setDevice(fileP) self.domDocument.save(tmpTextStream, 5) else: print("Could not open file :", self.demoFile) print("Error code :", fileP.error()) fileP.close() def saveAs(self): ''' @summary Save as a new demography file ''' self.demoFile = QtGui.QFileDialog.getSaveFileName(self, self.tr("Save demography file"), "./database", self.tr("XML files (*.xml);;All files (*);;")) if self.demoFile: if self.demoFile[-4:] != ".xml": self.demoFile += ".xml" self.save() return True return False def addVar(self): ''' @summary Adds a variable to the demography ''' if self.tableView.model(): index = self.tableView.currentIndex() if index.isValid(): self.tableView.model().insertRow(index.row()) else: self.tableView.model().insertRow(self.tableView.model().rowCount()) def deleteVar(self): ''' @summary Removes a variable from the demography ''' if self.tableView.model(): index = self.tableView.currentIndex() if index.isValid(): self.tableView.model().removeRow(index.row())
class XmlHandler(): ''' Handler used to save session info to an xml file. ''' def __init__(self, distributedObjects, rootname): self.Xml = QDomDocument("xmldoc") self.rootname = rootname self.rootNode = QDomElement() self.clear() def createNode(self, nodeName, parentNode=None, withAttribs={}): ''' Create and insert node @param nodeName: String representing name of node @param parentNode: QDomElement representing parent node. Root will be parent if this is None @param withAttribs: dict with node attributes @return node on success, None on error ''' if isinstance(nodeName, str) and len(nodeName) != 0: node = self.Xml.createElement(nodeName) if isinstance(withAttribs, dict) and withAttribs != {}: for key, value in withAttribs.items(): node.setAttribute(key, value) if parentNode == None: self.rootNode.appendChild(node) else: if isinstance(parentNode, QDomElement): parentNode.appendChild(node) return node return None def getNode(self, nodeName, parent=None): ''' Get first xml node by name @return QDomElement ''' if isinstance(nodeName, str) and len(nodeName) != 0: if parent == None or not isinstance(parent, QDomNode): return self.rootNode.firstChildElement(nodeName) else: return parent.firstChildElement(nodeName) def getAttributes(self, node): ''' Get a dict with attributes of node @param node: QDomElement @return dict(QString, QString) with attributes ''' attribs = {} if isinstance(node, QDomElement) or isinstance(node, QDomNode): namedNodeMap = node.attributes() for i in range(namedNodeMap.count()): item = namedNodeMap.item(i) attribs[str(item.nodeName())] = str(item.nodeValue()) return attribs def save(self, filename): """Writes session info to xml file. Overwrites existing files""" if not filename.endswith(".xml"): filename = filename + ".xml" file_object = QFile(filename) if not file_object.open(QIODevice.WriteOnly): logging.error("File %s could not be opened.", filename) else: file_object.writeData(self.Xml.toString()) file_object.close() def clear(self): ''' Clear xml doc and reset root node''' self.Xml.clear() self.rootNode = self.Xml.createElement(self.rootname) self.Xml.appendChild(self.rootNode) def load(self, filename): """Loads session info from xml file. Returns false if loading fails, true otherwise.""" if not exists(filename): logging.error("Cannot restore session - File %s not found.", filename) return False file_object = QFile(filename) self.Xml.clear() if not file_object.open(QIODevice.ReadOnly): logging.error("File %s could not be opened.", filename) return False else: if not self.Xml.setContent(file_object.readAll()): logging.error("self.Xml.setContent() failed.") file_object.close() return False file_object.close() self.rootNode = self.Xml.documentElement() return True
class XFORMDocument: """ class to generate an Xml file that is needed for data collection using mobile device. The class creates the file and QDOM sections for holding data once the file is called """ def __init__(self, fname): """ Initalize the class so that we have a new file everytime document generation method is called """ self.dt_text = QDate() self.file_handler = FilePaths() self.doc = QDomDocument() self.form = None self.fname = fname self.doc_with_entities = [] self.supports_doc = self.document() def document(self): """ use the globally defined Document name for supporting document :return: """ global DOCUMENT return DOCUMENT def form_name(self): """ Format the name for the new file to be created. We need to ensure it is .xml file. :return: """ if len(self.fname.split(".")) > 1: return self.fname else: return self.fname+"{}".format(DOCEXTENSION) def set_form_name(self, local_name): """ Allow the user to update the name of the file. This method will be called to return a new file with the local_name given :param local_name: string :return: QFile """ self.fname = local_name+"{}".format(DOCEXTENSION) self.form.setFileName(self.fname) self.create_form() return self.fname def create_form(self): """ Create an XML file that will be our XFORM Document for reading and writing We want a new file when everytime we are creating XForm type: file :return: file """ self.form = QFile(os.path.join(FORM_HOME, self.form_name())) if not QFileInfo(self.form).suffix() == DOCEXTENSION: self.form_name() if not self.form.open(QIODevice.ReadWrite | QIODevice.Truncate | QIODevice.Text): return self.form.OpenError def create_node(self, name): """ Create a XML element node :param name: :return: node :rtype: QelementNode """ return self.doc.createElement(name) def create_text_node(self, text): """ Create an XML text node :param text: :return: """ return self.doc.createTextNode(text) def create_node_attribute(self, node, key, value): """ Create an attribute and attach it to the node :param node: Qnode :param key: Qnode name :param value: Qnode value :return: QNode """ return node.setAttribute(key, value) def xform_document(self): """ :return: QDomDocument """ return self.doc def write_to_form(self): """ Write data to xml file from the base calling class to an output file created earlier :return: """ if isinstance(self.form, QFile): self.form.write(self.doc.toByteArray()) self.form.close() self.doc.clear() else: return None def update_form_data(self): """ Update the xml file with changes that the user has made. Particular section of the document will be deleted or added :return: """ pass
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment and blunder from GNU Gama """ # gama-local OK? if self.gama_path is None: logging.error("GNU gama path is None") return (None, None) # fix = 0 free network fix = sum([1 for p, s in self.points if s == 'FIX']) adj = sum([1 for p, s in self.points if s == 'ADJ']) if adj == 0 or len(self.observations) < 2: # no unknowns or observations logging.error("GNU gama no unknowns or not enough observations") return (None, None) doc = QDomDocument() doc.appendChild(doc.createComment('Gama XML created by Ulyxes')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') # parameters.setAttribute('sigma-act', 'apriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute('distance-stdev', \ str(self.stdev_dist) + ' ' + \ str(self.stdev_dist1)) points_observations.setAttribute('direction-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) points_observations.setAttribute('angle-stdev', str(math.sqrt(2) * self.stdev_angle / 3600.0 * 10000)) points_observations.setAttribute('zenith-angle-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if 'elev' in p and p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if 'east' in p and 'north' in p and \ p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if 'east' in p and 'north' in p and \ p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if 'elev' in p and p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) for o in self.observations: if 'station' in o: # station record sta = doc.createElement('obs') sta.setAttribute('from', o['station']) # instrument height ih = 0 if 'ih' in o: ih = o['ih'] points_observations.appendChild(sta) else: # observation th = 0 if 'th' in o: th = o['th'] if self.dimension == 2: # horizontal network if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o and 'v' in o: # horizontal distance hd = math.sin(o['v'].GetAngle()) * o['distance'] tmp = doc.createElement('distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only pass elif self.dimension == 3: # 3d if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o: tmp = doc.createElement('s-distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['distance'])) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) if 'v' in o: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['v'].GetAngle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension logging.error("GNU gama unknown dimension") return (None, None) # generate temp file name f = tempfile.NamedTemporaryFile() tmp_name = f.name f.close() f = open(tmp_name + '.xml', 'w') f.write(doc.toString()) #f.write(doc.toByteArray()) f.close() # run gama-local status = os.system(self.gama_path + ' ' + tmp_name + '.xml --text ' + tmp_name + '.txt --xml ' + tmp_name + 'out.xml ' + '--cov-band 0') if status != 0: logging.error("GNU gama failed") return (None, None) xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc = QDomDocument() doc.setContent(xmlInputSource, xmlParser) # get adjusted coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted coordinates") return (None, None) res = [] adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': p = {} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p['id'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p['east'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p['north'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p['elev'] = float(ppp.firstChild().nodeValue()) res.append(p) adj_nodes = doc.elementsByTagName('orientation-shifts') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted orientations") return (None, None) adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'orientation': for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': pid = str(ppp.firstChild().nodeValue()) for p in res: if p['id'] == pid: break else: break elif ppp.nodeName() == 'approx': p['appr_ori'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'adj': p['ori'] = float(ppp.firstChild().nodeValue()) # std-dev # TODO usefull for one unknown point in 3D # TODO band must be 0 adj_nodes = doc.elementsByTagName('cov-mat') if adj_nodes.count() < 1: logging.error("GNU gama no covariance matrix") return (None, None) adj_node = adj_nodes.at(0) ii = 0 for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'flt': w = float(pp.firstChild().nodeValue()) if ii == 0: res[0]['std_east'] = math.sqrt(w) ii += 1 elif ii == 1: res[0]['std_north'] = math.sqrt(w) ii += 1 elif ii == 2: res[0]['std_elev'] = math.sqrt(w) ii += 1 elif ii == 3: res[0]['std_ori'] = math.sqrt(w) ii += 1 adj_nodes = doc.elementsByTagName('observations') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted observations") return (None, None) blunder = {'std-residual': 0} adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() in ['direction', 'slope-distance', 'zenith-angle']: o = {'std-residual': 0} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'from': o['from'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'to': o['to'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'f': o['f'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'std-residual': o['std-residual'] = float(ppp.firstChild().nodeValue()) if o['std-residual'] > self.krit and \ o['std-residual'] > blunder['std-residual'] and \ o['f'] > 10: # extra observations ratio blunder = dict(o) xmlFile.close() # remove input xml and output xml os.remove(tmp_name + '.xml') os.remove(tmp_name + '.txt') os.remove(tmp_name + 'out.xml') return (res, blunder)
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment and blunder from GNU Gama """ # gama-local OK? if self.gama_path is None: logging.error("GNU gama path is None") return (None, None) # fix = 0 free network fix = sum([1 for p, s in self.points if s == 'FIX']) adj = sum([1 for p, s in self.points if s == 'ADJ']) if adj == 0 or len(self.observations) < 2: # no unknowns or observations logging.error("GNU gama no unknowns or not enough observations") return (None, None) doc = QDomDocument() doc.appendChild(doc.createComment('Gama XML created by Ulyxes')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') # parameters.setAttribute('sigma-act', 'apriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute( 'distance-stdev', str(self.stdev_dist) + ' ' + str(self.stdev_dist1)) points_observations.setAttribute( 'direction-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) points_observations.setAttribute( 'angle-stdev', str(math.sqrt(2) * self.stdev_angle / 3600.0 * 10000)) points_observations.setAttribute( 'zenith-angle-stdev', str(self.stdev_angle / 3600.0 * 10000.0)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p['id']) if p['east'] is not None and p['north'] is not None: tmp.setAttribute('y', str(p['east'])) tmp.setAttribute('x', str(p['north'])) if p['elev'] is not None: tmp.setAttribute('z', str(p['elev'])) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) for o in self.observations: if 'station' in o: # station record sta = doc.createElement('obs') sta.setAttribute('from', o['station']) # instrument height ih = 0 if 'ih' in o: ih = o['ih'] points_observations.appendChild(sta) else: # observation th = 0 if 'th' in o: th = o['th'] if self.dimension == 2: # horizontal network if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o and 'v' in o: # horizontal distance hd = math.sin(o['v'].GetAngle()) * o['distance'] tmp = doc.createElement('distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only pass elif self.dimension == 3: # 3d if 'hz' in o: tmp = doc.createElement('direction') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['hz'].GetAngle('GON'))) sta.appendChild(tmp) if 'distance' in o: tmp = doc.createElement('s-distance') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['distance'])) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) if 'v' in o: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o['id']) tmp.setAttribute('val', str(o['v'].GetAngle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension logging.error("GNU gama unknown dimension") return (None, None) # generate temp file name f = tempfile.NamedTemporaryFile() tmp_name = f.name f.close() f = open(tmp_name + '.xml', 'w') f.write(doc.toByteArray()) f.close() # run gama-local status = os.system(self.gama_path + ' ' + tmp_name + '.xml --text ' + tmp_name + '.txt --xml ' + tmp_name + 'out.xml') if status != 0: logging.error("GNU gama failed") return (None, None) xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource, xmlParser) # get adjusted coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted coordinates") return (None, None) res = [] adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': p = {} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p['id'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p['east'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p['north'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p['elev'] = float(ppp.firstChild().nodeValue()) # TODO standard deviation of coords to p res.append(p) adj_nodes = doc.elementsByTagName('observations') if adj_nodes.count() < 1: logging.error("GNU gama no adjusted observations") return (None, None) blunder = {'std-residual': 0} adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() in [ 'direction', 'slope-distance', 'zenith-angle' ]: o = {'std-residual': 0} for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'from': o['from'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'to': o['to'] = str(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'f': o['f'] = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'std-residual': o['std-residual'] = float(ppp.firstChild().nodeValue()) if o['std-residual'] > self.krit and \ o['std-residual'] > blunder['std-residual'] and \ o['f'] > 10: # extra observations ratio blunder = dict(o) xmlFile.close() # remove input xml and output xml os.remove(tmp_name + '.xml') os.remove(tmp_name + '.txt') os.remove(tmp_name + 'out.xml') return (res, blunder)
def getObservations (self, offering="", properties=[], features=[], procedures=[], filters=None, resultModel = ""): """ :param offering: Offering name :type offering: str :param properties: Selected properties names :type properties: str list :param features: Selected features of interest names :type features: str list :param procedures: Selected procedures names :type procedures: str list :param filters: Configured filters :type filters: FilterRequest :param resultModel: Selected result model :type resultModel: str :return: xml data """ doc = QDomDocument() doc.appendChild(doc.createProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"')) root = doc.createElement('GetObservation') root.setAttribute('xmlns',"http://www.opengis.net/sos/1.0") root.setAttribute('xmlns:ows',"http://www.opengis.net/ows/1.1") root.setAttribute('xmlns:gml',"http://www.opengis.net/gml") root.setAttribute('xmlns:ogc',"http://www.opengis.net/ogc") root.setAttribute('xmlns:om',"http://www.opengis.net/om/1.0") root.setAttribute('xmlns:xsi',"http://www.w3.org/2001/XMLSchema-instance") root.setAttribute('xsi:schemaLocation',"http://www.opengis.net/sos/1.0 http://schemas.opengis.net/sos/1.0.0/sosGetObservation.xsd") root.setAttribute('service',"SOS") root.setAttribute('version',"1.0.0") root.setAttribute('srsName',self[offering].srsName) doc.appendChild(root) offer = doc.createElement("offering") offer.appendChild(doc.createTextNode(offering)) root.appendChild (offer) if filters.temporalFilter: timeEvent = doc.createElement("eventTime") operator = doc.createElement("ogc:%s" % filters.temporalOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild (doc.createTextNode ("om:samplingTime")) operand = doc.createElement(filters.temporalOperand) if filters.temporalOperand == "gml:TimeInstant": timePos = doc.createElement("gml:timePosition") timePos.appendChild(doc.createTextNode(str(filters.temporalValue))) operand.appendChild (timePos) elif filters.temporalOperand == "gml:TimePeriod": begin = doc.createElement("gml:beginPosition") begin.appendChild(doc.createTextNode(str(filters.temporalValue).split()[0])) end = doc.createElement("gml:endPosition") end.appendChild(doc.createTextNode(str(filters.temporalValue).split()[-1])) operand.appendChild(begin) operand.appendChild(end) root.appendChild(timeEvent) timeEvent.appendChild(operator) operator.appendChild (prop) operator.appendChild (operand) for proc in procedures: procElement = doc.createElement("procedure") procElement.appendChild (doc.createTextNode(proc)) root.appendChild (procElement) for prop in properties: propElement = doc.createElement("observedProperty") propElement.appendChild(doc.createTextNode(prop)) root.appendChild (propElement) foi = doc.createElement("featureOfInterest") if len (features) else None for foiName in features: foiElement = doc.createElement("ObjectID") foiElement.appendChild(doc.createTextNode(foiName)) foi.appendChild (foiElement) if filters.spatialFilter and not foi: foi = doc.createElement("featureOfInterest") operator = doc.createElement("ogc:%s" % filters.spatialOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild (doc.createTextNode ("urn:ogc:data:location")) operator.appendChild (prop) try: if filters.spatialOperand == "gml:Point": gmlNode = QgsOgcUtils.geometryToGML(QgsGeometry.fromPoint(filters._spatialValue), doc) elif filters.spatialOperand == "gml:Envelope": gmlNode = QgsOgcUtils.rectangleToGMLEnvelope(QgsGeometry.fromRect(filters._spatialValue).boundingBox(), doc) elif filters.spatialOperand == "gml:Polygon": gmlNode = QgsOgcUtils.geometryToGML(QgsGeometry.fromPolygon(filters._spatialValue), doc) elif filters.spatialOperand == "gml:LineString": gmlNode = QgsOgcUtils.geometryToGML(QgsGeometry.fromPolyline(filters._spatialValue), doc) gmlNode.setAttribute('srsName',self[offering].srsName) operator.appendChild (gmlNode) except: pass foi.appendChild(operator) #Lista de features o filtro espacial if foi: root.appendChild(foi) if filters.scalarFilter: result = doc.createElement("result") operator = doc.createElement("ogc:PropertyIs%s" % filters.scalarOperator) prop = doc.createElement("ogc:PropertyName") prop.appendChild (doc.createTextNode (filters.scalarOperand)) operator.appendChild (prop) if filters.scalarOperator in ["Between"]: try: lower = doc.createElement ("ogc:LowerBoundary") lowValue = doc.createElement ("ogc:Literal") lowValue.appendChild(doc.createTextNode(str(filters.scalarValue).split()[0])) lower.appendChild (lowValue) upper = doc.createElement ("ogc:UpperBoundary") upValue = doc.createElement ("ogc:Literal") upValue.appendChild(doc.createTextNode(str(filters.scalarValue).split()[-1])) upper.appendChild (upValue) operator.appendChild (lower) operator.appendChild (upper) except: pass else: value = doc.createElement ("ogc:Literal") value.appendChild(doc.createTextNode(str(filters.scalarValue))) operator.appendChild (value) root.appendChild(result) result.appendChild(operator) responseFormat = doc.createElement ("responseFormat") responseFormat.appendChild (doc.createTextNode('text/xml;subtype="om/1.0.0"')) root.appendChild (responseFormat) resultModelElement = doc.createElement ("resultModel") resultModelElement.appendChild (doc.createTextNode(resultModel)) root.appendChild (resultModelElement) responseMode = doc.createElement ("responseMode") responseMode.appendChild (doc.createTextNode("inline")) root.appendChild (responseMode) return doc.toString(4)
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment from GNU Gama """ # fix = 0 free network fix = 0 adj = 0 for p, s in self.points: if s == 'FIX': fix += 1 else: adj += 1 if adj == 0 or len(self.observations) == 0: # no unknowns or observations return None doc = QDomDocument() doc.appendChild( doc.createComment( 'Gama XML created by SurveyingCalculation plugin for QGIS')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute( 'distance-stdev', str(self.stdev_dist) + ' ' + str(self.stdev_dist1)) points_observations.setAttribute('direction-stdev', str(self.stdev_angle)) points_observations.setAttribute('angle-stdev', str(math.sqrt(self.stdev_angle * 2))) points_observations.setAttribute('zenith-angle-stdev', str(self.stdev_angle)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) if self.dimension == 1: hd = doc.createElement('height-differences') points_observations.appendChild(hd) for o in self.observations: if o.station == 'station': # station record st_id = o.point_id if o.th is None: ih = 0 else: ih = o.th if self.dimension in [2, 3]: sta = doc.createElement('obs') sta.setAttribute('from', o.point_id) points_observations.appendChild(sta) else: # observation if self.dimension == 2: # horizontal network if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: # horizontal distance hd = o.horiz_dist() if hd is not None: tmp = doc.createElement('distance') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only 1d if o.th is None: th = 0 else: th = o.th if o.d is not None and o.v is not None: tmp = doc.createElement('dh') tmp.setAttribute('from', st_id) tmp.setAttribute('to', o.point_id) # TODO hibaterjedes tmp.setAttribute('stdev', '1') sz = math.sin(o.v.get_angle()) w = self.stdev_dist + self.stdev_dist1 * o.d.d / 1000 ro_cc = 200 * 100 * 100 / math.pi if o.d.mode == 'SD': cz = math.cos(o.v.get_angle()) tmp.setAttribute('val', str(o.d.d * cz + ih - th)) tmp.setAttribute( 'stdev', str( math.sqrt(cz**2 * w**2 + (o.d.d * 1000)**2 * sz**2 * (self.stdev_angle / RO_CC)**2))) else: tz = math.tan(o.v.get_angle()) tmp.setAttribute( 'val', str(o.d.d / math.tan(o.v.get_angle()) + ih - th)) tmp.setAttribute( 'stdev', str( math.sqrt((1 / tz)**2 * w**2 + (o.d.d * 1000)**2 * (o.d.d * 1000)**2 * (1 / sz**2)**2 * (self.stdev_angle / RO_CC)**2))) hd.appendChild(tmp) elif self.dimension == 3: # 3d if o.th is None: th = 0 else: th = o.th if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: if o.d.mode == 'SD': tmp = doc.createElement('s-distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) else: tmp = doc.createElement('distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('to', o.point_id) sta.appendChild(tmp) if o.v is not None: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.v.get_angle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension return None # generate temp file name tmpf = QTemporaryFile(QDir.temp().absoluteFilePath('w')) tmpf.open(QIODevice.WriteOnly) tmpf.close() tmp_name = tmpf.fileName() f = QFile(tmp_name + '.xml') if f.open(QIODevice.WriteOnly): f.write(doc.toByteArray()) f.close() # run gama-local if self.gama_prog is None: return None status = QProcess.execute(self.gama_prog, [ tmp_name + '.xml', '--text', tmp_name + '.txt', '--xml', tmp_name + 'out.xml' ]) if status != 0: return None xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource, xmlParser) f_txt = QFile(tmp_name + '.txt') f_txt.open(QIODevice.ReadOnly) res = f_txt.readAll().data() f_txt.close() # store coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: return res adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p = Point(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p.e = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p.n = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p.z = float(ppp.firstChild().nodeValue()) ScPoint(p).store_coord(self.dimension) # remove input xml and output xml tmpf.remove() f_txt.remove() f.remove() xmlFile.remove() return res
def adjust(self): """ Export data to GNU Gama xml, adjust the network and read result :returns: result list of adjusment from GNU Gama """ # fix = 0 free network fix = 0 adj = 0 for p, s in self.points: if s == 'FIX': fix += 1 else: adj += 1 if adj == 0 or len(self.observations) == 0: # no unknowns or observations return None doc = QDomDocument() doc.appendChild(doc.createComment('Gama XML created by Land Surveying plugin for QGIS')) gama_local = doc.createElement('gama-local') gama_local.setAttribute('version', '2.0') doc.appendChild(gama_local) network = doc.createElement('network') network.setAttribute('axes-xy', 'ne') network.setAttribute('angles', 'left-handed') gama_local.appendChild(network) description = doc.createElement('description') if self.dimension == 1: description.appendChild(doc.createTextNode('GNU Gama 1D network')) elif self.dimension == 2: description.appendChild(doc.createTextNode('GNU Gama 2D network')) elif self.dimension == 3: description.appendChild(doc.createTextNode('GNU Gama 3D network')) network.appendChild(description) parameters = doc.createElement('parameters') parameters.setAttribute('sigma-apr', '1') parameters.setAttribute('conf-pr', str(self.probability)) parameters.setAttribute('tol-abs', '1000') parameters.setAttribute('sigma-act', 'aposteriori') parameters.setAttribute('update-constrained-coordinates', 'yes') network.appendChild(parameters) points_observations = doc.createElement('points-observations') points_observations.setAttribute('distance-stdev', str(self.stdev_dist) + ' ' + str(self.stdev_dist1)) points_observations.setAttribute('direction-stdev', str(self.stdev_angle)) points_observations.setAttribute('angle-stdev', str(math.sqrt(self.stdev_angle * 2))) points_observations.setAttribute('zenith-angle-stdev', str(self.stdev_angle)) network.appendChild(points_observations) for p, s in self.points: if self.dimension == 1: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'z') else: if fix == 0: tmp.setAttribute('adj', 'Z') else: tmp.setAttribute('adj', 'z') points_observations.appendChild(tmp) elif self.dimension == 2: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if s == 'FIX': tmp.setAttribute('fix', 'xy') else: if fix == 0: # free network tmp.setAttribute('adj', 'XY') else: tmp.setAttribute('adj', 'xy') points_observations.appendChild(tmp) elif self.dimension == 3: tmp = doc.createElement('point') tmp.setAttribute('id', p.id) if p.e is not None and p.n is not None: tmp.setAttribute('y', str(p.e)) tmp.setAttribute('x', str(p.n)) if p.z is not None: tmp.setAttribute('z', str(p.z)) if s == 'FIX': tmp.setAttribute('fix', 'xyz') else: if fix == 0: tmp.setAttribute('adj', 'XYZ') else: tmp.setAttribute('adj', 'xyz') points_observations.appendChild(tmp) for o in self.observations: if o.station == 'station': # station record sta = doc.createElement('obs') sta.setAttribute('from', o.point_id) if o.th is None: ih = 0 else: ih = o.th points_observations.appendChild(sta) else: # observation if self.dimension == 2: # horizontal network if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: # horizontal distance hd = o.horiz_dist() if hd is not None: tmp = doc.createElement('distance') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(hd)) sta.appendChild(tmp) elif self.dimension == 1: # elevations only pass elif self.dimension == 3: # 3d if o.th is None: th = o.th else: th = 0 if o.hz is not None: tmp = doc.createElement('direction') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.hz.get_angle('GON'))) sta.appendChild(tmp) if o.d is not None: if o.d.mode == 'SD': tmp = doc.createElement('s-distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) else: tmp = doc.createElement('distance') tmp.setAttribute('val', str(o.d.d)) tmp.setAttribute('to', o.point_id) sta.appendChild(tmp) if o.v is not None: tmp = doc.createElement('z-angle') tmp.setAttribute('to', o.point_id) tmp.setAttribute('val', str(o.v.get_angle('GON'))) tmp.setAttribute('from_dh', str(ih)) tmp.setAttribute('to_dh', str(th)) sta.appendChild(tmp) else: # unknown dimension return None #print doc.toprettyxml(indent=" ") # generate temp file name tmpf = QTemporaryFile( QDir.temp().absoluteFilePath('w') ) tmpf.open(QIODevice.WriteOnly) tmpf.close() tmp_name = tmpf.fileName() f = QFile(tmp_name + '.xml') if f.open(QIODevice.WriteOnly): f.write(doc.toByteArray()) f.close() # run gama-local if self.gama_prog is None: return None # status = call([str(self.gama_prog), str(tmp_name) + '.xml', '--text', # str(tmp_name) + '.txt', '--xml', str(tmp_name) + 'out.xml']) status = QProcess.execute(self.gama_prog, [ tmp_name+'.xml', '--text', tmp_name+'.txt', '--xml', tmp_name+'out.xml']) if status != 0: return None xmlParser = QXmlSimpleReader() xmlFile = QFile(tmp_name + 'out.xml') xmlInputSource = QXmlInputSource(xmlFile) doc.setContent(xmlInputSource,xmlParser) f_txt = QFile(tmp_name + '.txt') f_txt.open(QIODevice.ReadOnly) res = f_txt.readAll().data() f_txt.close() # store coordinates adj_nodes = doc.elementsByTagName('adjusted') if adj_nodes.count() < 1: return res adj_node = adj_nodes.at(0) for i in range(len(adj_node.childNodes())): pp = adj_node.childNodes().at(i) if pp.nodeName() == 'point': for ii in range(len(pp.childNodes())): ppp = pp.childNodes().at(ii) if ppp.nodeName() == 'id': p = Point(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Y' or ppp.nodeName() == 'y': p.e = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'X' or ppp.nodeName() == 'x': p.n = float(ppp.firstChild().nodeValue()) elif ppp.nodeName() == 'Z' or ppp.nodeName() == 'z': p.z = float(ppp.firstChild().nodeValue()) ScPoint(p).store_coord(self.dimension) # remove input xml and output xml tmpf.remove() f_txt.remove() f.remove() xmlFile.remove() return res
def test_constructor_remove_more_kids(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 20) kds = [] gkds = [] ngks = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) qdn.appendChild(kds[-1]) ngkids = self.__rnd.randint(1, 20) gkds.append([]) ngks.append(ngkids) for g in range(ngkids): gkds[n].append(doc.createElement("grandkid%s" % g)) kds[-1].appendChild(gkds[n][-1]) # print doc.toString() ci = ComponentItem(qdn) self.assertEqual(ci.parent, None) self.assertEqual(ci.node, qdn) self.assertEqual(ci.childNumber(), 0) self.assertEqual(ci.node.nodeName(), nname) for k in range(nkids): ks = ci.child(k) self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, kds[k]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "kid%s" % k) self.assertEqual(ks.parent, ci) for g in range(ngks[k]): self.assertTrue(isinstance(ks.child(g), ComponentItem)) self.assertTrue(isinstance(ks.child(g).parent, ComponentItem)) self.assertEqual(ks.child(g).childNumber(), g) self.assertEqual(ks.child(g).node, gkds[k][g]) self.assertEqual(ks.child(g).parent.node, ks.node) self.assertEqual(ks.child(g).node.nodeName(), "grandkid%s" % g) self.assertEqual(ks.child(g).parent, ks) rmvd = self.__rnd.randint(0, nkids - 1) nrm = self.__rnd.randint(1, nkids - rmvd) kd = [] for r in range(nrm): kd.append(ci.child(rmvd + r)) self.assertEqual(ci.removeChildren(rmvd, nrm), True) for r in range(nrm): qdn.removeChild(kd[r].node) for k in range(nkids): if k >= rmvd and k <= rmvd + nrm: continue kk = k if k < rmvd else k - nrm ks = ci.child(kk) self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), kk) self.assertEqual(ks.node, kds[k]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "kid%s" % k) self.assertEqual(ks.parent, ci) for g in range(ngks[k]): self.assertTrue(isinstance(ks.child(g), ComponentItem)) self.assertTrue(isinstance(ks.child(g).parent, ComponentItem)) self.assertEqual(ks.child(g).childNumber(), g) self.assertEqual(ks.child(g).node, gkds[k][g]) self.assertEqual(ks.child(g).parent.node, ks.node) self.assertEqual(ks.child(g).node.nodeName(), "grandkid%s" % g) self.assertEqual(ks.child(g).parent, ks)
def test_constructor_insert_more_kids(self): fun = sys._getframe().f_code.co_name print "Run: %s.%s() " % (self.__class__.__name__, fun) doc = QDomDocument() nname = "definition" qdn = doc.createElement(nname) doc.appendChild(qdn) nkids = self.__rnd.randint(1, 5) kds = [] gkds = [] ngks = [] for n in range(nkids): kds.append(doc.createElement("kid%s" % n)) qdn.appendChild(kds[-1]) ngkids = self.__rnd.randint(1, 5) gkds.append([]) ngks.append(ngkids) for g in range(ngkids): gkds[n].append(doc.createElement("grandkid%s" % g)) kds[-1].appendChild(gkds[n][-1]) ci = ComponentItem(qdn) self.assertEqual(ci.parent, None) self.assertEqual(ci.node, qdn) self.assertEqual(ci.childNumber(), 0) self.assertEqual(ci.node.nodeName(), nname) for k in range(nkids): ks = ci.child(k) self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, kds[k]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "kid%s" % k) self.assertEqual(ks.parent, ci) for g in range(ngks[k]): self.assertTrue(isinstance(ks.child(g), ComponentItem)) self.assertTrue(isinstance(ks.child(g).parent, ComponentItem)) self.assertEqual(ks.child(g).childNumber(), g) self.assertEqual(ks.child(g).node, gkds[k][g]) self.assertEqual(ks.child(g).parent.node, ks.node) self.assertEqual(ks.child(g).node.nodeName(), "grandkid%s" % g) self.assertEqual(ks.child(g).parent, ks) insd = self.__rnd.randint(0, nkids) nin = self.__rnd.randint(1, 5) inkd = [] for n in range(nin): inkd.append(doc.createElement("insertedkid%s" % n)) if insd == nkids + n: if n == 0: qdn.insertAfter(inkd[n], ci.child(nkids - 1).node) else: qdn.insertAfter(inkd[n], inkd[n - 1]) else: qdn.insertBefore(inkd[n], ci.child(insd).node) self.assertEqual(ci.insertChildren(insd, nin), True) for k in range(nkids): if k >= insd and k < insd + nin: mnin = k - insd ks = ci.child(k) self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, inkd[mnin]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "insertedkid%s" % mnin) self.assertEqual(ks.parent, ci) continue kk = k if k < insd else k - nin ks = ci.child(k) self.assertTrue(isinstance(ks, ComponentItem)) self.assertTrue(isinstance(ks.parent, ComponentItem)) self.assertEqual(ks.childNumber(), k) self.assertEqual(ks.node, kds[kk]) self.assertEqual(ks.parent.node, qdn) self.assertEqual(ks.node.nodeName(), "kid%s" % kk) self.assertEqual(ks.parent, ci) for g in range(ngks[kk]): self.assertTrue(isinstance(ks.child(g), ComponentItem)) self.assertTrue(isinstance(ks.child(g).parent, ComponentItem)) self.assertEqual(ks.child(g).childNumber(), g) self.assertEqual(ks.child(g).node, gkds[kk][g]) self.assertEqual(ks.child(g).parent.node, ks.node) self.assertEqual(ks.child(g).node.nodeName(), "grandkid%s" % g) self.assertEqual(ks.child(g).parent, ks)