Exemplo n.º 1
0
 def initConfigFile(self):
     """
     初始化配置文件
     :return:
     """
     config = ConfigFile()
     self.configParams = config.readConfigParams()
Exemplo n.º 2
0
 def configNewButtonPressed(self):
     print("New Config Dialogue")
     text, ok = QtWidgets.QInputDialog.getText(self, 'New Config File',
                                               'Enter File Name')
     if ok:
         print("Create Config File: ", text)
         ConfigFile.createDefaultConfig(text)
Exemplo n.º 3
0
 def updateMTab(self, mtab):
     cf = ConfigFile()
     cf.setConfig(mtab)
     self.lockGitFSDir()
     try:
         cf.writeFile(self.getMTabFileName())
     finally:
         self.unlockGitFSDir()
Exemplo n.º 4
0
    def saveButtonPressed(self):
        print("ConfigWindow - Save Pressed")

        ConfigFile.settings["bL0CheckCoords"] = int(
            self.l0CheckCoordsCheckBox.isChecked())
        ConfigFile.settings["fL0LonMin"] = float(self.lonMinLineEdit.text())
        ConfigFile.settings["fL0LonMax"] = float(self.lonMaxLineEdit.text())
        ConfigFile.settings[
            "cL0Direction"] = self.directionComboBox.currentText()
        ConfigFile.settings["bL0CleanSunAngle"] = int(
            self.l0CleanSunAngleCheckBox.isChecked())
        ConfigFile.settings["bL0CleanRotatorAngle"] = int(
            self.l0CleanRotatorAngleCheckBox.isChecked())
        ConfigFile.settings["fL0SunAngleMin"] = float(
            self.l0SunAngleMinLineEdit.text())
        ConfigFile.settings["fL0SunAngleMax"] = float(
            self.l0SunAngleMaxLineEdit.text())
        ConfigFile.settings["fL0RotatorAngleMin"] = float(
            self.l0RotatorAngleMinLineEdit.text())
        ConfigFile.settings["fL0RotatorAngleMax"] = float(
            self.l0RotatorAngleMaxLineEdit.text())
        ConfigFile.settings["fL0RotatorHomeAngle"] = float(
            self.l0RotatorHomeAngleLineEdit.text())
        ConfigFile.settings["fL0RotatorDelay"] = float(
            self.l0RotatorDelayLineEdit.text())
        ConfigFile.settings["bL0SplitRawFile"] = int(
            self.l0SplitRawFileCheckBox.isChecked())

        ConfigFile.settings["fL3aInterpInterval"] = float(
            self.l3InterpIntervalLineEdit.text())

        ConfigFile.settings["bL4EnableQualityFlags"] = int(
            self.l4QualityFlagCheckBox.isChecked())
        ConfigFile.settings["fL4SignificantEsFlag"] = float(
            self.l4EsFlagLineEdit.text())
        ConfigFile.settings["fL4DawnDuskFlag"] = float(
            self.l4DawnDuskFlagLineEdit.text())
        ConfigFile.settings["fL4RainfallHumidityFlag"] = float(
            self.l4RainfallHumidityFlagLineEdit.text())
        ConfigFile.settings["fL4TimeInterval"] = int(
            self.l4TimeIntervalLineEdit.text())
        ConfigFile.settings["fL4RhoSky"] = float(self.l4RhoSkyLineEdit.text())
        ConfigFile.settings["bL4EnableWindSpeedCalculation"] = int(
            self.l4EnableWindSpeedCalculationCheckBox.isChecked())
        ConfigFile.settings["fL4DefaultWindSpeed"] = float(
            self.l4DefaultWindSpeedLineEdit.text())
        ConfigFile.settings["bL4PerformNIRCorrection"] = int(
            self.l4NIRCorrectionCheckBox.isChecked())
        #ConfigFile.settings["bL4EnablePercentLtCorrection"] = int(self.l4EnablePercentLtCheckBox.isChecked())
        ConfigFile.settings["fL4PercentLt"] = float(
            self.l4PercentLtLineEdit.text())

        ConfigFile.saveConfig(self.name)

        QtWidgets.QMessageBox.about(self, "Edit Config File",
                                    "Config File Saved")
        self.close()
Exemplo n.º 5
0
	def __init__(self, path=""):
		Modules.__init__(self)
		ConfigFile.__init__(self)
		
		self.services = []
		self.controllers = []
		
		self.pushcallbacks = {}
		self.pusherrbacks = {}
		
		# Read module files from subfolders
		self.servicemodules = self.loadModules(SERVICE_PATH, ServiceBase)
		self.controllermodules = self.loadModules(CONTROLLER_PATH, ControllerBase)
	def __init__(self, path=""):
		Modules.__init__(self)
		ConfigFile.__init__(self)
		
		self.services = []
		self.controllers = []
		
		self.pushcallbacks = {}
		self.pusherrbacks = {}
		
		# Read module files from subfolders
		self.servicemodules = self.loadModules(SERVICE_PATH, ServiceBase)
		self.controllermodules = self.loadModules(CONTROLLER_PATH, ControllerBase)
