Exemplo n.º 1
0
def loadProject(filename):
  # clear the map layer registry
  QgsMapLayerRegistry.instance().removeAllMapLayers()

  assert os.path.exists(filename), "project file does not exist: " + filename

  # load the project
  QgsProject.instance().read(QFileInfo(filename))
  assert QgsMapLayerRegistry.instance().mapLayers(), "no layers in map layer registry"

  doc = QDomDocument()
  with open(filename) as f:
    doc.setContent(f.read())

  # map settings
  mapSettings = QgsMapSettings()
  mapSettings.readXML(doc.elementsByTagName("mapcanvas").at(0))

  # visible layers
  layerIds = []
  nodes = doc.elementsByTagName("legendlayer")
  for i in range(nodes.count()):
    elem = nodes.at(i).toElement().elementsByTagName("legendlayerfile").at(0).toElement()
    if elem.attribute("visible") == "1":
      layerIds.append(elem.attribute("layerid"))
  mapSettings.setLayers(layerIds)

  # canvas color
  red = int(doc.elementsByTagName("CanvasColorRedPart").at(0).toElement().text())
  green = int(doc.elementsByTagName("CanvasColorGreenPart").at(0).toElement().text())
  blue = int(doc.elementsByTagName("CanvasColorBluePart").at(0).toElement().text())
  mapSettings.setBackgroundColor(QColor(red, green, blue))

  return mapSettings
Exemplo n.º 2
0
    def getlocalseasons(self, id):
        '''
        @type id: str
        @rtype: list
        '''
        seasons = {}
        
        if self._storage.exists('shows/%s/en.xml' % id):
            data = self._storage.getdata('shows/%s/en.xml' % id)
            
            xml = QDomDocument()
            xml.setContent(data)
            
            episodes = xml.elementsByTagName('Episode')
            
            for episode in range(episodes.count()):
                seasonid = unicode(QString(episodes.at(episode).toElement().elementsByTagName('seasonid').at(0).childNodes().at(0).toText().data()))
                seasonnum = QString(episodes.at(episode).toElement().elementsByTagName('SeasonNumber').at(0).childNodes().at(0).toText().data()).toInt()
                
                if seasonnum[1]:
                    if seasonnum[0] > 0:
                        if not seasonid in seasons:
                            newseason = season()
                            newseason.id = seasonid
                            newseason.number = seasonnum[0]
                            newseason.image = 'seasonbanners/%s-%d.jpg' % (id, newseason.number)
                            
                            newseason.showid = id
                            
                            seasons[seasonid] = newseason

        return sorted(seasons.values(), key = lambda item: item.number)
Exemplo n.º 3
0
    def testQgsCentroidFillSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = 'QgsCentroidFillSymbolLayerV2'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsCentroidFillSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsCentroidFillSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'regular_star'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'#55aaff'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'#00ff00'
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 4
0
 def searchshow(self, name):
     '''
     @type name: str
     @rtype: list
     '''
     data = self._request('http://www.thetvdb.com/api/GetSeries.php?seriesname=%s' % name)
     
     xml = QDomDocument()
     xml.setContent(data)
     
     showsxml = xml.elementsByTagName('Series')
     shows = []
     
     for i in range(len(showsxml)):
         newshow = show()
         newshow.id = unicode(QString(showsxml.at(i).toElement().elementsByTagName('seriesid').at(0).childNodes().at(0).toText().data()))
         newshow.name = unicode(QString(showsxml.at(i).toElement().elementsByTagName('SeriesName').at(0).childNodes().at(0).toText().data()))
         newshow.description = unicode(QString(showsxml.at(i).toElement().elementsByTagName('Overview').at(0).childNodes().at(0).toText().data()))
         newshow.image = unicode(QString(showsxml.at(i).toElement().elementsByTagName('banner').at(0).firstChild().toText().data()))
         newshow.data = showsxml.at(i).toElement()
         
         if len(newshow.image):
             self._download(urljoin(urljoin(choice(self.__mirrors[1]), '/banners/'), newshow.image), newshow.image)
         
         shows.append(newshow)
         
     return shows
Exemplo n.º 5
0
    def testQgsSVGFillSymbolLayer(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = 'QgsSVGFillSymbolLayer'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSVGFillSymbolLayer())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 'accommodation_camping.svg'
        mValue = os.path.basename(mSymbolLayer.svgFilePath())
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 6
        mValue = mSymbolLayer.patternWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 6
0
        def getTargetWindows():
            file = self._getFile(layer)
            if file is None:
                return None

            doc = QDomDocument()
            doc.setContent(file)
            file.close()

            nodes = doc.elementsByTagName('TargetWindow')
            if nodes.count == 0:
                return None

            node = nodes.item(0)
            targetWindow = {'ulX': None, 'ulY': None, 'lrX': None, 'lrY': None}
            labels = {
                'UpperLeftX': 'ulX',
                'UpperLeftY': 'ulY',
                'LowerRightX': 'lrX',
                'LowerRightY': 'lrY'
            }
            for key, value in labels.iteritems():
                text = node.firstChildElement(key).text()
                if len(text) == 0:
                    continue
                targetWindow[value] = float(text)

            if None in targetWindow.values():
                return None

            return targetWindow
Exemplo n.º 7
0
    def testQgsSvgMarkerSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = 'QgsSvgMarkerSymbolLayerV2'
        mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsSvgMarkerSymbolLayerV2.createFromSld(mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSvgMarkerSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = u'skull.svg'
        mValue = os.path.basename(mSymbolLayer.path())
        print "VALUE", mSymbolLayer.path()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 12
        mValue = mSymbolLayer.size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 45
        mValue = mSymbolLayer.angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 8
0
  def xmlDownloaded(self,nr,state):
    """ populate the plugins object with the fetched data """
    if not self.httpId.has_key(nr):
      return
    reposName = self.httpId[nr]
    if state:                             # fetching failed
      self.mRepositories[reposName]["state"] =  3
      self.mRepositories[reposName]["error"] = self.mRepositories[reposName]["QPHttp"].errorString()
    else:
      repoData = self.mRepositories[reposName]["xmlData"]
      reposXML = QDomDocument()
      reposXML.setContent(repoData.data())
      pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
      if pluginNodes.size():
        for i in range(pluginNodes.size()):
          fileName = pluginNodes.item(i).firstChildElement("file_name").text().simplified()
          if not fileName:
              fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().trimmed().split("?")[0]).fileName()
          name = fileName.section(".", 0, 0)
          name = unicode(name)
          experimental = False
          if pluginNodes.item(i).firstChildElement("experimental").text().simplified().toUpper() in ["TRUE","YES"]:
            experimental = True
          plugin = {
            "name"          : pluginNodes.item(i).toElement().attribute("name"),
            "version_avail" : pluginNodes.item(i).toElement().attribute("version"),
            "desc_repo"     : pluginNodes.item(i).firstChildElement("description").text().simplified(),
            "desc_local"    : "",
            "author"        : pluginNodes.item(i).firstChildElement("author_name").text().simplified(),
            "homepage"      : pluginNodes.item(i).firstChildElement("homepage").text().simplified(),
            "url"           : pluginNodes.item(i).firstChildElement("download_url").text().simplified(),
            "experimental"  : experimental,
            "filename"      : fileName,
            "status"        : "not installed",
            "error"         : "",
            "error_details" : "",
            "version_inst"  : "",
            "repository"    : reposName,
            "localdir"      : name,
            "read-only"     : False}
          qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().simplified()
          if not qgisMinimumVersion: qgisMinimumVersion = "1"
          qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().simplified()
          if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
          #if compatible, add the plugin to the list
          if not pluginNodes.item(i).firstChildElement("disabled").text().simplified().toUpper() in ["TRUE","YES"]:
           if compareVersions(QGIS_VER, qgisMinimumVersion) < 2 and compareVersions(qgisMaximumVersion, QGIS_VER) < 2:
              #add the plugin to the cache
              plugins.addFromRepository(plugin)
      # set state=2, even if the repo is empty
      self.mRepositories[reposName]["state"] = 2

    self.emit(SIGNAL("repositoryFetched(QString)"), reposName )

    # is the checking done?
    if not self.fetchingInProgress():
      plugins.rebuild()
      self.saveCheckingOnStartLastDate()
      self.emit(SIGNAL("checkingDone()"))
Exemplo n.º 9
0
    def ReadProjectInfoXml(self):
        try:
            result = DlgCrcCheck.smethod_0(None, self.m_strProjectInfoFullName)
        except:
            return False
        if not result:
            return False

        doc = QDomDocument()
        qFile = QFile(self.m_strProjectInfoFullName)
        if qFile.open(QFile.ReadOnly):
            doc.setContent(qFile)
            qFile.close()
        else:
            raise UserWarning, "can not open file:" + self.m_strProjectInfoFullName
        dialogNodeList = doc.elementsByTagName("ProjectListClass")
        if dialogNodeList.isEmpty():
            raise UserWarning, "This file is not correct."
        dialogElem = dialogNodeList.at(0).toElement()

        ctrlNodesList = dialogElem.elementsByTagName("ProjectInfo")
        for i in range(ctrlNodesList.count()):
            pj = ProjectInfo()
            lineEditElem = ctrlNodesList.at(i).toElement()
            objectNameNode = lineEditElem.elementsByTagName("Name").at(0)
            objectNameElem = objectNameNode.toElement()
            pj.Name = objectNameElem.text()

            pathElem = objectNameElem.nextSiblingElement()
            pj.Path = pathElem.text()

            createdElem = pathElem.nextSiblingElement()
            pj.Created = createdElem.text()

            procedureNameElem = createdElem.nextSiblingElement()
            pj.ProcedureName = procedureNameElem.text()

            projNameElem = procedureNameElem.nextSiblingElement()
            pj.ProjName = projNameElem.text()

            ptElem = projNameElem.nextSiblingElement()
            pj.Pt = ptElem.text()

            subProjNameElem = ptElem.nextSiblingElement()
            pj.SubProjName = subProjNameElem.text()

            userNameElem = subProjNameElem.nextSiblingElement()
            pj.UserName = userNameElem.text()

            workspaceNameElem = userNameElem.nextSiblingElement()
            pj.WorkspaceName = workspaceNameElem.text()

            fullNameElem = workspaceNameElem.nextSiblingElement()
            pj.FullName = fullNameElem.text()

            self.ProjectsList.append(pj)
        return True
