Exemplo n.º 1
0
def save_project_to_file(fn):
    QgsProject.instance().write(QtCore.QFileInfo(fn))
    sleep(0.1)
Exemplo n.º 2
0
import os
Exemplo n.º 3
0
    def on_tree_clicked(self, modelIndex):

        file_path = self.model.filePath(modelIndex)
        fileInfo = QtCore.QFileInfo(file_path)
        #print fileInfo.filePath()
        self.emit(QtCore.SIGNAL("open_file"), fileInfo.filePath())
Exemplo n.º 4
0
 def setCurrentFile(self, fileName):
     self.curFile = QtCore.QFileInfo(fileName).canonicalFilePath()
     self.isUntitled = False
     self.document().setModified(False)
     self.setWindowModified(False)
     self.setWindowTitle(self.userFriendlyCurrentFile() + "[*]")
Exemplo n.º 5
0
	def check_path(self, file_path):
		"""Checks file/path exists or return none"""
		d = QtCore.QFileInfo(file_path)
		if d.exists():
			return file_path
		return None
Exemplo n.º 6
0
if len(sys.argv) == 1:
    print "Error: You have to specify the file to check"
    sys.exit(1)

for fileIndex in range(1, len(sys.argv)):
    path = sys.argv[fileIndex]
    print "Processing " + path
    xmlFile = QtCore.QFile(path)

    if xmlFile.exists():
        if (xmlFile.open(QtCore.QIODevice.ReadOnly)):
            doc = QtXml.QDomDocument()
            doc.setContent(xmlFile.readAll())
            root = doc.documentElement()
            if (root.tagName() == "map"):
                imagePath = QtCore.QFileInfo(path).absolutePath(
                ) + "/" + root.firstChildElement("mapFile").text()

                if not QtCore.QFile.exists(imagePath):
                    print QtCore.QString(
                        "Error: Map file %1 does not exist").arg(imagePath)
                    sys.exit(2)

                colorList = []
                divisionTag = root.firstChildElement("division")
                while (not divisionTag.isNull()):
                    colorTag = divisionTag.firstChildElement("color")
                    red = colorTag.firstChildElement("red").text().toInt()[0]
                    green = colorTag.firstChildElement(
                        "green").text().toInt()[0]
                    blue = colorTag.firstChildElement("blue").text().toInt()[0]
                    contains = colorList.count(QtGui.qRgb(red, green, blue))
Exemplo n.º 7
0
    def eliminate(self, inLayer, boundary, progressBar, outFileName):
        # keep references to the features to eliminate
        fidsToEliminate = inLayer.selectedFeaturesIds()

        if outFileName:  # user wants a new shape file to be created as result
            provider = inLayer.dataProvider()
            error = QgsVectorFileWriter.writeAsVectorFormat(
                inLayer, outFileName, provider.encoding(), inLayer.crs(),
                "ESRI Shapefile")

            if error != QgsVectorFileWriter.NoError:
                QtGui.QMessageBox.warning(
                    self, self.tr("Eliminate"),
                    self.tr("Error creating output file"))
                return None

            outLayer = QgsVectorLayer(
                outFileName,
                QtCore.QFileInfo(outFileName).completeBaseName(), "ogr")

        else:
            QtGui.QMessageBox.information(
                self, self.tr("Eliminate"),
                self.tr("Please specify output shapefile"))
            return None

        # delete features to be eliminated in outLayer
        outLayer.setSelectedFeatures(fidsToEliminate)
        outLayer.startEditing()

        if outLayer.deleteSelectedFeatures():
            if self.saveChanges(outLayer):
                outLayer.startEditing()
        else:
            QtGui.QMessageBox.warning(self, self.tr("Eliminate"),
                                      self.tr("Could not delete features"))
            return None

        # ANALYZE
        start = 20.00
        progressBar.setValue(start)
        add = 80.00 / len(fidsToEliminate)

        lastLen = 0
        geomsToMerge = dict()

        # we go through the list and see if we find any polygons we can merge the selected with
        # if we have no success with some we merge and then restart the whole story
        while (lastLen !=
               inLayer.selectedFeatureCount()):  #check if we made any progress
            lastLen = inLayer.selectedFeatureCount()
            fidsToDeselect = []

            #iterate over the polygons to eliminate
            for fid2Eliminate in inLayer.selectedFeaturesIds():
                feat = QgsFeature()

                if inLayer.getFeatures(QgsFeatureRequest().setFilterFid(
                        fid2Eliminate).setSubsetOfAttributes(
                            [])).nextFeature(feat):
                    geom2Eliminate = feat.geometry()
                    bbox = geom2Eliminate.boundingBox()
                    fit = outLayer.getFeatures(
                        QgsFeatureRequest().setFilterRect(bbox))
                    mergeWithFid = None
                    mergeWithGeom = None
                    max = 0

                    selFeat = QgsFeature()
                    while fit.nextFeature(selFeat):
                        selGeom = selFeat.geometry()

                        if geom2Eliminate.intersects(
                                selGeom):  # we have a candidate
                            iGeom = geom2Eliminate.intersection(selGeom)

                            if boundary:
                                selValue = iGeom.length()
                            else:
                                # we need a common boundary
                                if 0 < iGeom.length():
                                    selValue = selGeom.area()
                                else:
                                    selValue = 0

                            if selValue > max:
                                max = selValue
                                mergeWithFid = selFeat.id()
                                mergeWithGeom = QgsGeometry(
                                    selGeom)  # deep copy of the geometry

                    if mergeWithFid != None:  # a successful candidate
                        newGeom = mergeWithGeom.combine(geom2Eliminate)

                        if outLayer.changeGeometry(mergeWithFid, newGeom):
                            # write change back to disc
                            if self.saveChanges(outLayer):
                                outLayer.startEditing()
                            else:
                                return None

                            # mark feature as eliminated in inLayer
                            fidsToDeselect.append(fid2Eliminate)
                        else:
                            QtGui.QMessageBox.warning(
                                self, self.tr("Eliminate"),
                                self.
                                tr("Could not replace geometry of feature with id %s"
                                   ) % (mergeWithFid))
                            return None

                        start = start + add
                        progressBar.setValue(start)
            # end for fid2Eliminate

            # deselect features that are already eliminated in inLayer
            inLayer.deselect(fidsToDeselect)

        #end while

        if inLayer.selectedFeatureCount() > 0:
            # copy all features that could not be eliminated to outLayer
            if outLayer.addFeatures(inLayer.selectedFeatures()):
                # inform user
                fidList = ""

                for fid in inLayer.selectedFeaturesIds():
                    if not fidList == "":
                        fidList += ", "

                    fidList += str(fid)

                QtGui.QMessageBox.information(
                    self, self.tr("Eliminate"),
                    self.tr("Could not eliminate features with these ids:\n%s")
                    % (fidList))
            else:
                QtGui.QMessageBox.warning(self, self.tr("Eliminate"),
                                          self.tr("Could not add features"))

        # stop editing outLayer and commit any pending changes
        if not self.saveChanges(outLayer):
            return None

        if outFileName:
            if self.addToCanvasCheck.isChecked():
                ftools_utils.addShapeToCanvas(outFileName)
            else:
                QtGui.QMessageBox.information(
                    self, self.tr("Eliminate"),
                    self.tr("Created output shapefile:\n%s") % (outFileName))

        self.iface.mapCanvas().refresh()
