Esempio n. 1
0
  def open_dict(self, changed):
    """
    Open a dialog box where the user can choose which file to load.
    """
    dialog = QFileDialog()
    ret = dialog.exec_()

    # if the user validate its choice
    if ret:
      # get te path and set it in the line edit
      path = dialog.selectedFiles()[0]
      self.pathToDict.setText(path)
      dict_file = QFile(path)
      opened = dict_file.open(QIODevice.ReadOnly)
      if not opened:
        return
      buf = dict_file.readLine()
      if len(buf):
        self.word_list.append(str(buf).rstrip('\n'))
      while buf != "":
        buf = ""
        buf = dict_file.readLine()
        if len(buf):
          self.word_list.append(str(buf).rstrip('\n'))
      dict_file.close()
      self.editDictContent.setEnabled(True)
Esempio n. 2
0
    def getActivePlugins(self, filename=None):
        '''
        Function checks xml and returns if plugin was active on previous program execution
        xmlfile: specifies alternative path to xml file with plugin information
        '''

        if not filename:
            filename = self.xmlFile

        if os.path.exists(filename):
            fileObject = QFile(filename)
            Xml = QDomDocument("xmldoc")
            Xml.clear()
            if (fileObject.open(QIODevice.ReadOnly)):
                Xml.setContent(fileObject.readAll())
                fileObject.close()

            rootNode = Xml.documentElement()
            nodeList = rootNode.elementsByTagName("plugin")

            for i in range(nodeList.length()):
                bpNode = nodeList.at(i).toElement()
                path = str(bpNode.attribute("path"))
                if path in self.pluginActions:
                    self.pluginActions[path].setLoaded(
                        bpNode.attribute("active") == "y")
                else:
                    logging.warning(
                        "No plugin for %s found, maybe it was moved/deleted?",
                        path)
Esempio n. 3
0
  def insert ( self, fileName ) :
    #
    nodes = []
    links = []

    dom = QtXml.QDomDocument ( self.name )

    file = QFile ( fileName )
    if file.open ( QtCore.QIODevice.ReadOnly ) :
      if dom.setContent ( file )  :
        root = dom.documentElement ()
        if root.nodeName () == 'node' :
          #print ':: parsing node from XML ...'
          nodes.append ( self.addNodeFromXML ( root ) )
          self.correct_id ( nodes, links )
        elif root.nodeName () == 'nodenet' :
          #print ':: parsing nodenet from XML ...'
          nodeNet = NodeNetwork ( 'tmp', root )
          nodeNet.fileName = fileName
          ( nodes, links ) = self.add ( nodeNet )
        else :
          print '!! unknown XML document format'
    file.close()
    #if DEBUG_MODE : print '>> NodeNetwork( %s ).insert node_id = %d link_id = %d' % ( self.name, self.node_id, self.link_id )
    #if DEBUG_MODE : self.printInfo ()
    return ( nodes, links )
Esempio n. 4
0
 def savePluginInfo(self, xmlfile=None):
     ''' 
     write plugin info to xml (plugin active/inactive ...)
     xmlfile: specifies alternative path to xml file with plugin information (default: plugins/plugins.xml)
     '''
     #create xml
     Xml = QDomDocument("xmldoc")
     rootNode = Xml.createElement("SysCDbgActivePlugins")
     Xml.appendChild(rootNode)
     
     for i in range(self.pluginActions.__len__()):
         pluginNode = Xml.createElement("plugin")
         pluginNode.setAttribute("path", self.pluginActions[i].path)
         if self.pluginActions[i].isChecked():
             pluginNode.setAttribute("active", "y")
         else:
             pluginNode.setAttribute("active", "n")
         rootNode.appendChild(pluginNode)
                
     #create and write xml file
     fname = self.xmlFile
     if xmlfile != None:
         fname = xmlfile
         if fname.endswith(".xml") == False:
             fname += ".xml"
     
     fileObject = QFile(fname)
     fileObject.open(QIODevice.WriteOnly)
     fileObject.writeData(Xml.toString())
     fileObject.close()
Esempio n. 5
0
 def save(self):
     if self.filename.startsWith("Unnamed"):
         filename = QFileDialog.getSaveFileName(self,
                 "Text Editor -- Save File As", self.filename,
                 "Text files (*.txt *.*)")
         if filename.isEmpty():
             return
         self.filename = filename
     self.setWindowTitle(QFileInfo(self.filename).fileName())
     exception = None
     fh = None
     try:
         fh = QFile(self.filename)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec("UTF-8")
         stream << self.toPlainText()
         self.document().setModified(False)
     except EnvironmentError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
Esempio n. 6
0
 def __init__(self, platform, msiFileName, productName, manufacturer, productVersion, language):
     self.platform = platform
     self.msiFile  = FileObject(msiFileName) 
     self.tempDir = tempfile.mkdtemp()
     self.productCode = msilib.gen_uuid()
     self.upgradeCode = msilib.gen_uuid()
     self.productVersion = productVersion
     self.manufacturer = manufacturer
     self.language = language
     self.productName = productName
     self.RegsitryComponent = "RegistryComponent"
     self.registryRecords = []
     
     self.template =  QFile(":/files/pyMagicTemplateMSI2.msi")
     self.template.open(QFile.ReadOnly) 
     data = self.template.readAll()
     self.templatePath = msiFileName
     x = QFile(self.templatePath)
     if  x.open(QFile.WriteOnly):
         print "opened file for write"
         x.write(data)
     else:
         print "could not open file for writing"
         
     x.close()
     self.template.close()