Exemplo n.º 10
0
  def xmlDownloaded(self,nr,state):
    """ populate the plugins object with the fetched data """
    if not self.httpId.has_key(nr):
      return
    reposName = self.httpId[nr]
    if state:                             # fetching failed
      self.mRepositories[reposName]["state"] =  3
      self.mRepositories[reposName]["error"] = self.mRepositories[reposName]["QPHttp"].errorString()
    else:
      repoData = self.mRepositories[reposName]["xmlData"]
      reposXML = QDomDocument()
      reposXML.setContent(repoData.data())
      pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
      if pluginNodes.size():
        for i in range(pluginNodes.size()):
          fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().trimmed()).fileName()
          name = fileName.section(".", 0, 0)
          name = str(name)
          plugin = {}
          plugin[name] = {
            "name"          : pluginNodes.item(i).toElement().attribute("name"),
            "version_avail" : pluginNodes.item(i).toElement().attribute("version"),
            "desc_repo"     : pluginNodes.item(i).firstChildElement("description").text().trimmed(),
            "desc_local"    : "",
            "author"        : pluginNodes.item(i).firstChildElement("author_name").text().trimmed(),
            "homepage"      : pluginNodes.item(i).firstChildElement("homepage").text().trimmed(),
            "url"           : pluginNodes.item(i).firstChildElement("download_url").text().trimmed(),
            "filename"      : fileName,
            "status"        : "not installed",
            "error"         : "",
            "error_details" : "",
            "version_inst"  : "",
            "repository"    : reposName,
            "localdir"      : name,
            "read-only"     : False}
          qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().trimmed()
          if not qgisMinimumVersion: qgisMinimumVersion = "0"
          # please use the tag below only if really needed! (for example if plugin development is abandoned)
          qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().trimmed()
          if not qgisMaximumVersion: qgisMaximumVersion = "2"
          #if compatible, add the plugin to the list
          if compareVersions(QGIS_VER, qgisMinimumVersion) < 2 and compareVersions(qgisMaximumVersion, QGIS_VER) < 2:
            if QGIS_VER[0]=="0" or qgisMinimumVersion[0]=="1" or name=="plugin_installer":
              plugins.addPlugin(plugin)
        plugins.workarounds()
        self.mRepositories[reposName]["state"] = 2
      else:
        #print "Repository parsing error"
        self.mRepositories[reposName]["state"] = 3
        self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller","Couldn't parse output from the repository")

    self.emit(SIGNAL("repositoryFetched(QString)"), reposName )

    # is the checking done?
    if not self.fetchingInProgress():
      plugins.getAllInstalled()
      self.emit(SIGNAL("checkingDone()"))
Exemplo n.º 11
0
 def readXML(self,n):
     filename=glob.glob('*.qgs')
     xml = open(filename[0]).read()
     doc = QDomDocument()
     doc.setContent(xml)
     filelist = doc.elementsByTagName("legendlayerfile")
     layerfile = filelist.at(n).toElement()
     layerid = layerfile.attribute('layerid')
     visible = int(layerfile.attribute('visible'))
     return layerid, bool(visible)
Exemplo n.º 12
0
 def __add_layer_definition_file(self, file_name, root_group):
     """
     shamelessly copied from
     https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp
     """
     qfile = QFile(file_name)
     if not qfile.open(QIODevice.ReadOnly):
         return None
     doc = QDomDocument()
     if not doc.setContent(qfile):
         return None
     file_info = QFileInfo(qfile)
     QDir.setCurrent(file_info.absoluteDir().path())
     root = QgsLayerTreeGroup()
     ids = doc.elementsByTagName('id')
     for i in xrange(0, ids.size()):
         id_node = ids.at(i)
         id_elem = id_node.toElement()
         old_id = id_elem.text()
         layer_name = old_id[:-17]
         date_time = QDateTime.currentDateTime()
         new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz')
         id_elem.firstChild().setNodeValue(new_id)
         tree_layer_nodes = doc.elementsByTagName('layer-tree-layer')
         for j in xrange(0, tree_layer_nodes.count()):
             layer_node = tree_layer_nodes.at(j)
             layer_elem = layer_node.toElement()
             if old_id == layer_elem.attribute('id'):
                 layer_node.toElement().setAttribute('id', new_id)
     layer_tree_elem = doc.documentElement().firstChildElement(
         'layer-tree-group')
     load_in_legend = True
     if not layer_tree_elem.isNull():
         root.readChildrenFromXML(layer_tree_elem)
         load_in_legend = False
     layers = QgsMapLayer.fromLayerDefinition(doc)
     QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend)
     nodes = root.children()
     for node in nodes:
         root.takeChild(node)
     del root
     root_group.insertChildNodes(-1, nodes)
     return None
Exemplo n.º 13
0
 def __add_layer_definition_file(self, file_name, root_group):
     """
     shamelessly copied from
     https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp
     """
     qfile = QFile(file_name)
     if not qfile.open(QIODevice.ReadOnly):
         return None
     doc = QDomDocument()
     if not doc.setContent(qfile):
         return None
     file_info = QFileInfo(qfile)
     QDir.setCurrent(file_info.absoluteDir().path())
     root = QgsLayerTreeGroup()
     ids = doc.elementsByTagName('id')
     for i in xrange(0, ids.size()):
         id_node = ids.at(i)
         id_elem = id_node.toElement()
         old_id = id_elem.text()
         layer_name = old_id[:-17]
         date_time = QDateTime.currentDateTime()
         new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz')
         id_elem.firstChild().setNodeValue(new_id)
         tree_layer_nodes = doc.elementsByTagName('layer-tree-layer')
         for j in xrange(0, tree_layer_nodes.count()):
             layer_node = tree_layer_nodes.at(j)
             layer_elem = layer_node.toElement()
             if old_id == layer_elem.attribute('id'):
                 layer_node.toElement().setAttribute('id', new_id)
     layer_tree_elem = doc.documentElement().firstChildElement('layer-tree-group')
     load_in_legend = True
     if not layer_tree_elem.isNull():
         root.readChildrenFromXML(layer_tree_elem)
         load_in_legend = False
     layers = QgsMapLayer.fromLayerDefinition(doc)
     QgsMapLayerRegistry.instance().addMapLayers(layers, load_in_legend)
     nodes = root.children()
     for node in nodes:
         root.takeChild(node)
     del root
     root_group.insertChildNodes(-1, nodes)
     return None
Exemplo n.º 14
0
    def hasTargetWindows(self, layer):
        file = self._getFile(layer)
        if file is None:
            return False

        doc = QDomDocument()
        doc.setContent(file)
        file.close()

        nodes = doc.elementsByTagName('TargetWindow')
        return True if nodes.count() > 0 else False
Exemplo n.º 15
0
    def getlocalshows(self):
        '''
        @rtype: list
        '''
        shows = []
        
        if self._storage.exists('shows'):
            showdirs = self._storage.listdir('shows')
            
            for showdir in showdirs:
                data = self._storage.getdata('shows/%s/en.xml' % showdir)
                
                if data != None:
                    xml = QDomDocument()
                    xml.setContent(data)
            
                    showxml = xml.elementsByTagName('Series').at(0)
                    
                    newshow = show()
                    newshow.id = unicode(QString(showxml.toElement().elementsByTagName('id').at(0).childNodes().at(0).toText().data()))
                    newshow.name = unicode(QString(showxml.toElement().elementsByTagName('SeriesName').at(0).childNodes().at(0).toText().data()))
                    newshow.description = unicode(QString(showxml.toElement().elementsByTagName('Overview').at(0).childNodes().at(0).toText().data()))
                    newshow.image = unicode(QString(showxml.toElement().elementsByTagName('banner').at(0).firstChild().toText().data()))
                    newshow.data = showxml.toElement()
                    
                    newshow.actors = unicode(QString(showxml.toElement().elementsByTagName('Actors').at(0).childNodes().at(0).toText().data())).strip('|').split('|')
                    newshow.contentrating = unicode(QString(showxml.toElement().elementsByTagName('ContentRating').at(0).childNodes().at(0).toText().data()))

                    firstaired = unicode(QString(showxml.toElement().elementsByTagName('FirstAired').at(0).childNodes().at(0).toText().data()))
                    if firstaired != '':
                        newshow.firstaired = datetime.fromtimestamp(mktime(strptime(firstaired, '%Y-%m-%d')))
                    else:
                        newshow.firstaired = datetime.now()

                    newshow.genre = unicode(QString(showxml.toElement().elementsByTagName('Genre').at(0).childNodes().at(0).toText().data())).strip('|').split('|')
                    newshow.imdb = unicode(QString(showxml.toElement().elementsByTagName('IMDB_ID').at(0).childNodes().at(0).toText().data()))
                    newshow.network = unicode(QString(showxml.toElement().elementsByTagName('Network').at(0).childNodes().at(0).toText().data()))

                    rating = unicode(QString(
                        showxml.toElement().elementsByTagName('Rating').at(0).childNodes().at(0).toText().data()))

                    if rating != '':
                        newshow.rating = float(rating)
                    else:
                        newshow.rating = 0.0

                    newshow.runtime = int(unicode(QString(showxml.toElement().elementsByTagName('Runtime').at(0).childNodes().at(0).toText().data())))
                    newshow.status = unicode(QString(showxml.toElement().elementsByTagName('Status').at(0).childNodes().at(0).toText().data()))
                    
                    shows.append(newshow)
        
        return shows
Exemplo n.º 16
0
def composers(projectfile, mapsettings):
    with open(projectfile) as f:
        xml = f.read()

    doc = QDomDocument()
    doc.setContent(xml)
    nodes = doc.elementsByTagName("Composer")
    for nodeid in range(nodes.count()):
        node = nodes.at(0).toElement()
        name = node.attribute("title")
        compositionnodes = doc.elementsByTagName("Composition")
        if compositionnodes.count() == 0:
            continue

        compositionelm = compositionnodes.at(0).toElement()
        comp = QgsComposition(mapsettings)
        comp.readXML(compositionelm, doc)
        atlaselm = node.firstChildElement("Atlas")
        comp.atlasComposition().readXML(atlaselm, doc)
        comp.addItemsFromXML(node, doc)
        comp.refreshZList()
        yield name, comp
Exemplo n.º 17
0
def composers(projectfile, mapsettings):
    with open(projectfile) as f:
        xml = f.read()

    doc = QDomDocument()
    doc.setContent(xml)
    nodes = doc.elementsByTagName("Composer")
    for nodeid in range(nodes.count()):
        node = nodes.at(0).toElement()
        name = node.attribute("title")
        compositionnodes = doc.elementsByTagName("Composition")
        if compositionnodes.count() == 0:
            continue

        compositionelm = compositionnodes.at(0).toElement()
        comp = QgsComposition(mapsettings)
        comp.readXML(compositionelm, doc)
        atlaselm = node.firstChildElement("Atlas")
        comp.atlasComposition().readXML(atlaselm, doc)
        comp.addItemsFromXML(node, doc)
        comp.refreshZList()
        yield name, comp