Exemplo n.º 7
0
 def getMTab(self, lock=True):
     cf = ConfigFile()
     if lock:
         self.lockGitFSDir()
     try:
         cf.readFile(self.getMTabFileName())
     except IOError:
         pass
     finally:
         if lock:
             self.unlockGitFSDir()
     logging.debug('read configuration: %s\n' %cf.getConfig())
     return cf.getConfig()
Exemplo n.º 8
0
 def __init__(self, tipi_io):
     self.tipi_io = tipi_io
     self.specreg = {
         ClockFile.filename(): ClockFile(self.tipi_io),
         ConfigFile.filename(): ConfigFile(self.tipi_io),
         CurlFile.filename(): CurlFile(self.tipi_io),
         PioFile.filename(): PioFile(self.tipi_io),
         RebootFile.filename(): RebootFile(self.tipi_io),
         ShutdownFile.filename(): ShutdownFile(self.tipi_io),
         StatusFile.filename(): StatusFile(self.tipi_io),
         TcpFile.filename(): TcpFile(self.tipi_io),
         UpgradeFile.filename(): UpgradeFile(self.tipi_io),
         VariablesFile.filename(): VariablesFile(self.tipi_io)
     }
Exemplo n.º 9
0
 def configEditButtonPressed(self):
     print("Edit Config Dialogue")
     print("index: ", self.configComboBox.currentIndex())
     print("text: ", self.configComboBox.currentText())
     configFileName = self.configComboBox.currentText()
     configPath = os.path.join("Config", configFileName)
     if os.path.isfile(configPath):
         ConfigFile.loadConfig(configFileName)
         configDialog = ConfigWindow(configFileName, self)
         #configDialog = CalibrationEditWindow(configFileName, self)
         configDialog.show()
     else:
         #print("Not a Config File: " + configFileName)
         message = "Not a Config File: " + configFileName
         QtWidgets.QMessageBox.critical(self, "Error", message)
Exemplo n.º 10
0
    def getCalibrationSettings(self):
        print("CalibrationEditWindow - getCalibrationSettings")
        ConfigFile.refreshCalibrationFiles()
        calFileName = self.calibrationFileComboBox.currentText()
        calConfig = ConfigFile.getCalibrationConfig(calFileName)
        #print(calConfig["enabled"])
        #print(calConfig["frameType"])
        self.calibrationEnabledCheckBox.blockSignals(True)
        self.calibrationFrameTypeComboBox.blockSignals(True)

        self.calibrationEnabledCheckBox.setChecked(bool(calConfig["enabled"]))
        index = self.calibrationFrameTypeComboBox.findText(
            str(calConfig["frameType"]))
        self.calibrationFrameTypeComboBox.setCurrentIndex(index)

        self.calibrationEnabledCheckBox.blockSignals(False)
        self.calibrationFrameTypeComboBox.blockSignals(False)
Exemplo n.º 11
0
    def configDeleteButtonPressed(self):
        print("Delete Config Dialogue")
        print("index: ", self.configComboBox.currentIndex())
        print("text: ", self.configComboBox.currentText())
        configFileName = self.configComboBox.currentText()
        configPath = os.path.join("Config", configFileName)
        if os.path.isfile(configPath):
            configDeleteMessage = "Delete " + configFileName + "?"

            reply = QtWidgets.QMessageBox.question(self, 'Message', configDeleteMessage, \
                    QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No, QtWidgets.QMessageBox.No)

            if reply == QtWidgets.QMessageBox.Yes:
                ConfigFile.deleteConfig(configFileName)
        else:
            #print("Not a Config File: " + configFileName)
            message = "Not a Config File: " + configFileName
            QtWidgets.QMessageBox.critical(self, "Error", message)
Exemplo n.º 12
0
    def ReadConfig(self):
        self.configFile = ConfigFile()
        configItems=self.configFile.ReadConfig()

        for item in configItems:
            part=item.strip('\n').split('&&')
            if len(part)!=1:
                if part[0]=='attrFilePath':
                    self.attrFilePath=part[1]
                    self.LoadJson()
                elif part[0]=='plugeDictionaryFilePath':
                    self.plugeDictionaryFilePath=part[1]
                    self.PlugeDict()
                elif part[0]=='saveCorpusFilePath':
                    self.saveCorpusFilePath=part[1]
                    self.SaveCorpus()
                elif part[0]=='readCorpusFilePath':
                    self.readCorpusFilePath=part[1]
                    self.LoadCorpus()
                elif part[0]=='historyInputList':
                    self.historyInputList=part[1].split('||')