Esempio n. 7
0
    def changeResolution(self):
        fileName = QFileDialog.getOpenFileName(
            self,
            'Load .prn file',
            directory=self.settings.value('unpacker/dir_open',
                                          QDir.currentPath()),
            filter='PRN files (*.prn *.bin);;All (*)')
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QFile.ReadWrite):
            QMessageBox.warning(
                self, "Unpacker .prn",
                "Unable load file {}:\n{}.".format(fileName,
                                                   file.errorString()))
            return
        self.settings.setValue('unpacker/dir_open', QFileInfo(file).path())
        data = QDataStream(file)
        data.setByteOrder(QDataStream.LittleEndian)
        headerVersion = data.readInt32()
        xdpi = data.readInt32()
        ydpi = data.readInt32()

        dialog = ChangeResolutionDialog(xdpi, ydpi, self)
        if dialog.exec_():
            file.seek(4)
            data.writeInt32(dialog.sbXdpi.value())
            data.writeInt32(dialog.sbYdpi.value())
            self.status.showMessage("Resolution changed successful", 7000)
        file.close()
Esempio n. 8
0
    def save(self, content, path=None):
        """
        Write a temprorary file with .tnj extension and copy it over the
        original one.
        .nsf = Ninja Swap File
        #FIXME: Where to locate addExtension, does not fit here
        """
        new_path = False
        if path:
            self.attach_to_path(path)
            new_path = True

        save_path = self._file_path

        if not save_path:
            raise NinjaNoFileNameException("I am asked to write a "
                                           "file but no one told me where")
        swap_save_path = "%s.nsp" % save_path

        # If we have a file system watcher, remove the file path
        # from its watch list until we are done making changes.
        if self.__watcher:
            self.__watcher.removePath(save_path)

        flags = QIODevice.WriteOnly | QIODevice.Truncate
        f = QFile(swap_save_path)
        if settings.use_platform_specific_eol():
            flags |= QIODevice.Text

        if not f.open(flags):
            raise NinjaIOException(f.errorString())

        stream = QTextStream(f)
        encoding = get_file_encoding(content)
        if encoding:
            stream.setCodec(encoding)

        encoded_stream = stream.codec().fromUnicode(content)
        f.write(encoded_stream)
        f.flush()
        f.close()
        #SIGNAL: Will save (temp, definitive) to warn folder to do something
        self.emit(SIGNAL("willSave(QString, QString)"),
                  swap_save_path, save_path)
        self.__mtime = os.path.getmtime(swap_save_path)
        shutil.move(swap_save_path, save_path)
        self.reset_state()

        # If we have a file system watcher, add the saved path back
        # to its watch list, otherwise create a watcher and start
        # watching
        if self.__watcher:
            if new_path:
                self.__watcher.removePath(self.__watcher.files()[0])
                self.__watcher.addPath(self._file_path)
            else:
                self.__watcher.addPath(save_path)
        else:
            self.start_watching()
        return self
    def WriteUserInfoFile(self):
        if QFile.exists(self.m_strUserInfoFullName):
            fl = QFile.remove(self.m_strUserInfoFullName)
            f = open(self.m_strUserInfoFullName, 'w')
            f.flush()
            f.close()

        else:
            f = open(self.m_strUserInfoFullName, 'w')
            # f = open("D:/xml/phxasar.txt")
            f.flush()
            f.close()

        file0 = QFile(self.m_strUserInfoFullName)
        file0.open(QIODevice.WriteOnly)
        dataStream = QDataStream(file0)
        dataStream.writeQString(QString("UserList"))
        dataStream.writeQString(QString(self.m_strUserInfoFullName))
        dataStream.writeQString(QString(self.m_Key))
        dataStream.writeQString(QString(self.m_IV))
        dataStream.writeInt(len(self.ListUserInfo))

        for userInfo in self.ListUserInfo:
            userInfo.writeData(dataStream)
        file0.flush()
        file0.close()
        return True
Esempio n. 10
0
 def run(self):
     self.ui.label.setText(self.ui.ui.neredenEdit.text())
     dosyaOku = QFile(self.ui.ui.neredenEdit.text())
     dosyaOku.open(QIODevice.ReadOnly)
     oku = 1024*1024
     partBoyutu = int(self.ui.ui.mbEdit.text())
     self.ui.progressBar.setMaximum(dosyaOku.size()/oku)
     partAdi = self.ui.ui.nereyeEdit.text()
     sayac = 0
     partSayici = 1
     while not dosyaOku.atEnd():
         partAdi = "%s%s"%(partAdi[:-3], str(partSayici).zfill(3))
         self.ui.label2.setText(partAdi)
         partSayici += 1
         dosyaYaz = QFile(partAdi)
         if dosyaYaz.exists() and not self.uzerineYaz:
             self.emit(SIGNAL("durdur"))
             return
         dosyaYaz.open(QIODevice.WriteOnly)
         #self.uzerineYaz = False
         for i in range(partBoyutu):
             dosyaYaz.writeData(dosyaOku.read(oku))
             sayac += 1
             self.emit(SIGNAL("value"), sayac)
             self.msleep(1)
             if dosyaOku.atEnd(): break
         dosyaYaz.close()
     self.msleep(500)
Esempio n. 11
0
 def exportXml(self, fname):
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='{0}'?>\n"
                    "<!DOCTYPE MOVIES>\n"
                    "<MOVIES VERSION='1.0'>\n".format(CODEC))
         for key, movie in self.__movies:
             stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' "
                        "ACQUIRED='{2}'>\n".format(movie.year,
                        movie.minutes,
                        movie.acquired.toString(Qt.ISODate))) \
                    << "<TITLE>" << Qt.escape(movie.title) \
                    << "</TITLE>\n<NOTES>"
             if not movie.notes.isEmpty():
                 stream << "\n" << Qt.escape(
                         encodedNewlines(movie.notes))
             stream << "\n</NOTES>\n</MOVIE>\n"
         stream << "</MOVIES>\n"
     except EnvironmentError as e:
         error = "Failed to export: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Exported {0} movie records to {1}".format(
                 len(self.__movies),
                 QFileInfo(fname).fileName())
Esempio n. 12
0
 def importDOM(self, fname):
     dom = QDomDocument()
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         if not dom.setContent(fh):
             raise ValueError("could not parse XML")
     except (IOError, OSError, ValueError) as e:
         error = "Failed to import: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
     try:
         self.populateFromDOM(dom)
     except ValueError as e:
         return False, "Failed to import: {0}".format(e)
     self.__fname = QString()
     self.__dirty = True
     return True, "Imported {0} movie records from {1}".format(
                 len(self.__movies), QFileInfo(fname).fileName())