Exemplo n.º 8
0
    def __init__(self, iface):

        self.iface = iface
        self.mLayer = None
        self.tLayer = None

        # Import required plugins and if missing show the plugin's name
        import sys
        ftPath = os.path.join(
            str(QtCore.QFileInfo(QgsApplication.qgisUserDbFilePath()).path()),
            'python/plugins/fTools')
        if not ftPath in sys.path:
            sys.path.append(ftPath)
        req_plugin = "ftools 0.5.10"
        try:
            import ftools_utils
        except:
            QtGui.QMessageBox.information(
                self, self.tr("Missing Plugins"),
                self.tr("Missing plugin: %s" % req_plugin))

        QtGui.QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_qm_mkgrid()
        self.ui.setupUi(self)
        self.setFixedSize(460, 582)
        QtCore.QObject.connect(self.ui.toolOut, QtCore.SIGNAL("clicked()"),
                               self.outFile)
        QtCore.QObject.connect(self.ui.spnUnitArea,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.offset)
        QtCore.QObject.connect(self.ui.spnSideLength,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.offset)
        QtCore.QObject.connect(self.ui.spnXmax,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.updateCellCount)
        QtCore.QObject.connect(self.ui.spnXmin,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.updateCellCount)
        QtCore.QObject.connect(self.ui.spnYmax,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.updateCellCount)
        QtCore.QObject.connect(self.ui.spnYmin,
                               QtCore.SIGNAL("valueChanged(double)"),
                               self.updateCellCount)
        #QObject.connect(self.inShape, SIGNAL("currentIndexChanged(QString)"), self.updateInput)
        QtCore.QObject.connect(self.ui.rdoArea, QtCore.SIGNAL("clicked()"),
                               self.updateCellCount)
        QtCore.QObject.connect(self.ui.rdoSideLength,
                               QtCore.SIGNAL("clicked()"),
                               self.updateCellCount)
        QtCore.QObject.connect(self.ui.rdoHexagon, QtCore.SIGNAL("clicked()"),
                               self.updateCellCount)
        QtCore.QObject.connect(self.ui.rdoSquare, QtCore.SIGNAL("clicked()"),
                               self.updateCellCount)
        QtCore.QObject.connect(self.ui.btnUpdate, QtCore.SIGNAL("clicked()"),
                               self.updateLayer)
        QtCore.QObject.connect(self.ui.btnCanvas, QtCore.SIGNAL("clicked()"),
                               self.updateCanvas)
        self.ui.buttonOk = self.ui.buttonBox_2.button(
            QtGui.QDialogButtonBox.Ok)
        self.setWindowTitle(self.tr("Create Planning Unit Grid"))
        layermap = QgsMapLayerRegistry.instance().mapLayers()
        for name, layer in layermap.iteritems():
            self.ui.inShape.addItem(unicode(layer.name()))
        self.ui.progressBar.setRange(0, 100)
Exemplo n.º 9
0
 def _store_previous_directory(self, settings, path):
     previous_file = QtCore.QFileInfo(path)
     settings.setValue("InPath", previous_file.absoluteDir().absolutePath())