Exemplo n.º 18
0
def loadProject(filename):
    # clear the map layer registry
    QgsMapLayerRegistry.instance().removeAllMapLayers()

    assert os.path.exists(filename), "project file does not exist: " + filename

    # load the project
    QgsProject.instance().read(QFileInfo(filename))
    assert QgsMapLayerRegistry.instance().mapLayers(
    ), "no layers in map layer registry"

    doc = QDomDocument()
    with open(filename) as f:
        doc.setContent(f.read())

    # map settings
    mapSettings = QgsMapSettings()
    mapSettings.readXML(doc.elementsByTagName("mapcanvas").at(0))

    # visible layers
    layerIds = []
    nodes = doc.elementsByTagName("legendlayer")
    for i in range(nodes.count()):
        elem = nodes.at(i).toElement().elementsByTagName("legendlayerfile").at(
            0).toElement()
        if elem.attribute("visible") == "1":
            layerIds.append(elem.attribute("layerid"))
    mapSettings.setLayers(layerIds)

    # canvas color
    red = int(
        doc.elementsByTagName("CanvasColorRedPart").at(0).toElement().text())
    green = int(
        doc.elementsByTagName("CanvasColorGreenPart").at(0).toElement().text())
    blue = int(
        doc.elementsByTagName("CanvasColorBluePart").at(0).toElement().text())
    mapSettings.setBackgroundColor(QColor(red, green, blue))

    return mapSettings
Exemplo n.º 19
0
 def map_settings(self):
     """
     Return the settings that have been set for the map canvas.
     @return: A QgsMapSettings instance with the settings read from the project.
     """
     xml = open(QgsProject.instance().fileName()).read()
     doc = QDomDocument()
     doc.setContent(xml)
     canvasnodes = doc.elementsByTagName("mapcanvas")
     node = canvasnodes.at(0).toElement()
     settings = QgsMapSettings()
     settings.readXML(node)
     return settings
    def testQgsSimpleLineSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsSimpleLineSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsSimpleLineSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('LineSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSimpleLineSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#aa007f')
        mValue = mSymbolLayer.color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 1.26
        mValue = mSymbolLayer.width()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.RoundCap
        mValue = mSymbolLayer.penCapStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.MiterJoin
        mValue = mSymbolLayer.penJoinStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = True
        mValue = mSymbolLayer.useCustomDashPattern()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = [5.0, 2.0]
        mValue = mSymbolLayer.customDashVector()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 21
0
    def testQgsSimpleLineSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString('QgsSimpleLineSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(),
                                                  mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsSimpleLineSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('LineSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSimpleLineSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#aa007f')
        mValue = mSymbolLayer.color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 1.26
        mValue = mSymbolLayer.width()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.RoundCap
        mValue = mSymbolLayer.penCapStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.MiterJoin
        mValue = mSymbolLayer.penJoinStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = True
        mValue = mSymbolLayer.useCustomDashPattern()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = [5.0, 2.0]
        mValue = mSymbolLayer.customDashVector()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
    def testQgsPointPatternFillSymbolLayer(self):
        '''
        Create a new style from a .sld file and match test
        '''
        # at the moment there is an empty createFromSld implementation
        # that return nulls
        mTestName = QString('QgsPointPatternFillSymbolLayer')
        mFilePath = QDir.toNativeSeparators(
            QString ('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsPointPatternFillSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsPointPatternFillSymbolLayer())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'triangle')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ffaa00')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ff007f')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 5
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 3
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 23
0
    def testQgsPointPatternFillSymbolLayer(self):
        '''
        Create a new style from a .sld file and match test
        '''
        # at the moment there is an empty createFromSld implementation
        # that return nulls
        mTestName = QString('QgsPointPatternFillSymbolLayer')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(),
                                                  mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsPointPatternFillSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsPointPatternFillSymbolLayer())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'triangle')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ffaa00')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ff007f')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 5
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 3
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
    def testQgsEllipseSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsEllipseSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsEllipseSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsEllipseSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'circle')
        mValue = mSymbolLayer.symbolName()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ffff7f')
        mValue = mSymbolLayer.fillColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#aaaaff')
        mValue = mSymbolLayer.outlineColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 7
        mValue = mSymbolLayer.symbolWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 5
        mValue = mSymbolLayer.symbolHeight()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 25
0
    def testQgsEllipseSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString('QgsEllipseSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(),
                                                  mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsEllipseSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsEllipseSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'circle')
        mValue = mSymbolLayer.symbolName()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ffff7f')
        mValue = mSymbolLayer.fillColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#aaaaff')
        mValue = mSymbolLayer.outlineColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 7
        mValue = mSymbolLayer.symbolWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 5
        mValue = mSymbolLayer.symbolHeight()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 26
0
    def getlocalepisodes(self, showid, seasonid):
        '''
        @type showid: str
        @type seasonid: str
        @rtype: list
        '''
        episodes = []

        if self._storage.exists('shows/%s/en.xml' % showid):
            data = self._storage.getdata('shows/%s/en.xml' % showid)
            
            xml = QDomDocument()
            xml.setContent(data)
            
            episodelist = xml.elementsByTagName('Episode')
            
            for episodenum in range(episodelist.count()):
                
                if seasonid == unicode(QString(episodelist.at(episodenum).toElement().elementsByTagName('seasonid').at(0).childNodes().at(0).toText().data())):
                    
                    newepisode = episode()
                    
                    number = QString(episodelist.at(episodenum).toElement().elementsByTagName('EpisodeNumber').at(0).childNodes().at(0).toText().data()).toInt()
                    if number[1]:
                        newepisode.number = number[0]
                    else:
                        newepisode.number = 0
                    
                    if newepisode.number > 0:
                        newepisode.id = unicode(QString(episodelist.at(episodenum).toElement().elementsByTagName('id').at(0).childNodes().at(0).toText().data()))
                        newepisode.name = unicode(QString(episodelist.at(episodenum).toElement().elementsByTagName('EpisodeName').at(0).childNodes().at(0).toText().data()))
                        newepisode.description = unicode(QString(episodelist.at(episodenum).toElement().elementsByTagName('Overview').at(0).childNodes().at(0).toText().data()))
                                            
                        datestring = unicode(QString(episodelist.at(episodenum).toElement().elementsByTagName('FirstAired').at(0).childNodes().at(0).toText().data()))
                        if len(datestring) > 0:
                            newepisode.date = datetime.fromtimestamp(mktime(strptime(datestring, '%Y-%m-%d')))
                                                    
                        newepisode.showid = showid
                        newepisode.seasonid = seasonid
                        
                        newepisode.watched = self.getwatched(newepisode.showid, newepisode.seasonid, newepisode.id)

                        episodes.append(newepisode)
                
        return sorted(episodes, key = lambda item: item.number)