Exemplo n.º 13
0
 def getConfig(self, name):
     if self.config is not None and name in self.config:
         return self.config[name]
     cf = ConfigFile()
     files = []
     f = self.getConfigFileName(name)
     logging.debug('getConfig filename for %s is %s' %(name, f))
     if f is None:
         return None
     files.append(f)
     if name == 'gitfsdir':
         self.lockGitFSDir()
     try:
         cf.readFile(files)
     except IOError:
         # ignore files that don't exist and the like.
         pass
     finally:
         if name == 'gitfsdir':
             self.unlockGitFSDir()
     self.config = cf.getConfig()
     return self.config
Exemplo n.º 14
0
 def calibrationFileChanged(self, i):
     print("CalibrationEditWindow - Calibration File Changed")
     print("Current index", i, "selection changed ",
           self.calibrationFileComboBox.currentText())
     calFileName = self.calibrationFileComboBox.currentText()
     calDir = ConfigFile.getCalibrationDirectory()
     calPath = os.path.join(calDir, calFileName)
     #print("calPath: " + calPath)
     if os.path.isfile(calPath):
         self.getCalibrationSettings()
         self.calibrationEnabledCheckBox.setEnabled(True)
         self.calibrationFrameTypeComboBox.setEnabled(True)
     else:
         self.calibrationEnabledCheckBox.setEnabled(False)
         self.calibrationFrameTypeComboBox.setEnabled(False)
Exemplo n.º 15
0
    def __init__(self, dirName):
        
        # рабочий каталог должен существовать
        if not path.exists(dirName):
            print u'Working dir {0} not exists'.format(dirName)
            raise Exception(u'Working dir not exists')

        # мы должны иметь полные права доступа к рабочему каталогу
        if not check_permissions(dirName, read=True, write=True, execute=True):
            print u'No rwx permissions for directory {0}'.format(dirName)
            raise Exception(u'No rwx permissions for directory')

        # сохраняем необходимые значения
        self._path = dirName
        self._cfgFile = ConfigFile([self._read_cfg, self._write_cfg], self.CFG_FILE_NAME, dirName)

        self._entries = self._cfgFile.read()
        self.check_entries()
	def Init():
		RootWindow.root=Tk()
		RootWindow.root.title("Generator wizytówek")
		RootWindow.root.iconbitmap(r"ikona.ico")
		
		MainWindow.Init(RootWindow.root)
		EntryWindow.Init()

		ConfigFile.Read(RootWindow.root)

		if ConfigFile.lastTemplate!="":
			error=TemplateFile.Read(ConfigFile.lastTemplate,RootWindow.root)
			if error==1:
				ConfigFile.lastTemplate=""
			RootWindow.newTemp=0

		MenuBar.Init(RootWindow.root)

		RootWindow.root.config(menu=MenuBar.GetMenu())

		RootWindow.root.protocol("WM_DELETE_WINDOW",RootWindow.Close)
	def Close():
		ConfigFile.Write()
		RootWindow.root.destroy()
Exemplo n.º 18
0
    def processMulti(self, level):
        print("Process Multi-Level")

        # Load Config file
        configFileName = self.configComboBox.currentText()
        configPath = os.path.join("Config", configFileName)
        if not os.path.isfile(configPath):
            message = "Not valid Config File: " + configFileName
            QtWidgets.QMessageBox.critical(self, "Error", message)
            return
        ConfigFile.loadConfig(configFileName)

        # Select data files
        openFileNames = QtWidgets.QFileDialog.getOpenFileNames(
            self, "Open File")
        print("Files:", openFileNames)
        if not openFileNames[0]:
            return
        fileNames = openFileNames[0]
        #calibrationDirectory = settings["sCalibrationFolder"].strip('"')
        #preprocessDirectory = settings["sPreprocessFolder"].strip('"')

        # Select Output Directory
        dataDirectory = QtWidgets.QFileDialog.getExistingDirectory(
            self, "Select Output Directory")
        print("Output Directory:", dataDirectory)
        if not dataDirectory:
            return

        # Copy to backup folder if same directory
        fileNames = self.createBackupFiles(fileNames, dataDirectory)

        windFile = self.windFileLineEdit.text()

        print("Process Calibration Files")
        filename = ConfigFile.filename
        calFiles = ConfigFile.settings["CalibrationFiles"]
        calibrationMap = Controller.processCalibrationConfig(
            filename, calFiles)

        print("Preprocess Raw Files")
        checkCoords = int(ConfigFile.settings["bL0CheckCoords"])
        startLongitude = float(ConfigFile.settings["fL0LonMin"])
        endLongitude = float(ConfigFile.settings["fL0LonMax"])
        direction = ConfigFile.settings["cL0Direction"]
        print("Preprocess Longitude Data", startLongitude, endLongitude,
              direction)
        cleanRotatorAngle = int(ConfigFile.settings["bL0CleanRotatorAngle"])
        cleanSunAngle = int(ConfigFile.settings["bL0CleanSunAngle"])
        angleMin = float(ConfigFile.settings["fL0SunAngleMin"])
        angleMax = float(ConfigFile.settings["fL0SunAngleMax"])
        splitRawFile = int(ConfigFile.settings["bL0SplitRawFile"])
        print("Preprocess Angle Data", cleanSunAngle, cleanRotatorAngle,
              angleMin, angleMax)
        rotatorAngleMin = float(ConfigFile.settings["fL0RotatorAngleMin"])
        rotatorAngleMax = float(ConfigFile.settings["fL0RotatorAngleMax"])
        rotatorHomeAngle = float(ConfigFile.settings["fL0RotatorHomeAngle"])
        rotatorDelay = float(ConfigFile.settings["fL0RotatorDelay"])
        print("Preprocess Rotator Data", rotatorAngleMin, rotatorAngleMax,
              rotatorHomeAngle, rotatorDelay)
        #Controller.preprocessData(preprocessDirectory, dataDirectory, calibrationMap, \
        #                          checkCoords, startLongitude, endLongitude, direction, \
        #                          doCleaning, angleMin, angleMax)
        PreprocessRawFile.processFiles(fileNames, dataDirectory, calibrationMap, \
                                  checkCoords, startLongitude, endLongitude, direction, \
                                  cleanRotatorAngle, cleanSunAngle, angleMin, angleMax, \
                                  rotatorAngleMin, rotatorAngleMax, rotatorHomeAngle, rotatorDelay, \
                                  splitRawFile)
        print("Process Raw Files")
        Controller.processDirectory(dataDirectory, calibrationMap, level,
                                    windFile)