Esempio n. 13
0
 def saveQDataStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QDataStream(fh)
         stream.writeInt32(MovieContainer.MAGIC_NUMBER)
         stream.writeInt32(MovieContainer.FILE_VERSION)
         stream.setVersion(QDataStream.Qt_4_2)
         for key, movie in self.__movies:
             stream << movie.title
             stream.writeInt16(movie.year)
             stream.writeInt16(movie.minutes)
             stream << movie.acquired << movie.notes
     except EnvironmentError as e:
         error = "Failed to save: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {0} movie records to {1}".format(
                 len(self.__movies),
                 QFileInfo(self.__fname).fileName())
Esempio n. 14
0
 def saveQTextStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         for key, movie in self.__movies:
             stream << "{{MOVIE}} " << movie.title << "\n" \
                    << movie.year << " " << movie.minutes << " " \
                    << movie.acquired.toString(Qt.ISODate) \
                    << "\n{NOTES}"
             if not movie.notes.isEmpty():
                 stream << "\n" << movie.notes
             stream << "\n{{ENDMOVIE}}\n"
     except EnvironmentError as e:
         error = "Failed to save: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {0} movie records to {1}".format(
                 len(self.__movies),
                 QFileInfo(self.__fname).fileName())
Esempio n. 15
0
 def exportXml(self, fname):
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='{0}'?>\n"
                    "<!DOCTYPE MOVIES>\n"
                    "<MOVIES VERSION='1.0'>\n".format(CODEC))
         for key, movie in self.__movies:
             stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' "
                        "ACQUIRED='{2}'>\n".format(movie.year,
                        movie.minutes,
                        movie.acquired.toString(Qt.ISODate))) \
                    << "<TITLE>" << Qt.escape(movie.title) \
                    << "</TITLE>\n<NOTES>"
             if not movie.notes.isEmpty():
                 stream << "\n" << Qt.escape(encodedNewlines(movie.notes))
             stream << "\n</NOTES>\n</MOVIE>\n"
         stream << "</MOVIES>\n"
     except EnvironmentError as e:
         error = "Failed to export: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Exported {0} movie records to {1}".format(
             len(self.__movies),
             QFileInfo(fname).fileName())
Esempio n. 16
0
 def save(self):
     exception = None
     fh = None
     try:
         if self.filename.isEmpty():
             raise IOError("no filename specified for saving")
         fh = QFile(self.filename)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QDataStream(fh)
         stream.writeInt32(MAGIC_NUMBER)
         stream.writeInt16(FILE_VERSION)
         stream.setVersion(QDataStream.Qt_4_1)
         for ship in self.ships:
             stream << ship.name << ship.owner << ship.country \
                    << ship.description
             stream.writeInt32(ship.teu)
         self.dirty = False
     except IOError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
Esempio n. 17
0
 def saveQTextStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         for key, movie in self.__movies:
             stream << "{{MOVIE}} " << movie.title << "\n" \
                    << movie.year << " " << movie.minutes << " " \
                    << movie.acquired.toString(Qt.ISODate) \
                    << "\n{NOTES}"
             if not movie.notes.isEmpty():
                 stream << "\n" << movie.notes
             stream << "\n{{ENDMOVIE}}\n"
     except EnvironmentError as e:
         error = "Failed to save: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {0} movie records to {1}".format(
             len(self.__movies),
             QFileInfo(self.__fname).fileName())
Esempio n. 18
0
def escribir_archivo(nombre_de_archivo, contenido):
    """ Se escribe en el archivo, si el nombre no tiene extensión se agrega .c
    """

    extension = (os.path.splitext(nombre_de_archivo)[-1])[1:]
    if not extension:
        nombre_de_archivo += '.c'

    try:
        f = QFile(nombre_de_archivo)
        if not f.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning("Guardar", "No se escribio en %s: %s" % (
                nombre_de_archivo, f.errorString()))

            return False

        flujo = QTextStream(f)
        encode_flujo = flujo.codec().fromUnicode(contenido)
        f.write(encode_flujo)
        f.flush()
        f.close()

    except:
        pass

    return os.path.abspath(nombre_de_archivo)
Esempio n. 19
0
    def getActivePlugins(self, filename=None):
        '''
        Function checks xml and returns if plugin was active on previous program execution
        xmlfile: specifies alternative path to xml file with plugin information
        '''

        if not filename:
            filename = self.xmlFile

        if os.path.exists(filename):
            fileObject = QFile(filename)
            Xml = QDomDocument("xmldoc")
            Xml.clear()
            if (fileObject.open(QIODevice.ReadOnly)):
                Xml.setContent(fileObject.readAll())
                fileObject.close()

            rootNode = Xml.documentElement()
            nodeList = rootNode.elementsByTagName("plugin")

            for i in range(nodeList.length()):
                bpNode = nodeList.at(i).toElement()
                path = str(bpNode.attribute("path"))
                if path in self.pluginActions:
                    self.pluginActions[path].setLoaded(bpNode.attribute("active") == "y")
                else:
                    logging.warning("No plugin for %s found, maybe it was moved/deleted?", path)
Esempio n. 20
0
 def run(self):
     self.ui.label.setText(self.ui.ui.nereyeEdit.text())
     dosyaListesi = self.birlestir(self.ui.ui.neredenEdit.text())
     dosyaYaz = QFile(self.ui.ui.nereyeEdit.text())
     if dosyaYaz.exists() and not self.uzerineYaz:
         self.emit(SIGNAL("durdur"))
         return
     dosyaYaz.open(QIODevice.WriteOnly)
     
     oku = 1024*1024
     boyut = self.toplamBoyut(dosyaListesi)/oku
     self.ui.progressBar.setMaximum(boyut)
     sayac = 0
     for i in dosyaListesi:
         self.ui.label2.setText(i)
         dosyaOku = QFile(i)
         dosyaOku.open(QIODevice.ReadOnly)
         while not dosyaOku.atEnd():
             dosyaYaz.writeData(dosyaOku.read(oku))
             sayac += 1
             self.emit(SIGNAL("value"), sayac)
             self.msleep(1)
             if dosyaOku.atEnd(): break
     dosyaYaz.close()
     self.msleep(500)