Exemplo n.º 27
0
    def testQgsLinePatternFillSymbolLayer(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString('QgsLinePatternFillSymbolLayer')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(),
                                                  mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsLinePatternFillSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsLinePatternFillSymbolLayer())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ff55ff')
        mValue = mSymbolLayer.color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 1.5
        mValue = mSymbolLayer.lineWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 4
        mValue = mSymbolLayer.distance()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 57
        mValue = mSymbolLayer.lineAngle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
    def testQgsLinePatternFillSymbolLayer(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsLinePatternFillSymbolLayer')
        mFilePath = QDir.toNativeSeparators(
            QString ('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsLinePatternFillSymbolLayer.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsLinePatternFillSymbolLayer())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ff55ff')
        mValue = mSymbolLayer.color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 1.5
        mValue = mSymbolLayer.lineWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 4
        mValue = mSymbolLayer.distance()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 57
        mValue = mSymbolLayer.lineAngle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
    def testQgsMarkerLineSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsMarkerLineSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsMarkerLineSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('LineSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsMarkerLineSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QgsMarkerLineSymbolLayerV2.CentralPoint
        mValue = mSymbolLayer.placement()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString (u'circle')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#000000')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ff0000')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 30
0
    def testQgsMarkerLineSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString('QgsMarkerLineSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(),
                                                  mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsMarkerLineSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('LineSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsMarkerLineSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QgsMarkerLineSymbolLayerV2.CentralPoint
        mValue = mSymbolLayer.placement()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'circle')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#000000')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ff0000')
        mValue = mSymbolLayer.subSymbol().symbolLayer(0).color().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 31
0
    def testQgsFontMarkerSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString('QgsFontMarkerSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(),
                                                  mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsFontMarkerSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsFontMarkerSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'Arial')
        mValue = mSymbolLayer.fontFamily()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QChar(0x4d)
        mValue = mSymbolLayer.character()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 6.23
        mValue = mSymbolLayer.size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 3
        mValue = mSymbolLayer.angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
    def testQgsFontMarkerSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsFontMarkerSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsFontMarkerSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PointSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsFontMarkerSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'Arial')
        mValue = mSymbolLayer.fontFamily()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QChar(0x4d)
        mValue = mSymbolLayer.character()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 6.23
        mValue = mSymbolLayer.size()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 3
        mValue = mSymbolLayer.angle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 33
0
    def __loadmirrors(self):
        data = self._request('http://www.thetvdb.com/api/%s/mirrors.xml' % self.__apikey())

        xml = QDomDocument()
        xml.setContent(data)
        
        mirrors = xml.elementsByTagName('Mirror')
        
        for i in range(len(mirrors)):
            typemask = QString(mirrors.at(i).toElement().elementsByTagName('typemask').at(0).childNodes().at(0).toText().data()).toInt()
            mirrorpath = unicode(QString(mirrors.at(i).toElement().elementsByTagName('mirrorpath').at(0).childNodes().at(0).toText().data()))
            
            if typemask[1]:
                if typemask[0] & 1:
                    self.__mirrors[0].append(mirrorpath)
                    
                if typemask[0] & 2:
                    self.__mirrors[1].append(mirrorpath)
                    
                if typemask[0] & 4:
                    self.__mirrors[2].append(mirrorpath)
    def testQgsSimpleFillSymbolLayerV2(self):
        '''Create a new style from a .sld file and match test.
        '''
        mTestName = QString ('QgsSimpleFillSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(
                unitTestDataPath(), mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile (mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile,True)
        mFile.close()
        mSymbolLayer = QgsSimpleFillSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSimpleFillSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.SolidPattern
        mValue = mSymbolLayer.brushStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ffaa7f')
        mValue = mSymbolLayer.borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.DotLine
        mValue = mSymbolLayer.borderStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 0.26
        mValue = mSymbolLayer.borderWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue,mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 35
0
    def testQgsSimpleFillSymbolLayerV2(self):
        '''Create a new style from a .sld file and match test.
        '''
        mTestName = QString('QgsSimpleFillSymbolLayerV2')
        mFilePath = QDir.toNativeSeparators(
            QString('%1/symbol_layer/%2.sld').arg(unitTestDataPath(),
                                                  mTestName))

        mDoc = QDomDocument(mTestName)
        mFile = QFile(mFilePath)
        mFile.open(QIODevice.ReadOnly)
        mDoc.setContent(mFile, True)
        mFile.close()
        mSymbolLayer = QgsSimpleFillSymbolLayerV2.createFromSld(
            mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement())

        mExpectedValue = type(QgsSimpleFillSymbolLayerV2())
        mValue = type(mSymbolLayer)
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.SolidPattern
        mValue = mSymbolLayer.brushStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = QString(u'#ffaa7f')
        mValue = mSymbolLayer.borderColor().name()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = Qt.DotLine
        mValue = mSymbolLayer.borderStyle()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage

        mExpectedValue = 0.26
        mValue = mSymbolLayer.borderWidth()
        mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue)
        assert mExpectedValue == mValue, mMessage
Exemplo n.º 36
0
    def loadqlr(self):
        path = QFileDialog.getOpenFileName(self.iface.mainWindow(), "Add QGIS Layer Definition", QDir.home().path(), "*.qlr")
        if not path:
            return

        with open(path, 'r') as f:
            content = f.read()

        doc = QDomDocument()
        doc.setContent(content)
        layernode = doc.elementsByTagName('maplayer').at(0)
        layerelm = layernode.toElement()

        layertype = layerelm.attribute("type")
        layer = None
        if layertype == "vector":
            layer = QgsVectorLayer()
        elif layertype == 'raster':
            layer = QgsRasterLayer()

        ok = layer.readLayerXML(layerelm)
        if ok:
            QgsMapLayerRegistry.instance().addMapLayer(layer)
Exemplo n.º 37
0
    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
Exemplo n.º 38
0
    def xmlDownloaded(self, nr, state):
        """ populate the plugins object with the fetched data """
        if not self.httpId.has_key(nr):
            return
        reposName = self.httpId[nr]
        if state:  # fetching failed
            self.mRepositories[reposName]["state"] = 3
            self.mRepositories[reposName]["error"] = self.mRepositories[
                reposName]["QPHttp"].errorString()
        else:
            repoData = self.mRepositories[reposName]["xmlData"]
            reposXML = QDomDocument()
            reposXML.setContent(repoData.data())
            pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
            if pluginNodes.size():
                for i in range(pluginNodes.size()):
                    fileName = pluginNodes.item(i).firstChildElement(
                        "file_name").text().strip()
                    if not fileName:
                        fileName = QFileInfo(
                            pluginNodes.item(i).firstChildElement(
                                "download_url").text().strip().split("?")
                            [0]).fileName()
                    name = fileName.partition(".")[0]
                    experimental = False
                    if pluginNodes.item(i).firstChildElement(
                            "experimental").text().strip().upper() in [
                                "TRUE", "YES"
                            ]:
                        experimental = True
                    icon = pluginNodes.item(i).firstChildElement(
                        "icon").text().strip()
                    if icon and not icon.startswith("http"):
                        icon = "http://%s/%s" % (QUrl(
                            self.mRepositories[reposName]["url"]).host(), icon)

                    plugin = {
                        "id":
                        name,
                        "name":
                        pluginNodes.item(i).toElement().attribute("name"),
                        "version_available":
                        pluginNodes.item(i).toElement().attribute("version"),
                        "description":
                        pluginNodes.item(i).firstChildElement(
                            "description").text().strip(),
                        "author_name":
                        pluginNodes.item(i).firstChildElement(
                            "author_name").text().strip(),
                        "homepage":
                        pluginNodes.item(i).firstChildElement(
                            "homepage").text().strip(),
                        "download_url":
                        pluginNodes.item(i).firstChildElement(
                            "download_url").text().strip(),
                        "category":
                        pluginNodes.item(i).firstChildElement(
                            "category").text().strip(),
                        "tags":
                        pluginNodes.item(i).firstChildElement(
                            "tags").text().strip(),
                        "changelog":
                        pluginNodes.item(i).firstChildElement(
                            "changelog").text().strip(),
                        "author_email":
                        pluginNodes.item(i).firstChildElement(
                            "author_email").text().strip(),
                        "tracker":
                        pluginNodes.item(i).firstChildElement(
                            "tracker").text().strip(),
                        "code_repository":
                        pluginNodes.item(i).firstChildElement(
                            "repository").text().strip(),
                        "downloads":
                        pluginNodes.item(i).firstChildElement(
                            "downloads").text().strip(),
                        "average_vote":
                        pluginNodes.item(i).firstChildElement(
                            "average_vote").text().strip(),
                        "rating_votes":
                        pluginNodes.item(i).firstChildElement(
                            "rating_votes").text().strip(),
                        "icon":
                        icon,
                        "experimental":
                        experimental,
                        "filename":
                        fileName,
                        "installed":
                        False,
                        "available":
                        True,
                        "status":
                        "not installed",
                        "error":
                        "",
                        "error_details":
                        "",
                        "version_installed":
                        "",
                        "zip_repository":
                        reposName,
                        "library":
                        "",
                        "readonly":
                        False
                    }
                    qgisMinimumVersion = pluginNodes.item(i).firstChildElement(
                        "qgis_minimum_version").text().strip()
                    if not qgisMinimumVersion: qgisMinimumVersion = "2"
                    qgisMaximumVersion = pluginNodes.item(i).firstChildElement(
                        "qgis_maximum_version").text().strip()
                    if not qgisMaximumVersion:
                        qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
                    #if compatible, add the plugin to the list
                    if not pluginNodes.item(i).firstChildElement(
                            "disabled").text().strip().upper() in [
                                "TRUE", "YES"
                            ]:
                        if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion,
                                        qgisMaximumVersion):
                            #add the plugin to the cache
                            plugins.addFromRepository(plugin)
            # set state=2, even if the repo is empty
            self.mRepositories[reposName]["state"] = 2

        self.repositoryFetched.emit(reposName)

        # is the checking done?
        if not self.fetchingInProgress():
            self.checkingDone.emit()
Exemplo n.º 39
0
    def xmlDownloaded(self):
        """ populate the plugins object with the fetched data """
        reply = self.sender()
        reposName = reply.property('reposName')
        if reply.error() != QNetworkReply.NoError:                             # fetching failed
            self.mRepositories[reposName]["state"] = 3
            self.mRepositories[reposName]["error"] = reply.errorString()
            if reply.error() == QNetworkReply.OperationCanceledError:
                self.mRepositories[reposName]["error"] += "\n\n" + QCoreApplication.translate("QgsPluginInstaller", "If you haven't cancelled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window.")
        else:
            reposXML = QDomDocument()
            content = reply.readAll()
            # Fix lonely ampersands in metadata
            a = QByteArray()
            a.append("& ")
            b = QByteArray()
            b.append("&amp; ")
            content = content.replace(a, b)
            reposXML.setContent(content)
            pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
            if pluginNodes.size():
                for i in range(pluginNodes.size()):
                    fileName = pluginNodes.item(i).firstChildElement("file_name").text().strip()
                    if not fileName:
                        fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().strip().split("?")[0]).fileName()
                    name = fileName.partition(".")[0]
                    experimental = False
                    if pluginNodes.item(i).firstChildElement("experimental").text().strip().upper() in ["TRUE", "YES"]:
                        experimental = True
                    deprecated = False
                    if pluginNodes.item(i).firstChildElement("deprecated").text().strip().upper() in ["TRUE", "YES"]:
                        deprecated = True
                    icon = pluginNodes.item(i).firstChildElement("icon").text().strip()
                    if icon and not icon.startswith("http"):
                        icon = "http://%s/%s" % (QUrl(self.mRepositories[reposName]["url"]).host(), icon)

                    if pluginNodes.item(i).toElement().hasAttribute("plugin_id"):
                        plugin_id = pluginNodes.item(i).toElement().attribute("plugin_id")
                    else:
                        plugin_id = None

                    plugin = {
                        "id": name,
                        "plugin_id": plugin_id,
                        "name": pluginNodes.item(i).toElement().attribute("name"),
                        "version_available": pluginNodes.item(i).toElement().attribute("version"),
                        "description": pluginNodes.item(i).firstChildElement("description").text().strip(),
                        "about": pluginNodes.item(i).firstChildElement("about").text().strip(),
                        "author_name": pluginNodes.item(i).firstChildElement("author_name").text().strip(),
                        "homepage": pluginNodes.item(i).firstChildElement("homepage").text().strip(),
                        "download_url": pluginNodes.item(i).firstChildElement("download_url").text().strip(),
                        "category": pluginNodes.item(i).firstChildElement("category").text().strip(),
                        "tags": pluginNodes.item(i).firstChildElement("tags").text().strip(),
                        "changelog": pluginNodes.item(i).firstChildElement("changelog").text().strip(),
                        "author_email": pluginNodes.item(i).firstChildElement("author_email").text().strip(),
                        "tracker": pluginNodes.item(i).firstChildElement("tracker").text().strip(),
                        "code_repository": pluginNodes.item(i).firstChildElement("repository").text().strip(),
                        "downloads": pluginNodes.item(i).firstChildElement("downloads").text().strip(),
                        "average_vote": pluginNodes.item(i).firstChildElement("average_vote").text().strip(),
                        "rating_votes": pluginNodes.item(i).firstChildElement("rating_votes").text().strip(),
                        "icon": icon,
                        "experimental": experimental,
                        "deprecated": deprecated,
                        "filename": fileName,
                        "installed": False,
                        "available": True,
                        "status": "not installed",
                        "error": "",
                        "error_details": "",
                        "version_installed": "",
                        "zip_repository": reposName,
                        "library": "",
                        "readonly": False
                    }
                    qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().strip()
                    if not qgisMinimumVersion:
                        qgisMinimumVersion = "2"
                    qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().strip()
                    if not qgisMaximumVersion:
                        qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
                    #if compatible, add the plugin to the list
                    if not pluginNodes.item(i).firstChildElement("disabled").text().strip().upper() in ["TRUE", "YES"]:
                        if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):
                            #add the plugin to the cache
                            plugins.addFromRepository(plugin)
                self.mRepositories[reposName]["state"] = 2
            else:
                # no plugin metadata found
                self.mRepositories[reposName]["state"] = 3
                if reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) == 200:
                    self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options.")
                else:
                    self.mRepositories[reposName]["error"] = QCoreApplication.translate("QgsPluginInstaller", "Status code:") + " %d %s" % (
                        reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
                        reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute)
                    )

        self.repositoryFetched.emit(reposName)

        # is the checking done?
        if not self.fetchingInProgress():
            self.checkingDone.emit()

        reply.deleteLater()