Exemplo n.º 19
0
 def setCalibrationSettings(self):
     print("CalibrationEditWindow - setCalibrationSettings")
     calFileName = self.calibrationFileComboBox.currentText()
     enabled = self.calibrationEnabledCheckBox.isChecked()
     frameType = self.calibrationFrameTypeComboBox.currentText()
     ConfigFile.setCalibrationConfig(calFileName, enabled, frameType)
def main(activation_path,logFile):
    startTime = datetime.now()
    conf_file = ConfigFile("config.json")
    attri = conf_file.readJson()
    path = activation_path
    logs_text = attri['logsText']["main"]
    if os.path.isdir(path):
        activation_code = os.path.basename(path)

    try:
        dirct_arr = []
        #save the retunr of each function valid to storage the shapefile array that after is insert in geopdf
        #hacer que guarde todas dentro del diccionario ver como lo actualiza para luego cuando valla ala otra carpeta tire de estas
        values={}
        for dirs in os.listdir(path):
            #walk inside each main folder "VECTOR, RASTER and RTP"
            gdb = attri["FoldersToCheck"][0]
            lyr = attri["FoldersToCheck"][1]
            report = attri["FoldersToCheck"][2]
            has_gdb = False
            if path.find("AEM") != -1:
                pass
            else:
                #check the different folders inside the product_version folder.
                #1.Check the VECTOR folder
                if gdb in dirs:
                    root2 = os.path.join(path, gdb)
                    for root3, dirs_gdb, files in os.walk(root2):
                        #get the different vector layer names
                        if len(dirs_gdb) > 0:
                            for dir in dirs_gdb:
                                if attri["VectorFormats"]["GDB"]["types"][0] in dir:
                                    path = os.path.join(root3, dir)
                                    VectorLayer = globals()[attri["VectorFormats"]["GDB"]["className"]]
                                    vectortype = VectorLayer(root3,attri,activation_code)
                                    vectortype.checkextension(path)
                            has_gdb= True
                        elif len(dirs_gdb) == 0 and len(files) > 0 and has_gdb== False:
                            err = logs_text["no_gdb"].copy()
                            initial_err = activation_code + "|" + splitroot(root3,activation_code) + "|" + gdb + "|" +  logFile.getCatValue( attri['VectorFormats']['GDB']['not_correct_file']) + "|" + logFile.getIssueValue(attri['VectorFormats']['GDB']['not_correct_file']) +"|"
                            err.insert(0,initial_err)
                            logFile.writelogs(err)
                            for file in files:
                                err2 = logs_text["extension"].copy()
                                initial_err = activation_code + "|" + splitroot(root3,activation_code) + "|" + gdb + "|" +  logFile.getCatValue( attri['VectorFormats']['GDB']['not_correct_file']) + "|" + logFile.getIssueValue(attri['VectorFormats']['GDB']['not_correct_file']) +"|"
                                err2.insert(0,initial_err)
                                err2.insert(2,file)
                                logFile.writelogs(err2)
                            #validate each vector layer                   
                elif lyr in dirs:
                    root2 = os.path.join(path, lyr)
                    for root3, dirs_lyr, files in os.walk(root2):
                        VectorLayer = globals()[attri["VectorFormats"]["symbology"]["className"]]
                        vectortype = VectorLayer(root3,attri,activation_code)
                        vectortype.checkextension(files)
                elif report in dirs:
                        root2 = os.path.join(path, report)
                        for root3, dirs_lyr, files in os.walk(root2):
                            VectorLayer = globals()[attri["VectorFormats"]["report"]["className"]]
                            vectortype = VectorLayer(root3,attri,activation_code)
                            vectortype.checkextension(files)


        time = logs_text["time"]
        #shutil.rmtree(attri["Temp_root"])
        time.append(str(datetime.now() - startTime))
        #logFile.writelogs(time)
        #print("FINISH")

    except Exception as ex:
        e = logs_text["e"]
        e.append(str(ex))
        logFile.writelogs(e)
        time = logs_text["time"]
        time.append(str(datetime.now() - startTime))
        logFile.writelogs(time)