Esempio n. 21
0
    def startScanning(self):
        if self.comboDevice.count()==0:
            return
        self.scanner.setSelectedColor(self.comboColor.currentIndex())
        self.scanner.setSelectedResolution(self.comboResolution.currentIndex())
        self.scanner.setSelectedScanArea(self.comboArea.currentIndex())
        ext = self.scanner.extension
        args = self.scanner.getArgs()

        self.statusbar.showMessage("Scan Started")
        wait(20)
        self.process.start('scanimage', args)
        if not self.process.waitForFinished(-1) or self.process.exitCode():
            self.statusbar.showMessage("Scanning Failed !")
            return
        data = self.process.readAllStandardOutput()

        filename = self.filenameEdit.text() + ext
        # to get more accurate scanned area when A4 at 300 dpi
        if (self.scanner.crop_needed):
            image = QImage.fromData(data)
            image = image.copy(self.scanner.crop_rect)
            image.save(filename)
        else:
            img_file = QFile(filename, self)
            img_file.open(QIODevice.WriteOnly)
            img_file.write(data)
            img_file.close()
        data.clear()
        self.statusbar.showMessage("Scan Completed Successfully")
        self.filenameEdit.setText(self.newFileName())
Esempio n. 22
0
 def save(self, new):
     fh = QFile("tools/" + self.name + ".tool")
     if new and fh.exists():
         return False
     if fh.open(QIODevice.WriteOnly):
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         stream << ("<?xml version='1.0' encoding='%s'?>\n<!DOCTYPE TOOL>\n<TOOL\n" % CODEC)
         stream << (
             "TIPDIAM='%s'\nSYRDIAM='%s'\nPATHWIDTH='%s'\nPATHHEIGHT='%s'\nJOGSPEED='%s'\nSUCKBACK='%s'\nPUSHOUT='%s'\n"
             "PATHSPEED='%s'\nPAUSEPATHS='%s'\nCLEARANCE='%s'\nDEPOSITIONRATE='%s'\n>"
             % (
                 self.tipDiam,
                 self.syrDiam,
                 self.pathWidth,
                 self.pathHeight,
                 self.jogSpeed,
                 self.suckback,
                 self.pushout,
                 self.pathSpeed,
                 self.pausePaths,
                 self.clearance,
                 self.depRate,
             )
         )
         stream << ("\n</TOOL>")
         fh.close()
     return True
Esempio n. 23
0
 def importSAX(self, fname):
     error = None
     fh = None
     try:
         handler = SaxMovieHandler(self)
         parser = QXmlSimpleReader()
         parser.setContentHandler(handler)
         parser.setErrorHandler(handler)
         fh = QFile(fname)
         input = QXmlInputSource(fh)
         self.clear(False)
         if not parser.parse(input):
             raise ValueError(handler.error)
     except (IOError, OSError, ValueError) as e:
         error = "Failed to import: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__fname = QString()
         self.__dirty = True
         return True, "Imported {0} movie records from {1}".format(
             len(self.__movies),
             QFileInfo(fname).fileName())
Esempio n. 24
0
 def _replace_results(self):
     result = QMessageBox.question(self, self.tr("Replace Files Contents"),
         self.tr("Are you sure you want to replace the content in "
                 "this files?\n(The change is not reversible)"),
         buttons=QMessageBox.Yes | QMessageBox.No)
     if result == QMessageBox.Yes:
         for index in xrange(self._result_widget.topLevelItemCount()):
             parent = self._result_widget.topLevelItem(index)
             root_dir_name = unicode(parent.dir_name_root)
             file_name = unicode(parent.text(0))
             file_path = file_manager.create_path(root_dir_name, file_name)
             file_object = QFile(file_path)
             if not file_object.open(QFile.ReadOnly):
                 return
             stream = QTextStream(file_object)
             content = stream.readAll()
             file_object.close()
             pattern = self._find_widget.pattern_line_edit.text()
             case_sensitive = self._find_widget.case_checkbox.isChecked()
             type_ = QRegExp.RegExp if \
                 self._find_widget.type_checkbox.isChecked() else \
                 QRegExp.FixedString
             target = QRegExp(pattern, case_sensitive, type_)
             content.replace(target, self._find_widget.replace_line.text())
             file_manager.store_file_content(file_path, content, False)
Esempio n. 25
0
 def saveQDataStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QDataStream(fh)
         stream.writeInt32(MovieContainer.MAGIC_NUMBER)
         stream.writeInt32(MovieContainer.FILE_VERSION)
         stream.setVersion(QDataStream.Qt_4_2)
         for key, movie in self.__movies:
             stream << movie.title
             stream.writeInt16(movie.year)
             stream.writeInt16(movie.minutes)
             stream << movie.acquired << movie.location \
                    << movie.notes
     except EnvironmentError as e:
         error = "Failed to save: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Saved {0} movie records to {1}".format(
             len(self.__movies),
             QFileInfo(self.__fname).fileName())
Esempio n. 26
0
 def importDOM(self, fname):
     dom = QDomDocument()
     error = None
     fh = None
     try:
         fh = QFile(fname)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(str(fh.errorString()))
         if not dom.setContent(fh):
             raise ValueError("could not parse XML")
     except (IOError, OSError, ValueError) as e:
         error = "Failed to import: {0}".format(e)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
     try:
         self.populateFromDOM(dom)
     except ValueError as e:
         return False, "Failed to import: {0}".format(e)
     self.__fname = QString()
     self.__dirty = True
     return True, "Imported {0} movie records from {1}".format(
         len(self.__movies),
         QFileInfo(fname).fileName())