Exemplo n.º 40
0
class EntityImporter():
    """
    class constructor
    """
    def __init__(self, instance):
        """
        Initialize variables
        """
        self.instance = instance
        self.instance_doc = QDomDocument()
        self.set_instance_document(self.instance)
        self.key_watch = 0

    def set_instance_document(self, file_p):
        """
        :param file_p: str
        :return: file
        :rtype QFile
        """
        file_path = QFile(file_p)
        if file_path.open(QIODevice.ReadOnly):
            self.instance_doc.setContent(file_path)

    def entity_attributes_from_instance(self, entity):
        """
        Get particular entity attributes from the
        instance document
        param: table short_name
        type: string
        return: table column name and column data
        :rtype: dictionary
        """
        attributes = {}
        nodes = self.instance_doc.elementsByTagName(entity)
        entity_nodes = nodes.item(0).childNodes()
        if entity_nodes:
            for j in range(entity_nodes.count()):
                node_val = entity_nodes.item(j).toElement()
                attributes[node_val.nodeName()] = node_val.text().rstrip()
        return attributes

    def social_tenure_definition_captured(self):
        """
        Let find find out if str is defined for the particular data collection
        file instance. if exist, bool the result
        :return:
        """
        has_str_defined = False
        try:
            attributes = self.entity_attributes_from_instance('social_tenure')
            if attributes is not None or len(attributes) > 0:
                has_str_defined = True
        except:
            pass
        return has_str_defined

    def process_social_tenure(self, attributes, ids):
        """
        Save social tenure entity. It has to be saved separately
        because its need to be saved last and its handled differently
        :return:
        """
        if attributes and ids:
            entity_add = Save2DB('social_tenure', attributes, ids)
            entity_add.objects_from_supporting_doc(self.instance)
            entity_add.save_to_db()
Exemplo n.º 41
0
  def xmlDownloaded(self):
    """ populate the plugins object with the fetched data """
    reply = self.sender()
    reposName = reply.property( 'reposName' )
    if reply.error() != QNetworkReply.NoError:                             # fetching failed
      self.mRepositories[reposName]["state"] =  3
      self.mRepositories[reposName]["error"] = str(reply.error())
    else:
      reposXML = QDomDocument()
      reposXML.setContent(reply.readAll())
      pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
      if pluginNodes.size():
        for i in range(pluginNodes.size()):
          fileName = pluginNodes.item(i).firstChildElement("file_name").text().strip()
          if not fileName:
              fileName = QFileInfo(pluginNodes.item(i).firstChildElement("download_url").text().strip().split("?")[0]).fileName()
          name = fileName.partition(".")[0]
          experimental = False
          if pluginNodes.item(i).firstChildElement("experimental").text().strip().upper() in ["TRUE","YES"]:
            experimental = True
          icon = pluginNodes.item(i).firstChildElement("icon").text().strip()
          if icon and not icon.startswith("http"):
            icon = "http://%s/%s" % ( QUrl(self.mRepositories[reposName]["url"]).host() , icon )

          plugin = {
            "id"            : name,
            "name"          : pluginNodes.item(i).toElement().attribute("name"),
            "version_available" : pluginNodes.item(i).toElement().attribute("version"),
            "description"   : pluginNodes.item(i).firstChildElement("description").text().strip(),
            "author_name"   : pluginNodes.item(i).firstChildElement("author_name").text().strip(),
            "homepage"      : pluginNodes.item(i).firstChildElement("homepage").text().strip(),
            "download_url"  : pluginNodes.item(i).firstChildElement("download_url").text().strip(),
            "category"      : pluginNodes.item(i).firstChildElement("category").text().strip(),
            "tags"          : pluginNodes.item(i).firstChildElement("tags").text().strip(),
            "changelog"     : pluginNodes.item(i).firstChildElement("changelog").text().strip(),
            "author_email"  : pluginNodes.item(i).firstChildElement("author_email").text().strip(),
            "tracker"       : pluginNodes.item(i).firstChildElement("tracker").text().strip(),
            "code_repository"  : pluginNodes.item(i).firstChildElement("repository").text().strip(),
            "downloads"     : pluginNodes.item(i).firstChildElement("downloads").text().strip(),
            "average_vote"  : pluginNodes.item(i).firstChildElement("average_vote").text().strip(),
            "rating_votes"  : pluginNodes.item(i).firstChildElement("rating_votes").text().strip(),
            "icon"          : icon,
            "experimental"  : experimental,
            "filename"      : fileName,
            "installed"     : False,
            "available"     : True,
            "status"        : "not installed",
            "error"         : "",
            "error_details" : "",
            "version_installed" : "",
            "zip_repository"    : reposName,
            "library"      : "",
            "readonly"     : False
          }
          qgisMinimumVersion = pluginNodes.item(i).firstChildElement("qgis_minimum_version").text().strip()
          if not qgisMinimumVersion: qgisMinimumVersion = "2"
          qgisMaximumVersion = pluginNodes.item(i).firstChildElement("qgis_maximum_version").text().strip()
          if not qgisMaximumVersion: qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
          #if compatible, add the plugin to the list
          if not pluginNodes.item(i).firstChildElement("disabled").text().strip().upper() in ["TRUE","YES"]:
            if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):
              #add the plugin to the cache
              plugins.addFromRepository(plugin)
      # set state=2, even if the repo is empty
      self.mRepositories[reposName]["state"] = 2

    self.repositoryFetched.emit( reposName )

    # is the checking done?
    if not self.fetchingInProgress():
      self.checkingDone.emit()

    del reply
Exemplo n.º 42
0
    def doXml(self, operate):

        self.listWidget.clear()
        self.listWidget.addItem(QString("没有找到相关内容!"))
        file = QFile("my.xml")
        if (not file.open(QIODevice.ReadOnly)):
            raise Exception("open file Err")
        doc = QDomDocument()
        status, rrorMsg, errorLine, errorColumn = doc.setContent(file)
        if (not status):
            file.close()
            raise Exception(str(rrorMsg))
        file.close()

        # 以标签名进行查找
        list = doc.elementsByTagName(QString("图书"))  # 获取所有图书元素的列表

        for i in range(list.count()):
            e = list.at(i).toElement()
            if (e.attribute(QString("编号")) == self.lineEdit.text()):
                # 如果元素的“编号”属性值与我们所查的相同
                if (operate == "delete"):  # 如果是删除操作
                    root = doc.documentElement()
                    # 从根节点上删除该节点
                    root.removeChild(list.at(i))
                    file = QFile("my.xml")
                    if (not file.open(QIODevice.WriteOnly
                                      | QIODevice.Truncate)):
                        raise Exception("open file Err")
                    out = QTextStream(file)
                    doc.save(out, 4)
                    file.close()
                    self.listWidget.clear()
                    self.listWidget.addItem(QString("删除成功!"))
                elif operate is "update":
                    # 如果是更新操作
                    child = list.at(i).childNodes()
                    # 将它子节点的首个子节点(就是文本节点)的内容更新
                    child.at(0).toElement().firstChild().setNodeValue(
                        self.lineEdit_2.text())
                    child.at(1).toElement().firstChild().setNodeValue(
                        self.lineEdit_3.text())
                    file = QFile("my.xml")
                    if (not file.open(QIODevice.WriteOnly
                                      | QIODevice.Truncate)):
                        raise Exception("Open file Err")
                    out = QTextStream(file)
                    doc.save(out, 4)
                    file.close()
                    self.listWidget.clear()
                    self.listWidget.addItem(QString("更新成功!"))
                elif operate is "find":
                    # 如果是查找操作
                    self.listWidget.clear()
                    self.listWidget.addItem(e.tagName() +
                                            e.attribute(QString("编号")))
                    list = e.childNodes()
                    for i in range(list.count()):

                        node = list.at(i)
                        if (node.isElement()):
                            self.listWidget.addItem(
                                "   " + node.toElement().tagName() + " : " +
                                node.toElement().text())
Exemplo n.º 43
0
    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)
Exemplo n.º 44
0
    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)
Exemplo n.º 45
0
class EntityImporter():
    """
    class constructor
    """
    def __init__(self, instance):
        """
        Initialize variables
        """
        self.instance = instance
        self.instance_doc = QDomDocument()
        self.set_instance_document(self.instance)
        self.key_watch = 0

    def set_instance_document(self, file_p):
        """
        :param file_p: str
        :return: file
        :rtype QFile
        """
        file_path = QFile(file_p)
        if file_path.open(QIODevice.ReadOnly):
            self.instance_doc.setContent(file_path)

    def entity_attributes_from_instance(self, entity):
        """
        Get particular entity attributes from the
        instance document
        param: table short_name
        type: string
        return: table column name and column data
        :rtype: dictionary
        """
        attributes = {}
        nodes = self.instance_doc.elementsByTagName(entity)
        entity_nodes = nodes.item(0).childNodes()
        if entity_nodes:
            for j in range(entity_nodes.count()):
                node_val = entity_nodes.item(j).toElement()
                attributes[node_val.nodeName()] = node_val.text().rstrip()
        return attributes

    def social_tenure_definition_captured(self):
        """
        Let find find out if str is defined for the particular data collection
        file instance. if exist, bool the result
        :return:
        """
        has_str_defined = False
        try:
            attributes = self.entity_attributes_from_instance('social_tenure')
            if attributes is not None or len(attributes) > 0:
                has_str_defined = True
        except:
            pass
        return has_str_defined

    def process_social_tenure(self, attributes, ids):
        """
        Save social tenure entity. It has to be saved separately
        because its need to be saved last and its handled differently
        :return:
        """
        if attributes and ids:
            entity_add = Save2DB('social_tenure', attributes, ids)
            entity_add.objects_from_supporting_doc(self.instance)
            entity_add.save_to_db()