Exemplo n.º 21
0
 def __init__(self):
     cfg = ConfigFile(FILE_COPY_CONFIG_PATH)
     self.copier = FileCopier(cfg.file_copier_spec())
Exemplo n.º 22
0
class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):    
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)
        self.btnLoadPlugeDict.hide()

        self.viewList = list()
        self.PluDictViewList = list()
        self.historyInputList = list()
        #词典列表
        self.PlugeDictionary=list()
        '''
        读取配置文件
        '''
        self.ReadConfig()

        self.checkBoxPlugeDict.stateChanged.connect(self.LoadPlugeDict)
        self.btnExcel2Json.clicked.connect(self.Excel2Json)
        self.btnLoadJson.clicked.connect(self.getAttrFilePath)
        self.btnLoadCorpus.clicked.connect(self.getReadCorpusFilePath)
        self.btnPreviousPage.clicked.connect(self.PreviousPage)
        self.btnNextPage.clicked.connect(self.NextPage)
        self.btnJumpPage.clicked.connect(self.JumpPage)
        self.btnSaveCorpus.clicked.connect(self.getSaveCorpusFilePath)
        self.btnCommit.clicked.connect(self.Commit)
        self.btnLoadPlugeDict.clicked.connect(self.getPlugeDictionaryFilePath)
        self.btnOpenInputHistory.clicked.connect(self.ShowInputHistoryDock)
        self.btnClearInputHistory.clicked.connect(self.ClearInputHistory)
        self.btnResearch.clicked.connect(self.Research)
        self.lineEditResearch.textChanged.connect(self.Research)
        self.listWidgetResearch.itemClicked.connect(self.CommitResearch)
        self.btnEntityResearch.clicked.connect(self.EntityResearch)
        self.SetHistoryInputDock()

    def CommitResearch(self,qModelIndex):
        self.UpdateAttr(1)
        text=self.sourceText
        text=text.split('}')[0]
        tlist=self.listWidgetResearch.selectedItems()
        tlist=[t.text() for t in list(tlist)]
        text=text+','+','.join(tlist)+'}'
        self.lineEditResult.setText(text)

    def Research(self):
        self.listWidgetResearch.clear()
        self.sourceText=self.lineEditResult.text()
        compileString=self.lineEditResearch.text()
        #print(compileString)
        cp=re.compile('%s'%compileString)
        for items in self.PlugeDictionary:
            for item in items:
               #print(item)
               if len(re.findall(cp,item))!=0:
                   self.listWidgetResearch.addItem(item)

    def ClearInputHistory(self):
        self.historyInputListWidget.clear()
        self.historyInputList=[]

    def ShowInputHistoryDock(self):
        self.dockWidgetHistoryInput.show()

    def SetHistoryInputDock(self):
        self.historyInputListWidget=QListWidget()
        self.dockWidgetHistoryInput.setWidget(self.historyInputListWidget)
        self.historyInputListWidget.addItems(self.historyInputList)
        self.historyInputListWidget.itemClicked.connect(self.HistoryInput2lineEditResult)

    def HistoryInput2lineEditResult(self,qModelIndex):
        #print(qModelIndex)
        tlist=self.historyInputListWidget.selectedItems()
        text=[t.text() for t in list(tlist)]
        self.lineEditResult.setText(','.join(text))

    def LoadPlugeDict(self):
        if self.checkBoxPlugeDict.isChecked():
            self.btnLoadPlugeDict.show()
            for listWidget in self.PluDictViewList:
                listWidget.show()
        else:
            self.btnLoadPlugeDict.hide()
            for listWidget in self.PluDictViewList:
                listWidget.hide()

        self.UpdateAttr('')

    def Excel2Json(self):
        ex = excel2json(self)
        ex.show()

    def getAttrFilePath(self):
        tmpPath, _ = QFileDialog.getOpenFileName(self,
                                                  r'打开JSON',
                                                  r'./',
                                                  r'JSON File(*.json)')
        if tmpPath !='':
            self.attrFilePath=tmpPath
            self.LoadJson()

    def getReadCorpusFilePath(self):
        tmpPath, _ = QFileDialog.getOpenFileName(self,
                                                  r'打开语料',
                                                  r'./',
                                                  r'Excel File(*.xls *.xlsx)')
        if tmpPath !='':
            self.readCorpusFilePath=tmpPath
            self.LoadCorpus()

    def getSaveCorpusFilePath(self):
        filepath,_ = QFileDialog.getSaveFileName(self,
                                                r'保存语料',
                                                r'./',
                                                r'Excel File (*.xls)')
        tmpPath=filepath
        if tmpPath !='':
            self.saveCorpusFilePath=tmpPath
            self.SaveCorpus()

    def getPlugeDictionaryFilePath(self):
        tmpPath, _ = QFileDialog.getOpenFileName(self,
                                                  r'打开JSON',
                                                  r'./',
                                                  r'JSON File(*.json)')
        if tmpPath !='':
            self.plugeDictionaryFilePath=tmpPath
            self.PlugeDict()

    def LoadJson(self):
        self.jr=JsonReader(self.attrFilePath)
        self.ShowEntity()

    def EntityResearch(self):
        try:
            self.comboBoxEntitys.currentIndexChanged.disconnect(self.ShowAttribute)
        except:
            print('the slot dont have sign')

        entityList = self.jr.getEntityList()
        string = self.lineEditEntityResearch.text()
        cp = re.compile(string)
        researchList = list()
        for entity in entityList:
            if re.findall(cp,entity) != []:
                researchList.append(entity)
        self.comboBoxEntitys.clear()
        self.comboBoxEntitys.addItems(researchList)
        self.comboBoxEntitys.currentIndexChanged.connect(self.ShowAttribute)

    def ShowEntity(self):
        try:
            self.comboBoxEntitys.currentIndexChanged.disconnect(self.ShowAttribute)
        except:
            print('the slot dont have sign')
        self.comboBoxEntitys.clear()
        self.comboBoxEntitys.addItems(self.jr.getEntityList())
        self.comboBoxEntitys.currentIndexChanged.connect(self.ShowAttribute)
    
    def ShowAttribute(self,i):
        entity=self.comboBoxEntitys.currentText()

        attrList,attrListLength = self.jr.getCurrentEntityAttributeList(entity)

        #print(attrListLength)
        if len(self.viewList) < attrListLength:
            listIndex = -1
            for view in self.viewList:
                slm = QStringListModel()
                listIndex+=1
                view.clear()
                view.addItems(self.jr.getAttributeItems(entity,listIndex))

            widgetColumnIndex=listIndex
            widgetRowIndex=0

            for i in range(attrListLength-len(self.viewList)):
                #print(slm)
                listIndex+=1
                widgetColumnIndex+=1
                
                if widgetColumnIndex > 4:
                    widgetRowIndex+=1
                    widgetColumnIndex=0
                print(r'widgetRowIndex:{},widgetColumnIndex:{}'.format(widgetRowIndex,widgetColumnIndex))
                tmpListView = QListWidget()
                tmpListView.addItems(self.jr.getAttributeItems(entity,listIndex))
                tmpListView.itemClicked.connect(self.UpdateAttr)
                # 按住CTRL可多选
                tmpListView.setSelectionMode(QAbstractItemView.ExtendedSelection)
                self.viewList.append(tmpListView)
                self.gridLayoutAttrListView.addWidget(tmpListView,widgetRowIndex,widgetColumnIndex)
        else:
            for index in range(attrListLength):
                self.viewList[index].clear()
                self.viewList[index].addItems(self.jr.getAttributeItems(entity,index))
                self.viewList[index].show()

            for index in range(attrListLength,len(self.viewList)):
                self.viewList[index].hide() 

    def UpdateAttr(self,qModelIndex):
        result=[]
        for view in self.viewList:
            tlist = view.selectedItems()
            text = [t.text() for t in list(tlist)]
            result+=text

        if self.checkBoxPlugeDict.isChecked():
            for pdview in self.PluDictViewList:
                tlist = pdview.selectedItems()
                text = [t.text() for t in list(tlist)]
                result+=text

        self.lineEditResult.setText('{'+','.join(result)+'}')

    def LoadCorpus(self):
        self.cr=CorpusReader(self.readCorpusFilePath)
        id,corpu=self.cr.getCorpu(1)
        self.UpdataCorpu(id,corpu)

    #上一页
    def PreviousPage(self):
        id=self.cr.getId()
        id,corpu=self.cr.getCorpu(id-1)
        self.UpdataCorpu(id,corpu)
        self.lineEditResult.setText(self.cr.getCorpuResult(id))

    #下一页
    def NextPage(self):
        id=self.cr.getId()
        id,corpu=self.cr.getCorpu(id+1)
        self.UpdataCorpu(id,corpu)
        self.lineEditResult.setText(self.cr.getCorpuResult(id))

    #页面跳转
    def JumpPage(self):
        id=int(self.lineEditPage.text())
        _,corpu=self.cr.getCorpu(id)
        self.UpdataCorpu(id,corpu)
        self.lineEditResult.setText(self.cr.getCorpuResult(id))

    def UpdataCorpu(self,id,corpu):
        self.lblNo.setText(str(id))
        self.lblSourceCorpu.setText(corpu)

    def SaveCorpus(self):
        self.cr.setSavePath(self.saveCorpusFilePath)

    #提交结果
    def Commit(self):
        id=self.cr.getId()
        corpu=self.lineEditResult.text()
        self.cr.Commit(id,corpu)
        self.cr.Save()
        '''将输入加载到历史输入框中'''
        if corpu not in self.historyInputList:
            self.historyInputList.append(corpu)
            self.historyInputListWidget.addItem(corpu)

    def PlugeDict(self):
        self.plugeDictjr=JsonReader(self.plugeDictionaryFilePath)
        self.plugeDictAttrList=self.plugeDictjr.getEntityList()
        widgetRowIndex=0
        widgetColumnIndex=-1
        for attrTitle in self.plugeDictAttrList:
            #print(self.plugeDictjr.getPlugeDictAttrItems(attrTitle))
            widgetColumnIndex+=1
                
            if widgetColumnIndex > 4:
                widgetRowIndex+=1
                widgetColumnIndex=0
            print(r'widgetRowIndex:{},widgetColumnIndex:{}'.format(widgetRowIndex,widgetColumnIndex))
            tmpListView = QListWidget()
            item=self.plugeDictjr.getPlugeDictAttrItems(attrTitle)
            self.PlugeDictionary.append(item)
            tmpListView.addItems(item)
            tmpListView.itemClicked.connect(self.UpdateAttr)
                # 按住CTRL可多选
            tmpListView.setSelectionMode(QAbstractItemView.ExtendedSelection)
            self.PluDictViewList.append(tmpListView)
            tmpListView.hide()
            self.gridLayoutPlugeDictListView.addWidget(tmpListView,widgetRowIndex,widgetColumnIndex)

    def closeEvent(self, event):
        """
        重写closeEvent方法,实现dialog窗体关闭时执行一些代码
        :param event: close()触发的事件
        :return: None
        """
        configItems=list()
        
        try:
            configItems.append('historyInputList&&'+"||".join(self.historyInputList))
            configItems.append('readCorpusFilePath&&'+self.readCorpusFilePath)
            configItems.append('attrFilePath&&'+self.attrFilePath)
            configItems.append('plugeDictionaryFilePath&&'+self.plugeDictionaryFilePath)
            configItems.append('saveCorpusFilePath&&'+self.saveCorpusFilePath)           
        except:
            print('存在设置没有设定')
        self.configFile.WriteConfig(configItems)

    def ReadConfig(self):
        self.configFile = ConfigFile()
        configItems=self.configFile.ReadConfig()

        for item in configItems:
            part=item.strip('\n').split('&&')
            if len(part)!=1:
                if part[0]=='attrFilePath':
                    self.attrFilePath=part[1]
                    self.LoadJson()
                elif part[0]=='plugeDictionaryFilePath':
                    self.plugeDictionaryFilePath=part[1]
                    self.PlugeDict()
                elif part[0]=='saveCorpusFilePath':
                    self.saveCorpusFilePath=part[1]
                    self.SaveCorpus()
                elif part[0]=='readCorpusFilePath':
                    self.readCorpusFilePath=part[1]
                    self.LoadCorpus()
                elif part[0]=='historyInputList':
                    self.historyInputList=part[1].split('||')