Esempio n. 27
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
Esempio n. 28
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
Esempio n. 29
0
    def on_pushButton_5_clicked(self):

        self.listWidget.clear()  # 先清空显示

        file = QFile("my.xml")
        if (not file.open(QIODevice.ReadOnly)):
            raise Exception("open my.xml Err")
        doc = QDomDocument()
        status, rrorMsg, errorLine, errorColumn = doc.setContent(file)
        if (not status):
            file.close()
            raise Exception(str(rrorMsg))
        file.close()

        docElem = doc.documentElement()  # 返回根元素

        n = docElem.firstChild()
        while (not n.isNull()):
            if (n.isElement()):
                e = n.toElement()
                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())
            n = n.nextSibling()
Esempio n. 30
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
Esempio n. 31
0
 def writeGcpFile(gc, path):
     outFile = QFile(path)
     if (not outFile.open(QIODevice.WriteOnly | QIODevice.Text)):
         return 'Unable to open GCP file for writing'
     outStream = QTextStream(outFile)
     outStream << gc.asCsv()
     outFile.close()
Esempio n. 32
0
 def save(self):
     exception = None
     fh = None
     try:
         if self.filename.isEmpty():
             raise IOError("no filename specified for saving")
         fh = QFile(self.filename)
         if not fh.open(QIODevice.WriteOnly):
             raise IOError(str(fh.errorString()))
         stream = QDataStream(fh)
         stream.writeInt32(MAGIC_NUMBER)
         stream.writeInt16(FILE_VERSION)
         stream.setVersion(QDataStream.Qt_4_1)
         for ship in self.ships:
             stream << ship.name << ship.owner << ship.country \
                    << ship.description
             stream.writeInt32(ship.teu)
         self.dirty = False
     except IOError as e:
         exception = e
     finally:
         if fh is not None:
             fh.close()
         if exception is not None:
             raise exception
    def testQgsSVGFillSymbolLayer(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsSVGFillSymbolLayer')
        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 = 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 (str (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
Esempio n. 34
0
    def savePluginInfo(self, filename=None):
        '''
        write plugin info to xml (plugin active/inactive ...)
        xmlfile: specifies alternative path to xml file with plugin information
        '''

        if not filename:
            filename = self.xmlFile

        # create xml
        Xml = QDomDocument("xmldoc")
        rootNode = Xml.createElement("SysCDbgActivePlugins")
        Xml.appendChild(rootNode)

        for i in self.pluginActions.itervalues():
            pluginNode = Xml.createElement("plugin")
            pluginNode.setAttribute("path", i.path)
            if i.isChecked():
                pluginNode.setAttribute("active", "y")
            else:
                pluginNode.setAttribute("active", "n")
            rootNode.appendChild(pluginNode)

        # create and write xml file
        fileObject = QFile(filename)
        fileObject.open(QIODevice.WriteOnly)
        fileObject.writeData(Xml.toString())
        fileObject.close()
Esempio n. 35
0
def main(argv):
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(QPixmap(":/logo_small")))
    app.setOrganizationName('Hardcoded Software')
    app.setApplicationName('moneyGuru')
    settings = QSettings()
    LOGGING_LEVEL = logging.DEBUG if adjust_after_deserialization(settings.value('DebugMode')) else logging.WARNING
    setupQtLogging(level=LOGGING_LEVEL)
    logging.debug('started in debug mode')
    if ISLINUX:
        stylesheetFile = QFile(':/stylesheet_lnx')
    else:
        stylesheetFile = QFile(':/stylesheet_win')
    stylesheetFile.open(QFile.ReadOnly)
    textStream = QTextStream(stylesheetFile)
    style = textStream.readAll()
    stylesheetFile.close()
    app.setStyleSheet(style)
    lang = settings.value('Language')
    locale_folder = op.join(BASE_PATH, 'locale')
    hscommon.trans.install_gettext_trans_under_qt(locale_folder, lang)
    # Many strings are translated at import time, so this is why we only import after the translator
    # has been installed
    from qt.app import MoneyGuru
    app.setApplicationVersion(MoneyGuru.VERSION)
    mgapp =  MoneyGuru()
    install_excepthook()
    exec_result = app.exec_()
    del mgapp
    # Since PyQt 4.7.2, I had crashes on exit, and from reading the mailing list, it seems to be
    # caused by some weird crap about C++ instance being deleted with python instance still living.
    # The worst part is that Phil seems to say this is expected behavior. So, whatever, this
    # gc.collect() below is required to avoid a crash.
    gc.collect()
    return exec_result
Esempio n. 36
0
    def get_searchable_content(self):
        """
        Pulls out tags from the object and returns them in order to be used by the filtered() method.
        """
        f = QFile(self.fileinfo.absoluteFilePath())
        f.open(QIODevice.ReadOnly)
        #stream = QTextStream(f)
        #stream.setCodec("UTF-8")
        try:
            doc = QDomDocument()
            doc.setContent( f.readAll() )
            docelt = doc.documentElement()

            texts = []

            for tagName in FileSystemItem.xmlSearchableTags:
                nodes = docelt.elementsByTagName(tagName)
                for i in range(nodes.count()):
                    node = nodes.at(i)
                    value = node.firstChild().toText().data()
                    #print value
                    texts.append( value )

            # Add keywords
            nodes = docelt.elementsByTagName("keywordList")
            for i in range(nodes.count()):
                kwnode = nodes.at(i)
                valnodes = kwnode.toElement().elementsByTagName("value")
                for j in range(valnodes.count()):
                    value = valnodes.at(j).firstChild().toText().data()
                    texts.append(value)

            return u' '.join(texts)
        finally:
            f.close()
    def testQgsSvgMarkerSymbolLayerV2(self):
        '''
        Create a new style from a .sld file and match test
        '''
        mTestName = QString ('QgsSvgMarkerSymbolLayerV2')
        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 = 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 = QString(u'skull.svg')
        mValue = os.path.basename (str(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
Esempio n. 38
0
 def _replace_results(self):
     result = QMessageBox.question(
         self,
         self.tr("Replace Files Contents"),
         self.tr("Are you sure you want to replace the content in "
                 "this files?\n(The change is not reversible)"),
         buttons=QMessageBox.Yes | QMessageBox.No)
     if result == QMessageBox.Yes:
         for index in range(self._result_widget.topLevelItemCount()):
             parent = self._result_widget.topLevelItem(index)
             root_dir_name = parent.dir_name_root
             file_name = parent.text(0)
             file_path = file_manager.create_path(root_dir_name, file_name)
             file_object = QFile(file_path)
             if not file_object.open(QFile.ReadOnly):
                 return
             stream = QTextStream(file_object)
             content = stream.readAll()
             file_object.close()
             pattern = self._find_widget.pattern_line_edit.text()
             case_sensitive = self._find_widget.case_checkbox.isChecked()
             type_ = QRegExp.RegExp if \
                 self._find_widget.type_checkbox.isChecked() else \
                 QRegExp.FixedString
             target = QRegExp(pattern, case_sensitive, type_)
             content.replace(target, self._find_widget.replace_line.text())
             file_manager.store_file_content(file_path, content, False)
Esempio n. 39
0
    def __init__(self, args, parent=None):
        QObject.__init__(self, parent)

        # variable declarations
        self.m_defaultPageSettings = {}
        self.m_pages = []
        self.m_verbose = args.verbose
        self.m_page = WebPage(self)
        self.m_returnValue = 0
        self.m_terminated = False
        # setup the values from args
        self.m_scriptFile = args.script
        self.m_args = args.script_args

        self.m_filesystem = FileSystem(self)
        self.m_pages.append(self.m_page)

        do_action('PhantomInitPre')

        if not args.proxy:
            QNetworkProxyFactory.setUseSystemConfiguration(True)
        else:
            proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0],
                                  int(args.proxy[1]))
            QNetworkProxy.setApplicationProxy(proxy)

        # Provide WebPage with a non-standard Network Access Manager
        self.m_netAccessMan = NetworkAccessManager(args.disk_cache,
                                                   args.ignore_ssl_errors,
                                                   self)
        self.m_page.setNetworkAccessManager(self.m_netAccessMan)

        self.m_page.javaScriptConsoleMessageSent.connect(
            self.printConsoleMessage)

        self.m_defaultPageSettings['loadImages'] = args.load_images
        self.m_defaultPageSettings['loadPlugins'] = args.load_plugins
        self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent()
        self.m_defaultPageSettings[
            'localAccessRemote'] = args.local_access_remote
        self.m_page.applySettings(self.m_defaultPageSettings)

        self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile))

        # inject our properties and slots into javascript
        self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self)
        self.m_page.mainFrame().addToJavaScriptWindowObject(
            'fs', self.m_filesystem)

        bootstrap = QFile(':/bootstrap.js')
        if not bootstrap.open(QFile.ReadOnly):
            sys.exit('Can not bootstrap!')
        bootstrapper = str(bootstrap.readAll())
        bootstrap.close()
        if not bootstrapper:
            sys.exit('Can not bootstrap!')
        self.m_page.mainFrame().evaluateJavaScript(bootstrapper)

        do_action('PhantomInitPost')