Exemplo n.º 46
0
class InstanceUUIDExtractor():
    """
    Class constructor
    """
    def __init__(self, path):
        """
        Initatlize class variables
        """
        self.file_path = path
        self.file = None
        self.new_list = []
        self.doc = QDomDocument()
        self.node = QDomNode()

    def set_file_path(self, path):
        """
        Update the path based on the new file being read
        :param path:
        :return:
        """
        self.file_path = path

    def unset_path(self):
        """Clear the current document path"""
        self.file_path = None

    def set_document(self):
        """
        :return:
        """
        self.file = QFile(self.file_path)
        if self.file.open(QIODevice.ReadOnly):
            self.doc.setContent(self.file)
        self.file.close()

    def update_document(self):
        '''Update the current instance by clearing the document in the cache '''
        self.doc.clear()
        self.set_document()

    def on_file_passed(self):
        """
        Pass the raw file to an xml document object and format the its filename to GeoODK standards
        :return:
        """
        try:
            self.set_document()
            self.read_uuid_element()
            self.doc.clear()
            self.file.close()
            self.rename_file()
        except:
            pass

    def read_uuid_element(self):
        """
        get the uuid element and text from the xml document from the mobile divice
        """
        node = self.doc.elementsByTagName("meta")
        for i in range(node.count()):
            node = node.item(i).firstChild().toElement()
            self.node = node.text()
        return self.node

    def document_entities(self, profile):
        """
        Get entities in the document
        :return:
        """
        self.set_document()
        node_list = []
        nodes = self.doc.elementsByTagName(profile)
        node = nodes.item(0).childNodes()
        if node:
            for j in range(node.count()):
                node_val = node.item(j)
                node_list.append(node_val.nodeName())
        return node_list

    def profile_entity_nodes(self, profile):
        '''
        Fetch and return QDomNodeList for entities of a
        profile
        :rtype: QDomNodeList
        '''
        self.set_document()
        nodes = self.doc.elementsByTagName(profile)
        return nodes.item(0).childNodes()

    def document_entities_with_data(self, profile, selected_entities):
        """
        Get entities in the dom document matching user
        selected entities
        :rtype: OrderedDict
        """

        instance_data = OrderedDict()
        self.set_document()
        nodes = self.doc.elementsByTagName(profile)
        entity_nodes = nodes.item(0).childNodes()
        for attrs in range(entity_nodes.count()):
            if entity_nodes.item(attrs).nodeName() in selected_entities:
                name_entity = entity_nodes.item(attrs).nodeName()
                attr_nodes = self.doc.elementsByTagName(name_entity)
                instance_data[attr_nodes] = name_entity
        return instance_data

    def attribute_data_from_nodelist(self, args_list):
        """
        process nodelist data before Importing  attribute data into db
        """
        repeat_instance_data = OrderedDict()
        attribute_data = OrderedDict()
        for attr_nodes, entity in args_list.iteritems():
            '''The assuption is that there are repeated entities from mobile sub forms. handle them separately'''
            if attr_nodes.count() > 1:
                for i in range(attr_nodes.count()):
                    attrib_node = attr_nodes.at(i).childNodes()
                    attr_list = OrderedDict()
                    for j in range(attrib_node.count()):
                        field_name = attrib_node.at(j).nodeName()
                        field_value = attrib_node.at(j).toElement().text()
                        attr_list[field_name] = field_value
                    repeat_instance_data['{}'.format(i) + entity] = attr_list
            else:
                '''Entities must appear onces in the form'''
                node_list_var = OrderedDict()
                attr_node = attr_nodes.at(0).childNodes()
                for j in range(attr_node.count()):
                    field_name = attr_node.at(j).nodeName()
                    field_value = attr_node.at(j).toElement().text()
                    node_list_var[field_name] = field_value
                attribute_data[entity] = node_list_var
        return attribute_data, repeat_instance_data

    def read_attribute_data_from_node(self, node, entity_name):
        """Read attribute data from a node item"""
        node_list_var = OrderedDict()
        attributes = OrderedDict()
        attr_node = node.at(0).childNodes()
        for j in range(attr_node.count()):
            field_name = attr_node.at(j).nodeName()
            field_value = attr_node.at(j).toElement().text()
            node_list_var[field_name] = field_value
        attributes[entity_name] = node_list_var
        return attributes

    def str_definition(self, instance=None):
        """
        Check if the instance file has entry social tenure
        :return:
        """
        if instance:
            self.set_file_path(instance)
            self.set_document()
        attributes = {}
        nodes = self.doc.elementsByTagName('social_tenure')
        entity_nodes = nodes.item(0).childNodes()
        if entity_nodes:
            for j in range(entity_nodes.count()):
                node_val = entity_nodes.item(j).toElement()
                attributes[node_val.nodeName()] = node_val.text().rstrip()
        return attributes

    def has_str_captured_in_instance(self, instance):
        """
        Bool if the str inclusion is required based on whether is captured or not
        :return:
        """
        count = len(self.str_definition(instance))
        return True if count > 1 else False

    def entity_atrributes(self):
        """
        Get collected data from the entity in the document
        :return:
        """
        pass

    def uuid_element(self):
        """
        Format the guuid from the file
        :return:
        """
        return self.node.replace(":", "")

    def rename_file(self):
        """
        Remane the existing instance file with Guuid from the mobile divice to conform with GeoODk naming
        convention
        :return:
        """
        if isinstance(self.file, QFile):
            dir_n, file_n = os.path.split(self.file_path)
            os.chdir(dir_n)
            if not file_n.startswith(UUID):
                new_file_name = self.uuid_element() + ".xml"
                isrenamed = self.file.setFileName(new_file_name)
                os.rename(file_n, new_file_name)
                self.new_list.append(new_file_name)
                return isrenamed
            else:
                self.new_list.append(self.file.fileName())
            self.file.close()
        else:
            return

    def file_list(self):
        """
        check through the list of document to ensure they are complete file path
        """
        complete_file = []
        for fi in self.new_list:
            if os.path.isfile(fi):
                complete_file.append(fi)
            else:
                continue
        return complete_file

    def close_document(self):
        '''Close all the open documents and unset current paths'''
        self.file_path = None
        self.doc.clear()
        self.new_list = None
Exemplo n.º 47
0
class ConfigurationUtils:
    PROFILE = 'Profile'
    SOCIAL_TENURE = 'SocialTenure'
    CONFIGURATION = 'Configuration'

    def __init__(self, document):
        """
        A utility class for STDM configuration.
        :param document: The configuration
        :type document: QDomDocument
        """
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath())
        self.document = document

    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.datetime.now().strftime('%d-%m-%Y %H:%M:%S')
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))
        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def check_config_file_exists(self, config_file):
        """
        Checks if config file exists
        :returns True if folder exists else False
        :rtype bool
        """
        if os.path.isfile(
                os.path.join(self.file_handler.localPath(), config_file)):

            return True
        else:
            return False

    def read_stc(self, config_file_name):
        """
        Reads provided config file
        :returns QDomDocument, QDomDocument.documentElement()
        :rtype tuple
        """
        config_file_path = os.path.join(self.file_handler.localPath(),
                                        config_file_name)

        config_file_path = QFile(config_file_path)
        config_file = os.path.basename(config_file_name)
        if self.check_config_file_exists(config_file):

            self.document = QDomDocument()

            status, msg, line, col = self.document.setContent(config_file_path)
            if not status:
                error_message = u'Configuration file cannot be loaded: {0}'. \
                    format(msg)
                self.append_log(str(error_message))

                raise ConfigurationException(error_message)

            self.doc_element = self.document.documentElement()

    def find_node(self, name):
        """
        Get nodes inside a document by a tag name.
        :param document: The xml document
        :type document: QDomDocument
        :param name: the tag name
        :type name: String
        :return: The nodes list
        :rtype: List
        """
        node_list = self.document.elementsByTagName(name)
        nodes = []
        for i in range(node_list.length()):
            node = node_list.item(i)
            nodes.append(node)
        return nodes

    def add_attribute_to_nodes(self, nodes, attr, value):
        """
        Adds an attribute with value to node lists.
        :param nodes: List of nodes
        :type nodes: QNodeList
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        for node in nodes:
            element = node.toElement()
            element.setAttribute(attr, value)

    def add_attribute_by_node_name(self, node_name, attr, value):
        """
        Add attribute with value to nodes by node name.
        :param node_name: The name of the node.
        :type node_name: Strong
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        nodes = self.find_node(node_name)
        self.add_attribute_to_nodes(nodes, attr, value)

    def profile_first_child(self, tag_name):
        """
        Gets the first child of profile node
        with a specified tag name.
        :param tag_name: The tag name to be used
        to search the child.
        :type tag_name: String
        :return: Dictionary of parent (profile node) and
        the child element.
        :rtype: OrderedDict
        """
        profile_nodes = self.find_node(self.PROFILE)
        first_child = OrderedDict()
        for profile_node in profile_nodes:
            profile_child = profile_node.firstChildElement(tag_name)
            first_child[profile_node] = profile_child
        return first_child

    def social_tenure_elements(self):
        """
        Get all social tenure element in a dom_document.
        :return: List of social tenure element
        :rtype: OrderedDict
        """
        social_tenure_nodes = self.profile_first_child(self.SOCIAL_TENURE)
        return social_tenure_nodes

    def run(self):
        nodes = self.find_node('Entity')

        self.add_attribute_to_nodes(nodes, 'Test', 'One')
Exemplo n.º 48
0
    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
Exemplo n.º 49
0
class EntityImporter():
    """
    class constructor
    """
    def __init__(self, instance):
        """
        Initialize variables
        """
        self.instance = instance
        self.instance_doc = QDomDocument()
        self.set_instance_document(self.instance)
        self.key_watch = 0

    def set_instance_document(self, file_p):
        """

        :return:
        """
        file_path = QFile(file_p)
        if file_path.open(QIODevice.ReadOnly):
            self.instance_doc.setContent(file_path)

    def geomsetter(self, val):
        """
        Get user preferred geometry
        :param val:
        :return:int
        """
        global GEOMPARAM
        GEOMPARAM = val
        return GEOMPARAM

    def geom(self):
        """
        Return the geometry value
        :return:
        """
        return GEOMPARAM

    def entity_attributes_from_instance(self, entity):
        """
        Get particular entity attributes from the
        instance document
        param: table short_name
        type: string
        return: table column name and column data
        :rtype: dictionary
        """
        attributes = {}
        nodes = self.instance_doc.elementsByTagName(entity)
        entity_nodes = nodes.item(0).childNodes()
        if entity_nodes:
            for j in range(entity_nodes.count()):
                node_val = entity_nodes.item(j).toElement()
                attributes[node_val.nodeName()] = node_val.text().rstrip()
        return attributes

    def instance_group_id(self):
        """
        Get the unique identifier in the the current instance
        for group identification of related instance
        :param: node name
        :type: String
        :return: identifier code
        :rtype: string
        """
        global GROUPCODE
        gp_code = self.instance_doc.elementsByTagName('identity')
        if gp_code:
            user_code = gp_code.at(0).toElement().text()
            if user_code != '' or user_code is not None:
                GROUPCODE = user_code
                return user_code
            else:
                return None

    def process_import_to_db(self, entity, ids):
        """
        Save the object data to the database, object saved here
        does not form parent to any other entity
        :return:
        """
        success = False
        if self.instance_doc is not None:
            attributes = self.entity_attributes_from_instance(entity)
            entity_add = Save2DB(entity, attributes, ids)
            entity_add.objects_from_supporting_doc(self.instance)
            child_id = entity_add.save_to_db()
            entity_add.get_srid(GEOMPARAM)
            self.key_watch = entity_add.key
            success = True
        return child_id, success

    def process_parent_entity_import(self, entity):
        """
        Save entities that are parent to child tables first returning their iDS
        :param entity:
        :return:boool
        :return: gid
        :rtype: string
        """
        success = False
        if self.instance_doc is not None:
            attributes = self.entity_attributes_from_instance(entity)
            entity_add = Save2DB(entity, attributes)
            entity_add.objects_from_supporting_doc(self.instance)
            entity_add.get_srid(GEOMPARAM)
            ref_id = entity_add.save_parent_to_db()
            success = True
        return ref_id, success

    def social_tenure_definition_captured(self):
        """
        Let find find out if str is defined for the particular data collection
        file instance. if exist, bool the result
        :return:
        """
        has_str_defined = False
        try:
            attributes = self.entity_attributes_from_instance('social_tenure')
            if attributes is not None or len(attributes) > 0:
                has_str_defined = True
        except:
            pass
        return has_str_defined

    def process_social_tenure(self, ids):
        """
        Save socail tenure entity. It has to be saved separately
        because its need to be saved last and its handled differently
        :return:
        """
        if self.social_tenure_definition_captured():
            attributes = self.entity_attributes_from_instance('social_tenure')
            if attributes:
                entity_add = Save2DB('social_tenure', attributes, ids)
                entity_add.objects_from_supporting_doc(self.instance)
                entity_add.save_to_db()
        else:
            return None