Exemplo n.º 23
0
main()

my_generator = (letter for letter in 'abcdefg')

#import tempfile
#[fh,filename]=tempfile.mkstemp(prefix="tmp.");
#print(filename,fh)
#os.close(fh)

import TempFilename
filename=TempFilename.generate()
fh=open(filename,'w')
print(fh)
x=0
while(x<10):  fh.write(str(x)); x+=3
fh.close()
os.remove(filename)

config=ConfigFile("test/data/ice.0-43.config")
print(config.lookup("donor-consensus"))

a=[1.1, 6.4, 9.3, 3.4, 9.2, 4.6, 1.6, 0.3]
b=list(map(lambda x:x+random.uniform(-10,10),a))
[mean,SD,min,max]=SummaryStats.summaryStats(a)
print(mean,"+/-",SD)
print("sum=",SummaryStats.sum(a))
print("r=",SummaryStats.correlation(a,b))



Exemplo n.º 24
0
class WorkDir(object):

    CFG_FILE_NAME = u'.dirstate.cfg'

    def __init__(self, dirName):
        
        # рабочий каталог должен существовать
        if not path.exists(dirName):
            print u'Working dir {0} not exists'.format(dirName)
            raise Exception(u'Working dir not exists')

        # мы должны иметь полные права доступа к рабочему каталогу
        if not check_permissions(dirName, read=True, write=True, execute=True):
            print u'No rwx permissions for directory {0}'.format(dirName)
            raise Exception(u'No rwx permissions for directory')

        # сохраняем необходимые значения
        self._path = dirName
        self._cfgFile = ConfigFile([self._read_cfg, self._write_cfg], self.CFG_FILE_NAME, dirName)

        self._entries = self._cfgFile.read()
        self.check_entries()


    def _read_cfg(self, cfgFilePath = None):
        cfg = {}
        if not cfgFilePath is None:
            with open(cfgFilePath) as cfgFile:
                for line in cfgFile:
                    line = line.decode('utf-8').rstrip()
                    if not line:
                        continue
                    if not line.startswith(u'/'):
                        linksList = []
                        cfg[line] = linksList
                    else:
                        linksList.append(line)
        return cfg


    def _write_cfg(self, cfgFilePath, cfg):
        with open(cfgFilePath, 'w') as cfgFile:
            for entryName, links in cfg.iteritems():
                if not links:
                    continue
                toWrite = [s.encode('utf-8') + '\n' for s in [entryName] + links]
                cfgFile.writelines(toWrite)



    def get_entries(self):
        return self._entries


    def get_entry_links(self, entry, defVal = None):
        return self._entries.get(entry, defVal)


    def check_entries(self):
        # ищем новые файлы
        for entry in self.get_dir_entries():
            if not entry in self._entries:
                self._entries[entry] = []
        # ищем удаленные файлы и удаляем их из списка
        for entry in self._entries.keys():
            if not path.exists(path.join(self._path, entry)):
                self.delete_links(entry)
                del self._entries[entry]


    def delete_links(self, entry):
        links = self._entries[entry]
        for link in links:
            try:
                os.unlink(link)
            except Exception as ex:
                print 'Error symlink deletion: {0}'.format(link)


    def split_entries(self):
        workEntries = {}
        newEntries = {}
        removedEntries = {}
        for entry in self._entries.keys():
            links = self._entries[entry]
            entryPath = path.join(self._path, entry)
            if not path.exists(entryPath):  # файл был удален
                self.delete_links(entry)
                del self._entries[entry]
            elif not links:                 # новый файл
                newEntries[entry] = links
            else:
                workEntries[entry] = links
        return workEntries, newEntries, removedEntries


    def get_dir_entries(self):
        '''
        Чтение списка файлов в рабочем каталоге.
        Исключаются файлы, начинающиеся с точки '.'
        '''
        return [entry for entry in os.listdir(self._path) if not entry[0] == u'.']


    def save_state(self):
        '''Сохранение состояния рабочего каталога'''
        self._cfgFile.write(self._entries)
        print u'Состояние каталога {} сохранено'.format(self._path)