Esempio n. 40
0
def read_project(settings, openFileName):
    """ Toplevel reader routine. """

    status = None
    handle = None
    try:
        handle = QFile(openFileName)
        if not handle.open(QIODevice.ReadOnly):
            raise IOError(handle.errorString())

        stream = QDataStream(handle)

        # check header
        magic = stream.readInt32()
        if magic != MAGIC_NUMBER:
            status = ("Unrecognized file type - \n{0}\nis not "
                           "a sconcho spf file!").format(openFileName)
            raise IOError(status)

        version = stream.readInt32()
        stream.setVersion(QDataStream.Qt_4_5)

        # initialize API specific entries
        repeatLegends = {}
        rowRepeats = []
        textItems = []
        rowLabels = {}
        columnLabels = {}

        if version == 1:
            (patternGridItems, legendItems, colors, activeSymbol, 
             patternRepeats) = read_API_1_version(stream, settings)

        elif version == 2:
             (patternGridItems, legendItems, colors, activeSymbol, 
             patternRepeats, repeatLegends, rowRepeats, textItems) = \
                     read_API_2_version(stream, settings)
        elif version == 3:
             (patternGridItems, legendItems, colors, activeSymbol, 
             patternRepeats, repeatLegends, rowRepeats, textItems,
             rowLabels, columnLabels) = \
                     read_API_3_version(stream, settings)
        else:
            raise IOError("unsupported API version")
            

    except (IOError, OSError) as e:
        status = "Failed to open %s: %s " % (openFileName, e)

    finally:
        if handle is not None:
            handle.close()
        if status is not None:
            return (False, status, None, None, None, None, None, None, 
                    None, None)

    return (True, None, patternGridItems, legendItems, colors, 
            activeSymbol, patternRepeats, repeatLegends, rowRepeats,
            textItems, rowLabels, columnLabels)
Esempio n. 41
0
 def loadStyle(self, layer, filename):
     qfile = QFile(filename)
     if not qfile.open(QIODevice.ReadOnly):
         Log.debug("Unable to open file " + filename)
         return
     rules = qfile.readData(qfile.size())
     qfile.close()
     layer.loadNamedStyle(filename)
Esempio n. 42
0
 def setStyle(self, widget, style_qss):
     qssFile = QFile(style_qss)
     qssFile.open(QFile.ReadOnly)
     # set style sheet
     styleSheet = qssFile.readAll()
     styleSheet = unicode(styleSheet, encoding='utf8')
     widget.setStyleSheet(styleSheet)
     qssFile.close()
Esempio n. 43
0
 def loadStyle(self, layer, filename):
     qfile = QFile(filename)
     if not qfile.open(QIODevice.ReadOnly):
         Log.debug("Unable to open file " + filename)
         return
     rules = qfile.readData(qfile.size())
     qfile.close()
     layer.loadNamedStyle(filename)
Esempio n. 44
0
 def save(self, url, path):
     log.info('save(): %s to %s' % (colorize((url, path))))
     file = QFile(path)
     cached = self.cache.data(QUrl(url)).readAll()
     if file.open(QIODevice.WriteOnly):
         file.write(cached)
     file.close()
     return path
