def isApisIni(ini): s = QSettings(ini, QSettings.IniFormat) requiredKeysIsFile = ['database_file'] requiredKeysIsDir = ['flightpath_dir', 'image_dir', 'ortho_image_dir', 'repr_image_dir', 'insp_image_dir'] requiredKeys = ['hires_vertical', 'hires_oblique_digital', 'hires_oblique_analog'] isIni = True errorKeys = [] for k in requiredKeysIsFile: key = "APIS/"+k if not s.contains(key)or not os.path.isfile(s.value(key)): isIni = False errorKeys.append(k) for k in requiredKeysIsDir: key = "APIS/"+k if not s.contains(key) or not os.path.isdir(s.value(key)): isIni = False errorKeys.append(k) for k in requiredKeys: key = "APIS/"+k if not s.contains(key): isIni = False errorKeys.append(k) return isIni, s if isIni else u"Folgende Schlüssel in der INI Datei sind nicht korrekt oder nicht vorhanden: " + u", ".join(errorKeys)
def selectFile(self): output = self.alg.getOutputFromName('OUTPUT_LAYER') fileFilter = output.getFileFilter(self.alg) settings = QSettings() if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) lastEncoding = settings.value('/Processing/encoding', 'System') fileDialog = QgsEncodingFileDialog(self, self.tr('Save file'), path, fileFilter, lastEncoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(True) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() encoding = unicode(fileDialog.encoding()) output.encoding = encoding filename = unicode(files[0]) selectedFileFilter = unicode(fileDialog.selectedNameFilter()) if not filename.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))): ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter) if ext: filename = filename + ext.group(1) self.leOutputFile.setText(filename) settings.setValue('/Processing/LastOutputPath', os.path.dirname(filename)) settings.setValue('/Processing/encoding', encoding)
def rearrangeToolbars(profile): settings = QSettings() key = "profilesplugin/Profiles/%s/geometry" % profile if settings.contains(key): iface.mainWindow().restoreGeometry(settings.value(key)) else: toolbars = [el for el in iface.mainWindow().children() if isinstance(el, QToolBar) and el.isVisible()] toolbars = sorted(toolbars, key=lambda t: (t.geometry().top(), t.geometry().left())) for toolbar in toolbars: iface.mainWindow().removeToolBarBreak(toolbar) for toolbar in toolbars: iface.mainWindow().insertToolBarBreak(toolbar) rowWidth = 0 lastY = None for toolbar in toolbars: if lastY is None: lastY = toolbar.geometry().top() actions = [a for a in toolbar.actions() if a.isVisible()] toolbarWidth = toolbar.actionGeometry(actions[-1]).right() rowWidth += toolbarWidth #print toolbar.objectName(), toolbarWidth, rowWidth if rowWidth < iface.mainWindow().width(): iface.mainWindow().removeToolBarBreak(toolbar) else: lastY += toolbar.geometry().height() rowWidth = toolbarWidth toolbar.move(QPoint(rowWidth - toolbarWidth, lastY))
def accept(self): s = QSettings() connName = self.leName.text() #if not connName.isEmpty(): Porting QGIS 2.0 if connName is not None and connName != "": key = "/CSIAtlante/services/" + connName # warn if entry was renamed to an existing connection if self.origName != connName and s.contains(key + "/url"): res = QMessageBox.warning(self, self.tr("Salva connessione"), #str(self.tr("Connessione %1 esistente : sovrascrivere?")).arg(connName), self.tr("Connessione " + connName + " esistente : sovrascrivere?"), QMessageBox.Ok | QMessageBox.Cancel) if res == QMessageBox.Cancel: return # on rename delete original entry first if self.origName is not None and self.origName != "" and self.origName != connName: s.remove("/CSIAtlante/services/" + self.origName) s.setValue(key + "/url", self.leURL.text().strip()) s.setValue(key + "/usr", self.leUser.text().strip()) s.setValue(key + "/pwd", self.lePassword.text().strip()) # test su servizio di login per feedback url, usr, pwd = self.leURL.text().strip(), self.leUser.text().strip(), self.lePassword.text().strip() tab = 'login' cod = -1 msg = "" errorCause = "" try: jsonObj = csiutils.GetGenericJSONObj(url, usr=usr, pwd=pwd, tab=tab) if 'cod' in jsonObj.keys(): cod = jsonObj['cod'] if 'msg' in jsonObj.keys(): msg = jsonObj['msg'] if 'errorCause' in jsonObj.keys(): errorCause = jsonObj['errorCause'] if cod == 0: QMessageBox.warning(self, self.tr("Verifica servizio login"), self.tr(msg)) pass elif cod == 1: # uscita! QMessageBox.warning(self, self.tr("Verifica servizio login"), self.tr(msg)) return except Exception, ex: txt = str(ex) QMessageBox.information(None, "Errore", \ "Impossibile leggere l'elenco dal servizio:\n%s \ntab: \n%s \nControllare la connessione di rete.\n[%s]" % (url, tab, txt)) csiutils.Cursor.Restore() # no return procede oltre return # QDialog.accept(self)
def showFileSelectionDialog(self): settings = QSettings() text = unicode(self.text.text()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = unicode(settings.value('/Processing/LastInputPath')) else: path = '' ret = QFileDialog.getOpenFileNames(self, self.tr('Open file'), path, self.tr('All files(*.*);;') + self.param.getFileFilter()) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(unicode(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(unicode(f) for f in files)) else: rowdif = len(files) - (self.table.rowCount() - self.row) for i in range(rowdif): self.panel.addRow() for i, f in enumerate(files): self.table.cellWidget(i + self.row, self.col).setText(f)
def __loadFields(self): settings = QSettings() self.__readSettingsStrToLineEdit(settings, "magic_plugin_pkg__package_name", self.ui.lineEditPackageName) self.__readSettingsStrToLineEdit(settings, "magic_plugin_pkg__package_ident", self.ui.lineEditPackageIdent) self.__readSettingsStrToLineEdit(settings, "magic_plugin_pkg__package_version", self.ui.lineEditPackageVersion) self.__readSettingsStrToLineEdit( settings, "magic_plugin_pkg__scripts_directory", self.ui.lineEditScriptsDirectory) self.__readSettingsStrToLineEdit(settings, "magic_plugin_pkg__output_directory", self.ui.lineEditOutputDirectory) self.__readSettingsStrToLineEdit( settings, "magic_plugin_pkg__output_directory_custom", self.ui.lineEditOutputDirectoryCustom) value = settings.value("magic_plugin_pkg__permissions", "preserve") if value == "preserve": self.ui.rbPermissionsPreserve.setChecked(True) else: self.ui.rbPermissionsRecommended.setChecked(True) if settings.contains("magic_plugin_pkg__simple_or_custom"): if settings.value("magic_plugin_pkg__simple_or_custom").toString( ) == "simple": self.ui.gbSimple.setChecked(True) self.ui.gbCustom.setChecked(False) else: self.ui.gbCustom.setChecked(True) self.ui.gbSimple.setChecked(False)
def read_settings(self): """ Uses QSettings, which will store the setting in different locations depending on OS For Linux normally in ~/.config/.config/OJ/EDreporter.conf For Windows in the registry at \HKEY_CURRENT_USER\Software\OJ\EDreporter """ config = QSettings('OJ', 'EDreporter') # (organization, application name) if not config.contains('saveHistory'): # If config are not defined, we're in the first run and save defaults print('no config - making one') config.setValue('saveHistory', True) # Save data between runs to make statistics config.setValue('authenticated', False) # Are we authenticated with the API yet? config.setValue('readNetLogs', True) # Should we analyse the NetLog folder and all logs? (must be enabled in Elite's settings) config.setValue('systemsDataFile', '.\eddb_data\systems.json') # JOSN data for systems (downloaded) config.setValue('stationsDataFile', '.\eddb_data\stations.json') # JOSN data for stations (downloaded) config.setValue('systemsDataURL', 'https://eddb.io/archive/v4/systems.json') # URL for systems JSON download config.setValue('stationsDataURL', 'https://eddb.io/archive/v4/stations.json') # URL for stations JSON download config.setValue('NetLogFolder', os.path.expanduser("~") + '\AppData\Local\Frontier_Developments\Products\elite-dangerous-64\Logs') # E:D Horizons default config.setValue('historyDatabase', '.\history.db') self.saveHistory = config.value('saveHistory', type=bool) self.authenticated= config.value('authenticated', type=bool) self.readNetLogs = config.value('readNetLogs', type=bool) self.NetLogFolder = config.value('NetLogFolder', type=str) self.historyDatabase = config.value('historyDatabase', type=str) self.stationsDataFile= config.value('stationsDataFile', type=str) self.systemsDataFile = config.value('systemsDataFile', type=str) self.stationsDataURL = config.value('stationsDataURL', type=str) self.systemsDataURL = config.value('systemsDataURL', type=str)
def __init__(self): super(ProcessingToolbox, self).__init__(None) self.setupUi(self) self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.modeComboBox.clear() self.modeComboBox.addItems([self.tr('Simplified interface'), self.tr('Advanced interface')]) settings = QSettings() if not settings.contains(self.USE_CATEGORIES): settings.setValue(self.USE_CATEGORIES, True) useCategories = settings.value(self.USE_CATEGORIES, type=bool) if useCategories: self.modeComboBox.setCurrentIndex(0) else: self.modeComboBox.setCurrentIndex(1) self.modeComboBox.currentIndexChanged.connect(self.modeHasChanged) self.searchBox.textChanged.connect(self.textChanged) self.algorithmTree.customContextMenuRequested.connect( self.showPopupMenu) self.algorithmTree.doubleClicked.connect(self.executeAlgorithm) if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(self.tr('Search...')) self.fillTree()
def selectFile(self): output = self.alg.getOutputFromName('OUTPUT_LAYER') fileFilter = output.getFileFilter(self.alg) settings = QSettings() if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) lastEncoding = settings.value('/Processing/encoding', 'System') fileDialog = QgsEncodingFileDialog(self, self.tr('Save file'), path, fileFilter, lastEncoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(True) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() encoding = unicode(fileDialog.encoding()) output.encoding = encoding filename = unicode(files[0]) selectedFileFilter = unicode(fileDialog.selectedNameFilter()) if not filename.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,5})", fileFilter))): ext = re.search("\*(\.[a-z]{1,5})", selectedFileFilter) if ext: filename = filename + ext.group(1) self.leOutputFile.setText(filename) settings.setValue('/Processing/LastOutputPath', os.path.dirname(filename)) settings.setValue('/Processing/encoding', encoding)
def __init__(self): QDockWidget.__init__(self, None) self.setupUi(self) self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.modeComboBox.clear() self.modeComboBox.addItems(["Simplified interface", "Advanced interface"]) settings = QSettings() if not settings.contains(self.USE_CATEGORIES): settings.setValue(self.USE_CATEGORIES, True) useCategories = settings.value(self.USE_CATEGORIES, type=bool) if useCategories: self.modeComboBox.setCurrentIndex(0) else: self.modeComboBox.setCurrentIndex(1) self.modeComboBox.currentIndexChanged.connect(self.modeHasChanged) self.searchBox.textChanged.connect(self.textChanged) self.algorithmTree.customContextMenuRequested.connect(self.showPopupMenu) self.algorithmTree.doubleClicked.connect(self.executeAlgorithm) if hasattr(self.searchBox, "setPlaceholderText"): self.searchBox.setPlaceholderText(self.tr("Search...")) self.fillTree()
def saveToSpatialite(self): fileFilter = self.output.tr('Spatialite files(*.sqlite)', 'OutputFile') settings = QSettings() if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) encoding = settings.value('/Processing/encoding', 'System') fileDialog = QgsEncodingFileDialog(self, self.tr('Save Spatialite'), path, fileFilter, encoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(False) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() encoding = unicode(fileDialog.encoding()) self.output.encoding = encoding fileName = unicode(files[0]) selectedFileFilter = unicode(fileDialog.selectedNameFilter()) if not fileName.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))): ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter) if ext: fileName += ext.group(1) settings.setValue('/Processing/LastOutputPath', os.path.dirname(fileName)) settings.setValue('/Processing/encoding', encoding) uri = QgsDataSourceURI() uri.setDatabase(fileName) uri.setDataSource('', self.output.name.lower(), 'the_geom') self.leText.setText("spatialite:" + uri.uri())
def connect(self, parent=None): conn_name = self.connectionName() settings = QSettings() settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name)) if not settings.contains("database"): # non-existent entry? raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name) from qgis.core import QgsDataSourceURI uri = QgsDataSourceURI() settingsList = ["service", "host", "port", "database", "username", "password"] service, host, port, database, username, password = map(lambda x: settings.value(x, "", type=str), settingsList) useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool) sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int) settings.endGroup() if service: uri.setConnection(service, database, username, password, sslmode) else: uri.setConnection(host, port, database, username, password, sslmode) uri.setUseEstimatedMetadata(useEstimatedMetadata) try: return self.connectToUri(uri) except ConnectionError, e: return False
def showSelectionDialog(self): # Find the file dialog's working directory settings = QSettings() text = self.leText.text() if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = settings.value('/Processing/LastInputPath') else: path = '' if self.isFolder: folder = QFileDialog.getExistingDirectory(self, self.tr('Select folder'), path) if folder: self.leText.setText(folder) settings.setValue('/Processing/LastInputPath', os.path.dirname(folder)) else: filenames = QFileDialog.getOpenFileNames(self, self.tr('Select file'), path, '*.' + self.ext) if filenames: self.leText.setText(u';'.join(filenames)) settings.setValue('/Processing/LastInputPath', os.path.dirname(filenames[0]))
def connect(self, parent=None): conn_name = self.connectionName() settings = QSettings() settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name)) if not settings.contains("database"): # non-existent entry? raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name) from qgis.core import QgsDataSourceURI uri = QgsDataSourceURI() settingsList = ["service", "host", "port", "database", "username", "password"] service, host, port, database, username, password = map(lambda x: settings.value(x, "", type=str), settingsList) useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool) sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int) settings.endGroup() if service: uri.setConnection(service, database, username, password, sslmode) else: uri.setConnection(host, port, database, username, password, sslmode) uri.setUseEstimatedMetadata(useEstimatedMetadata) try: return self.connectToUri(uri) except ConnectionError as e: return False
def findDataDir(self,name): if not len(QApplication.applicationName()): print "QApplication.applicationName() is not set" return '' s = QSettings() if s.contains('datadir'): datadir = unicode(s.value('datadir')) imagepath = os.path.join(datadir,name) if os.path.exists(imagepath): return imagepath else: dirname = os.path.dirname(name) datadirsuffix = os.path.join( 'share',unicode(QApplication.applicationName())) dirpath = os.path.normpath(os.path.join(datadirsuffix,dirname)) for root, dirs, files in os.walk('/usr', None, True): if not root.endswith(dirpath): continue for f in files: filepath = os.path.join(root,f) if filepath.endswith(name): pos = filepath.find(name) if pos == -1: continue datadir = os.path.normpath(root[:pos]) s.setValue('datadir',datadir) return filepath return ''
def saveToSpatialite(self): fileFilter = self.output.tr('Spatialite files(*.sqlite)', 'OutputFile') settings = QSettings() if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) encoding = settings.value('/Processing/encoding', 'System') fileDialog = QgsEncodingFileDialog( self, self.tr('Save Spatialite'), path, fileFilter, encoding) fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(False) if fileDialog.exec_() == QDialog.Accepted: files = fileDialog.selectedFiles() encoding = unicode(fileDialog.encoding()) self.output.encoding = encoding fileName = unicode(files[0]) selectedFileFilter = unicode(fileDialog.selectedNameFilter()) if not fileName.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))): ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter) if ext: fileName += ext.group(1) settings.setValue('/Processing/LastOutputPath', os.path.dirname(fileName)) settings.setValue('/Processing/encoding', encoding) uri = QgsDataSourceURI() uri.setDatabase(fileName) uri.setDataSource('', self.output.name.lower(), 'the_geom') self.leText.setText("spatialite:" + uri.uri())
def loadSettings(self, firstTime): qsettings = QSettings() websettings = self.ui.webview.settings() self.fSavedSettings = { # Main MOD_KEY_MAIN_PROJECT_FOLDER: qsettings.value(MOD_KEY_MAIN_PROJECT_FOLDER, MOD_DEFAULT_MAIN_PROJECT_FOLDER, type=str), MOD_KEY_MAIN_REFRESH_INTERVAL: qsettings.value(MOD_KEY_MAIN_REFRESH_INTERVAL, MOD_DEFAULT_MAIN_REFRESH_INTERVAL, type=int), # Host MOD_KEY_HOST_VERBOSE: qsettings.value(MOD_KEY_HOST_VERBOSE, MOD_DEFAULT_HOST_VERBOSE, type=bool), MOD_KEY_HOST_PATH: qsettings.value(MOD_KEY_HOST_PATH, MOD_DEFAULT_HOST_PATH, type=str), # WebView MOD_KEY_WEBVIEW_INSPECTOR: qsettings.value(MOD_KEY_WEBVIEW_INSPECTOR, MOD_DEFAULT_WEBVIEW_INSPECTOR, type=bool), MOD_KEY_WEBVIEW_VERBOSE: qsettings.value(MOD_KEY_WEBVIEW_VERBOSE, MOD_DEFAULT_WEBVIEW_VERBOSE, type=bool), MOD_KEY_WEBVIEW_SHOW_INSPECTOR: qsettings.value(MOD_KEY_WEBVIEW_SHOW_INSPECTOR, MOD_DEFAULT_WEBVIEW_SHOW_INSPECTOR, type=bool) } inspectorEnabled = self.fSavedSettings[ MOD_KEY_WEBVIEW_INSPECTOR] and not USING_LIVE_ISO websettings.setAttribute(QWebSettings.DeveloperExtrasEnabled, inspectorEnabled) if firstTime: if qsettings.contains("Geometry"): self.restoreGeometry(qsettings.value("Geometry", "")) else: self.setWindowState(self.windowState() | Qt.WindowMaximized) if inspectorEnabled and self.fSavedSettings[ MOD_KEY_WEBVIEW_SHOW_INSPECTOR]: QTimer.singleShot(1000, self.ui.webinspector.show) self.ui.act_file_inspect.setVisible(inspectorEnabled) if self.fIdleTimerId != 0: self.killTimer(self.fIdleTimerId) self.fIdleTimerId = self.startTimer( self.fSavedSettings[MOD_KEY_MAIN_REFRESH_INTERVAL])
def __init__(self, parent = None): QObject.__init__(self, parent) self.jinja = Environment(loader = FileSystemLoader("data/templates"), autoescape = True) self.jinja.filters["likes"] = filter_likes self.jinja.filters["twitterise"] = filter_twitterise self.jinja.filters["timesince"] = filter_timesince self.mapper = Mapper() self.mapper.connect("/", controller = "LolViews", action = "feed") self.mapper.connect("/login", controller = "LolViews", action = "login") self.mapper.connect("/user/:user", controller = "LolViews", action = "feed") self.notes = NotificationServer() from PyQt4.QtCore import QSettings settings = QSettings() if settings.contains("session"): from cPickle import loads self.session = loads(str(settings.value("session").toString())) else: self.session = Session() self.ff = FriendFeedAPI(self.session) self.deferredResponses = set()
def showFileSelectionDialog(self): settings = QSettings() text = unicode(self.text.text()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = unicode(settings.value('/Processing/LastInputPath')) else: path = '' ret = QFileDialog.getOpenFileNames( self, self.tr('Open file'), path, self.tr('All files(*.*);;') + self.param.getFileFilter()) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(unicode(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(unicode(f) for f in files)) else: rowdif = len(files) - (self.table.rowCount() - self.row) for i in range(rowdif): self.panel.addRow() for i, f in enumerate(files): self.table.cellWidget(i + self.row, self.col).setText(f)
def postgis_path_to_uri(path): """Convert layer path from QgsBrowserModel to full QgsDataSourceURI. :param path: The layer path from QgsBrowserModel :type path: string :returns: layer uri. :rtype: QgsDataSourceURI """ connection_name = path.split('/')[1] schema = path.split('/')[2] table_name = path.split('/')[3] settings = QSettings() key = "/PostgreSQL/connections/" + connection_name service = settings.value(key + "/service") host = settings.value(key + "/host") port = settings.value(key + "/port") if not port: port = "5432" db = settings.value(key + "/database") use_estimated_metadata = settings.value( key + "/estimatedMetadata", False, type=bool) sslmode = settings.value( key + "/sslmode", QgsDataSourceURI.SSLprefer, type=int) username = "" password = "" if settings.value(key + "/saveUsername") == "true": username = settings.value(key + "/username") if settings.value(key + "/savePassword") == "true": password = settings.value(key + "/password") # Old save setting if settings.contains(key + "/save"): username = settings.value(key + "/username") if settings.value(key + "/save") == "true": password = settings.value(key + "/password") uri = QgsDataSourceURI() if service: uri.setConnection(service, db, username, password, sslmode) else: uri.setConnection(host, port, db, username, password, sslmode) uri.setUseEstimatedMetadata(use_estimated_metadata) # Obtain the geometry column name connector = PostGisDBConnector(uri) tables = connector.getVectorTables(schema) tables = [table for table in tables if table[1] == table_name] if not tables: return None table = tables[0] geom_col = table[8] uri.setDataSource(schema, table_name, geom_col) return uri
def addValueToCustomSizesDict(self, newValueDict): settings = QSettings() if not settings.contains('DSGTools/CustomSizes/'+newValueDict['comboText']+'/shape'): settings.beginGroup('DSGTools/CustomSizes/'+newValueDict['comboText']) settings.setValue('shape', newValueDict['shape']) settings.setValue('value', newValueDict['value']) settings.endGroup() self.populateSizesComboBox()
def load(self, scheme): """Load the settings for the scheme. Called on init.""" s = QSettings() s.beginGroup("fontscolors/" + scheme) # load font defaultfont = "Lucida Console" if os.name == "nt" else "monospace" self.font = QFont(s.value("fontfamily", defaultfont, type(""))) self.font.setPointSizeF(s.value("fontsize", 10.0, float)) # load base colors s.beginGroup("basecolors") for name in baseColors: if s.contains(name): self.baseColors[name] = QColor(s.value(name, "", type(""))) else: self.baseColors[name] = baseColorDefaults[name]() s.endGroup() # get the list of supported styles from ly.colorize all_styles = ly.colorize.default_mapping() default_styles = set() for group, styles in all_styles: d = self._inherits[group] = {} for style in styles: if style.base: default_styles.add(style.base) d[style.name] = style.base default_scheme = ly.colorize.default_scheme # load default styles s.beginGroup("defaultstyles") for name in default_styles: self.defaultStyles[name] = f = QTextCharFormat() css = default_scheme[None].get(name) if css: css2fmt(css, f) s.beginGroup(name) self.loadTextFormat(f, s) s.endGroup() s.endGroup() # load specific styles s.beginGroup("allstyles") for group, styles in all_styles: self.allStyles[group]= {} s.beginGroup(group) for style in styles: self.allStyles[group][style.name] = f = QTextCharFormat() css = default_scheme[group].get(style.name) if css: css2fmt(css, f) s.beginGroup(style.name) self.loadTextFormat(f, s) s.endGroup() s.endGroup() s.endGroup()
def showSelectionDialog(self): if isinstance(self.output, OutputDirectory): self.selectDirectory() return filefilter = self.output.getFileFilter(self.alg) settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): path = unicode(settings.value('/Processing/LastBatchOutputPath')) else: path = '' filename = QFileDialog.getSaveFileName(self, self.tr('Save file'), path, filefilter) if filename: filename = unicode(filename) settings.setValue('/Processing/LastBatchOutputPath', os.path.dirname(filename)) dlg = AutofillDialog(self.alg) dlg.exec_() if dlg.mode is not None: try: if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL: self.table.cellWidget(self.row, self.col).setValue(filename) elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS: n = self.table.rowCount() - self.row for i in range(n): name = filename[:filename.rfind('.')] \ + str(i + 1) + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER: n = self.table.rowCount() - self.row for i in range(n): widget = self.table.cellWidget( i + self.row, dlg.param) param = self.alg.parameters[dlg.param] if isinstance( param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): s = unicode(widget.getText()) s = os.path.basename(s) s = os.path.splitext(s)[0] elif isinstance(param, ParameterBoolean): s = str(widget.currentIndex() == 0) elif isinstance(param, ParameterSelection): s = unicode(widget.currentText()) elif isinstance(param, ParameterFixedTable): s = unicode(widget.table) else: s = unicode(widget.text()) name = filename[:filename.rfind('.')] + s \ + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) except: pass
class Storage: def __init__(self): self.settings = QSettings('Christian Dancke Tuen', 'Desktop Harmony') def write_settings(self, username, password, ip, port): self.settings.setValue('username', str(username)) self.settings.setValue('password', str(password)) self.settings.setValue('ip', str(ip)) self.settings.setValue('port', str(port)) del self.settings def remove_settings(self): self.settings.clear() def read_settings(self): username = self.settings.value('username') password = self.settings.value('password') ip = self.settings.value('ip') port = self.settings.value('port') return username, password, ip, port def read_username(self): if self.settings.contains('username'): return str(self.settings.value('username', type=str)) else: return "" def read_password(self): if self.settings.contains('password'): return str(self.settings.value('password', type=str)) else: return "" def read_ip(self): if self.settings.contains('ip'): return str(self.settings.value('ip', type=str)) else: return "" def read_port(self): if self.settings.contains('port'): return str(self.settings.value('port', type=str)) else: return "5222"
def show_dialog(self, key): settings = QSettings('jp.yustam.drop', 's3') if settings.contains(key): value = settings.value(key, type=str) text, ok = QtGui.QInputDialog.getText(self, 'Settings', 'Input ' + key, text=value) else: text, ok = QtGui.QInputDialog.getText(self, 'Settings', 'Input ' + key) if ok: settings.setValue(key, text)
def restore_GUI(self): settings = QSettings('ad9910clientsettings.ini', QSettings.IniFormat) settings.setFallbacksEnabled(False) for aspinbox in self.findChildren( QtGui.QDoubleSpinBox) + self.findChildren(QtGui.QSpinBox): name = aspinbox.objectName() if settings.contains(name): value = settings.value(name).toDouble()[0] aspinbox.setValue(value) if settings.contains('History'): self.history = settings.value('History', [], str) if settings.contains('windowposition'): self.move(settings.value("windowposition").toPoint()) if settings.contains('windowsize'): self.resize(settings.value("windowsize").toSize())
class NewConnectionDialog(QDialog, BASE_CLASS): """Dialogue to add a new CSW entry""" def __init__(self, conn_name=None): """init""" QDialog.__init__(self) self.setupUi(self) self.settings = QSettings() self.conn_name = None self.conn_name_orig = conn_name def accept(self): """add CSW entry""" conn_name = self.leName.text().strip() conn_url = self.leURL.text().strip() if any([conn_name == '', conn_url == '']): QMessageBox.warning(self, self.tr('Save connection'), self.tr('Both Name and URL must be provided')) return if '/' in conn_name: QMessageBox.warning(self, self.tr('Save connection'), self.tr('Name cannot contain \'/\'')) return if conn_name is not None: key = '/MetaSearch/%s' % conn_name keyurl = '%s/url' % key key_orig = '/MetaSearch/%s' % self.conn_name_orig # warn if entry was renamed to an existing connection if all([self.conn_name_orig != conn_name, self.settings.contains(keyurl)]): res = QMessageBox.warning(self, self.tr('Save connection'), self.tr('Overwrite %s?') % conn_name, QMessageBox.Ok | QMessageBox.Cancel) if res == QMessageBox.Cancel: return # on rename delete original entry first if all([self.conn_name_orig is not None, self.conn_name_orig != conn_name]): self.settings.remove(key_orig) self.settings.setValue(keyurl, conn_url) self.settings.setValue('/MetaSearch/selected', conn_name) QDialog.accept(self) def reject(self): """back out of dialogue""" QDialog.reject(self)
def showSelectionDialog(self): if isinstance(self.output, OutputDirectory): self.selectDirectory() return filefilter = self.output.getFileFilter(self.alg) settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): path = unicode(settings.value('/Processing/LastBatchOutputPath')) else: path = '' filename = QFileDialog.getSaveFileName(self, self.tr('Save file'), path, filefilter) if filename: filename = unicode(filename) settings.setValue('/Processing/LastBatchOutputPath', os.path.dirname(filename)) dlg = AutofillDialog(self.alg) dlg.exec_() if dlg.mode is not None: try: if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL: self.table.cellWidget(self.row, self.col).setValue(filename) elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS: n = self.table.rowCount() - self.row for i in range(n): name = filename[:filename.rfind('.')] \ + unicode(i + 1) + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER: n = self.table.rowCount() - self.row for i in range(n): widget = self.table.cellWidget(i + self.row, dlg.param) param = self.alg.parameters[dlg.param] if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): s = unicode(widget.getText()) s = os.path.basename(s) s = os.path.splitext(s)[0] elif isinstance(param, ParameterBoolean): s = unicode(widget.currentIndex() == 0) elif isinstance(param, ParameterSelection): s = unicode(widget.currentText()) elif isinstance(param, ParameterFixedTable): s = unicode(widget.table) else: s = unicode(widget.text()) name = filename[:filename.rfind('.')] + s \ + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) except: pass
def addValueToCustomSizesDict(self, newValueDict): settings = QSettings() if not settings.contains('DSGTools/CustomSizes/' + newValueDict['comboText'] + '/shape'): settings.beginGroup('DSGTools/CustomSizes/' + newValueDict['comboText']) settings.setValue('shape', newValueDict['shape']) settings.setValue('value', newValueDict['value']) settings.endGroup() self.populateSizesComboBox()
def switchScheme(self, scheme): if scheme not in self._shortcuts: s = QSettings() key = "shortcuts/{0}/{1}/{2}".format(scheme, self.collection.name, self.name) if s.contains(key): self._shortcuts[scheme] = ([QKeySequence(v) for v in s.value(key) or []], False) else: # default self._shortcuts[scheme] = (self.defaultShortcuts(), True) self.display(scheme)
def read_setting(key, object_type=str): """ Loads the value from the QSettings specified by the key :param key: Key from the QSettings maps :param object_type: Type to return (defaults to str) :return: The value if present; else "" """ s = QSettings() if s.contains(key): return s.value(key, type=object_type) return ""
def apisPluginSettings(): s = QSettings() if s.contains("APIS/config_ini"): if os.path.isfile(s.value("APIS/config_ini")): return isApisIni(s.value("APIS/config_ini")) else: #Settings INI as stored does not exist return False, u"Ausgewählte APIS INI Datei ({0}) ist nicht vorhanden!".format(s.value("APIS/config_ini")) else: #Settings INI is not stored return False, u"Keine APIS INI Datei ausgewählt! "
def connect(self, parent=None): conn_name = self.connectionName() settings = QSettings() settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name)) if not settings.contains("sqlitepath"): # non-existent entry? raise InvalidDataException(u'there is no defined database connection "%s".' % conn_name) database = settings.value("sqlitepath") uri = QgsDataSourceURI() uri.setDatabase(database) return self.connectToUri(uri)
def storeConnectionConfiguration(self, server, database): name = self.connectionEdit.text() (host, port, user, password) = self.getServerConfiguration(server) settings = QSettings() if not settings.contains('PostgreSQL/servers/'+name+'/host'): settings.beginGroup('PostgreSQL/connections/'+name) settings.setValue('database', database) settings.setValue('host', host) settings.setValue('port', port) settings.setValue('username', user) settings.setValue('password', password) settings.endGroup()
def run(self): logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='/home/user/.khtsync.log', filemode='w') settings = QSettings("Khertan Software", "KhtSync") logging.debug('Setting loaded') while True: try: #Re read the settings settings.sync() logging.debug('Setting synced') #Verify the default interval if not settings.contains('refresh_interval'): refresh_interval = 600 else: refresh_interval = int(settings.value('refresh_interval'))*60 if refresh_interval<600: refresh_interval = 600 logging.debug('refresh interval loaded') nb_accounts = settings.beginReadArray('accounts') logging.info('Found %s account to sync' % (str(nb_accounts),)) for index in range(nb_accounts): settings.setArrayIndex(index) try: # logging.exception('Connecting to %s',str(sync.hostname)) sync = khtsync.Sync(hostname=settings.value('hostname'), \ port=int(settings.value('port')), \ username=settings.value('username'), \ password=settings.value('password'), \ local_dir=settings.value('local_dir'), \ remote_dir=settings.value('remote_dir')) logging.info('Connecting to %s',str(sync.hostname)) # logging.debug('test') sync.connect() sync.sync() sync.close() except: logging.exception('Error occur while syncing with %s',str(sync.hostname)) settings.endArray() logging.debug('Finished loop') except Error,err: logging.exception(str(err)) logging.debug(str(err)) time.sleep(refresh_interval)
class CartoDBNewConnectionDialog(QDialog): def __init__(self, user=None): QDialog.__init__(self) self.ui = Ui_NewConnection() self.ui.setupUi(self) self.settings = QSettings() self.user = None self.user_orig = user def accept(self): user = self.ui.userTX.text().strip() apiKey = self.ui.apiKeyTX.text().strip() multiuser = self.ui.multiuserCH.isChecked() if any([user == '', apiKey == '']): QMessageBox.warning( self, QApplication.translate('CartoDBPlugin', 'Save connection'), QApplication.translate( 'CartoDBPlugin', 'Both User and Api Key must be provided')) return if user is not None: key = '/CartoDBPlugin/%s' % user keyapi = '%s/api' % key keymultiuser = '******' % key key_orig = '/CartoDBPlugin/%s' % self.user_orig # warn if entry was renamed to an existing connection if all([self.user_orig != user, self.settings.contains(keyapi)]): res = QMessageBox.warning( self, QApplication.translate('CartoDBPlugin', 'Save connection'), QApplication.translate('CartoDBPlugin', 'Overwrite {}?').format(user), QMessageBox.Ok | QMessageBox.Cancel) if res == QMessageBox.Cancel: return # on rename delete original entry first if all([self.user_orig is not None, self.user_orig != user]): self.settings.remove(key_orig) self.settings.setValue(keyapi, apiKey) self.settings.setValue(keymultiuser, multiuser) self.settings.setValue('/CartoDBPlugin/selected', user) QDialog.accept(self) def reject(self): # Back out of dialogue QDialog.reject(self)
def read(key, object_type=str): """Reads the given setting key. Args: key: str, key to look up. object_type: convert the value to the given object type. Returns: setting value if found, None if not found. """ s = QSettings() if s.contains(key): return s.value(key, type=object_type) else: return None
def selectDirectory(self): settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): lastDir = unicode(settings.value('/Processing/LastBatchOutputPath')) else: lastDir = '' dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly) if dirName: self.table.cellWidget(self.row, self.col).setValue(dirName) settings.setValue('/Processing/LastBatchOutputPath', dirName)
def storeConnection(self, server, database): (host, port, user, password) = self.getServerConfiguration(server) connection = server+'_'+database settings = QSettings() if not settings.contains('PostgreSQL/connections/'+connection+'/database'): settings.beginGroup('PostgreSQL/connections/'+connection) settings.setValue('database', database) settings.setValue('host', host) settings.setValue('port', port) settings.setValue('username', user) settings.setValue('password', password) settings.endGroup() return True return False
def installFromZipFile(pluginPath): """Install and activate plugin from the specified package """ result = None with zipfile.ZipFile(pluginPath, 'r') as zf: pluginName = os.path.split(zf.namelist()[0])[0] pluginFileName = os.path.splitext(os.path.basename(pluginPath))[0] pluginsDirectory = home_plugin_path if not QDir(pluginsDirectory).exists(): QDir().mkpath(pluginsDirectory) # If the target directory already exists as a link, # remove the link without resolving QFile(os.path.join(pluginsDirectory, pluginFileName)).remove() try: # Test extraction. If fails, then exception will be raised # and no removing occurs unzip(unicode(pluginPath), unicode(pluginsDirectory)) # Removing old plugin files if exist removeDir(QDir.cleanPath(os.path.join(pluginsDirectory, pluginFileName))) # Extract new files unzip(unicode(pluginPath), unicode(pluginsDirectory)) except: result = QCoreApplication.translate('BoundlessConnect', 'Failed to unzip the plugin package\n{}.\nProbably it is broken'.format(pluginPath)) if result is None: updateAvailablePlugins() loadPlugin(pluginName) plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[pluginName] settings = QSettings() if settings.contains('/PythonPlugins/' + pluginName): if settings.value('/PythonPlugins/' + pluginName, False, bool): startPlugin(pluginName) reloadPlugin(pluginName) else: unloadPlugin(pluginName) loadPlugin(pluginName) else: if startPlugin(pluginName): settings.setValue('/PythonPlugins/' + pluginName, True) return result
class CreateSettings(QWidget): def __init__(self, device=None): QWidget.__init__(self) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, "../../config/user") QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, "../../config/sys") if device == 'UGV': self.settings = QSettings(QSettings.SystemScope, "TRADR", "UGV") self.settings_ugv() elif device == 'UAV': self.settings_uav() elif device == 'InField': self.settings_infield() elif device == 'CommandTable': self.settings_commandtable() else: self.settings = QSettings(QSettings.IniFormat, QSettings.SystemScope, "TRADR", "InField") print self.settings.contains("RobotState/Battery") print self.settings.value("RobotState/Battery", 'Not there').toString()
def connect(self, parent=None): conn_name = self.connectionName() settings = QSettings() settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name)) if not settings.contains("sqlitepath"): # non-existent entry? raise InvalidDataException( u'there is no defined database connection "%s".' % conn_name) database = settings.value("sqlitepath") uri = QgsDataSourceURI() uri.setDatabase(database) return self.connectToUri(uri)
def switchScheme(self, scheme): if scheme not in self._shortcuts: s = QSettings() key = "shortcuts/{0}/{1}/{2}".format(scheme, self.collection.name, self.name) if s.contains(key): try: shortcuts = s.value(key, [], QKeySequence) except TypeError: # PyQt4 raises TypeError when an empty list was stored shortcuts = [] self._shortcuts[scheme] = (shortcuts, False) else: # default self._shortcuts[scheme] = (self.defaultShortcuts(), True) self.display(scheme)
class OptionsDialog(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.ui = form.Ui_Form() self.ui.setupUi(self) self.init_events() self.settings = QSettings() self.load_settings() def init_events(self): QObject.connect(self.ui.ok_button, SIGNAL("clicked()"), self.ok) QObject.connect(self.ui.cancel_button, SIGNAL("clicked()"), self.cancel) def save_settings(self): self.settings.setValue("server", QVariant(self.ui.server_input.text())) self.settings.setValue("port", QVariant(self.ui.port_input.value())) self.settings.setValue("ssl", QVariant(self.ui.ssl_input.isChecked())) self.settings.setValue("username", QVariant(self.ui.username_input.text())) self.settings.sync() def load_settings(self): if self.settings.contains("username"): self.ui.password_input.setFocus() self.ui.server_input.setText(self.settings.value("server", QVariant('imap.gmail.com')).toString()) self.ui.port_input.setValue(self.settings.value("port", QVariant(993)).toInt()[0]) self.ui.ssl_input.setChecked(self.settings.value("ssl", QVariant(True)).toBool()) self.ui.username_input.setText(self.settings.value("username", QVariant('')).toString()) def ok(self): self.hide() self.save_settings() archiver = storage.IMAPMailArchiver(str(self.ui.server_input.text()), str(self.ui.port_input.value()), True, str(self.ui.username_input.text()), str(self.ui.password_input.text())) global plugin plugin = Plugin(archiver) def cancel(self): app.quit()
def set_connection(self, databaseidx, dbname=None): """ Connect to selected postgresql database """ selected = self.combo_database.itemText(databaseidx) or dbname if not selected: return settings = QSettings() settings.beginGroup("/PostgreSQL/connections/{}".format(selected)) if not settings.contains("database"): # no entry? QMessageBox.critical(self, "Error", "There is no defined database connection") return uri = QgsDataSourceURI() settingsList = [ "service", "host", "port", "database", "username", "password" ] service, host, port, database, username, password = map( lambda x: settings.value(x, "", type=str), settingsList) useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool) sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int) settings.endGroup() if service: uri.setConnection(service, database, username, password, sslmode) else: uri.setConnection(host, port, database, username, password, sslmode) uri.setUseEstimatedMetadata(useEstimatedMetadata) # connect to db self.connect_to_uri(uri) # update schema list self.update_schema_list()
def accept(self): s = QSettings() self.leName.setText( self.formatConnectionName(self.leUsername.text(), self.leHost.text(), self.lePort.text(), self.leDatabase.text())) connName = self.leName.text() #if not connName.isEmpty(): Porting QGIS 2.0 if connName is not None and connName != "": key = "/CSIAtlante/connections/" + connName # warn if entry was renamed to an existing connection if self.origName != connName and s.contains(key + "/host"): res = QMessageBox.warning( self, self.tr("Salva connessione"), #str(self.tr("Connessione %1 esistente : sovrascrivere?")).arg(connName), self.tr("Connessione " + connName + " esistente : sovrascrivere?"), QMessageBox.Ok | QMessageBox.Cancel) if res == QMessageBox.Cancel: return # on rename delete original entry first #if not self.origName.isEmpty() and self.origName != connName: Porting QGIS 2.0 if self.origName is not None and self.origName != "" and self.origName != connName: s.remove("/CSIAtlante/connections/" + self.origName) s.setValue( key + "/host", self.leHost.text().strip()) # trimmed()) Porting QGIS 2.0 s.setValue( key + "/port", self.lePort.text().strip()) # trimmed()) Porting QGIS 2.0 s.setValue( key + "/database", self.leDatabase.text().strip()) # trimmed()) Porting QGIS 2.0 s.setValue( key + "/username", self.leUsername.text().strip()) # trimmed()) Porting QGIS 2.0 s.setValue( key + "/password", self.lePassword.text().strip()) # trimmed()) Porting QGIS 2.0 QDialog.accept(self)
def addFile(self): settings = QSettings() if settings.contains('/Processing/LastInputPath'): path = settings.value('/Processing/LastInputPath') else: path = '' files = QFileDialog.getOpenFileNames(self, self.tr('Select file(s)'), path, self.tr('All files (*.*)')) model = self.lstLayers.model() for filePath in files: item = QStandardItem(filePath) model.appendRow(item) settings.setValue('/Processing/LastInputPath', os.path.dirname(files[0]))
def read(self, items): ''' Get the value of the user defined items from the STDM registry tree ''' userKeys = {} settings = QSettings() settings.beginGroup("/") groups = settings.childGroups() for group in groups: if str(group) == self.groupPath: for t in items: tKey = self.groupPath + "/" + t if settings.contains(tKey): tValue = settings.value(tKey) userKeys[t] = tValue break return userKeys
def checkRIsInstalled(ignoreRegistrySettings=False): if isWindows(): path = RUtils.RFolder() if path == '': return RUtils.tr( 'R folder is not configured.\nPlease configure ' 'it before running R scripts.') R_INSTALLED = 'R_INSTALLED' settings = QSettings() if not ignoreRegistrySettings: if settings.contains(R_INSTALLED): return if isWindows(): if ProcessingConfig.getSetting(RUtils.R_USE64): execDir = 'x64' else: execDir = 'i386' command = [ RUtils.RFolder() + os.sep + 'bin' + os.sep + execDir + os.sep + 'R.exe', '--version' ] else: command = ['R --version'] proc = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stdin=open(os.devnull), stderr=subprocess.STDOUT, universal_newlines=True, ).stdout for line in iter(proc.readline, ''): if 'R version' in line: settings.setValue(R_INSTALLED, True) return html = RUtils.tr( '<p>This algorithm requires R to be run. Unfortunately, it ' 'seems that R is not installed in your system, or it is not ' 'correctly configured to be used from QGIS</p>' '<p><a href="http://docs.qgis.org/testing/en/docs/user_manual/processing/3rdParty.html">Click here</a> ' 'to know more about how to install and configure R to be used with QGIS</p>' ) return html
def connection_from_name(name): settings = QSettings() settings.beginGroup(u"/PostgreSQL/connections/%s" % name) if not settings.contains("database"): # non-existent entry? raise Exception('There is no defined database connection "%s".' % name) settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"] service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList] sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int) uri = QgsDataSourceURI() if service: uri.setConnection(service, database, username, password, sslmode, authcfg) else: uri.setConnection(host, port, database, username, password, sslmode, authcfg) return connection_from_uri(uri)
def read(self, items): """ Get the value of the user defined items from the STDM registry tree param items: List of registry keys to fetch. type items: list """ userKeys = {} settings = QSettings() settings.beginGroup("/") groups = settings.childGroups() for group in groups: if str(group) == self._base_group(): for t in items: tKey = self.groupPath + "/" + t if settings.contains(tKey): tValue = settings.value(tKey) userKeys[t] = tValue break return userKeys