Exemplo n.º 25
0
 def __init__(self):
     cfg = ConfigFile(FILE_COPY_CONFIG_PATH)
     self.copier = FileCopier(cfg.file_copier_spec())
Exemplo n.º 26
0
from ConfigFile import ConfigFile
from ConfigFile import LogFile

# variables used for debugging the code
DEBUG = False
WIN_DEBUG = False

# specifies the root directory for the program to be run in.
ROOT_DIR = '/users/groups/cs235ta/submission_driver/'

# if running on a windows machine, adjust accordingly.
if WIN_DEBUG:
    ROOT_DIR = 'path'

# create the config file object from the file.
config_file_object = ConfigFile(ROOT_DIR + 'compiler_global.cfg')


#=====================================================#
# store_grade                                         #
#       ammends the given file, updating the          #
#       net_id's score, or inserting it if the first  #
#       submission.                                   #
#                                                     #
#       the file that this function will update is    #
#       "LabXXgrades.csv". This file is located in    #
#       the "/public_html/XX20XX_submissions" folder  #
#                                                     #
# Parameters:                                         #
#       file_name (str): e.g. "Lab01grades.csv"
#       net_id (): The student's net ID
Exemplo n.º 27
0
from LogFile import LogFile  #my logging mechs
from LogFile import ErrorMsg  #the error struct
from datetime import date
from LogFile import SeverityLevel
import datetime
import os
import re
import pandas as pn
import xlrd
import shutil
##### methods ######