Esempio n. 45
0
def read_project(settings, openFileName):
    """ Toplevel reader routine. """

    status = None
    handle = None
    try:
        handle = QFile(openFileName)
        if not handle.open(QIODevice.ReadOnly):
            raise IOError(handle.errorString())

        stream = QDataStream(handle)

        # check header
        magic = stream.readInt32()
        if magic != MAGIC_NUMBER:
            status = ("Unrecognized file type - \n{0}\nis not "
                      "a sconcho spf file!").format(openFileName)
            raise IOError(status)

        version = stream.readInt32()
        stream.setVersion(QDataStream.Qt_4_5)

        # initialize API specific entries
        repeatLegends = {}
        rowRepeats = []
        textItems = []
        rowLabels = {}
        columnLabels = {}

        if version == 1:
            (patternGridItems, legendItems, colors, activeSymbol,
             patternRepeats) = read_API_1_version(stream, settings)

        elif version == 2:
            (patternGridItems, legendItems, colors, activeSymbol,
            patternRepeats, repeatLegends, rowRepeats, textItems) = \
                    read_API_2_version(stream, settings)
        elif version == 3:
            (patternGridItems, legendItems, colors, activeSymbol,
            patternRepeats, repeatLegends, rowRepeats, textItems,
            rowLabels, columnLabels) = \
                    read_API_3_version(stream, settings)
        else:
            raise IOError("unsupported API version")

    except (IOError, OSError) as e:
        status = "Failed to open %s: %s " % (openFileName, e)

    finally:
        if handle is not None:
            handle.close()
        if status is not None:
            return (False, status, None, None, None, None, None, None, None,
                    None)

    return (True, None, patternGridItems, legendItems, colors, activeSymbol,
            patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels,
            columnLabels)
    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
Esempio n. 47
0
 def set_log_path(self, log_path):
     for i in range(self.repeat_count * 2):
         f = QFile( log_path )
         if not f.open(QIODevice.Append | QIODevice.Text):
             f = None
             if i == self.repeat_count:
                 log_path = QDir.temp().absoluteFilePath("SurveyingCalculation.log")
     f.close()
     self.logfile = log_path
Esempio n. 48
0
    def __init__(self, parent, args):
        QObject.__init__(self, parent)

        # variable declarations
        self.m_defaultPageSettings = {}
        self.m_pages = []
        self.m_verbose = args.verbose
        self.m_page = WebPage(self)
        self.m_returnValue = 0
        self.m_terminated = False
        # setup the values from args
        self.m_scriptFile = args.script
        self.m_args = args.script_args

        self.m_filesystem = FileSystem(self)

        self.m_pages.append(self.m_page)

        do_action('PhantomInitPre')

        if args.proxy is None:
            QNetworkProxyFactory.setUseSystemConfiguration(True)
        else:
            proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1]))
            QNetworkProxy.setApplicationProxy(proxy)

        # Provide WebPage with a non-standard Network Access Manager
        self.m_netAccessMan = NetworkAccessManager(self, args.disk_cache, args.cookies, args.ignore_ssl_errors)
        self.m_page.setNetworkAccessManager(self.m_netAccessMan)

        self.m_page.javaScriptConsoleMessageSent.connect(self.printConsoleMessage)

        self.m_defaultPageSettings['loadImages'] = args.load_images
        self.m_defaultPageSettings['loadPlugins'] = args.load_plugins
        self.m_defaultPageSettings['javascriptEnabled'] = True
        self.m_defaultPageSettings['XSSAuditingEnabled'] = False
        self.m_defaultPageSettings['userAgent'] = self.m_page.userAgent()
        self.m_defaultPageSettings['localAccessRemote'] = args.local_access_remote
        self.m_page.applySettings(self.m_defaultPageSettings)

        self.libraryPath = os.path.dirname(os.path.abspath(self.m_scriptFile))

        # inject our properties and slots into javascript
        self.m_page.mainFrame().addToJavaScriptWindowObject('phantom', self)
        self.m_page.mainFrame().addToJavaScriptWindowObject('fs', self.m_filesystem)

        bootstrap = QFile(':/bootstrap.js')
        if not bootstrap.open(QFile.ReadOnly):
            sys.exit('Can not bootstrap!')
        bootstrapper = str(bootstrap.readAll())
        bootstrap.close()
        if not bootstrapper:
            sys.exit('Can not bootstrap!')
        self.m_page.mainFrame().evaluateJavaScript(bootstrapper)

        do_action('PhantomInitPost')
Esempio n. 49
0
 def __init__(self):
     path = os.path.join(os.path.dirname(__file__), 'regex-lib.xml')
     if os.path.isfile(path):
         try:
             f = QFile(path)
             f.open(QIODevice.ReadOnly | QIODevice.Text)
             self.data = QTextStream(f).readAll()
         finally:
             if f:
                 f.close()
Esempio n. 50
0
 def set_log_path(self, log_path):
     for i in range(self.repeat_count * 2):
         f = QFile(log_path)
         if not f.open(QIODevice.Append | QIODevice.Text):
             f = None
             if i == self.repeat_count:
                 log_path = QDir.temp().absoluteFilePath(
                     "SurveyingCalculation.log")
     f.close()
     self.logfile = log_path
Esempio n. 51
0
 def downloadFinished(self, reply):
     if reply.error():
         print("Failed to download")
     else:
         attFile = QFile(self.downloadAs)
         attFile.open(QIODevice.WriteOnly)
         attFile.write(reply.readAll())
         attFile.close()
         print("Succeeded")
     reply.deleteLater()
Esempio n. 52
0
 def downloadFinished(self, reply):
     if reply.error():
         print("Failed to download")
     else:
         attFile = QFile(self.downloadAs)
         attFile.open(QIODevice.WriteOnly)
         attFile.write(reply.readAll())
         attFile.close()
         print("Succeeded")
     reply.deleteLater()