Exemplo n.º 50
0
class ConfigurationUtils():
    PROFILE = 'Profile'
    SOCIAL_TENURE = 'SocialTenure'
    CONFIGURATION = 'Configuration'

    def __init__(self, document):
        """
        A utility class for STDM configuration.
        :param document: The configuration
        :type document: QDomDocument
        """
        self.file_handler = FilePaths()
        self.log_file_path = '{}/logs/migration.log'.format(
            self.file_handler.localPath()
        )
        self.document = document

    def append_log(self, info):
        """
        Append info to a single file
        :param info: update information to save to file
        :type info: str
        """
        info_file = open(self.log_file_path, "a")
        time_stamp = datetime.datetime.now().strftime(
            '%d-%m-%Y %H:%M:%S'
        )
        info_file.write('\n')
        info_file.write('{} - '.format(time_stamp))
        info_file.write(info)
        info_file.write('\n')
        info_file.close()

    def check_config_file_exists(self, config_file):
        """
        Checks if config file exists
        :returns True if folder exists else False
        :rtype bool
        """
        if os.path.isfile(os.path.join(
                self.file_handler.localPath(),
                config_file)
        ):

            return True
        else:
            return False

    def read_stc(self, config_file_name):
        """
        Reads provided config file
        :returns QDomDocument, QDomDocument.documentElement()
        :rtype tuple
        """
        config_file_path = os.path.join(
            self.file_handler.localPath(),
            config_file_name
        )

        config_file_path = QFile(config_file_path)
        config_file = os.path.basename(config_file_name)
        if self.check_config_file_exists(config_file):

            self.document = QDomDocument()

            status, msg, line, col = self.document.setContent(config_file_path)
            if not status:
                error_message = u'Configuration file cannot be loaded: {0}'.\
                    format(msg)
                self.append_log(str(error_message))

                raise ConfigurationException(error_message)

            self.doc_element = self.document.documentElement()

    def find_node(self, name):
        """
        Get nodes inside a document by a tag name.
        :param document: The xml document
        :type document: QDomDocument
        :param name: the tag name
        :type name: String
        :return: The nodes list
        :rtype: List
        """
        node_list = self.document.elementsByTagName(name)
        nodes = []
        for i in range(node_list.length()):
            node = node_list.item(i)
            nodes.append(node)
        return nodes

    def add_attribute_to_nodes(self, nodes, attr, value):
        """
        Adds an attribute with value to node lists.
        :param nodes: List of nodes
        :type nodes: QNodeList
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        for node in nodes:
            element = node.toElement()
            element.setAttribute(attr, value)

    def add_attribute_by_node_name(self, node_name, attr, value):
        """
        Add attribute with value to nodes by node name.
        :param node_name: The name of the node.
        :type node_name: Strong
        :param attr: The attribute text
        :type attr: String
        :param value: The value of the attribute.
        :type value: String
        :return:
        :rtype:
        """
        nodes = self.find_node(node_name)
        self.add_attribute_to_nodes(nodes, attr, value)

    def profile_first_child(self, tag_name):
        """
        Gets the first child of profile node
        with a specified tag name.
        :param tag_name: The tag name to be used
        to search the child.
        :type tag_name: String
        :return: Dictionary of parent (profile node) and
        the child element.
        :rtype: OrderedDict
        """
        profile_nodes = self.find_node(self.PROFILE)
        first_child = OrderedDict()
        for profile_node in profile_nodes:
            profile_child = profile_node.firstChildElement(
                tag_name
            )
            first_child[profile_node] = profile_child
        return first_child

    def social_tenure_elements(self):
        """
        Get all social tenure element in a dom_document.
        :return: List of social tenure element
        :rtype: OrderedDict
        """
        social_tenure_nodes = self.profile_first_child(
            self.SOCIAL_TENURE
        )
        return social_tenure_nodes


    def run(self):
        nodes = self.find_node('Entity')

        self.add_attribute_to_nodes(nodes, 'Test', 'One')
Exemplo n.º 51
0
    def xmlDownloaded(self, nr, state):
        """ populate the plugins object with the fetched data """
        if not self.httpId.has_key(nr):
            return
        reposName = self.httpId[nr]
        if state:  # fetching failed
            self.mRepositories[reposName]["state"] = 3
            self.mRepositories[reposName]["error"] = self.mRepositories[
                reposName]["QPHttp"].errorString()
        else:
            repoData = self.mRepositories[reposName]["xmlData"]
            reposXML = QDomDocument()
            reposXML.setContent(repoData.data())
            pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
            if pluginNodes.size():
                for i in range(pluginNodes.size()):
                    fileName = pluginNodes.item(i).firstChildElement(
                        "file_name").text().simplified()
                    if not fileName:
                        fileName = QFileInfo(
                            pluginNodes.item(i).firstChildElement(
                                "download_url").text().trimmed().split("?")
                            [0]).fileName()
                    name = fileName.section(".", 0, 0)
                    name = unicode(name)
                    experimental = False
                    if pluginNodes.item(i).firstChildElement(
                            "experimental").text().simplified().toUpper() in [
                                "TRUE", "YES"
                            ]:
                        experimental = True
                    plugin = {
                        "name":
                        pluginNodes.item(i).toElement().attribute("name"),
                        "version_avail":
                        pluginNodes.item(i).toElement().attribute("version"),
                        "desc_repo":
                        pluginNodes.item(i).firstChildElement(
                            "description").text().simplified(),
                        "desc_local":
                        "",
                        "author":
                        pluginNodes.item(i).firstChildElement(
                            "author_name").text().simplified(),
                        "homepage":
                        pluginNodes.item(i).firstChildElement(
                            "homepage").text().simplified(),
                        "url":
                        pluginNodes.item(i).firstChildElement(
                            "download_url").text().simplified(),
                        "experimental":
                        experimental,
                        "filename":
                        fileName,
                        "status":
                        "not installed",
                        "error":
                        "",
                        "error_details":
                        "",
                        "version_inst":
                        "",
                        "repository":
                        reposName,
                        "localdir":
                        name,
                        "read-only":
                        False
                    }
                    qgisMinimumVersion = pluginNodes.item(i).firstChildElement(
                        "qgis_minimum_version").text().simplified()
                    if not qgisMinimumVersion: qgisMinimumVersion = "0"
                    # please use the tag below only if really needed! (for example if plugin development is abandoned)
                    qgisMaximumVersion = pluginNodes.item(i).firstChildElement(
                        "qgis_maximum_version").text().simplified()
                    if not qgisMaximumVersion: qgisMaximumVersion = "2"
                    #if compatible, add the plugin to the list
                    if not pluginNodes.item(i).firstChildElement(
                            "disabled").text().simplified().toUpper() in [
                                "TRUE", "YES"
                            ]:
                        if compareVersions(
                                QGIS_VER,
                                qgisMinimumVersion) < 2 and compareVersions(
                                    qgisMaximumVersion, QGIS_VER) < 2:
                            if QGIS_VER[0] == qgisMinimumVersion[0] or (
                                    qgisMinimumVersion != "0"
                                    and qgisMaximumVersion != "2"
                            ):  # to be deleted
                                #add the plugin to the cache
                                plugins.addFromRepository(plugin)
            # set state=2, even if the repo is empty
            self.mRepositories[reposName]["state"] = 2

        self.emit(SIGNAL("repositoryFetched(QString)"), reposName)

        # is the checking done?
        if not self.fetchingInProgress():
            plugins.rebuild()
            self.saveCheckingOnStartLastDate()
            self.emit(SIGNAL("checkingDone()"))
Exemplo n.º 52
0
    def load(self):
        settings = QSettings('Boundless', 'BoundlessConnect')
        repoUrl = settings.value('repoUrl', '', unicode)

        repoPath = os.path.abspath(repoUrl)
        repoFile = os.path.join(repoPath, 'plugins.xml')

        repoXML = QDomDocument()
        with codecs.open(repoFile, 'r', encoding='utf-8') as f:
            content = f.read()
            repoXML.setContent(content)

        pluginNodes = repoXML.elementsByTagName('pyqgis_plugin')
        if pluginNodes.size():
            for i in xrange(pluginNodes.size()):
                fileName = pluginNodes.item(i).firstChildElement('file_name').text().strip()
                if not fileName:
                    fileName = QFileInfo(pluginNodes.item(i).firstChildElement('download_url').text().strip().split('?')[0]).fileName()
                name = fileName.partition('.')[0]

                experimental = False
                if pluginNodes.item(i).firstChildElement('experimental').text().strip().upper() in ['TRUE', 'YES']:
                    experimental = True

                deprecated = False
                if pluginNodes.item(i).firstChildElement('deprecated').text().strip().upper() in ['TRUE', 'YES']:
                    deprecated = True

                icon = pluginNodes.item(i).firstChildElement('icon').text().strip()

                if pluginNodes.item(i).toElement().hasAttribute('plugin_id'):
                    plugin_id = pluginNodes.item(i).toElement().attribute('plugin_id')
                else:
                    plugin_id = None

                plugin = {
                    'id': name,
                    'plugin_id': plugin_id,
                    'name': pluginNodes.item(i).toElement().attribute('name'),
                    'version_available': pluginNodes.item(i).toElement().attribute('version'),
                    'description': pluginNodes.item(i).firstChildElement('description').text().strip(),
                    'about': pluginNodes.item(i).firstChildElement('about').text().strip(),
                    'author_name': pluginNodes.item(i).firstChildElement('author_name').text().strip(),
                    'homepage': pluginNodes.item(i).firstChildElement('homepage').text().strip(),
                    'download_url': 'file:///{}'.format(os.path.join(repoPath, fileName)),
                    'category': pluginNodes.item(i).firstChildElement('category').text().strip(),
                    'tags': pluginNodes.item(i).firstChildElement('tags').text().strip(),
                    'changelog': pluginNodes.item(i).firstChildElement('changelog').text().strip(),
                    'author_email': pluginNodes.item(i).firstChildElement('author_email').text().strip(),
                    'tracker': pluginNodes.item(i).firstChildElement('tracker').text().strip(),
                    'code_repository': pluginNodes.item(i).firstChildElement('repository').text().strip(),
                    'downloads': pluginNodes.item(i).firstChildElement('downloads').text().strip(),
                    'average_vote': pluginNodes.item(i).firstChildElement('average_vote').text().strip(),
                    'rating_votes': pluginNodes.item(i).firstChildElement('rating_votes').text().strip(),
                    'icon': icon,
                    'experimental': experimental,
                    'deprecated': deprecated,
                    'filename': fileName,
                    'installed': False,
                    'available': True,
                    'status': 'not installed',
                    'error': '',
                    'error_details': '',
                    'version_installed': '',
                    "zip_repository": boundlessRepoName,
                    'library': '',
                    'readonly': False
                }

                qgisMinimumVersion = pluginNodes.item(i).firstChildElement('qgis_minimum_version').text().strip()
                if not qgisMinimumVersion:
                    qgisMinimumVersion = '2'
                qgisMaximumVersion = pluginNodes.item(i).firstChildElement('qgis_maximum_version').text().strip()
                if not qgisMaximumVersion:
                    qgisMaximumVersion = qgisMinimumVersion[0] + '.99'
                # If compatible, add the plugin to the list
                if not pluginNodes.item(i).firstChildElement('disabled').text().strip().upper() in ['TRUE', 'YES']:
                    if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion, qgisMaximumVersion):
                        # Add the plugin to the cache
                        repo = boundlessRepoName
                        try:
                            self.repoCache[repo] += [plugin]
                        except:
                            self.repoCache[repo] = [plugin]
Exemplo n.º 53
0
    def xmlDownloaded(self):
        """ populate the plugins object with the fetched data """
        reply = self.sender()
        reposName = reply.property('reposName')
        if reply.error() != QNetworkReply.NoError:  # fetching failed
            self.mRepositories[reposName]["state"] = 3
            self.mRepositories[reposName]["error"] = reply.errorString()
            if reply.error() == QNetworkReply.OperationCanceledError:
                self.mRepositories[reposName][
                    "error"] += "\n\n" + QCoreApplication.translate(
                        "QgsPluginInstaller",
                        "If you haven't cancelled the download manually, it was most likely caused by a timeout. In this case consider increasing the connection timeout value in QGIS options window."
                    )
        else:
            reposXML = QDomDocument()
            content = reply.readAll()
            # Fix lonely ampersands in metadata
            reposXML.setContent(content.replace("& ", "&amp; "))
            pluginNodes = reposXML.elementsByTagName("pyqgis_plugin")
            if pluginNodes.size():
                for i in range(pluginNodes.size()):
                    fileName = pluginNodes.item(i).firstChildElement(
                        "file_name").text().strip()
                    if not fileName:
                        fileName = QFileInfo(
                            pluginNodes.item(i).firstChildElement(
                                "download_url").text().strip().split("?")
                            [0]).fileName()
                    name = fileName.partition(".")[0]
                    experimental = False
                    if pluginNodes.item(i).firstChildElement(
                            "experimental").text().strip().upper() in [
                                "TRUE", "YES"
                            ]:
                        experimental = True
                    deprecated = False
                    if pluginNodes.item(i).firstChildElement(
                            "deprecated").text().strip().upper() in [
                                "TRUE", "YES"
                            ]:
                        deprecated = True
                    icon = pluginNodes.item(i).firstChildElement(
                        "icon").text().strip()
                    if icon and not icon.startswith("http"):
                        icon = "http://%s/%s" % (QUrl(
                            self.mRepositories[reposName]["url"]).host(), icon)

                    if pluginNodes.item(i).toElement().hasAttribute(
                            "plugin_id"):
                        plugin_id = pluginNodes.item(i).toElement().attribute(
                            "plugin_id")
                    else:
                        plugin_id = None

                    plugin = {
                        "id":
                        name,
                        "plugin_id":
                        plugin_id,
                        "name":
                        pluginNodes.item(i).toElement().attribute("name"),
                        "version_available":
                        pluginNodes.item(i).toElement().attribute("version"),
                        "description":
                        pluginNodes.item(i).firstChildElement(
                            "description").text().strip(),
                        "about":
                        pluginNodes.item(i).firstChildElement(
                            "about").text().strip(),
                        "author_name":
                        pluginNodes.item(i).firstChildElement(
                            "author_name").text().strip(),
                        "homepage":
                        pluginNodes.item(i).firstChildElement(
                            "homepage").text().strip(),
                        "download_url":
                        pluginNodes.item(i).firstChildElement(
                            "download_url").text().strip(),
                        "category":
                        pluginNodes.item(i).firstChildElement(
                            "category").text().strip(),
                        "tags":
                        pluginNodes.item(i).firstChildElement(
                            "tags").text().strip(),
                        "changelog":
                        pluginNodes.item(i).firstChildElement(
                            "changelog").text().strip(),
                        "author_email":
                        pluginNodes.item(i).firstChildElement(
                            "author_email").text().strip(),
                        "tracker":
                        pluginNodes.item(i).firstChildElement(
                            "tracker").text().strip(),
                        "code_repository":
                        pluginNodes.item(i).firstChildElement(
                            "repository").text().strip(),
                        "downloads":
                        pluginNodes.item(i).firstChildElement(
                            "downloads").text().strip(),
                        "average_vote":
                        pluginNodes.item(i).firstChildElement(
                            "average_vote").text().strip(),
                        "rating_votes":
                        pluginNodes.item(i).firstChildElement(
                            "rating_votes").text().strip(),
                        "icon":
                        icon,
                        "experimental":
                        experimental,
                        "deprecated":
                        deprecated,
                        "filename":
                        fileName,
                        "installed":
                        False,
                        "available":
                        True,
                        "status":
                        "not installed",
                        "error":
                        "",
                        "error_details":
                        "",
                        "version_installed":
                        "",
                        "zip_repository":
                        reposName,
                        "library":
                        "",
                        "readonly":
                        False
                    }
                    qgisMinimumVersion = pluginNodes.item(i).firstChildElement(
                        "qgis_minimum_version").text().strip()
                    if not qgisMinimumVersion: qgisMinimumVersion = "2"
                    qgisMaximumVersion = pluginNodes.item(i).firstChildElement(
                        "qgis_maximum_version").text().strip()
                    if not qgisMaximumVersion:
                        qgisMaximumVersion = qgisMinimumVersion[0] + ".99"
                    #if compatible, add the plugin to the list
                    if not pluginNodes.item(i).firstChildElement(
                            "disabled").text().strip().upper() in [
                                "TRUE", "YES"
                            ]:
                        if isCompatible(QGis.QGIS_VERSION, qgisMinimumVersion,
                                        qgisMaximumVersion):
                            #add the plugin to the cache
                            plugins.addFromRepository(plugin)
                self.mRepositories[reposName]["state"] = 2
            else:
                # no plugin metadata found
                self.mRepositories[reposName]["state"] = 3
                if reply.attribute(
                        QNetworkRequest.HttpStatusCodeAttribute) == 200:
                    self.mRepositories[reposName][
                        "error"] = QCoreApplication.translate(
                            "QgsPluginInstaller",
                            "Server response is 200 OK, but doesn't contain plugin metatada. This is most likely caused by a proxy or a wrong repository URL. You can configure proxy settings in QGIS options."
                        )
                else:
                    self.mRepositories[reposName][
                        "error"] = QCoreApplication.translate(
                            "QgsPluginInstaller",
                            "Status code:") + " %d %s" % (
                                reply.attribute(
                                    QNetworkRequest.HttpStatusCodeAttribute),
                                reply.attribute(
                                    QNetworkRequest.HttpReasonPhraseAttribute))

        self.repositoryFetched.emit(reposName)

        # is the checking done?
        if not self.fetchingInProgress():
            self.checkingDone.emit()

        reply.deleteLater()
Exemplo n.º 54
0
class InstanceUUIDExtractor():
    """
    Class constructor
    """
    def __init__(self, path):
        """
        Initatlize class variables
        """
        self.file_path = path
        self.file = None
        self.new_list = []
        self.doc = QDomDocument()
        self.node = QDomNode()

    def set_file_path(self, path):
        """
        Update the path based on the new file being read
        :param path:
        :return:
        """
        self.file_path = path

    def set_document(self):
        """

        :return:
        """
        self.file = QFile(self.file_path)
        if self.file.open(QIODevice.ReadOnly):
            self.doc.setContent(self.file)

    def on_file_passed(self):
        """
        Pass the row file to an xml document and format the name to GeoODK standards
        :return:
        """
        try:
            self.set_document()
            self.read_uuid_element()
            self.doc.clear()
            self.file.close()
            self.rename_file()
        except:
            pass

    def read_uuid_element(self):
        """
        get the uuid element and text from the xml document from the mobile divice
        """
        node = self.doc.elementsByTagName("meta")
        for i in range(node.count()):
            node = node.item(i).firstChild().toElement()
            self.node = node.text()
        return self.node

    def document_entities(self, profile):
        """
        Get entities in the document
        :return:
        """
        self.set_document()
        node_list = []
        nodes = self.doc.elementsByTagName(profile)
        node = nodes.item(0).childNodes()
        if node:
            for j in range(node.count()):
                node_val = node.item(j)
                node_list.append(node_val.nodeName())
        return node_list

    def str_definition(self):
        """
        Check if the instance file has entry social tenure
        :return:
        """
        attributes = {}
        nodes = self.doc.elementsByTagName('social_tenure')
        entity_nodes = nodes.item(0).childNodes()
        if entity_nodes:
            for j in range(entity_nodes.count()):
                node_val = entity_nodes.item(j).toElement()
                attributes[node_val.nodeName()] = node_val.text().rstrip()
        return attributes

    def has_str_captured_in_instance(self):
        """
        Bool if the str inclusion is required based on whether is captured or not
        :return:
        """
        str_defined = False
        count = len(self.str_definition())
        if count > 1:
            str_defined = True
        else:
            str_defined = False
        return str_defined

    def entity_atrributes(self):
        """
        Get collected data from the entity in the document
        :return:
        """
        pass

    def uuid_element(self):
        """
        Format the guuid from the file
        :return:
        """
        return self.node.replace(":", "")

    def rename_file(self):
        """
        Remane the existing instance file with Guuid from the mobile divice to conform with GeoODk naming
        convention
        :return:
        """
        if isinstance(self.file, QFile):
            dir_n, file_n = os.path.split(self.file_path)
            os.chdir(dir_n)
            if not file_n.startswith(UUID):
                new_file_name = self.uuid_element() + ".xml"
                isrenamed = self.file.setFileName(new_file_name)
                os.rename(file_n, new_file_name)
                self.new_list.append(new_file_name)
                return isrenamed
            else:
                self.new_list.append(self.file.fileName())
            #print str(self.new_list)
        else:
            return