#entry point

#load up our config.  only place with out a log
Cfg = ConfigFile("File2JsonConfig.xml")
Log = LogFile(Cfg.logpath)
TotalFilesProcessed = 0
TotalRecordsProcessed = 0
TotalErrors = 0

try:
    xlspattern = re.compile(r"\w+\.xl(s|sm|sx)")
    #we'll loop through the files, and process them indvidually.

    for thefiles in os.listdir(Cfg.source_directory):
        sumJson = "["

        try:
            print("Processing File " + str(TotalFilesProcessed))
            TotalFilesProcessed = TotalFilesProcessed + 1
Exemplo n.º 28
0
 def refreshCalibrationFiles():
     print("SeaBASSHeader - refreshCalibrationFiles")
     calibrationPath = ConfigFile.getCalibrationDirectory()
     files = os.listdir(calibrationPath)
     SeaBASSHeader.settings["calibration_files"] = (','.join(files))
Exemplo n.º 29
0
import sys
from ConfigFile import ConfigFile

cd = ConfigFile('config_file.txt')

if len(sys.argv) == 3:
    key = sys.argv[1]
    value = sys.argv[2]
    print('writing data:  {0}, {1}'.format(key, value))

    cd[key] = value

else:

    print('reading data')
    for key in cd.keys():
        print('   {0} = {1}'.format(key, cd[key]))