Esempio n. 53
0
def httpDownload(theManager, theUrl, theOutPath, theProgressDlg=None):
    """ Download file from theUrl.
    Params:
        * theManager - a QNetworkManager instance
        * theUrl - url of file
        * theOutPath - output path
        * theProgressDlg - progress dialog widget
    Returns:
        True if success, otherwise return a tuple with format like this
        (QNetworkReply.NetworkError, error_message)
    Raises:
        * IOError - when cannot create theOutPath
    """

    # prepare output path
    myFile = QFile(theOutPath)
    if not myFile.open(QFile.WriteOnly):
        raise IOError(myFile.errorString())

    # slot to write data to file
    def writeData():
        myFile.write(myReply.readAll())

    myRequest = QNetworkRequest(QUrl(theUrl))
    myReply = theManager.get(myRequest)
    myReply.readyRead.connect(writeData)

    if theProgressDlg:
        # progress bar
        def progressEvent(theReceived, theTotal):

            QCoreApplication.processEvents()

            theProgressDlg.setLabelText("%s / %s" % (theReceived, theTotal))
            theProgressDlg.setMaximum(theTotal)
            theProgressDlg.setValue(theReceived)

        # cancel
        def cancelAction():
            myReply.abort()

        myReply.downloadProgress.connect(progressEvent)
        theProgressDlg.canceled.connect(cancelAction)

    # wait until finished
    while not myReply.isFinished():
        QCoreApplication.processEvents()

    myFile.close()

    myResult = myReply.error()
    if myResult == QNetworkReply.NoError:
        return True
    else:
        return (myResult, str(myReply.errorString()))
Esempio n. 54
0
    def method_30(self):
        filePath = define.appPath + "/Resource/settingData/phxtemplates.xml"
        fileInfo = QFileInfo(filePath)
        if fileInfo.exists():
            QFile.remove(filePath)

        doc = QDomDocument()
        rootElem = doc.createElement("Templates")
        xmlDeclaration = doc.createProcessingInstruction(
            "xml", "version=\"1.0\" encoding=\"utf-8\"")
        doc.appendChild(xmlDeclaration)

        for i in range(self.parametersPanel.gridModel.rowCount()):
            elem = doc.createElement(
                "Templates" + self.parametersPanel.gridModel.item(i, 0).text())
            valueElem = doc.createElement("title")
            valueElem.appendChild(
                doc.createTextNode(
                    self.parametersPanel.gridModel.item(i, 0).text()))
            elem.appendChild(valueElem)

            valueElem = doc.createElement("space")
            valueElem.appendChild(
                doc.createTextNode(
                    self.parametersPanel.gridModel.item(i, 1).text()))
            elem.appendChild(valueElem)

            valueElem = doc.createElement("value")
            valueElem.appendChild(
                doc.createTextNode(
                    self.parametersPanel.gridModel.item(i, 2).text()))
            elem.appendChild(valueElem)

            rootElem.appendChild(elem)

        doc.appendChild(rootElem)
        qFile = QFile(filePath)
        if qFile.open(QFile.WriteOnly):
            textStream = QTextStream(qFile)
            doc.save(textStream, 4)
            qFile.close()

            # ###CRC file is created.
            contents = None
            with open(filePath, 'rb', 0) as tempFile:
                contents = tempFile.read()
                tempFile.flush()
                tempFile.close()
            bytes = FasDataBlockFile.CRC_Calculation(contents)
            string_0 = QString(filePath)
            path = string_0.left(string_0.length() - 3) + "crc"
            fileStream = open(path, 'wb')
            fileStream.write(bytes)
            fileStream.close()
Esempio n. 55
0
    def __init__(self, parent = None):
        QObject.__init__(self, parent)
        self.m_webPage = QWebPage(self)

        converter = QFile(':/resources/coffee-script.js')
        converter.open(QFile.ReadOnly)

        script = QString.fromUtf8(converter.readAll())
        converter.close()
        self.m_webPage.mainFrame().evaluateJavaScript(script)
        self.m_webPage.mainFrame().addToJavaScriptWindowObject('converter', self)
Esempio n. 56
0
    def __init__(self):
        super(MainWindow, self).__init__(None)
        uic.loadUi("./mainwindow.ui", self)

        doc = QDomDocument()
        # 添加处理指令即XML说明
        instruction = QDomProcessingInstruction()
        instruction = doc.createProcessingInstruction(
            "xml", "version=\"1.0\" encoding=\"UTF-8\"")
        doc.appendChild(instruction)

        # 添加根元素
        root = doc.createElement(QString("书库"))
        doc.appendChild(root)  # 添加根元素

        # 添加第一个图书元素及其子元素
        book = doc.createElement(QString("图书"))
        id = doc.createAttribute(QString("编号"))
        title = doc.createElement(QString("书名"))
        author = doc.createElement(QString("作者"))
        text = QDomText()

        id.setValue(QString("1"))
        book.setAttributeNode(id)
        text = doc.createTextNode(QString("Qt"))
        title.appendChild(text)
        text = doc.createTextNode(QString("shiming"))
        author.appendChild(text)
        book.appendChild(title)  # 图书元素 添加 书名元素
        book.appendChild(author)  # 图书元素 添加 作者元素
        root.appendChild(book)  # 根元素 添加 图书元素

        # 添加第二个图书元素及其子元素
        book = doc.createElement(QString("图书"))
        id = doc.createAttribute(QString("编号"))
        title = doc.createElement(QString("书名"))
        author = doc.createElement(QString("作者"))

        id.setValue(QString("2"))
        book.setAttributeNode(id)
        text = doc.createTextNode(QString("Linux"))
        title.appendChild(text)
        text = doc.createTextNode(QString("yafei"))
        author.appendChild(text)
        book.appendChild(title)
        book.appendChild(author)
        root.appendChild(book)

        file = QFile("my.xml")
        if (not file.open(QIODevice.WriteOnly | QIODevice.Truncate)):
            raise Exception("open my.xml Err")
        out = QTextStream(file)
        doc.save(out, 4)  # 将文档保存到文件,4为子元素缩进字符数
        file.close()