Exemplo n.º 10
0
    def importFileOrLayer(self, source, schema, tablename, overwrite, singleGeom = False):

        if isinstance(source, basestring):
            layerName = QtCore.QFileInfo(source).completeBaseName()
        else:
            layerName = source.name()

        if tablename is None:
            tablename = layerName

        if not xmlNameIsValid(tablename, xmlNameRegex()):
            tablename = getPostGisTableName(name=tablename, names=[], unique=False)

        if overwrite:
            pk = "id"
            geom = "geom"
            providerName = "postgres"

            uri = QgsDataSourceURI()
            uri.setConnection(self.geodb.host, str(self.geodb.port), self.geodb.dbname, self.geodb.user, self.geodb.passwd)
            uri.setDataSource(schema, tablename, geom, "", pk)

            options = {}
            options['overwrite'] = True
            if singleGeom:
                options['forceSinglePartGeometryType'] = True

            if isinstance(source, basestring):
                layer = QgsVectorLayer(source, layerName, "ogr")
                if not layer.isValid() or layer.type() != QgsMapLayer.VectorLayer:
                    layer.deleteLater()
                    raise WrongLayerFileError("Error reading file {} or it is not a valid vector layer file".format(source))
            else:
                layer = source
                if not layer.isValid() or layer.type() != QgsMapLayer.VectorLayer:
                    raise WrongLayerFileError("Layer '%s' is not valid or is not a vector layer".format(layer.name()))

            ret, errMsg = QgsVectorLayerImport.importLayer(layer, uri.uri(), providerName, layer.crs(), False, False, options)
            if ret != 0:
                raise Exception(errMsg)
        else:
            if isinstance(source, QgsMapLayer):
                source = source.source()

            args = ["shp2pgsql", "-a"]
            if singleGeom:
                args.append("-S")
            args.extend([source, schema + "." + tablename])
            if os.name == 'nt':
                cmdline = subprocess.list2cmdline(args)
                data = None

                p = os.popen3(cmdline)
                data = p[1].read()

                cursor = self.geodb.con.cursor()
                newcommand = re.compile(";$", re.MULTILINE)

                # split the commands
                cmds = newcommand.split(data)
                for cmd in cmds[:-1]:
                    # run SQL commands within current DB connection
                    self.geodb._exec_sql(cursor, cmd)
                data = cmds[-1]

                self.geodb.con.commit()

                if data is None or len(data) == 0:
                    raise Exception("".join(p[2].readlines()))
            else:
                # start shp2pgsql as subprocess
                p = subprocess.Popen(args=args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                # read the output while the process is running
                data = ''
                cursor = self.geodb.con.cursor()
                newcommand = re.compile(";$", re.MULTILINE)
                while p.poll() == None:
                    data += p.stdout.read()

                    # split the commands
                    cmds = newcommand.split(data)
                    for cmd in cmds[:-1]:
                        # run SQL commands within current DB connection
                        self.geodb._exec_sql(cursor, cmd)
                    data = cmds[-1]

                # commit!
                self.db.con.commit()

                if p.returncode != 0:
                    raise Exception(p.stderr.readlines().join("\n"))
Exemplo n.º 11
0
    def __init__(self, iface):
        self.iface = iface

        # Import required plugins and if missing show the plugin's name
        ftPath = os.path.join(
            str(QtCore.QFileInfo(QgsApplication.qgisUserDbFilePath()).path()),
            'python/plugins/fTools')
        if not ftPath in sys.path:
            sys.path.append(ftPath)
        req_plugin = "ftools 0.5.10"
        try:
            import ftools_utils
        except:
            QtGui.QMessageBox.information(
                self, self.tr("Missing Plugins"),
                self.tr("Missing plugin: %s" % req_plugin))

        QtGui.QDialog.__init__(self)
        # Set up the user interface from Designer.
        self.ui = Ui_qm_calc()
        self.ui.setupUi(self)
        self.setFixedSize(809, 714)
        #
        self.setWindowTitle(
            self.tr("Calculate Planning Grid Conservation Factor Values"))
        # add input layers to select planning grid
        self.allLayers = ftools_utils.getLayerNames(
            [QGis.Polygon, QGis.Line, QGis.Point])
        layers = ftools_utils.getLayerNames([QGis.Polygon])
        self.ui.cbxPlanningGrid.addItems(layers)
        self.setMeasurePoints()
        self.setIdAndMeasureFields(self.ui.cbxPlanningGrid.currentText())
        self.setOutputField()
        self.ui.rdoSum.setChecked(True)
        self.ui.rdoMeasure.setChecked(True)
        # setup calculations list
        self.setCalculations()

        # connect methods to button interactions
        # selecting type of layer to measure
        QtCore.QObject.connect(self.ui.rdoPoints, QtCore.SIGNAL("clicked()"),
                               self.setMeasurePoints)
        QtCore.QObject.connect(self.ui.rdoLines, QtCore.SIGNAL("clicked()"),
                               self.setMeasureLines)
        QtCore.QObject.connect(self.ui.rdoAreas, QtCore.SIGNAL("clicked()"),
                               self.setMeasurePolygons)
        QtCore.QObject.connect(self.ui.rdoRaster, QtCore.SIGNAL("clicked()"),
                               self.setMeasureRasters)
        # selecting measure layer
        QtCore.QObject.connect(self.ui.cbxPlanningGrid,
                               QtCore.SIGNAL("currentIndexChanged(QString)"),
                               self.setIdAndMeasureFields)
        # select single or multiple variale output
        QtCore.QObject.connect(self.ui.rdoCalcSingle,
                               QtCore.SIGNAL("clicked()"), self.setSingle)
        QtCore.QObject.connect(self.ui.rdoCalcMulti,
                               QtCore.SIGNAL("clicked()"), self.setMulti)
        # selecting measure or calculation
        QtCore.QObject.connect(self.ui.rdoMeasure, QtCore.SIGNAL("clicked()"),
                               self.setMeasure)
        QtCore.QObject.connect(self.ui.rdoCalculate,
                               QtCore.SIGNAL("clicked()"), self.setCalculate)
        QtCore.QObject.connect(self.ui.rdoPresence, QtCore.SIGNAL("clicked()"),
                               self.setPresence)
        QtCore.QObject.connect(self.ui.cbxMeasureLayer,
                               QtCore.SIGNAL("currentIndexChanged(QString)"),
                               self.setCalcFields)
        # selecting field name
        QtCore.QObject.connect(self.ui.cbxSelectField,
                               QtCore.SIGNAL("currentIndexChanged(QString)"),
                               self.setOutputField)
        # calculation list actions
        QtCore.QObject.connect(self.ui.twCalculations,
                               QtCore.SIGNAL("itemSelectionChanged()"),
                               self.selectCalcForEdit)
        QtCore.QObject.connect(self.ui.pbCancel, QtCore.SIGNAL('clicked()'),
                               self.cancelCalcEdit)
        QtCore.QObject.connect(self.ui.pbNew, QtCore.SIGNAL('clicked()'),
                               self.newCalculation)
        QtCore.QObject.connect(self.ui.pbDelete, QtCore.SIGNAL('clicked()'),
                               self.deleteCalculation)
        QtCore.QObject.connect(self.ui.pbSave, QtCore.SIGNAL('clicked()'),
                               self.saveCalculation)
        # set main form buttons
        QtCore.QObject.connect(self.ui.pbOpenList, QtCore.SIGNAL('clicked()'),
                               self.loadCalculationList)
        QtCore.QObject.connect(self.ui.pbSaveList, QtCore.SIGNAL('clicked()'),
                               self.saveCalculationList)
        QtCore.QObject.connect(self.ui.pbClose, QtCore.SIGNAL('clicked()'),
                               self.close)
        QtCore.QObject.connect(self.ui.pbRun, QtCore.SIGNAL('clicked()'),
                               self.doCalculations)
Exemplo n.º 12
0
	def compile(self, file_path):

		self.current_file_path = file_path
		self.progress.show()

		arduino_path = self.main.settings.arduino_path()
		if not arduino_path:
			self.set_error("Arduino root path not found", "..nothing to do ..")
			return
		## Set Envoironment
		env = QtCore.QStringList()
		env << QtCore.QString("ARDUINO_DIR=").append()
		env << QtCore.QString("ARDUINO_BOARD=").append("atmega328")
		env << QtCore.QString("ARDUINO_sPORT=").append("s/ssdev/ttyUSB0")
		self.process.setEnvironment(env)

		print "----------------------------------------"

		## Set working dir
		sketch_dir = QtCore.QFileInfo(self.current_file_path).absolutePath()
		
		self.process.setWorkingDirectory(sketch_dir)

		command = QtCore.QString("sh ")
		## Create command sh arduinp_make.sh 
		#command.append("pwd  ") #.append(QtCore.QFileInfo(self.current_file_path).dir().path())
		#args = QtCore.QStringList()
		command.append(self.main.settings.app_path()).append("/etc/arduino_make.sh compile ")
		#command.append(QtCore.QFileInfo(self.current_file_path).dir().path())
		print "command=", command
		self.process.start(command)
		if self.process.waitForStarted(): 
			self.process.waitForFinished()
			result =  self.process.readAllStandardOutput()
			#print type(result), result
			error = self.process.readAllStandardError()
			#print type(error), error
			if error:
				print "is error"
				self.actionIcon.setIcon(Icon(Ico.CompileError))
				self.statusLabel.setText("Error")
				self.textWidget.setPlainText(QtCore.QString(error))
			else:
				print "is ok"
				self.statusLabel.setText("OK")
				self.actionIcon.setIcon(Icon(Ico.CompileOk))
				self.textWidget.setPlainText(QtCore.QString(result))



		self.progress.hide()
		return
		command = QtCore.QString()
		## Create command sh arduinp_make.sh 
		command.append("pwd") # sh ").append(self.main.settings.app_path()).append("/etc/arduino_make.sh compile")
		#args = QtCore.QStringList()
		#command.append(self.main.settings.app_path()).append("/etc/arduino_make.sh compile ")
		#command.append(QtCore.QFileInfo(self.current_file_path).dir().path())
		print "command=", command
		process = QtCore.QProcess(self)
		process.start(command)
		if process.waitForStarted(): 
			process.waitForFinished();
			result =  process.readAllStandardOutput()
			#print type(result), result
			error = process.readAllStandardError()
			#print type(error), error
			if error:
			
				self.textWidget.setPlainText(QtCore.QString(error))
			else:
				self.textWidget.setPlainText(QtCore.QString(result))
Exemplo n.º 13
0
 def directoryName(self, fullname):
     return QtCore.QFileInfo(fullname).absolutePath()
Exemplo n.º 14
0
    def showDialog(self):
        par_obj.file_array = []
        self.int_obj.selIntButton.setEnabled(False)
        #filepath = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
        for path in QtGui.QFileDialog.getOpenFileNames(
                self, 'Open file', self.par_obj.filepath,
                'Images(*.tif *.tiff *.png);;'):

            par_obj.file_array.append(path)

        self.par_obj.config['evalpath'] = str(
            QtCore.QFileInfo(path).absolutePath()) + '/'
        pickle.dump(
            self.par_obj.config,
            open(str(os.path.expanduser('~') + '/.densitycount/config.p'),
                 "w"))
        self.par_obj.csvPath = self.par_obj.config['evalpath']

        v2.import_data_fn(par_obj, par_obj.file_array)
        par_obj.left_2_calc = []
        par_obj.frames_2_load = {}
        if par_obj.file_ext == 'png':
            for i in range(0, par_obj.file_array.__len__()):
                par_obj.left_2_calc.append(i)
                par_obj.frames_2_load[i] = [0]
            self.int_obj.image_status_text.showMessage(
                'Status: Loading Images. Loading Image Num: ' +
                str(par_obj.file_array.__len__()))

        elif par_obj.file_ext == 'tiff' or par_obj.file_ext == 'tif':
            if par_obj.tiff_file.maxFrames > 1:
                for i in range(0, par_obj.file_array.__len__()):
                    par_obj.left_2_calc.append(i)
                    for b in range(0, par_obj.tiff_file.maxFrames):
                        par_obj.frames_2_load[i] = [0]
                    #try:
                    #    np.array(list(self.hyphen_range(fmStr)))-1
                    #    par_obj.frames_2_load[i] = np.array(list(self.hyphen_range(fmStr)))-1
                    #except:
                    #self.int_obj.image_status_text.showMessage('Status: The supplied range of image frames is in the wrong format. Please correct and click confirm images.')
                    #    return
                self.int_obj.image_status_text.showMessage(
                    'Status: Loading Images.')

            else:
                for i in range(0, par_obj.file_array.__len__()):
                    par_obj.left_2_calc.append(i)
                    par_obj.frames_2_load[i] = [0]

        count = 0
        for b in par_obj.left_2_calc:
            frames = par_obj.frames_2_load[b]
            for i in frames:
                count = count + 1

        par_obj.test_im_start = 0
        par_obj.test_im_end = count

        self.int_obj.image_status_text.showMessage('Status: Loading Images. ')
        if self.type == 'im':
            if (self.par_obj.file_array.__len__() > 0):
                self.int_obj.selIntButton.setEnabled(True)

        self.refreshTable()
Exemplo n.º 15
0
 def __init__(self, path, parent=None):
     # super(Node,self).__init__(QtCore.QFileInfo(path))
     Note.__init__(self, QtCore.QFileInfo(path), parent)
     self.dir = QtCore.QDir(path)
     self.repopulate()
Exemplo n.º 16
0
 def currentFile(self, filename):
     self._currentFile = QtCore.QFileInfo(filename).canonicalFilePath()
     self._isUntitled = False
     self.setWindowTitle(self.userFriendlyCurrentFile)
Exemplo n.º 17
0
    def loadXML(self):
        print "Loading XML..."
        fullPathFileName = QtGui.QFileDialog.getOpenFileName(
            self, "Open XML file", "./", "*.xml")
        if not fullPathFileName:
            print "Cancelled!"
        else:
            # Then ask for the appropriate map
            cbItem = tg2spinMap.keys()
            # simTick, ok = QtGui.QInputDialog.getInt(self, "Simulation Tick", "Enter Simulation Tick in microsecond", self.simTick, DEF_MIN_TIMER_TICK, 10000000, 1)

            mapItem, ok = QtGui.QInputDialog.getItem(
                self, "Select Map", "Which map will be used?", cbItem, 0,
                False)
            if ok is True:
                print "Will use", mapItem
                # self.initMap(mapItem)
                self.TGmap = tg2spinMap[str(mapItem)]
            else:
                print "Cancelled!"
                return

            fi = QtCore.QFileInfo()
            fi.setFile(fullPathFileName)
            fn = fi.fileName()
            self.dagFile.setText("Using {}".format(fn))
            print "Processing ", fullPathFileName
            parser = xml.sax.make_parser()

            # turn off namespace
            parser.setFeature(xml.sax.handler.feature_namespaces, 0)

            # override the default ContextHandler
            Handler = tgxmlHandler()
            parser.setContentHandler(Handler)
            parser.parse(str(fullPathFileName))

            if SHOW_PARSING_RESULT:
                showParsingResult(Handler)
            """ Let's put the c-like struct as a list:
                Let's create a variable cfg, which is a list of a dict.
                Then, let's create a variable dag, which is a list of cfg. Hence, dag is a list of a list of a dict.
            """
            dag = list()
            for nodes in Handler.Nodes:
                cfg = list()
                srcPayload = list()
                srcFound = False
                for target in nodes.Target:
                    dct = dict()
                    dct['nodeID'] = nodes.Id
                    dct['destID'] = target.destId
                    dct['nPkt'] = target.nPkt
                    dct['nDependant'] = target.nDependant
                    for d in range(target.nDependant):
                        srcIDkey = "dep{}_srcID".format(d)
                        nTriggerPktkey = "dep{}_nTriggerPkt".format(d)
                        dct[srcIDkey] = target.Dep[d].srcId
                        dct[nTriggerPktkey] = target.Dep[d].nTriggerPkt
                        # also search for SOURCE dependant
                        if target.Dep[d].srcId == DEF_SOURCE_ID:
                            srcFound = True
                            srcPayload.append(target.Dep[d].nTriggerPkt)
                    cfg.append(dct)
                    # and put the payload to the current word in the dict
                if srcFound:
                    self.srcTarget.append(nodes.Id)
                    # self.srcTarget[nodes.Id] = srcPayload --> ini yang lama sebelum aku REVISI
                dag.append(cfg)

            self.output = dag
            #self.output = experiment_dag0020()

            # for debugging:
            print "SpiNNaker usage  :", self.TGmap
            print "TG configuration :", self.output
            print "Source Target    :", self.srcTarget
Exemplo n.º 18
0
pathRelativo = QtCore.QDir.homePath().append("/.televideo")
#per le opzioni, se false è nella stessa cartella del programma, se no in .config nella home
relative = False
app = QtGui.QApplication(sys.argv)
#mi prendo percorso applicazione, per memorizzare file lì, se no si prende un path diverso a seconda di dove lanci app
path = app.arguments()
workingPath = QtCore.QDir()

if sys.platform == "win32":
    print "windows"
    # e aggiusto path
    winPath = QtCore.QString(app.applicationDirPath())
    workingPath.setCurrent(winPath)
else:
    print(sys.platform)
    filePathInfo = QtCore.QFileInfo(path[0])
    directory = filePathInfo.path()
    workingPath.setCurrent(directory)

#print(app.applicationDirPath())

#questo se il programma è installato in una posizione non scrivibile, quindi le immagini le salva in una cartella della home
testFile = QtCore.QFileInfo("COPYING")
if not testFile.isWritable():
    dir = QtCore.QDir(pathRelativo)
    if not dir.exists():
        dir.mkpath(pathRelativo)
    workingPath.setCurrent(pathRelativo)
    relative = True
    print(
        "Non posso scrivere: le immagine verranno memorizzate nella cartella .televideo della home su Linux o nel Registro in Windows"
Exemplo n.º 19
0
 def strippedName(self, fullFileName):
     '''return filename without path using QFileInfo'''
     return QtCore.QFileInfo(fullFileName).fileName()
Exemplo n.º 20
0
    def _update_file_menu(self):
        """
            Set up the File menu and update the menu with recent files
        """
        self.file_menu.clear()

        newAction = QtGui.QAction("&New Reduction...", self)
        newAction.setShortcut("Ctrl+N")
        newAction.setStatusTip("Start a new reduction")
        self.connect(newAction, QtCore.SIGNAL("triggered()"), self._new)

        openAction = QtGui.QAction("&Open...", self)
        openAction.setShortcut("Ctrl+O")
        openAction.setStatusTip(
            "Open an XML file containing reduction parameters")
        self.connect(openAction, QtCore.SIGNAL("triggered()"), self._file_open)

        saveAsAction = QtGui.QAction("Save as...", self)
        saveAsAction.setStatusTip("Save the reduction parameters to XML")
        self.connect(saveAsAction, QtCore.SIGNAL("triggered()"), self._save_as)

        saveAction = QtGui.QAction("&Save...", self)
        saveAction.setShortcut("Ctrl+S")
        saveAction.setStatusTip("Save the reduction parameters to XML")
        self.connect(saveAction, QtCore.SIGNAL("triggered()"), self._save)

        exportAction = QtGui.QAction("&Export...", self)
        exportAction.setShortcut("Ctrl+E")
        exportAction.setStatusTip("Export to python script for Mantid")
        self.connect(exportAction, QtCore.SIGNAL("triggered()"), self._export)

        quitAction = QtGui.QAction("&Quit", self)
        quitAction.setShortcut("Ctrl+Q")
        self.connect(quitAction, QtCore.SIGNAL("triggered()"), self.close)

        self.file_menu.addAction(newAction)
        self.file_menu.addAction(openAction)
        self.file_menu.addAction(saveAction)
        self.file_menu.addAction(saveAsAction)
        self.file_menu.addAction(exportAction)
        self.file_menu.addSeparator()

        if self.general_settings.debug:
            clearAction = QtGui.QAction("&Clear settings and quit", self)
            clearAction.setStatusTip(
                "Restore initial application settings and close the application"
            )
            self.connect(clearAction, QtCore.SIGNAL("triggered()"),
                         self._clear_and_close)
            self.file_menu.addAction(clearAction)

        self.file_menu.addAction(quitAction)

        # TOOLS menu
        instrAction = QtGui.QAction("Change &instrument...", self)
        instrAction.setShortcut("Ctrl+I")
        instrAction.setStatusTip("Select a new instrument")
        self.connect(instrAction, QtCore.SIGNAL("triggered()"),
                     self._change_instrument)

        debug_menu_item_str = "Turn debug mode ON"
        if self.general_settings.debug:
            debug_menu_item_str = "Turn debug mode OFF"
        debugAction = QtGui.QAction(debug_menu_item_str, self)
        debugAction.setStatusTip(debug_menu_item_str)
        self.connect(debugAction, QtCore.SIGNAL("triggered()"),
                     self._debug_mode)

        self.tools_menu.clear()
        self.tools_menu.addAction(instrAction)
        self.tools_menu.addAction(debugAction)

        # Cluster submission details
        if IS_IN_MANTIDPLOT and CLUSTER_ENABLED:
            jobAction = QtGui.QAction("Remote submission details", self)
            jobAction.setShortcut("Ctrl+R")
            jobAction.setStatusTip(
                "Set the cluster information for remote job submission")
            self.connect(jobAction, QtCore.SIGNAL("triggered()"),
                         self._cluster_details_dialog)
            self.tools_menu.addAction(jobAction)

        recent_files = []
        for fname in self._recent_files:
            if fname != self._filename and QtCore.QFile.exists(
                    fname) and fname not in recent_files:
                recent_files.append(fname)

        if len(recent_files) > 0:
            self.file_menu.addSeparator()
            for i, fname in enumerate(recent_files):
                action = QtGui.QAction(
                    "&%d %s" % (i + 1, QtCore.QFileInfo(fname).fileName()),
                    self)
                action.setData(fname)
                self.connect(action, QtCore.SIGNAL("triggered()"),
                             self.open_file)
                self.file_menu.addAction(action)
Exemplo n.º 21
0
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        WindowStateReader.__init__(self)
        WindowStateWriter.__init__(self)
        self._db = BookDbLayer()

        self.userConfigDir = QtCore.QDir.homePath() + QtCore.QDir.separator() + \
                             '.pyhomelib'
        if not QtCore.QFileInfo(self.userConfigDir).isDir():
            QtCore.QDir.home().mkdir('.pyhomelib')
        self.uiSettingsFile = self.userConfigDir + QtCore.QDir.separator() + \
                              'ui.xml'
        self.programSettings = MySettings(self.userConfigDir +
                                          QtCore.QDir.separator() +
                                          'pyhomelib.conf')

        if len(sys.argv) < 2:
            dbname = self.userConfigDir + QtCore.QDir.separator() + \
                     'default.sqlite'
        else:
            dbname = QtCore.QString.fromUtf8(sys.argv[1])

        genreModel = GenreTreeModelReader('genres.xml')

        info = QtCore.QFileInfo(dbname)
        if info.exists() and info.size() > 0:
            self._db.open(dbname)
        else:
            QtGui.QMessageBox.information(
                self, self.tr("Information"),
                QtCore.QString(
                    self.tr("Database doesn't exists, recreating: %1")).arg(
                        dbname))
            self._db.create(dbname, 'Default', '', genreModel.list(),
                            [self.tr('Favorites')])

        try:
            import sqlite3ext
            handle = db().driver().handle()
            sqlite3ext.load_icu(handle.data().ascobject())
        except ImportError:
            pass

        self.setupUi(self)
        QtGui.qApp.setStyleSheet(
            QtCore.QResource(":resources/pyhomelib.css").data())
        self.appTitle = self.windowTitle()
        self.prependToTitle(self._db.getDbProperty('name').toString())
        self.actionRuLetterA.setText(u"А")
        self.actionRuLetterB.setText(u"Б")
        self.actionRuLetterV.setText(u"В")
        self.actionRuLetterG.setText(u"Г")
        self.actionRuLetterD.setText(u"Д")
        self.actionRuLetterE.setText(u"Е")
        self.actionRuLetterYo.setText(u"Ё")
        self.actionRuLetterZh.setText(u"Ж")
        self.actionRuLetterZ.setText(u"З")
        self.actionRuLetterI.setText(u"И")
        self.actionRuLetterY.setText(u"Й")
        self.actionRuLetterK.setText(u"К")
        self.actionRuLetterL.setText(u"Л")
        self.actionRuLetterM.setText(u"М")
        self.actionRuLetterN.setText(u"Н")
        self.actionRuLetterO.setText(u"О")
        self.actionRuLetterP.setText(u"П")
        self.actionRuLetterR.setText(u"Р")
        self.actionRuLetterS.setText(u"С")
        self.actionRuLetterT.setText(u"Т")
        self.actionRuLetterU.setText(u"У")
        self.actionRuLetterF.setText(u"Ф")
        self.actionRuLetterH.setText(u"Х")
        self.actionRuLetterTs.setText(u"Ц")
        self.actionRuLetterCh.setText(u"Ч")
        self.actionRuLetterSh.setText(u"Ш")
        self.actionRuLetterSch.setText(u"Щ")
        self.actionRuLetterYy.setText(u"Ы")
        self.actionRuLetterEe.setText(u"Э")
        self.actionRuLetterYu.setText(u"Ю")
        self.actionRuLetterYa.setText(u"Я")

        self.lettersGroup = QtGui.QActionGroup(self)
        for a in self.findChildren(QtGui.QAction):
            if a.objectName().startsWith('actionRuLetter') or \
               a.objectName().startsWith('actionEnLetter'):
                self.lettersGroup.addAction(a)

        self.authorsModel = SqlQueryModel(self, self._db,
                                          "authorid, lastname, firstname",
                                          "libauthorname", None,
                                          "lastname, firstname")
        self.authorsView.setModel(self.authorsModel)
        self.setTableAuthorsModelQuery()
        self.authorsView.hideColumn(0)
        for index, name in enumerate(
            [self.tr("authorid"),
             self.tr("Last name"),
             self.tr("First name")]):
            self.authorsView.model().setHeaderData(index, QtCore.Qt.Horizontal,
                                                   name)

        self.sequencesModel = SqlQueryModel(self, self._db, "seqid, seqname",
                                            "libseqname", None, "seqname")
        self.sequencesView.setModel(self.sequencesModel)
        self.sequencesModel.select()
        self.sequencesView.hideColumn(0)
        for index, name in enumerate([self.tr("seqid"), self.tr("Sequence")]):
            self.sequencesView.model().setHeaderData(index,
                                                     QtCore.Qt.Horizontal,
                                                     name)

        self.genresTree.setModel(genreModel)
        self.genresTree.hideColumn(1)

        self.bookSearchModel = SqlQueryModel(
            self, self._db,
            "b.bookid, firstname, lastname, title, seqname, genredesc, lang, year",
            "libbook b LEFT JOIN libsequence s ON b.bookid = s.bookid LEFT JOIN libseqname sn ON s.seqid = sn.seqid LEFT JOIN libauthor a ON b.bookid = a.bookid LEFT JOIN libauthorname an ON a.authorid = an.authorid LEFT JOIN libgenre g ON b.bookid = g.bookid LEFT JOIN libgenrelist gl ON g.genreid = gl.genreid",
            "b.bookid = 0", None, "1")
        self.bookSearchView.setModel(self.bookSearchModel)
        self.bookSearchModel.select()
        self.bookSearchView.hideColumn(0)
        for index, name in enumerate([
                self.tr("bookid"),
                self.tr("First name"),
                self.tr("Last name"),
                self.tr("Book Title"),
                self.tr("Sequence"),
                self.tr("Genre"),
                self.tr("Lang"),
                self.tr("Year")
        ]):
            self.bookSearchModel.setHeaderData(index, QtCore.Qt.Horizontal,
                                               name)

        self.groupsModel = SqlQueryModel(self, self._db, "groupid, groupname",
                                         "libgrouplist", None, "groupname")
        self.groupsView.setModel(self.groupsModel)
        self.groupsModel.select()
        self.groupsView.hideColumn(0)
        for index, name in enumerate([self.tr("groupid"), self.tr("Group")]):
            self.groupsView.model().setHeaderData(index, QtCore.Qt.Horizontal,
                                                  name)

        self.booksByAuthorModel = SqlQueryModel(
            self, self._db, "bookid, title, seqname, genredesc, lang, year",
            "libauthor a INNER JOIN libbook b USING(bookid) LEFT JOIN libseqname s ON b.seqid = s.seqid LEFT JOIN libgenrelist g ON b.genreid = g.genreid",
            "a.authorid = ?")
        self.booksByAuthorView.setModel(self.booksByAuthorModel)
        self.booksByAuthorModel.addBindValue(0)
        self.booksByAuthorModel.select()
        self.booksByAuthorView.hideColumn(0)
        for index, name in enumerate([
                self.tr("bookid"),
                self.tr("Book Title"),
                self.tr("Sequence"),
                self.tr("Genre"),
                self.tr("Lang"),
                self.tr("Year")
        ]):
            self.booksByAuthorModel.setHeaderData(index, QtCore.Qt.Horizontal,
                                                  name)

        self.booksBySeqModel = SqlQueryModel(
            self, self._db,
            "bookid, firstname, lastname, title, genredesc, lang, year",
            "libsequence s INNER JOIN libbook b USING(bookid) LEFT JOIN libauthorname a ON b.authorid = a.authorid LEFT JOIN libgenrelist g ON b.genreid = g.genreid",
            "s.seqid = ?")
        self.booksBySeqView.setModel(self.booksBySeqModel)
        self.booksBySeqModel.addBindValue(0)
        self.booksBySeqModel.select()
        self.booksBySeqView.hideColumn(0)
        for index, name in enumerate([
                self.tr("bookid"),
                self.tr("First name"),
                self.tr("Last name"),
                self.tr("Book Title"),
                self.tr("Genre"),
                self.tr("Lang"),
                self.tr("Year")
        ]):
            self.booksBySeqModel.setHeaderData(index, QtCore.Qt.Horizontal,
                                               name)

        self.booksByGenreModel = SqlQueryModel(
            self, self._db,
            "bookid, firstname, lastname, title, seqname, lang, year",
            "libgenre g INNER JOIN libbook b USING(bookid) LEFT JOIN libauthorname a ON b.authorid = a.authorid LEFT JOIN libseqname s ON b.seqid = s.seqid",
            "g.genreid = ?")
        self.booksByGenreView.setModel(self.booksByGenreModel)
        self.booksByGenreModel.addBindValue(0)
        self.booksByGenreModel.select()
        self.booksByGenreView.hideColumn(0)
        for index, name in enumerate([
                self.tr("bookid"),
                self.tr("First name"),
                self.tr("Last name"),
                self.tr("Book Title"),
                self.tr("Sequence"),
                self.tr("Lang"),
                self.tr("Year")
        ]):
            self.booksByGenreModel.setHeaderData(index, QtCore.Qt.Horizontal,
                                                 name)

        self.booksByGroupModel = SqlQueryModel(
            self, self._db,
            "b.bookid, firstname, lastname, title, seqname, genredesc, lang, year",
            "libgroup g INNER JOIN libbook b USING(bookid) LEFT JOIN libseqname s ON b.seqid = s.seqid LEFT JOIN libauthorname a ON b.authorid = a.authorid LEFT JOIN libgenrelist gl ON b.genreid = gl.genreid",
            "g.groupid = ?")
        self.booksByGroupView.setModel(self.booksByGroupModel)
        self.booksByGroupModel.addBindValue(0)
        self.booksByGroupModel.select()
        self.booksByGroupView.hideColumn(0)
        for index, name in enumerate([
                self.tr("bookid"),
                self.tr("First name"),
                self.tr("Last name"),
                self.tr("Book Title"),
                self.tr("Sequence"),
                self.tr("Genre"),
                self.tr("Lang"),
                self.tr("Year")
        ]):
            self.booksByGroupModel.setHeaderData(index, QtCore.Qt.Horizontal,
                                                 name)

        self.readStateFrom(self.uiSettingsFile)
        self.actionRussianAlphabet.setChecked(
            self.ruLettersToolbar.isVisibleTo(self))
        self.actionEnglishAlphabet.setChecked(
            self.enLettersToolbar.isVisibleTo(self))

        if not self.programSettings.getRowHeight():
            self.programSettings.writeRowHeight(
                self.authorsView.verticalHeader().defaultSectionSize())
        else:
            self.setRowHeight(self.programSettings.getRowHeight())

        for key in ('/', 'Ctrl+F'):
            QtGui.QShortcut(key, self).activated.connect(
                self.on_quickFindShortcut_activated)

        self.parserThread = FB2BookParserThread()
        self.parserThread.bookParsed.connect(self.bookParsed)
        self.parserThread.start()
Exemplo n.º 22
0
 def redo(self):
     self.archivo = QtCore.QFileInfo(self.nombre_archivo).baseName()
     self.ruta = QtCore.QFileInfo(self.nombre_archivo).path()
     self.imagen = misc.imread(str(self.nombre_archivo))
     #carga imagen en el front end, incluye un resize
     self.mostrarImagen(self.imagenOriginal, self.imagen)
Exemplo n.º 23
0
 def strippedName(self, fullFileName):
     return QtCore.QFileInfo(fullFileName).fileName()
Exemplo n.º 24
0
	def on_edit_function(self):
		path = self.tree.currentItem().text(self.COLS.folder)
		fileinfo = QtCore.QFileInfo(self.tree.currentItem().data(self.COLS.icon, QtCore.Qt.UserRole).toString())
		d = FunctionEditDialog(self, self.main, fileinfo.fileName(), path, self.paths )
		d.show()
		self.load()
Exemplo n.º 25
0
def get_last_modification(fileName):
    """Get the last time the file was modified."""
    return QtCore.QFileInfo(fileName).lastModified()
Exemplo n.º 26
0
        elif path:
            fi = QtCore.QFileInfo(path)
        else:
            raise "Either path or FileInfo needs to be specified in Node::add call"
        if fi.isFile():
            self.children[fi.fileName()] = Note(fi, parent=self)
        elif fi.isDir():
            self.children[fi.fileName()] = Node(fi.filePath(), parent=self)

    def delete(self, fileinfo):
        if fileinfo.path() == self.dir.path():
            print "will delete ", fileinfo.filePath()
        else:
            print "need to find better parent"

    def getChildren(self):
        return self.children

    def get(self, fullpath):
        # need to extract first path level,
        # pass it onto the next Node
        pass


if __name__ == "__main__":
    root = Node('/home/dimon/Notes')
    print root
    # fi=QtCore.QFileInfo('/home/dimon/Notes/node1/SubNote1')
    fi = QtCore.QFileInfo('/home/dimon/Notes/node1')
    root.delete(fi)
def setLastDir(filename, tool_name=''):
    path = QtCore.QFileInfo(filename).absolutePath()
    settings = QtCore.QSettings(tool_name,"")
    settings.setValue("lastUsedDir", str(unicode(path)))
Exemplo n.º 28
0
 def _createNote(self, nodename):
     """create new Node"""
     nodepath = self.dir.filePath(nodename)
     fi = QtCore.QFileInfo(nodepath)
     self.children[fi.fileName()] = (fi, Note(fi, parent=self))
Exemplo n.º 29
0
    def __init__(self, iface, dock=None, parent=None):
        """Constructor for the dialog.

        :param iface: A Quantum GIS QGisAppInterface instance.
        :type iface: QGisAppInterface

        :param parent: Parent widget of this dialog
        :type parent: QWidget

        :param dock: Optional dock widget instance that we can notify of
            changes to the keywords.
        :type dock: Dock
        """

        QtGui.QDialog.__init__(self, parent)
        self.setupUi(self)

        # additional buttons
        self.button_save_pdf = QtGui.QPushButton(self.tr('Open PDF'))
        self.button_save_pdf.setObjectName('button_save_pdf')
        self.button_save_pdf.setToolTip(
            self.tr('Write report to PDF and open it in default viewer'))
        self.buttonBox.addButton(self.button_save_pdf,
                                 QtGui.QDialogButtonBox.ActionRole)

        self.button_open_composer = QtGui.QPushButton(self.tr('Open composer'))
        self.button_open_composer.setObjectName('button_open_composer')
        self.button_open_composer.setToolTip(
            self.tr('Prepare report and open it in QGIS composer'))
        self.buttonBox.addButton(self.button_open_composer,
                                 QtGui.QDialogButtonBox.ActionRole)

        self.button_save_pdf.clicked.connect(self.accept)
        self.button_open_composer.clicked.connect(self.accept)

        # Save reference to the QGIS interface and parent
        self.iface = iface
        self.parent = parent
        self.dock = dock

        self.create_pdf = False

        self.default_template_radio.toggled.connect(
            self.toggle_template_selectors)

        button = self.buttonBox.button(QtGui.QDialogButtonBox.Help)
        button.clicked.connect(self.show_help)

        self.unwanted_templates = ['merged_report.qpt']
        # Load templates from resources...
        template_dir_path = resources_path('qgis-composer-templates')
        templates_dir = QtCore.QDir(template_dir_path)
        templates_dir.setFilter(QtCore.QDir.Files | QtCore.QDir.NoSymLinks
                                | QtCore.QDir.NoDotAndDotDot)
        templates_dir.setNameFilters(['*.qpt', '*.QPT'])
        report_files = templates_dir.entryList()
        for unwanted_template in self.unwanted_templates:
            if unwanted_template in report_files:
                report_files.remove(unwanted_template)

        for f in report_files:
            self.template_combo.addItem(
                QtCore.QFileInfo(f).baseName(), template_dir_path + '/' + f)
        #  ...and user directory
        settings = QtCore.QSettings()
        path = settings.value('inasafe/reportTemplatePath', '', type=str)
        if path != '':
            templates_dir = QtCore.QDir(path)
            templates_dir.setFilter(QtCore.QDir.Files | QtCore.QDir.NoSymLinks
                                    | QtCore.QDir.NoDotAndDotDot)
            templates_dir.setNameFilters(['*.qpt', '*.QPT'])
            report_files = templates_dir.entryList()
            for f in report_files:
                self.template_combo.addItem(
                    QtCore.QFileInfo(f).baseName(), path + '/' + f)

        self.restore_state()
Exemplo n.º 30
0
    def saveTextData(self):

        #/ nome do método (logger)
        #/ ----------------------------------------------------------------------------------------
        #l_szMetodo = "clsTabelaPAR::saveTextData"

        #/ mensagem de erro
        #/ ----------------------------------------------------------------------------------------
        l_szError = None

        #** ---------------------------------------------------------------------------------------
        #*  m.poirot logger
        #*/
        #l_log = logging.getLogger ( l_szMetodo )
        #l_log.setLevel ( w_logLvl )
        #l_log.debug ( ">> " )

        #** ---------------------------------------------------------------------------------------
        #*  nome da tabela de PAR's
        #*/
        #assert ( self._szFName )
        ##l_log.info ( "Tabela de PAR's a salvar: " + self._szFName )

        #** ---------------------------------------------------------------------------------------
        #*/
        try:

            #** -----------------------------------------------------------------------------------
            #*  abre o arquivo de PAR
            #*/
            l_fdPAR = open(self._szFName, "w")
            #assert ( l_fdPAR )

            #** -----------------------------------------------------------------------------------
            #*  percorre todos os PAR's
            #*/
            for _, l_PAR in self._aItens:

                #** -------------------------------------------------------------------------------
                #*  cria a area de dados
                #*/
                l_lstData = "%s %s %d %.1f %.1f %.1f %.1f %.1f %.1f %d %d\n" % \
                            ( l_PAR._szKey, l_PAR._szDescr.replace ( ' ', '_' ),
                              l_PAR._iCab0, l_PAR._fHAnt0, l_PAR._fHAnt1,
                              l_PAR._fDstAntEixo, l_PAR._fDstAntPT0, l_PAR._fDstAntPT1,
                              l_PAR._fAngRampa, l_PAR._aiRetardo [ 0 ], l_PAR._iDecl )

                #** -------------------------------------------------------------------------------
                #*  grava no arquivo
                #*/
                l_fdPAR.write(l_lstData)

            #** -----------------------------------------------------------------------------------
            #*  fecha o arquivo
            #*/
            l_fdPAR.close()

            #** -----------------------------------------------------------------------------------
            #*  m.poirot logger
            #*/
            #l_log.debug ( "<< " )

            #** -----------------------------------------------------------------------------------
            #*/
            return (True, "Salvos {0} PARs em {1}".format(
                len(self._aItens),
                QtCore.QFileInfo(self._szFName).fileName()))

        #** ---------------------------------------------------------------------------------------
        #*/
        except (IOError, OSError), e:

            #** -----------------------------------------------------------------------------------
            #*/
            l_szError = "Erro no salvamento: {0}".format(e)