Example #1
0
    def snapping_finished(self, layer_id, completed):

        self.snap_thread.wait()

        if completed:

            if self.plugin.iface.mapCanvas().isCachingEnabled():
                self.layers[layer_id].setCacheImage(None)
            else:
                self.plugin.iface.mapCanvas().refresh()

            if self.remaining_layer_count > 0:
                row = self.snap_layers_lwidget.count()-self.remaining_layer_count
                with QReadLocker(self.lock):
                    self.remaining_layer_count -= 1
                self.__run_snap_thread(row)
                return

            QMessageBox.information(self, self.tr("Snapping"), self.tr("Snapping completed."))
        else:
            QMessageBox.information(self, self.tr("Snapping"), self.tr("Snapping cancelled."))

        self.snap_button.setEnabled(True)
        self.remove_layer_button.setEnabled(True)
        self.remove_all_layers_button.setEnabled(True)
        self.add_layers_button.setEnabled(True)
        self.snap_settings_gbox.setEnabled(True)
        self.create_backup_gbox.setEnabled(True)
        self.restore_geom_gbox.setEnabled(True)

        del self.snap_thread
        self.snap_thread = None
Example #2
0
    def saveProjectAs(self):
        ''' Save the project configuration under a different name '''
        try:
            # get the location for the new config file on disk
            start_dir = paths.OPUS_PROJECT_CONFIGS_PATH
            configDialog = QFileDialog()
            filter_str = QString("*.xml")
            fd = configDialog.getSaveFileName(self,QString("Save As..."),
                                              QString(start_dir), filter_str)
            # Check for cancel
            if not fd:
                return

            filename = QString(fd)
            # append xml extension if no extension was given
            if not filename.endsWith('.xml') and len(filename.split('.')) == 1:
                filename = filename + '.xml'

            if not self.saveProject(filename):
                return

            # hack: open the project right after save to properly change the
            # 'active project' related parameters
            self.openProject(filename)

        except:
            errorMessage = formatExceptionInfo(custom_message = \
                                               'Unexpected error saving config')
            QMessageBox.warning(self, 'Warning', errorMessage)
Example #3
0
    def onDictyExpressLink(self, link):
        if not self.data:
            return

        selectedIndexes = self.treeWidget.selectedIndexes()
        if not len(selectedIndexes):
            QMessageBox.information(
                self, "No gene ids selected",
                "Please select some genes and try again."
            )
            return
        model = self.treeWidget.model()
        mapToSource = model.mapToSource
        selectedRows = self.treeWidget.selectedIndexes()
        selectedRows = [mapToSource(index).row() for index in selectedRows]
        model = model.sourceModel()

        selectedGeneids = [self.row2geneinfo[row] for row in selectedRows]
        selectedIds = [self.geneinfo[i][0] for i in selectedGeneids]
        selectedIds = set(selectedIds)

        def fix(ddb):
            if ddb.startswith("DDB"):
                if not ddb.startswith("DDB_G"):
                    ddb = ddb.replace("DDB", "DDB_G")
                return ddb
            return None

        genes = [fix(gene) for gene in selectedIds if fix(gene)]
        url = str(link) % " ".join(genes)
        QDesktopServices.openUrl(QUrl(url))
    def accept(self):
        # Un-focus the currently focused widget to ensure that it's data validators were checked.
        focusWidget = QApplication.focusWidget()
        if focusWidget is not None:
            focusWidget.clearFocus()            
        
        # Can't accept if there are errors.
        if len(self._error_fields) > 0:
            msg = "Error: Invalid data in the following fields:\n"
            for field in self._error_fields:
                msg += field + '\n'
            QMessageBox.warning(self, "Error", msg)
            return

        # Inspect the user's changes to see if we need to warn about anything.
        closing_messages = self._getClosingMessages()

        if not self._applyTempOpSettingsRealOp():
            return
        else:
            # Success.  Close the dialog.
            for title, msg in closing_messages:
                QMessageBox.information( self, title, msg )
            self._tearDownEventFilters()
            self._cleanUpTempOperators()
            super( DatasetInfoEditorWidget, self ).accept()
Example #5
0
 def on_auto_changed(self):
     ' automation connects '
     if self.auto.currentIndex() is 1:
         self.locator.get_service('editor').fileSaved.connect(lambda:
             self.run())
         QMessageBox.information(self.dock, __doc__,
         '<b>Now Actions will Run Automatically when any File is Saved !')
     elif self.auto.currentIndex() is 2:
         self.locator.get_service('editor').fileExecuted.connect(lambda:
             self.run())
         QMessageBox.information(self.dock, __doc__,
         '<b>Now Actions will Run Automatically when any File is Executed !')
     elif self.auto.currentIndex() is 3:
         self.locator.get_service('editor').currentTabChanged.connect(lambda:
             self.run())
         QMessageBox.information(self.dock, __doc__,
         '<b>Now Actions will Run Automatically when current Tab is Changed')
     elif self.auto.currentIndex() is 4:
         self.locator.get_service('editor').fileOpened.connect(lambda:
             self.run())
         QMessageBox.information(self.dock, __doc__,
         '<b>Now Actions will Run Automatically when any File is Opened !')
     elif self.auto.currentIndex() is 5:
         self.locator.get_service('editor').beforeFileSaved.connect(lambda:
             self.run())
         QMessageBox.information(self.dock, __doc__,
         '<b>Now Actions will Run Automatically before any File is Saved !')
     self.group1.setDisabled(True)
Example #6
0
    def _loadedPage(self, backend, data):
        """ Callback for loadPage """
        if not backend:
            # Loading is finished
            self.process = None
            if self.backend:
                self.ui.contentEdit.setReadOnly(False)
                self.ui.loadButton.setEnabled(True)
                self.ui.loadButton.setText('Load')
            return
        if not data:
            self.content = None
            self.backend = None
            QMessageBox.critical(self, self.tr('Unable to open page'),
                                 'Unable to open page "%s" on %s: it does not exist.'
                                 % (self.ui.idEdit.text(),
                                    self.ui.backendBox.currentText()),
                                 QMessageBox.Ok)
            return

        self.content = data
        self.ui.contentEdit.setPlainText(self.content.content)
        self.setWindowTitle("QWebcontentedit - %s@%s" %(self.content.id,
                                                        backend.name))
        self.backend = backend    
    def setParamValues(self):
        if self.mUpdateExistingGroupBox.isChecked():
            fieldName = self.mExistingFieldComboBox.currentText()
        else:
            fieldName = self.mOutputFieldNameLineEdit.text()

        layer = dataobjects.getObjectFromName(self.cmbInputLayer.currentText())

        self.alg.setParameterValue('INPUT_LAYER', layer)
        self.alg.setParameterValue('FIELD_NAME', fieldName)
        self.alg.setParameterValue('FIELD_TYPE',
                                   self.mOutputFieldTypeComboBox.currentIndex())
        self.alg.setParameterValue('FIELD_LENGTH',
                                   self.mOutputFieldWidthSpinBox.value())
        self.alg.setParameterValue('FIELD_PRECISION',
                                   self.mOutputFieldPrecisionSpinBox.value())
        self.alg.setParameterValue('NEW_FIELD',
                                   self.mNewFieldGroupBox.isChecked())
        self.alg.setParameterValue('FORMULA', self.builder.expressionText())
        self.alg.setOutputValue('OUTPUT_LAYER', self.leOutputFile.text().strip() or None)

        msg = self.alg.checkParameterValuesBeforeExecuting()
        if msg:
            QMessageBox.warning(
                self, self.tr('Unable to execute algorithm'), msg)
            return False
        return True
Example #8
0
    def openModel(self):
        filename = unicode(QFileDialog.getOpenFileName(self,
                                                       self.tr('Open Model'), ModelerUtils.modelsFolder(),
                                                       self.tr('Processing models (*.model *.MODEL)')))
        if filename:
            try:
                alg = ModelerAlgorithm.fromFile(filename)
                self.alg = alg
                self.alg.setModelerView(self)
                self.textGroup.setText(alg.group)
                self.textName.setText(alg.name)
                self.repaintModel()

                self.view.centerOn(0, 0)
                self.hasChanged = False
            except WrongModelException as e:
                ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                       self.tr('Could not load model %s\n%s') % (filename, e.msg))
                QMessageBox.critical(self, self.tr('Could not open model'),
                                     self.tr('The selected model could not be loaded.\n'
                                             'See the log for more information.'))
            except Exception as e:
                ProcessingLog.addToLog(ProcessingLog.LOG_ERROR,
                                       self.tr('Could not load model %s\n%s') % (filename, e.args[0]))
                QMessageBox.critical(self, self.tr('Could not open model'),
                                     self.tr('The selected model could not be loaded.\n'
                                             'See the log for more information.'))
Example #9
0
 def warnUserHashFail():
    from PyQt4.QtGui import QMessageBox
    QMessageBox.warning(self, tr('Hash Failure'), tr("""The torrent download 
       is currently encountering too many packet hash failures to allow it to 
       progress properly. As a result, the torrent engine has been halted. You 
       should report this incident to the Armory team and turn off this feature 
       until further notice."""), QMessageBox.Ok)      
Example #10
0
    def toggleInteractive(self, checked):
        """
        If enable
        """
        logger.debug("toggling interactive mode to '%r'" % checked)

        if checked==True:
            if not self.topLevelOperatorView.FeatureImages.ready() \
            or self.topLevelOperatorView.FeatureImages.meta.shape==None:
                self.labelingDrawerUi.liveUpdateButton.setChecked(False)
                mexBox=QMessageBox()
                mexBox.setText("There are no features selected ")
                mexBox.exec_()
                return

        self.labelingDrawerUi.savePredictionsButton.setEnabled(not checked)
        self.topLevelOperatorView.FreezePredictions.setValue( not checked )

        # Auto-set the "show predictions" state according to what the user just clicked.
        if checked:
            self._viewerControlUi.checkShowPredictions.setChecked( True )
            self.handleShowPredictionsClicked()

        # If we're changing modes, enable/disable our controls and other applets accordingly
        if self.interactiveModeActive != checked:
            if checked:
                self.labelingDrawerUi.labelListView.allowDelete = False
                #self.labelingDrawerUi.AddLabelButton.setEnabled( False )
            else:
                self.labelingDrawerUi.labelListView.allowDelete = True
                #self.labelingDrawerUi.AddLabelButton.setEnabled( True )
        self.interactiveModeActive = checked
    def startProjectButtonClicked(self):
        """
        Start project button was clicked... We will now go through all the project setup.
        """
        if __main__.RootWindow.selected_project is None:
            pcw = ProjectCreationWidget()
            pcw.project_name = self.name_tb.text()
            pcw.project_author = self.author_tb.text()
            pcw.project_version = self.version_tb.text()
            pcw.clear_cache = self.clear_cache_cb.isChecked()
            __main__.RootWindow.push(pcw)
            __main__.RootWindow.removeWidgetFromHistory(self) # ensuring that one will not go back to this widget
            pcw.beginProjectInstallation()

        else:
            p = __main__.RootWindow.selected_project
            p.name = self.name_tb.text()
            p.author = self.author_tb.text()
            p.version = self.version_tb.text()
            p.update()
            QMessageBox.information(
                self,
                "Success!",
                "Your project details have been updated.",
                QMessageBox.Ok
            )
Example #12
0
def changeLanguage(cursor, language):
    """Changes the language of the pitch names."""
    selection = cursor.hasSelection()
    if selection:
        start = cursor.selectionStart()
        cursor.setPosition(cursor.selectionEnd())
        cursor.setPosition(0, QTextCursor.KeepAnchor)
        source = tokeniter.Source.selection(cursor)
    else:
        source = tokeniter.Source.document(cursor)
    
    pitches = PitchIterator(source)
    tokens = pitches.tokens()
    writer = ly.pitch.pitchWriter(language)
    
    if selection:
        # consume tokens before the selection, following the language
        source.consume(tokens, start)
    
    changed = False # track change of \language or \include language command
    with cursortools.compress_undo(cursor):
        try:
            with qutil.busyCursor():
                with cursortools.Editor() as e:
                    for t in tokens:
                        if isinstance(t, ly.lex.lilypond.Note):
                            # translate the pitch name
                            p = pitches.read(t)
                            if p:
                                n = writer(*p)
                                if n != t:
                                    e.insertText(source.cursor(t), n)
                        elif isinstance(t, LanguageName) and t != language:
                            # change the language name in a command
                            e.insertText(source.cursor(t), language)
                            changed = True
        except ly.pitch.PitchNameNotAvailable:
            QMessageBox.critical(None, app.caption(_("Pitch Name Language")), _(
                "Can't perform the requested translation.\n\n"
                "The music contains quarter-tone alterations, but "
                "those are not available in the pitch language \"{name}\"."
                ).format(name=language))
            return
        if changed:
            return
        if not selection:
            # there was no selection and no language command, so insert one
            insertLanguage(cursor.document(), language)
            return
    # there was a selection but no command, user must insert manually.
    QMessageBox.information(None, app.caption(_("Pitch Name Language")),
        '<p>{0}</p>'
        '<p><code>\\include "{1}.ly"</code> {2}</p>'
        '<p><code>\\language "{1}"</code> {3}</p>'.format(
            _("The pitch language of the selected text has been "
                "updated, but you need to manually add the following "
                "command to your document:"),
            language,
            _("(for LilyPond below 2.14), or"),
            _("(for LilyPond 2.14 and higher.)")))
Example #13
0
def open_last_opened_file_when_configured(configuration,
                                          main_window,
                                          tree_reference):
    """ Open the "lats opened filename" when selected in the configuration
    window
    @configuration: object of type Configuration
    @param main_window: change the title of this QMainWindow object
    @param tree_reference: reference of type Tree object

    """
    importer = src.modell.importer.TextImporter(configuration)
    last_file_name = configuration.data[str(CONFIG_ENUM.LastFilename)]
    if configuration.data[str(CONFIG_ENUM.StartWithLastFile)] == True \
            and last_file_name is not None and last_file_name != "":
        logging.debug("last file opened because of Option")
        logging.debug("filename: %s", last_file_name)

        if not os.path.isfile(last_file_name):
            logging.debug("last opened filename doesn't exist."
                          + " Stopping import.")
            QMessageBox.warning(main_window, "Warning",
                        '''Lastly opened file doesn't exist:'''
                        + last_file_name + ''' File won't be opened.''')
            return

        remainder_lines = importer.read_file(main_window.centralWidget(),
                                             last_file_name,
                                             tree_reference)
        change_window_title(last_file_name, main_window)

        src.gui.gui_snippets.ImportResult(main_window,
                     remainder_lines,
                     configuration)
    def save_properties(self):
        if not len(self.projectData.name.text().strip()):
            QMessageBox.critical(self, translations.TR_PROJECT_SAVE_INVALID,
                translations.TR_PROJECT_INVALID_MESSAGE)
            return

        self.project.name = self.projectData.name.text()
        self.project.description = self.projectData.description.toPlainText()
        self.project.license = self.projectData.cboLicense.currentText()
        self.project.main_file = self.projectExecution.path.text()
        self.project.url = self.projectData.url.text()
        self.project.project_type = self.projectData.txtType.text()
        # FIXME
        self.project.python_exec = \
            self.projectExecution.txtPythonInterpreter.text()
        self.project.python_path = \
            self.projectExecution.txtPythonPath.toPlainText()
        self.project.additional_builtins = [e for e in
            self.projectExecution.additional_builtins.text().split(' ') if e]
        self.project.pre_exec_script = self.projectExecution.txtPreExec.text()
        self.project.post_exec_script = self.projectExecution.txtPostExec.text()
        self.project.program_params = self.projectExecution.txtParams.text()
        self.project.venv = self.projectExecution.txtVenvPath.text()
        extensions = self.projectData.txtExtensions.text().split(', ')
        self.project.extensions = tuple(extensions)
        self.project.indentation = self.projectData.spinIndentation.value()
        self.project.use_tabs = self.projectData.checkUseTabs.isChecked()
        related = self.projectMetadata.txt_projects.toPlainText()
        related = [_path for _path in related.split('\n') if len(_path.strip())]
        self.project.related_projects = related
        self.project.save_project_properties()

        self.close()
Example #15
0
    def onNewFeaturesFromFeatureDlg(self):
        opFeatureSelection = self.topLevelOperatorView
        if opFeatureSelection is not None:
            # Re-initialize the scales and features
            self.initFeatureOrder()

            # Give the new features to the pipeline (if there are any)
            featureMatrix = numpy.asarray(self.featureDlg.selectedFeatureBoolMatrix)
            if featureMatrix.any():
                # Disable gui
                self.parentApplet.busy = True
                self.parentApplet.appletStateUpdateRequested.emit()
                QApplication.instance().setOverrideCursor(QCursor(Qt.WaitCursor))
                QApplication.instance().processEvents()

                try:
                    opFeatureSelection.SelectionMatrix.setValue(featureMatrix)
                except DatasetConstraintError as ex:
                    # The user selected some scales that were too big.
                    QMessageBox.critical(self, "Invalid selections", ex.message)
                    opFeatureSelection.SelectionMatrix.disconnect()

                # Re-enable gui
                QApplication.instance().restoreOverrideCursor()
                self.parentApplet.busy = False
                self.parentApplet.appletStateUpdateRequested.emit()
            else:
                # Not valid to give a matrix with no features selected.
                # Disconnect.
                opFeatureSelection.SelectionMatrix.disconnect()

                # Notify the workflow that some applets may have changed state now.
                # (For example, the downstream pixel classification applet can
                #  be used now that there are features selected)
                self.parentApplet.appletStateUpdateRequested.emit()
Example #16
0
def load_pattern_grid_items(patternGridItemInfo, knittingSymbols, unitCellWidth, unitCellHeight):
    """ extract all patternGridItems from a loaded sconcho project. """

    allPatternGridItems = []
    try:
        for newItem in patternGridItemInfo:
            colID = newItem["column"]
            rowID = newItem["row"]
            width = newItem["width"]
            height = newItem["height"]
            name = newItem["name"]
            color = QColor(newItem["color"])
            isHidden = newItem["isHidden"]
            category = newItem["category"]
            location = QPointF(colID * unitCellWidth, rowID * unitCellHeight)
            symbol = knittingSymbols[name]

            # if name == "nostitch":
            #    color = QColor("#6a6a6a")
            allPatternGridItems.append((location, colID, rowID, width, height, symbol, color, isHidden))

    except KeyError as e:
        logger.error(msg.errorLoadingGridText % e)
        QMessageBox.critical(None, msg.errorLoadingGridTitle, msg.errorLoadingGridText % e, QMessageBox.Close)
        return None

    return allPatternGridItems
Example #17
0
    def loadWebService(self):
        # get the selected row
        dataset_name,dataset_serviceType = self.getSelectedNameAndType()
        #dataset_name = unicode(dataset_name,"utf-8")

        #custom web service object
        dataset = self.selectdataSets(dataset_name,dataset_serviceType)

        urlWithParams = dataset.webServiceParams()
        if dataset.serviceType== "WMS":
            rlayer = QgsRasterLayer(dataset.webServiceParams(), dataset.getName(self.language), dataset.serviceType.lower())
            if not rlayer.isValid():
                #QMessageBox.information(None, "Error loading dataset", u"..Oops! " + unicode(dataset_name,"utf-8")+ "  cannot be loaded. Either the server is down or you have limited internet connectivity")
                QMessageBox.information(None, "Error loading dataset", u"..oops! Dataset: '{}' cannot be loaded. Either the server ({}) is down or you have limited internet connectivity".format(dataset_name,dataset.server))

            QgsMapLayerRegistry.instance().addMapLayer(rlayer)
            self.iface.legendInterface().setLayerExpanded(rlayer,False) # collapse the layer'slegend
        elif dataset.serviceType== "WFS":
            vlayer = QgsVectorLayer(dataset.webServiceParams(), dataset.getName(self.language), dataset.serviceType)
            #QMessageBox.information(None, "Error loading dataset:", str(dataset.webServiceParams()))
            if not vlayer.isValid():
                QMessageBox.information(None, "Error loading dataset", u"..oops! Dataset: '{}' cannot be loaded. Either the server ({}) is down or you have limited internet connectivity".format(dataset_name,dataset.server))
            QgsMapLayerRegistry.instance().addMapLayer(vlayer)
            #re-appear window
            self.dlg.raise_()
            self.dlg.activateWindow()
Example #18
0
 def _move_file(self):
     item = self.currentItem()
     if item.parent() is None:
         pathForFile = item.path
     else:
         pathForFile = os.path.join(item.path, item.text(0))
     pathProjects = [p.path for p in self.get_open_projects()]
     addToProject = ui_tools.AddToProject(pathProjects, self)
     addToProject.setWindowTitle(self.tr("Copy File to"))
     addToProject.exec_()
     if not addToProject.pathSelected:
         return
     name = file_manager.get_basename(pathForFile)
     path = file_manager.create_path(addToProject.pathSelected, name)
     try:
         content = file_manager.read_file_content(pathForFile)
         path = file_manager.store_file_content(path, content, newFile=True)
         file_manager.delete_file(pathForFile)
         index = item.parent().indexOfChild(item)
         item.parent().takeChild(index)
         self.add_existing_file(path)
     except file_manager.NinjaFileExistsException as ex:
             QMessageBox.information(self, self.tr("File Already Exists"),
                 self.tr("Invalid Path: the file '%s' already exists." %
                     ex.filename))
 def accept(self):
     try:
         self.setParamValues()
         msg = self.alg._checkParameterValuesBeforeExecuting()
         if msg:
             QMessageBox.warning(
                 self, self.tr('Unable to execute algorithm'), msg)
             return
         description = algAsDict(self.alg)
         description["name"] = self.settingsPanel.txtName.text().strip()
         description["group"] = self.settingsPanel.txtGroup.text().strip()
         if not (description["name"] and description["group"]):
             self.tabWidget.setCurrentIndex(1)
             return
         validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:'
         filename = ''.join(c for c in description["name"] if c in validChars).lower() + ".json"
         filepath = os.path.join(preconfiguredAlgorithmsFolder(), filename)
         with open(filepath, "w") as f:
             json.dump(description, f)
         self.toolbox.updateProvider('preconfigured')
     except AlgorithmDialogBase.InvalidParameterValue as e:
         try:
             self.buttonBox.accepted.connect(lambda:
                                             e.widget.setPalette(QPalette()))
             palette = e.widget.palette()
             palette.setColor(QPalette.Base, QColor(255, 255, 0))
             e.widget.setPalette(palette)
             self.lblProgress.setText(
                 self.tr('<b>Missing parameter value: %s</b>') % e.parameter.description)
             return
         except:
             QMessageBox.critical(self,
                                  self.tr('Unable to execute algorithm'),
                                  self.tr('Wrong or missing parameter values'))
     self.close()
Example #20
0
    def _rename_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self, self.tr("Rename File"),
            self.tr("Enter New File Name:"), text=item.text(0))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            fileName = os.path.join(
                file_manager.get_folder(pathForFile), fileName)
            if pathForFile == fileName:
                return
            try:
                fileName = file_manager.rename_file(pathForFile, fileName)
                name = file_manager.get_basename(fileName)
                mainContainer = main_container.MainContainer()
                if mainContainer.is_open(pathForFile):
                    mainContainer.change_open_tab_name(pathForFile, fileName)
                subitem = ProjectItem(item.parent(), name,
                    file_manager.get_folder(fileName))
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                index = item.parent().indexOfChild(item)
                subitem.parent().takeChild(index)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(self, self.tr("File Already Exists"),
                    self.tr("Invalid Path: the file '%s' already exists." %
                        ex.filename))
Example #21
0
 def _copy_file(self):
     #get the selected QTreeWidgetItem
     item = self.currentItem()
     if item.parent() is None:
         pathForFile = item.path
     else:
         pathForFile = os.path.join(item.path, item.text(0))
     pathProjects = [p.path for p in self.get_open_projects()]
     addToProject = ui_tools.AddToProject(pathProjects, self)
     addToProject.setWindowTitle(self.tr("Copy File to"))
     addToProject.exec_()
     if not addToProject.pathSelected:
         return
     name = QInputDialog.getText(self, self.tr("Copy File"),
         self.tr("File Name:"), text=item.text(0))[0]
     if not name:
         QMessageBox.information(self, self.tr("Invalid Name"),
             self.tr("The file name is empty, please enter a name"))
         return
     path = file_manager.create_path(addToProject.pathSelected, name)
     try:
         content = file_manager.read_file_content(pathForFile)
         path = file_manager.store_file_content(path, content, newFile=True)
         self.add_existing_file(path)
     except file_manager.NinjaFileExistsException as ex:
             QMessageBox.information(self, self.tr("File Already Exists"),
                 self.tr("Invalid Path: the file '%s' already exists." %
                     ex.filename))
 def get_screen_from_selected(self):
     clients = ""
     for client in self.get_selected_items():
         self.serv.conns[client].getscreen()
         clients +=self.serv.conns[client].getinfo() + " "
     if clients:
         QMessageBox.information(self, "Pobrano", "Sprawdź " + clients, QMessageBox.Ok)
 def check_existing_id(self, ds_id):
     gl = DataSourcesList()
     if ds_id in gl.data_sources.keys():
         QMessageBox.critical(self, self.tr('Error on save group'),
                              self.tr('Data source with such id already exists! Select new id for data source!'))
         return False
     return True
    def generate_heigth_profile_file(self, not_interactive_mode=False):
        if not self.zz is None and not self.yy is None and not self.xx is None:
            try:
                congruence.checkDir(self.heigth_profile_file_name)

                sys.stdout = EmittingStream(textWritten=self.writeStdOut)

                ST.write_shadow_surface(self.zz, self.xx, self.yy, outFile=congruence.checkFileName(self.heigth_profile_file_name))
                if not not_interactive_mode:
                    QMessageBox.information(self, "QMessageBox.information()",
                                            "Height Profile file " + self.heigth_profile_file_name + " written on disk",
                                            QMessageBox.Ok)
                if self.modify_y == 0:
                    dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0])
                if self.modify_y == 1:
                    dimension_y = self.si_to_user_units * (self.server.y[-1] - self.server.y[0]) * self.scale_factor_y
                elif self.modify_y == 2:
                    dimension_y = self.new_length

                self.send("PreProcessor_Data", ShadowPreProcessorData(error_profile_data_file=self.heigth_profile_file_name,
                                                                      error_profile_x_dim=self.dimension_x,
                                                                      error_profile_y_dim=dimension_y))
            except Exception as exception:
                QMessageBox.critical(self, "Error",
                                     exception.args[0],
                                     QMessageBox.Ok)
 def btnBox_Accepted(self):
     filename = self.ui.txtDataset.text.strip()
     if len(filename) == 0:
         QMessageBox.information(None, "Add Vector Layer",  "Need to specify a data file", QMessageBox.Ok)
         return ''
     else:
         return filename
 def _applyInternalPathToTempOps(self, index):
     if index == -1:
         return
     
     newInternalPath = str( self.internalDatasetNameComboBox.currentText() )
     
     # Save a copy of our settings
     oldInfos = {}
     for laneIndex, op in self.tempOps.items():
         oldInfos[laneIndex] = copy.copy( op.Dataset.value )
     
     # Attempt to apply to all temp operators
     try:
         for laneIndex, op in self.tempOps.items():
             info = copy.copy( op.Dataset.value )
             pathComponents = PathComponents(info.filePath)
             if pathComponents.internalPath != newInternalPath:
                 pathComponents.internalPath = newInternalPath
                 info.filePath = pathComponents.totalPath()
                 op.Dataset.setValue( info )
         self._error_fields.discard('Internal Dataset Name')
         return True
     except Exception as e:
         # Revert everything back to the previous state
         for laneIndex, op in self.tempOps.items():
             op.Dataset.setValue( oldInfos[laneIndex] )
         
         msg = "Could not set new internal path settings due to an exception:\n"
         msg += "{}".format( e )
         log_exception( logger, msg )
         QMessageBox.warning(self, "Error", msg)
         self._error_fields.add('Internal Dataset Name')
         return False
 def _applyDisplayModeToTempOps(self, index):
     if index == -1:
         return
     
     newDisplayMode = str( self.displayModeComboBox.itemData( index ).toString() )
     
     # Save a copy of our settings
     oldInfos = {}
     for laneIndex, op in self.tempOps.items():
         oldInfos[laneIndex] = copy.copy( op.Dataset.value )
     
     # Attempt to apply to all temp operators
     try:
         for laneIndex, op in self.tempOps.items():
             info = copy.copy( op.Dataset.value )
             if info.display_mode != newDisplayMode:
                 info.display_mode = newDisplayMode
                 op.Dataset.setValue( info )
         self._error_fields.discard('Channel Display')
         return True
     
     except Exception as e:
         # Revert everything back to the previous state
         for laneIndex, op in self.tempOps.items():
             op.Dataset.setValue( oldInfos[laneIndex] )
         
         msg = "Could not set new channel display settings due to an exception:\n"
         msg += "{}".format( e )
         log_exception( logger, msg )
         QMessageBox.warning(self, "Error", msg)
         self._error_fields.add('Channel Display')
         return False
     
     finally:
         self._updateDisplayModeCombo()
    def validate(self, ds_info):
        # validate common fields
        checks = [
            (ds_info.id, self.tr('Please, enter data source id')),
            (ds_info.alias, self.tr('Please, enter data source alias')),
            (ds_info.icon, self.tr('Please, select icon for data source')),
            (ds_info.group, self.tr('Please, select group for data source')),
            (ds_info.type, self.tr('Please, select type for data source')),
        ]

        for val, comment in checks:
            if not val:
                QMessageBox.critical(self, self.tr('Error on save data source'), self.tr(comment))
                return False

        checks_correct = [
            (self.id_validator, self.tr('Please, enter correct value for data source id')),
            (self.alias_validator, self.tr('Please, enter correct value for data source alias')),
        ]

        for val, comment in checks_correct:
            if not val.is_valid():
                QMessageBox.critical(self, self.tr('Error on save data source'), self.tr(comment))
                return False

        # validate special fields
        if not self.DRV_WIDGETS[ds_info.type].validate(ds_info):
            return False

        return True
    def _applyNormalizeDisplayToTempOps(self):
        # Save a copy of our settings
        oldInfos = {}
        new_norm = {"True":True,"False":False,"Default":None}[str(self.normalizeDisplayComboBox.currentText())]        
        
        new_drange = ( self.rangeMinSpinBox.value(), self.rangeMaxSpinBox.value() )
        if new_norm is False and (new_drange[0] == self.rangeMinSpinBox.minimum() \
        or new_drange[1] == self.rangeMaxSpinBox.minimum()):
            # no drange given, autonormalization cannot be switched off !
            QMessageBox.warning(None, "Warning", "Normalization cannot be switched off without specifying the data range !")
            self.normalizeDisplayComboBox.setCurrentIndex(1)
            return 
        
        for laneIndex, op in self.tempOps.items():
            oldInfos[laneIndex] = copy.copy( op.Dataset.value )

        try:
            for laneIndex, op in self.tempOps.items():
                info = copy.copy( op.Dataset.value )
                info.normalizeDisplay = new_norm
                op.Dataset.setValue( info )
            self._error_fields.discard('Normalize Display')
            return True
        except Exception as e:
            # Revert everything back to the previous state
            for laneIndex, op in self.tempOps.items():
                op.Dataset.setValue( oldInfos[laneIndex] )
            
            msg = "Could not apply normalization settings due to an exception:\n"
            msg += "{}".format( e )
            log_exception( logger, msg )
            QMessageBox.warning(self, "Error", msg)
            self._error_fields.add('Normalize Display')
            return False
Example #30
0
    def _add_new_file(self):
        item = self.currentItem()
        if item.parent() is None:
            pathForFile = item.path
        else:
            pathForFile = os.path.join(item.path, item.text(0))
        result = QInputDialog.getText(self, self.tr("New File"),
            self.tr("Enter the File Name:"))
        fileName = result[0]

        if result[1] and fileName.strip() != '':
            try:
                fileName = os.path.join(pathForFile, fileName)
                fileName = file_manager.store_file_content(
                    fileName, '', newFile=True)
                name = file_manager.get_basename(fileName)
                subitem = ProjectItem(item, name, pathForFile)
                subitem.setToolTip(0, name)
                subitem.setIcon(0, self._get_file_icon(name))
                mainContainer = main_container.MainContainer()
                mainContainer.open_file(fileName)
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(self, self.tr("File Already Exists"),
                    self.tr("Invalid Path: the file '%s' already exists." %
                        ex.filename))
Example #31
0
    def save_settings(self):
        """Save the settings before the application is closed with QSettings.

        Info saved: Tabs and projects opened, windows state(size and position).
        """
        qsettings = IDE.ninja_settings()
        data_qsettings = IDE.data_settings()
        main_container = self.get_service("main_container")
        editor_widget = None
        if main_container:
            editor_widget = main_container.get_current_editor()
        current_file = ''
        if editor_widget is not None:
            current_file = editor_widget.file_path
        if qsettings.value('preferences/general/loadFiles', True, type=bool):
            openedFiles = self.filesystem.get_files()
            projects_obj = self.filesystem.get_projects()
            projects = [projects_obj[proj].path for proj in projects_obj]
            data_qsettings.setValue('lastSession/projects', projects)
            files_info = []
            for path in openedFiles:
                editable = self.__neditables.get(openedFiles[path])
                if editable is not None and editable.is_dirty:
                    stat_value = 0
                else:
                    stat_value = os.stat(path).st_mtime
                files_info.append([path,
                                  editable.editor.getCursorPosition(),
                                  stat_value])
            data_qsettings.setValue('lastSession/openedFiles', files_info)
            if current_file is not None:
                data_qsettings.setValue('lastSession/currentFile', current_file)
            data_qsettings.setValue('lastSession/recentFiles',
                                    settings.LAST_OPENED_FILES)
        qsettings.setValue('preferences/editor/bookmarks',
                           settings.BOOKMARKS)
        qsettings.setValue('preferences/editor/breakpoints',
                           settings.BREAKPOINTS)

        # Session
        if self._session is not None:
            val = QMessageBox.question(
                self,
                translations.TR_SESSION_ACTIVE_IDE_CLOSING_TITLE,
                (translations.TR_SESSION_ACTIVE_IDE_CLOSING_BODY %
                    {'session': self.Session}),
                QMessageBox.Yes, QMessageBox.No)
            if val == QMessageBox.Yes:
                session_manager.SessionsManager.save_session_data(
                    self.Session, self)
        #qsettings.setValue('preferences/general/toolbarArea',
            #self.toolBarArea(self.toolbar))
        #Save if the windows state is maximixed
        if(self.isMaximized()):
            qsettings.setValue("window/maximized", True)
        else:
            qsettings.setValue("window/maximized", False)
            #Save the size and position of the mainwindow
            qsettings.setValue("window/size", self.size())
            qsettings.setValue("window/pos", self.pos())
        self.central.save_configuration()

        #Save the toolbar visibility
        qsettings.setValue("window/hide_toolbar", not self.toolbar.isVisible())
Example #32
0
 def showHelp(self):
     helpText = u"""In this dialog you can set up versioning support for a table. The table will be modified so that all changes will be recorded: there will be a column with start time and end time. Every row will have its start time, end time is assigned when the feature gets deleted. When a row is modified, the original data is marked with end time and new row is created. With this system, it's possible to get back to state of the table any time in history. When selecting rows from the table, you will always have to specify at what time do you want the rows."""
     QMessageBox.information(self, "Help", helpText)
Example #33
0
 def retrieveContact_eb(self, backend, error, backtrace):
     content = unicode(self.tr('Unable to get contact:\n%s\n')) % to_unicode(error)
     if logging.root.level <= logging.DEBUG:
         content += u'\n%s\n' % to_unicode(backtrace)
     QMessageBox.critical(self, self.tr('Error while getting contact'),
                          content, QMessageBox.Ok)
Example #34
0
 def _saveNotes_eb(self, backend, error, backtrace):
     content = unicode(self.tr('Unable to save notes:\n%s\n')) % to_unicode(error)
     if logging.root.level <= logging.DEBUG:
         content += '\n%s\n' % to_unicode(backtrace)
         QMessageBox.critical(self, self.tr('Error while saving notes'),
         content, QMessageBox.Ok)
Example #35
0
    def _updateOperatorFromGui(self):
        op = self.topLevelOperatorView

        # Read all gui settings before updating the operator
        # (The gui is still responding to operator changes,
        #  and we don't want it to update until we've read all gui values.)

        # Read Channel
        final_channel = self._drawer.inputChannelComboBox.currentIndex()
        core_channel = self._drawer.coreChannelComboBox.currentIndex()

        # Read Sigmas
        block_shape_dict = dict(op.SmootherSigma.value)
        block_shape_dict['x'] = self._sigmaSpinBoxes['x'].value()
        block_shape_dict['y'] = self._sigmaSpinBoxes['y'].value()
        block_shape_dict['z'] = self._sigmaSpinBoxes['z'].value()
        neededAxes = 'zyx' if self._drawer.sigmaSpinBox_Z.isVisible() else 'yx'
        sigmaIsZero = [block_shape_dict[index] < .1 for index in neededAxes]
        if any(sigmaIsZero) and not all(sigmaIsZero):
            mexBox = QMessageBox()
            mexBox.setText(
                "One of the smoothing sigma values is 0. Reset it to a value > 0.1 or set all sigmas to 0 for no smoothing."
            )
            mexBox.exec_()
            return

        # avoid 'kernel longer than line' errors
        shape = self.topLevelOperatorView.InputImage.meta.getTaggedShape()
        for ax in [
                item for item in 'zyx' if item in shape and shape[item] > 1
        ]:
            req_sigma = np.floor(shape[ax] / 3)
            if block_shape_dict[ax] > req_sigma:
                mexBox = QMessageBox()
                mexBox.setText("The sigma value {} for dimension '{}'"
                               "is too high, should be at most {:.1f}.".format(
                                   block_shape_dict[ax], ax, req_sigma))
                mexBox.exec_()
                return

        # Read Thresholds
        lowThreshold = self._drawer.lowThresholdSpinBox.value()
        highThreshold = self._drawer.highThresholdSpinBox.value()
        beta = self._drawer.lambdaSpinBoxGC.value()

        # Read Size filters
        minSize = self._drawer.minSizeSpinBox.value()
        maxSize = self._drawer.maxSizeSpinBox.value()

        # Read the current thresholding method
        curIndex = self._drawer.methodComboBox.currentIndex()

        op_index = curIndex
        if curIndex == 1 and self._drawer.preserveIdentitiesCheckbox.isChecked(
        ):
            curIndex = 3
        # Apply new settings to the operator
        op.CurOperator.setValue(curIndex)
        op.Channel.setValue(final_channel)
        op.CoreChannel.setValue(core_channel)
        op.SmootherSigma.setValue(block_shape_dict)
        op.LowThreshold.setValue(lowThreshold)
        op.HighThreshold.setValue(highThreshold)

        op.Beta.setValue(beta)
        op.MinSize.setValue(minSize)
        op.MaxSize.setValue(maxSize)
Example #36
0
 def processingFinished(self):
     self.stopProcessing()
     QMessageBox.information(self, self.tr("Finished"),
                             self.tr("Processing completed."))
Example #37
0
 def show_about_qt(self):
     """Show About Qt Dialog."""
     QMessageBox.aboutQt(self, translations.TR_ABOUT_QT)
Example #38
0
 def showWarning(self, parent, text):
     warn = QMessageBox.warning(parent, 'Warning',
              text, QMessageBox.Ok)
Example #39
0
    def remove_theme_callback(self):
        '''remove selected theme'''

        theme_name = str(self.comboBox.currentText())
        msb = QMessageBox()
        msb.setIcon(QMessageBox.Critical)
        msb.setWindowTitle("Message")

        if theme_name in ("Current theme", "Default theme"):
            msb.setStandardButtons(QMessageBox.Ok)
            msb.setText("'{}' cannot be deleted.".format(theme_name))
            msb.exec_()
        else:
            msb.setText(
                "Are you sure you want to delete '{}'?".format(theme_name))
            msb.setIcon(QMessageBox.Warning)
            msb.setStandardButtons(QMessageBox.Cancel | QMessageBox.Ok)
            if msb.exec_() == QMessageBox.Ok:
                index = self.themeList.index(self.curent_theme_name)
                self.comboBox.setCurrentIndex(index)
                CHOSEN_THEME = DealXML.get_child_by_name(
                    self.SETTINGS, "THEME", theme_name)
                self.SETTINGS.remove(CHOSEN_THEME)
                ET.ElementTree(self.SETTINGS).write(self.prefFileName)
                index = self.themeList.index(theme_name)
                self.comboBox.removeItem(index)
                self.themeList.remove(theme_name)
Example #40
0
    def branch(self):
        """create branch and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        base_branch = mtch.group(2)
        base_rev = mtch.group(3)
        assert (schema)
        dlg = QDialog()
        dlg.setWindowTitle('Enter branch name')
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        line_edit = QLineEdit(dlg)
        layout.addWidget(line_edit)
        layout.addWidget(button_box)
        if not dlg.exec_():
            return
        branch = line_edit.text()

        if not branch:
            print 'aborted'
            return

        pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info()))
        pcur.execute("SELECT * FROM " + schema + ".revisions "
                     "WHERE branch = '" + branch + "'")
        if pcur.fetchone():
            pcur.close()
            QMessageBox.warning(self.iface.mainWindow(), "Warning",
                                "Branch " + branch + ' already exists.')
            return
        pcur.close()

        # get the commit message
        if not self.q_commit_msg_dlg.exec_():
            return
        commit_msg = self.commit_msg_dlg.commitMessage.document().toPlainText()
        if not commit_msg:
            QMessageBox.warning(self.iface.mainWindow(), "Warning",
                                "No commit message, aborting commit")
            print "aborted"
            return
        versioning_base.add_branch(uri.connectionInfo(), schema, branch,
                                   commit_msg, base_branch, base_rev)
        grp_name = branch + ' revision head'
        grp_idx = self.iface.legendInterface().addGroup(grp_name)
        for layer_id in reversed(self.current_layers):
            layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
            new_uri = QgsDataSourceURI(layer.source())
            new_uri.setDataSource(schema + '_' + branch + '_rev_head',
                                  new_uri.table(), new_uri.geometryColumn(),
                                  new_uri.sql(), new_uri.keyColumn())
            display_name = QgsMapLayerRegistry.instance().mapLayer(
                layer_id).name()

            new_layer = self.iface.addVectorLayer(
                new_uri.uri().replace('()', ''), display_name, 'postgres')
            self.iface.legendInterface().moveLayer(new_layer, grp_idx)
Example #41
0
    def addStep(self):
        """
        Add step
        """
        action = self.actionsComboBox.currentText()
        descr = self.descriptionLine.text()
        descr = unicode(descr).replace('"', '')
        
        signal = self.AddStep
        if self.cancelAction.isEnabled():
            signal = self.UpdateStep

        if action in [ GuiSteps.FRAMEWORK_INFO, GuiSteps.FRAMEWORK_WARNING ]:
            fromCache = False
            if self.basicTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.basicTextCombo.currentText() == "ALIAS": fromAlias = True
            
            newText = self.basicTextLine.text()
            if not len(newText):
                QMessageBox.warning(self, "Assistant" , "Please to set a value!")
            else:
                parameters = { 'text': newText, 'from-cache': fromCache, 'from-alias': fromAlias }
                signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
        
        elif action in [ GuiSteps.FRAMEWORK_INTERACT ]:
            # read text from cache, alias or not ?
            fromCache = False
            if self.askTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.askTextCombo.currentText() == "ALIAS": fromAlias = True
            
            askText = self.askTextLine.text()
            if not len(askText):
                QMessageBox.warning(self, "Assistant" , "Please to set question to ask!")
            else:
                saveAskText = self.askTextCacheLine.text()
                if not len(saveAskText):
                    QMessageBox.warning(self, "Assistant" , "Please to set key destination cache!")
                else:
                    parameters = { 'key': saveAskText, 'value': askText, 'from-cache': fromCache, 'from-alias': fromAlias }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                        
        elif action in [ GuiSteps.FRAMEWORK_CHECK_STRING ]:
            fromCache = False
            if self.checkOutTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.checkOutTextCombo.currentText() == "ALIAS": fromAlias = True
            
            inText = self.checkInTextLine.text()
            if not len(inText):
                QMessageBox.warning(self, "Assistant" , "Please to set a cache key value!")
            else:
                outText = self.checkOutTextLine.text()
                if not len(outText):
                    QMessageBox.warning(self, "Assistant" , "Please to set a value!")
                else:
                    op = self.checkComboBox.currentText()
                    parameters = { 'key': inText, 'value': outText, 'from-cache': fromCache,
                                    'from-alias': fromAlias, "operator": op }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )
                    
        elif action in [ GuiSteps.FRAMEWORK_WAIT ]:
            fromCache = False
            if self.valueWaitCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.valueWaitCombo.currentText() == "ALIAS": fromAlias = True
            
            miscStr = self.valueWaitLine.text()
            if not len(miscStr):
                QMessageBox.warning(self, "Assistant" , "Please to set a value!")
            else:
                parameters = {'from-cache': fromCache, 'from-alias': fromAlias}
                signal.emit( str(action), unicode(descr), miscStr, parameters )
                
        elif action in [ GuiSteps.FRAMEWORK_CACHE_SET ]:
            fromCache = False
            if self.basicTextCombo.currentText() == "CACHE": fromCache = True
            fromAlias = False
            if self.basicTextCombo.currentText() == "ALIAS": fromAlias = True
            
            newText = self.basicTextLine.text()
            if not len(newText):
                QMessageBox.warning(self, "Assistant" , "Please to set a text value!")
            else:
                miscStr = self.cacheKeyName.text()
                if not len(miscStr):
                    QMessageBox.warning(self, "Assistant" , "Please to set a key name!")
                else:
                    parameters = { 'key': miscStr, 'value': newText, 'from-cache': fromCache, 'from-alias': fromAlias }
                    signal.emit( str(action), unicode(descr), EMPTY_VALUE, parameters )

        else:
            signal.emit( str(action), unicode(descr), EMPTY_VALUE, {} )
Example #42
0
 def messageBox(self, coretxt, detail):
     msg = QMessageBox(self)
     msg.setWindowTitle(self.configureError)
     msg.setText(self.configureErrorMsg)
     msg.setInformativeText(coretxt)
     msg.setIcon(QMessageBox.Critical)
     msg.setDetailedText(detail)
     msg.setStandardButtons(QMessageBox.Ok)
     ret = msg.exec_()
Example #43
0
 def _reglas(self):
     QMessageBox.information(self, self.tr("Reglas del Juego"), (
         "<h3>MiniSudoku</h3>Las reglas del juego son: <ul><li>Solo debes ingresar numeros del 1 al 4</li><li>Ninguno de los numeros puede coincidir ni vertical ni horizontalmente<img src='imagen1.png' /></li><li>Tampoco puede coincidir los numeros en grupos de 4<img src='imagen2.png' /></li><li>Al terminar, dale en probar y comprueba tu solucion</li></ul>"
     ))
Example #44
0
def updateField():
    maCouche = iface.activeLayer()
    layerName = maCouche.name()
    formTitle = layerName + u" - Attributs d'entités"
    layers = QgsMapLayerRegistry.instance().mapLayers(
    )  # liste des couches du projet

    for w in iface.mainWindow().findChildren(QDialog):
        if w.windowTitle() == formTitle and w.isActiveWindow():
            w.reject()

    vYear = u"year_end"
    vStatus = u"fk_status"
    vDestroy = u"usr_destroy"
    for feature in maCouche.getFeatures(QgsFeatureRequest(int(featureId))):
        msgBox = QMessageBox()
        if feature[vStatus] != 1301:
            if feature[vStatus] == 13002:
                text_arch = u"La conduite ID =" + str(
                    featureId) + u" a déjà été archivée en " + str(
                        feature[vYear])
            else:
                text_arch = u"La conduite ID =" + str(
                    featureId
                ) + u" ne peut être archivée si elle n'est pas en service"
            msgBox.setText(text_arch)
            msgBox.exec_()
        if feature[vStatus] == 1301:
            reply = QMessageBox.question(
                iface.mainWindow(), u"Définir le statut d'archivage",
                u"Est-ce que la conduite a été complétement détruite et supprimée du terrain (archivée détruite) ?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if reply == QMessageBox.Yes:
                #do something if yes
                #StatutArch = 13002
                Destroy = 't'
            else:
                #do something if no
                #StatutArch = 13002
                Destroy = 'f'

            input_rep = QInputDialog()
            year_end, ok = input_rep.getInt(
                None, u"Annee d'archivage ",
                u"indiquez l'ann\xe9e d'archive (4 chiffres)",
                datetime.now().year, 1860,
                datetime.now().year, 1)
            if ok:
                if not maCouche.isEditable():
                    maCouche.startEditing()
                feature[vStatus] = 13002
                feature[vDestroy] = Destroy
                feature[vYear] = year_end
                if iface.openFeatureForm(maCouche, feature):
                    maCouche.updateFeature(feature)
                    num_e = 0
                    num_v = 0
                    num_h = 0
                    num_i = 0
                    num_a = 0
                    for i in range(0, len(layerIds)):
                        if layerIds[i] not in layers:
                            text_layer = u"La couche avec ID = " + str(
                                layerIds[i]
                            ) + u" n'existe plus ou pas dans le projet, merci de vérifier la structure du projet sinon elle ne sera pas prise en compte dans l'archivage"
                            msgBox.setText(text_layer)
                            msgBox.exec_()
                    for layer in layers.values():
                        uri = QgsDataSourceURI(layer.source())
                        name = uri.schema() + "." + uri.table()
                        #if name in ["qwat_od.valve", "qwat_od.part" , "qwat_od.hydrant"]:
                        #if layer.name() == u"vannes" or layer.name() == u"\xe9l\xe9ments de montage" or layer.name() == u"hydrants" or layer.name() == u"introduction":
                        if layer.id() in layerIds:
                            # print unicode(layer.name())
                            num_elements = 0
                            if not layer.isEditable():
                                layer.startEditing()
                            req = QgsFeatureRequest(
                                feature.geometry().boundingBox()
                            ).setFilterExpression(' "fk_status" = \'1301\' ')
                            for feat in layer.getFeatures(req):
                                if feat.geometry().intersects(
                                        feature.geometry()):
                                    num = 0
                                    for f in maCouche.getFeatures(
                                            QgsFeatureRequest(
                                                feat.geometry().boundingBox()).
                                            setFilterExpression(
                                                ' "fk_status" != \'13002\' ')):
                                        if f.geometry().intersects(
                                                feat.geometry(
                                                )) and f.id() != featureId:
                                            num += 1
                                    # print("int",feat.id(),num)
                                    if num == 0:
                                        if feat[vStatus] != 13002:
                                            feat[vStatus] = 13002
                                            feat[vYear] = year_end
                                            layer.updateFeature(feat)
                                            num_elements += 1
                            #if layer.name() == u"vannes":
                            if name == "qwat_od.valve":
                                num_v = num_elements
                            #if layer.name() == u"\xe9l\xe9ments de montage":
                            if name == "qwat_od.part":
                                num_e = num_elements
                            #if layer.name() == u"hydrants":
                            if name == "qwat_od.hydrant":
                                num_h = num_elements
                            #if layer.name() == u"introduction":
                            if name == "qwat_od.subscriber":
                                num_i = num_elements
                            if name == "qwat_od.usr_prc_point":
                                num_a = num_elements

                    text = u"La conduite ID =" + str(
                        featureId) + u" a \xe9t\xe9 archiv\xe9e en " + str(
                            year_end)
                    if num_v > 0 or num_e > 0 or num_h > 0 or num_i > 0:
                        text += u"\n ainsi que :"
                        if num_v > 0:
                            text += u"\n - " + str(num_v) + u" vannes"
                        if num_e > 0:
                            text += u"\n - " + str(
                                num_e) + u" \xe9l\xe9ments de montage"
                        if num_h > 0:
                            text += u"\n - " + str(num_h) + u" hydrants"
                        if num_i > 0:
                            text += u"\n - " + str(num_i) + u" introductions"
                        if num_a > 0:
                            text += u"\n - " + str(
                                num_a
                            ) + u" \xe9l\xe9ments de protection cathodique"
                    msgBox.setText(text)
                    msgBox.exec_()
                else:
                    pass
            else:
                pass
        else:
            pass
Example #45
0
    def _valida(self):
        c00 = self.lineEdit.text()
        c01 = self.lineEdit1.text()
        c02 = self.lineEdit2.text()
        c03 = self.lineEdit3.text()
        c10 = self.lineEdit4.text()
        c11 = self.lineEdit5.text()
        c12 = self.lineEdit6.text()
        c13 = self.lineEdit7.text()
        c20 = self.lineEdit8.text()
        c21 = self.lineEdit9.text()
        c22 = self.lineEdit10.text()
        c23 = self.lineEdit11.text()
        c30 = self.lineEdit12.text()
        c31 = self.lineEdit13.text()
        c32 = self.lineEdit14.text()
        c33 = self.lineEdit15.text()
        print ""
        print(c00 + "-" + c01 + "-" + c02 + "-" + c03)
        print(c10 + "-" + c11 + "-" + c12 + "-" + c13)
        print(c20 + "-" + c21 + "-" + c22 + "-" + c23)
        print(c30 + "-" + c31 + "-" + c32 + "-" + c33)

        #Validando primer grupo diferentes numeros
        if (c00 == c01):
            print "rojo"
        if (c00 == c10):
            print "rojo"
            self.errorGrupo = True
        if (c00 == c11):
            print "rojo"
            self.errorGrupo = True
        if (c01 == c10):
            print "rojo"
            self.errorGrupo = True
        if (c01 == c11):
            print "rojo"
            self.errorGrupo = True
        if (c10 == c11):
            print "rojo"
            self.errorGrupo = True

        #Validando segundo grupo diferentes numeros
        if (c02 == c03):
            print "rojo"
        if (c02 == c12):
            print "rojo"
            self.errorGrupo = True
        if (c02 == c13):
            print "rojo"
            self.errorGrupo = True
        if (c03 == c12):
            print "rojo"
            self.errorGrupo = True
        if (c03 == c13):
            print "rojo"
            self.errorGrupo = True
        if (c12 == c13):
            print "rojo"
            self.errorGrupo = True

        #Validando tercer grupo diferentes numeros
        if (c20 == c21):
            print "rojo"
        if (c20 == c30):
            print "rojo"
            self.errorGrupo = True
        if (c20 == c31):
            print "rojo"
            self.errorGrupo = True
        if (c21 == c30):
            print "rojo"
            self.errorGrupo = True
        if (c21 == c31):
            print "rojo"
            self.errorGrupo = True
        if (c30 == c31):
            print "rojo"
            self.errorGrupo = True

        #Validando cuarto grupo diferentes numeros
        if (c22 == c23):
            print "rojo"
        if (c22 == c32):
            print "rojo"
            self.errorGrupo = True
        if (c22 == c33):
            print "rojo"
            self.errorGrupo = True
        if (c23 == c32):
            print "rojo"
            self.errorGrupo = True
        if (c23 == c33):
            print "rojo"
            self.errorGrupo = True
        if (c32 == c33):
            print "rojo"
            self.errorGrupo = True

        #validando primera linea horizontal
        if (c00 == c01):
            print "rojo"
            self.errorLineaH = True
        if (c00 == c02):
            print "rojo"
            self.errorLineaH = True
        if (c00 == c03):
            print "rojo"
            self.errorLineaH = True
        if (c01 == c02):
            print "rojo"
            self.errorLineaH = True
        if (c01 == c03):
            print "rojo"
            self.errorLineaH = True
        if (c02 == c03):
            print "rojo"
            self.errorLineaH = True

        #validando segunda linea horizontal
        if (c10 == c11):
            print "rojo"
            self.errorLineaH = True
        if (c10 == c12):
            print "rojo"
            self.errorLineaH = True
        if (c10 == c13):
            print "rojo"
            self.errorLineaH = True
        if (c11 == c12):
            print "rojo"
            self.errorLineaH = True
        if (c11 == c13):
            print "rojo"
            self.errorLineaH = True
        if (c12 == c13):
            print "rojo"
            self.errorLineaH = True

        #validando tercera linea horizontal
        if (c20 == c21):
            print "rojo"
            self.errorLineaH = True
        if (c20 == c22):
            print "rojo"
            self.errorLineaH = True
        if (c20 == c23):
            print "rojo"
            self.errorLineaH = True
        if (c21 == c22):
            print "rojo"
            self.errorLineaH = True
        if (c21 == c23):
            print "rojo"
            self.errorLineaH = True
        if (c22 == c23):
            print "rojo"
            self.errorLineaH = True

        #validando cuarta linea horizontal
        if (c30 == c31):
            print "rojo"
            self.errorLineaH = True
        if (c30 == c32):
            print "rojo"
            self.errorLineaH = True
        if (c30 == c33):
            print "rojo"
            self.errorLineaH = True
        if (c31 == c32):
            print "rojo"
            self.errorLineaH = True
        if (c31 == c33):
            print "rojo"
            self.errorLineaH = True
        if (c32 == c33):
            print "rojo"
            self.errorLineaH = True

        #validando primera linea vertical
        if (c00 == c10):
            print "rojo"
            self.errorLineaV = True
        if (c00 == c20):
            print "rojo"
            self.errorLineaV = True
        if (c00 == c30):
            print "rojo"
            self.errorLineaV = True
        if (c10 == c20):
            print "rojo"
            self.errorLineaV = True
        if (c10 == c30):
            print "rojo"
            self.errorLineaV = True
        if (c20 == c30):
            print "rojo"
            self.errorLineaV = True

        #validando segunda linea vertical
        if (c01 == c11):
            print "rojo"
            self.errorLineaV = True
        if (c01 == c21):
            print "rojo"
            self.errorLineaV = True
        if (c01 == c31):
            print "rojo"
            self.errorLineaV = True
        if (c11 == c21):
            print "rojo"
            self.errorLineaV = True
        if (c11 == c31):
            print "rojo"
            self.errorLineaV = True
        if (c21 == c31):
            print "rojo"
            self.errorLineaV = True

        #validando tercera linea vertical
        if (c02 == c12):
            print "rojo"
            self.errorLineaV = True
        if (c02 == c22):
            print "rojo"
            self.errorLineaV = True
        if (c02 == c32):
            print "rojo"
            self.errorLineaV = True
        if (c12 == c22):
            print "rojo"
            self.errorLineaV = True
        if (c12 == c32):
            print "rojo"
            self.errorLineaV = True
        if (c22 == c32):
            print "rojo"
            self.errorLineaV = True

        #validando cuarta linea vertical
        if (c03 == c13):
            print "rojo"
            self.errorLineaV = True
        if (c03 == c23):
            print "rojo"
            self.errorLineaV = True
        if (c03 == c33):
            print "rojo"
            self.errorLineaV = True
        if (c13 == c23):
            print "rojo"
            self.errorLineaV = True
        if (c13 == c33):
            print "rojo"
            self.errorLineaV = True
        if (c23 == c33):
            print "rojo"
            self.errorLineaV = True

        if (self.errorGrupo == False and self.errorLineaH == False
                and self.errorLineaV == False):
            QMessageBox.information(
                self, self.tr("Has terminado"),
                "<h3>Muy Bien!! felicidades, has completado el MiniSudoku.</h3>"
            )

        if (self.errorGrupo):
            self.label.setText("Tiene error en uno o mas grupos")
            self.errorGrupo = False

        if (self.errorLineaH):
            self.label.setText("Tiene error en una linea horizontal")
            self.errorLineaH = False

        if (self.errorLineaV):
            self.label.setText("Tiene error en una linea vertical")
            self.errorLineaV = False
Example #46
0
    def processLoading(self):
        '''
        Load all the layers in QGIS
        and apply corresponding style
        '''
        self.startTime = datetime.now()
        QApplication.setOverrideCursor(Qt.WaitCursor)

        # default style to apply for Cadastre layers
        self.themeDir = unicode(self.dialog.liTheme.currentText())
        if not os.path.exists(
                os.path.join(self.qc.plugin_dir, "styles/%s" % self.themeDir)):
            self.themeDir = self.defaultThemeDir

        # set Cadastre SVG path if not set
        cadastreSvgPath = os.path.join(self.qc.plugin_dir,
                                       "styles/%s/svg" % self.themeDir)
        s = QSettings()
        qgisSvgPaths = s.value("svg/searchPathsForSVG", 10, type=str)
        if not cadastreSvgPath in qgisSvgPaths:
            if qgisSvgPaths:
                qgisSvgPaths = u"%s|%s" % (qgisSvgPaths, cadastreSvgPath)
            else:
                qgisSvgPaths = u"%s" % cadastreSvgPath
            s.setValue("svg/searchPathsForSVG", qgisSvgPaths)
            self.qc.updateLog(
                u"* Le chemin contenant les SVG du plugin Cadastre a été ajouté dans les options de QGIS"
            )

        # Get selected options
        providerName = self.dialog.dbpluginclass.providerName()
        qgisCadastreLayers = []
        self.dialog.schema = unicode(self.dialog.liDbSchema.currentText())
        self.dialog.totalSteps = len(self.qgisCadastreLayerList)

        # Run the loading
        self.updateTimer()
        self.qc.updateLog(u'Chargement des tables :')

        # Get database list of tables
        if self.dialog.dbType == 'postgis':
            schemaSearch = [
                s for s in self.dialog.db.schemas()
                if s.name == self.dialog.schema
            ]
            schemaInst = schemaSearch[0]
            dbTables = self.dialog.db.tables(schemaInst)
        if self.dialog.dbType == 'spatialite':
            dbTables = self.dialog.db.tables()

        # Get commune filter by expression
        communeExpression = self.dialog.communeFilter.text()
        communeFilter = None
        cExp = QgsExpression(communeExpression)
        if not cExp.hasParserError():
            self.qc.updateLog(u'Filtrage à partir des communes : %s' %
                              communeExpression)
            cReq = QgsFeatureRequest(cExp)
            cTableList = [a for a in dbTables if a.name == 'geo_commune']
            cTable = cTableList[0]
            cUniqueCol = 'ogc_fid'
            cSchema = self.dialog.schema
            cGeomCol = 'geom'
            cLayerUri = self.dialog.db.uri()
            cLayerUri.setDataSource(cSchema, cTable.name, cGeomCol, '',
                                    cUniqueCol)
            clayer = QgsVectorLayer(cLayerUri.uri(), 'com', providerName)
            cfeatures = clayer.getFeatures(cReq)
            cids = [a['commune'] for a in cfeatures]
            if len(cids):
                communeFilter = cids
        else:
            self.qc.updateLog(
                u'Filtrage à partir des communes : expression invalide !')

        # Loop throuhg qgisQastreLayerList and load each corresponding table
        for item in self.qgisCadastreLayerList:

            if item['label'] not in self.mainLayers and self.dialog.cbMainLayersOnly.isChecked(
            ):
                continue

            if item.has_key('dbType') and item['dbType'] != self.dialog.dbType:
                continue

            # update progress bar
            self.qc.updateLog(u'* %s' % item['label'])
            self.dialog.step += 1
            self.qc.updateProgressBar()

            # Tables - Get db_manager table instance
            tableList = [a for a in dbTables if a.name == item['table']]
            if len(tableList) == 0 and not item.has_key('isView'):
                self.qc.updateLog(u'  - Aucune table trouvée pour %s' %
                                  item['label'])
                continue

            if tableList:
                table = tableList[0]
                source = table.name
                uniqueField = table.getValidQGisUniqueFields(True)
                if uniqueField:
                    uniqueCol = uniqueField.name
                else:
                    uniqueCol = 'ogc_fid'

            schema = self.dialog.schema

            # View
            if item.has_key('isView'):
                if self.dialog.dbType == 'spatialite':
                    schemaReplace = ''
                else:
                    schemaReplace = '"%s".' % self.dialog.schema
                source = item['table'].replace('schema.', schemaReplace)
                uniqueCol = item['key']
                schema = None

            sql = item['sql']
            geomCol = item['geom']

            if communeFilter:
                communeFilterText = "'" + "', '".join(communeFilter) + "'"
                nschema = ''
                if self.dialog.dbType == 'postgis':
                    nschema = '"%s".' % schema
                if 'subset' in item:
                    subset = item['subset']
                    sql += subset % communeFilterText
                else:
                    itemcol = item['table']
                    if item['table'] == 'geo_label':
                        itemcol = 'ogc_fid'
                    subset = itemcol + '''
                         IN (

                            SELECT b.''' + itemcol + '''
                            FROM  ''' + nschema + item['table'] + ''' b
                            JOIN  ''' + nschema + '''geo_commune c
                            ON ST_Within(b.geom, c.geom)
                            WHERE 2>1
                            AND c.geo_commune IN ( %s )

                        )
                    '''
                    if sql:
                        sql += ' AND '
                    sql += subset % communeFilterText

            # Create vector layer
            alayerUri = self.dialog.db.uri()
            alayerUri.setDataSource(schema, source, geomCol, sql, uniqueCol)

            vlayer = QgsVectorLayer(alayerUri.uri(), item['label'],
                                    providerName)

            # apply style
            qmlPath = os.path.join(
                self.qc.plugin_dir,
                "styles/%s/%s.qml" % (self.themeDir, item['name']))
            if os.path.exists(qmlPath):
                vlayer.loadNamedStyle(qmlPath)

            # append vector layer to the list
            qgisCadastreLayers.append(vlayer)

        self.updateTimer()

        # Get canvas and disable rendering
        from qgis.utils import iface
        canvas = iface.mapCanvas()
        canvas.freeze(True)

        # Add all layers to QGIS registry
        self.qc.updateLog(u'Ajout des couches dans le registre de QGIS')
        QgsMapLayerRegistry.instance().addMapLayers(qgisCadastreLayers)
        self.updateTimer()

        # Create a group "Cadastre" and move all layers into it
        self.qc.updateLog(u'Ajout des couches dans le groupe Cadastre')
        li = self.dialog.iface.legendInterface()
        groups = []
        for group in li.groupLayerRelationship():
            if group[0]:
                groups.append(group[0])
        if u"Cadastre" in groups:
            g1 = self.getGroupIndex(u"Cadastre")
            if not u'Fond' in groups:
                gf = li.addGroup(u'Fond', True, g1)
            else:
                gf = self.getGroupIndex(u'Fond')

            if not u'Étiquettes cadastre' in groups:
                ge = li.addGroup(u'Étiquettes cadastre', True, gf)
            else:
                ge = self.getGroupIndex(u'Étiquettes cadastre')

            if not u'Données cadastre' in groups:
                gd = li.addGroup(u'Données cadastre', True, gf)
            else:
                gd = self.getGroupIndex(u"Données cadastre")
        else:
            g1 = li.addGroup("Cadastre")
            gf = li.addGroup("Fond", True, g1)
            ge = li.addGroup(u'Étiquettes cadastre', True, gf)
            gd = li.addGroup(u'Données cadastre', True, gf)

        for layer in qgisCadastreLayers:
            #~ layer.updateExtents()
            # Get layer options
            qlayer = [
                a for a in self.qgisCadastreLayerList
                if a['label'] == layer.name()
            ]
            if qlayer:
                qlayer = qlayer[0]

                # Enable/Disable layer
                if not qlayer['active']:
                    li.setLayerVisible(layer, False)

                # Move layer to proper group
                if qlayer['group'] == 'E':
                    li.moveLayer(layer, ge)
                elif qlayer['group'] == 'D':
                    li.moveLayer(layer, gd)
                else:
                    li.moveLayer(layer, g1)
            else:
                # Move layer to Cadastre group
                li.moveLayer(layer, g1)

            # Do not expand layer legend
            li.setLayerExpanded(layer, False)

        # Close Cadastre group
        # li.setGroupExpanded(g1, False)

        self.updateTimer()

        # Zoom to full extent
        self.qc.updateLog(u'Zoom sur les couches')
        canvas.zoomToFullExtent()
        canvas.freeze(False)
        canvas.refresh()
        self.updateTimer()

        # progress bar
        self.dialog.step += 1
        self.qc.updateProgressBar()

        # Emit signal
        self.qc.updateLog(u'Mise à jour des outils cadastre')
        self.cadastreLoadingFinished.emit()
        self.updateTimer()

        # Final message
        QApplication.restoreOverrideCursor()
        QMessageBox.information(
            self.dialog, u"Cadastre",
            u"Les données ont bien été chargées dans QGIS")
        self.dialog.pbProcess.setValue(0)

        QApplication.restoreOverrideCursor()
Example #47
0
class RegistrationWindowPresenter(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.parent = parent
        self.rememberCheckBoxFlag = False
        loadUi('RegistrationWindow.ui', self)
        self.setWindowTitle(u'Регистрация')
        self.setWindowIcon(QIcon('icon.png'))
        self.loginTextEdit.setTextColor(QColor('gray'))
        self.loginTextEdit.setPlainText(u'Имя пользователя')
        self.loginTextEdit.setTextColor(QColor('black'))
        self.passwordTextEdit.setTextColor(QColor('gray'))
        self.passwordTextEdit.setPlainText(u'Пароль')
        self.passwordTextEdit.setTextColor(QColor('black'))
        self.repeatPasswordTextEdit.setTextColor(QColor('gray'))
        self.repeatPasswordTextEdit.setPlainText(u'Повторите пароль')
        self.repeatPasswordTextEdit.setTextColor(QColor('black'))
        self.emailTextEdit.setTextColor(QColor('gray'))
        self.emailTextEdit.setPlainText(u'Адрес электронной почты')
        self.emailTextEdit.setTextColor(QColor('black'))

        self.msg = QMessageBox()
        self.msg.setWindowIcon(QIcon('icon.png'))
        self.msg.setWindowTitle("!")
        self.msg.setStandardButtons(QMessageBox.Ok)

        self.rememberCheckBox.stateChanged.connect(self.checker)
        self.okButton.clicked.connect(self.on_okButton_click)
        self.cancelButton.clicked.connect(self.on_cancelButton_click)

    def checker(self, state):
        if state == QtCore.Qt.Checked:
            self.rememberCheckBoxFlag = not self.rememberCheckBoxFlag
        else:
            self.rememberCheckBoxFlag = not self.rememberCheckBoxFlag

    def on_cancelButton_click(self):
        self.close()

    def on_okButton_click(self):
        user_info = self.parent.service.get_login(self.loginTextEdit.toPlainText())
        if user_info:
            self.msg.setText(u"Пользователь с таким логином уже есть!")
            self.msg.exec_()
        elif self.passwordTextEdit.toPlainText() != self.repeatPasswordTextEdit.toPlainText():
            self.msg.setText(u"Пароли не совпадают!")
            self.msg.exec_()
        elif self.parent.service.get_email(self.emailTextEdit.toPlainText()):
            self.msg.setText(u"Пользователь с такой электронной почтой уже есть!")
            self.msg.exec_()
        elif len(self.emailTextEdit.toPlainText().split('@')) != 2:
            self.msg.setText(u"Такой формат электронной почты не поддерживается!")
            self.msg.exec_()
        elif not unicode(self.emailTextEdit.toPlainText()).split('@')[1] in ['gmail.com', 'mail.ru', 'yandex.ru']:
            self.msg.setText(u"Такой формат электронной почты не поддерживается!")
            self.msg.exec_()
        else:
            self.parent.service.delete_remember()
            if self.rememberCheckBoxFlag:
                self.parent.service.set_remember(self.loginTextEdit.toPlainText(), self.passwordTextEdit.toPlainText())
            self.parent.service.post_user(self.loginTextEdit.toPlainText(), self.passwordTextEdit.toPlainText(), self.emailTextEdit.toPlainText(), self.bornDateEdit.text())
            self.hide()
            self.parent.hide()
            self.parent.main = AlphabetWindowPresenter(self.parent, self.parent.service.get_login(self.loginTextEdit.toPlainText()))
            self.parent.main.show()
Example #48
0
 def _acerca(self):
     QMessageBox.information(
         self, self.tr("Realizado por"),
         "<h2>Ing. Diego Guerrero</h2><h3>Venezuela</h3>[email protected]"
     )
Example #49
0
    def search_music(self):
        self.search_dial = SearchDiag(self)
        self.search_dial.setWindowTitle('在线歌曲搜索')
        self.search_dial.exec()
        # self.search_dial.show()
        print(self.search_dial.flag)
        if (self.search_dial.flag):
            #判断是否有网络连接
            if (not self.if_net_avalible()):
                msg = '网络不可达'
                msg_box = QMessageBox(QMessageBox.Information, 'Info', msg)
                msg_box.exec_()
                return False
            self.search_author = self.search_dial.search_author
            self.search_m_name = self.search_dial.search_m_name
            self.save_path = self.search_dial.save_path
            print(self.save_path)
            #百度music api
            url = "http://box.zhangmen.baidu.com/x?op=12&count=1&title="+\
                  self.search_m_name+"$$"+self.search_author+"$$$$"
            print(url)
            c = pycurl.Curl()
            burl = bytes(url, encoding='utf-8')
            #获取搜索结果
            c.setopt(c.URL, burl)
            b3 = BytesIO()
            c.setopt(c.WRITEFUNCTION, b3.write)
            c.perform()
            http_code = c.getinfo(pycurl.HTTP_CODE)
            if (http_code == 404):
                msg = '找不到服务器'
                msg_box = QMessageBox(QMessageBox.Information, 'Info', msg)
                msg_box.exec_()
                return False
            res = b3.getvalue().decode('utf-8')
            b3.close()
            print(res)
            root = ElementTree.fromstring(res)
            #获取count节点
            node_count = root.find('count')
            print(node_count.text)
            #有搜索结果
            if (node_count.text == '1'):
                #获取url节点
                node_url = root.find('url')
                print(node_url)
                #获取encode节点
                node_encode = node_url.find('encode')
                print(node_encode)
                print(node_encode.text)
                url_encode = node_encode.text
                #获取decode节点
                node_decode = node_url.find('decode')
                print(node_decode)
                print(node_decode.text)
                url_decode = node_decode.text

                url0 = url_encode.rsplit('/', 1)[0]
                print(url0)
                url_new = url0 + '/' + url_decode
                print(url_new)
                #下载歌曲
                # burl_new = bytes(url_new, encoding='utf-8')
                c.setopt(c.URL, url_new)
                b4 = BytesIO()
                c.setopt(c.WRITEFUNCTION, b4.write)
                c.perform()
                res = b4.getvalue()
                b4.close()
                # print(res)
                #把mp3写入文件
                filename = self.search_author + '-' + self.search_m_name + '.mp3'
                path = os.path.join(self.save_path, filename)
                fn = codecs.open(path, 'wb')
                fn.write(res)
                fn.close()
                print('歌曲获取成功,保存至' + path)
                msg = '歌曲获取成功,保存至' + path
                msg_box = QMessageBox(QMessageBox.Information, "Info", msg)
                msg_box.exec_()
            else:
                msg = '未找到' + self.search_author + '的歌曲' + self.search_m_name
                msg_box = QMessageBox(QMessageBox.Information, "Info", msg)
                msg_box.exec_()
Example #50
0
 def okPressed(self):
     description = unicode(self.nameTextBox.text())
     if description.strip() == '':
         QMessageBox.warning(self, self.tr('Unable to define parameter'),
                             self.tr('Invalid parameter name'))
         return
     if self.param is None:
         validChars = \
             'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
         safeName = ''.join(c for c in description if c in validChars)
         name = safeName.lower()
         i = 2
         while name in self.alg.inputs:
             name = safeName.lower() + str(i)
     else:
         name = self.param.name
     if self.paramType \
             == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN \
             or isinstance(self.param, ParameterBoolean):
         self.param = ParameterBoolean(name, description,
                                       self.state.isChecked())
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
             isinstance(self.param, ParameterTableField):
         if self.parentCombo.currentIndex() < 0:
             QMessageBox.warning(
                 self, self.tr('Unable to define parameter'),
                 self.tr('Wrong or missing parameter values'))
             return
         parent = self.parentCombo.itemData(self.parentCombo.currentIndex())
         self.param = ParameterTableField(name, description, parent)
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \
             isinstance(self.param, ParameterRaster):
         self.param = ParameterRaster(name, description,
                                      self.yesNoCombo.currentIndex() == 1)
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \
             isinstance(self.param, ParameterTable):
         self.param = ParameterTable(name, description,
                                     self.yesNoCombo.currentIndex() == 1)
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \
             isinstance(self.param, ParameterVector):
         self.param = ParameterVector(
             name, description, [self.shapetypeCombo.currentIndex() - 1],
             self.yesNoCombo.currentIndex() == 1)
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \
             isinstance(self.param, ParameterMultipleInput):
         self.param = ParameterMultipleInput(
             name, description,
             self.datatypeCombo.currentIndex() - 1,
             self.yesNoCombo.currentIndex() == 1)
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \
             isinstance(self.param, ParameterNumber):
         try:
             vmin = unicode(self.minTextBox.text()).strip()
             if vmin == '':
                 vmin = None
             else:
                 vmin = float(vmin)
             vmax = unicode(self.maxTextBox.text()).strip()
             if vmax == '':
                 vmax = None
             else:
                 vmax = float(vmax)
             self.param = ParameterNumber(
                 name, description, vmin, vmax,
                 unicode(self.defaultTextBox.text()))
         except:
             QMessageBox.warning(
                 self, self.tr('Unable to define parameter'),
                 self.tr('Wrong or missing parameter values'))
             return
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \
             isinstance(self.param, ParameterString):
         self.param = ParameterString(name, description,
                                      unicode(self.defaultTextBox.text()))
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \
             isinstance(self.param, ParameterExtent):
         self.param = ParameterExtent(name, description)
     elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \
             isinstance(self.param, ParameterFile):
         isFolder = self.fileFolderCombo.currentIndex() == 1
         self.param = ParameterFile(name, description, isFolder=isFolder)
     self.param.optional = self.yesNoCombo.currentIndex() == 1
     self.close()
Example #51
0
 def changeModoMedicionTiempo(self):
     if self.confirmaChangeModo():
         self.setCentralWidget(ModoMedicionTiemposView())
         QMessageBox.information(self, "Cambio de Modo",
                                 "Se cambio a Modo Medicion de Tiempos",
                                 QMessageBox.Ok)
Example #52
0
    def restore(self):
        self.progressBarBackup.setMinimum(0)
        self.progressBarBackup.setMaximum(0)
        self.restoreButton.setEnabled(False)
        self.threads = []
        self.files_to_restore = {}
        for index, state in self.model_storage.checks.items():
            th = Thread(target=self.model_storage.exportChecked,
                        args=(self.lock, {
                            index: state
                        }, self.files_to_restore))
            th.start()
            self.threads.append(th)

        status = map(Thread.isAlive, self.threads)

        while any(status):
            qApp.processEvents()
            status = map(Thread.isAlive, self.threads)

        self.progressBarBackup.setMaximum(100)
        self.progressBarBackup.setValue(100)
        if self.files_to_restore:
            files_count = sum(
                len(f) for cat in self.files_to_restore.values()
                for date in cat.values() for f in date.values()[0])
            self.progressBarBackup.setMaximum(files_count)
            self.progressBarBackup.setValue(0)
            dialog = Restore_type(self)
            dialog.setModal(True)
            self.prev_or_spec, self.path_to_restore, ok = dialog.call(self)
            if ok:
                for storage, categories in self.files_to_restore.items():
                    dialog = QInputDialog()
                    dialog.setModal(True)
                    key, ok = dialog.getText(
                        self,
                        "Key",
                        "Enter key for <b>%s</b> storage" % storage,
                        mode=QLineEdit.Password)
                    if ok:
                        try:
                            key = str(key)
                            with open(
                                    self.current_dir + storage + sep + "init",
                                    'rb') as f:
                                hash_from_storage = f.read(64)
                                cipter_text = f.read()
                                encryptor = AES.new(key +
                                                    self.padding[len(key):])
                                plain = encryptor.decrypt(cipter_text)
                                if hash_from_storage == SHA256.new(
                                        plain).hexdigest():
                                    for cat, backups in categories.items():
                                        sorted_by_date = sorted(
                                            backups.keys(), key=lambda x: x)
                                        for backup in sorted_by_date:
                                            for fn in backups[backup]:
                                                path_to_file = self.current_dir + storage + sep + backup + sep + cat + sep + fn
                                                self.decrypt_and_save(
                                                    path_to_file,
                                                    key,
                                                    new_path=self.
                                                    path_to_restore + sep + cat
                                                    if not self.prev_or_spec
                                                    else '')
                                                self.progressBarBackup.setValue(
                                                    self.progressBarBackup.
                                                    value() + 1)
                                    self.progressBarBackup.setValue(
                                        self.progressBarBackup.maximum())
                                else:
                                    QMessageBox.about(self, "Error",
                                                      "Incorrect password!")
                        except UnicodeError:
                            QMessageBox.about(self, "Error",
                                              "Incorrect password!")
        else:
            QMessageBox.about(
                self, "Error",
                "Select the storage/backup/file before restoring!")
        self.restoreButton.setEnabled(True)
 def method_20(self, message):
     QMessageBox.information(self, "Result", message)
Example #54
0
 def addSlTask(self):
     index = self.komandTableView.currentIndex()
     print 'INDEX', index.row()
     if not index.isValid():
         print 'Index is not valid'
         QMessageBox.warning(self, u"Добаление записки", u"Сделайте выбор командировки")
         return
     selEmplDialog = SelectEmployeeDialog()
     if not selEmplDialog.exec_():
         return
     index = selEmplDialog.tableView.currentIndex()
     if not index.isValid():
         return
     row = index.row()
     employee = selEmplDialog.model.data[row]
     komand = self.model.data[index.row()]
     dialog = SlTaskDialog()
     dialog.dateEdit.setDate(QDate.currentDate())
     dialog.lineEdit_9.setText(komand.komand_zadan)
     dialog.lineEdit_6.setText(komand.komand_addr)
     dialog.lineEdit_7.setText(komand.komand_org)
     dialog.dateEdit_2.setDate(komand.komand_start)
     dialog.dateEdit_3.setDate(komand.komand_end)
     dialog.lineEdit_8.setText(komand.komand_cos)
     dialog.lineEdit_2.setText(employee.family+' '+employee.name+' '+employee.sname)
     dialog.lineEdit_3.setText(str(employee.tab_num))
     position = session.query(Position).filter_by(pos_id = employee.position).one()
     dialog.lineEdit_5.setText(position.pos_name)
     dept = session.query(Dept).filter_by(dept_id = position.dept).one()
     group = session.query(Group).filter_by(group_id = position.group).one()
     dialog.lineEdit_4.setText(dept.dept_long_name+' '+group.group_long_name)
     if not dialog.exec_():
         print 'Not Add slTask'
         return
     servrecord = ServRecord(
             komand.komand_id, 
             int(unicode(dialog.lineEdit.text())), #record_num 
             date(dialog.dateEdit.date().year(),
                 dialog.dateEdit.date().month(),
                 dialog.dateEdit.date().day()), #record_date 
             unicode(dialog.lineEdit_2.text()), #record_fio 
             int (dialog.lineEdit_3.text()), #record_tabnum
             unicode(dialog.lineEdit_4.text()), #record_str_podr 
             unicode(dialog.lineEdit_5.text()), #record_dolg 
             unicode(dialog.lineEdit_6.text()), #record_addr 
             unicode(dialog.lineEdit_7.text()), #record_ org
             date(dialog.dateEdit_2.date().year(), 
                 dialog.dateEdit_2.date().month(), 
                 dialog.dateEdit_2.date().day()), #record_start
             date(dialog.dateEdit_3.date().year(), 
                 dialog.dateEdit_3.date().month(), 
                 dialog.dateEdit_3.date().day()), #record_end 
             unicode(dialog.lineEdit_9.text()), #record_zadan
             unicode(dialog.lineEdit_8.text()), #record_osn 
             unicode(dialog.lineEdit_10.text()),#record_ruk_str_otpr_dolg, 
             unicode(dialog.lineEdit_11.text()),#record_ruk_str_otpr_fio, 
             unicode(dialog.lineEdit_12.text()),#record_ruk_str_prin_dolg, 
             unicode(dialog.lineEdit_13.text()),#record_ruk_str_prin_fio, 
             unicode(dialog.lineEdit_14.text()),#record_ruk_org_dolg, 
             unicode(dialog.lineEdit_15.text())#record_ruk_org_fio
             )
     self.sltaskmodel.emit(SIGNAL("layoutAboutToBeChanged()"))
     session.add(servrecord)
     session.commit()
     self.sltaskmodel.data = session.query(ServRecord).all()
     self.sltaskmodel.emit(SIGNAL("layoutChanged()"))
     self.servrecTableView.reset()
Example #55
0
class BDGExTools(QObject):
    def __init__(self, parent=None):
        """
        Constructor
        """
        super(BDGExTools, self).__init__()

        self.wmtsDict = dict()
        self.wmtsDict['1:250k'] = 'ctm250'
        self.wmtsDict['1:100k'] = 'ctm100'
        self.wmtsDict['1:50k'] = 'ctm50'
        self.wmtsDict['1:25k'] = 'ctm25'
        self.wmtsDict['Landsat7'] = 'landsat7'
        self.wmtsDict['RapidEye'] = 'rapideye'
        pass

    def __del__(self):
        pass

    def setUrllibProxy(self, url):
        """
        Sets the proxy
        """
        (enabled, host, port, user, password, type,
         urlsList) = self.getProxyConfiguration()
        if enabled == 'false' or type != 'HttpProxy':
            return

        for address in urlsList:
            if address in url:
                proxy = urllib2.ProxyHandler({})
                opener = urllib2.build_opener(proxy, urllib2.HTTPHandler)
                urllib2.install_opener(opener)
                return

        proxyStr = 'http://' + user + ':' + password + '@' + host + ':' + port
        proxy = urllib2.ProxyHandler({'http': proxyStr})
        opener = urllib2.build_opener(proxy, urllib2.HTTPHandler)
        urllib2.install_opener(opener)
        return

    def getProxyConfiguration(self):
        """
        Gets the proxy configuration from QSettings
        """
        settings = QSettings()
        settings.beginGroup('proxy')
        enabled = settings.value('proxyEnabled')
        host = settings.value('proxyHost')
        port = settings.value('proxyPort')
        user = settings.value('proxyUser')
        password = settings.value('proxyPassword')
        type = settings.value('proxyType')
        excludedUrls = settings.value('proxyExcludedUrls')
        try:
            urlsList = excludedUrls.split('|')
        except:
            urlsList = []
        settings.endGroup()
        return (enabled, host, port, user, password, type, urlsList)

    def getTileCache(self, layerName):
        """
        Makes the requisition to the tile cache service
        """
        url = "http://www.geoportal.eb.mil.br/mapcache?request=GetCapabilities"
        # set proxy
        self.setUrllibProxy(url)

        try:
            getCapa = urllib2.Request(url,
                                      headers={'User-Agent': "Magic Browser"})
            resp = urllib2.urlopen(getCapa)
            response = resp.read()
        except urllib2.URLError, e:
            QMessageBox.critical(None, self.tr("URL Error!"),
                                 '{0}\nReason: {1}'.format(e.args, e.reason))
            return None
        except urllib2.HTTPError, e:
            QMessageBox.critical(None, self.tr("HTTP Error!"),
                                 '{0}\nReason: {1}'.format(e.code, e.msg))
            return None
Example #56
0
 def changeModoAutomat(self):
     if self.confirmaChangeModo():
         self.setCentralWidget(ModoAutomatizacionView())
         QMessageBox.information(self, "Cambio de Modo",
                                 "Se cambio a Modo Automatizacion",
                                 QMessageBox.Ok)
Example #57
0
        # print homedir
        if not os.path.isdir(homedir):
            os.mkdir(homedir)

    # Create the Qt Application

    app = QApplication(sys.argv)
    backend = Backend()

    # Create and show the forms
    if sys.platform.startswith('win'):
        # Make sure the program is running w/ administrative privileges.
        import win32api
        from win32com.shell import shell, shellcon
        if not shell.IsUserAnAdmin():
            alertBox = QMessageBox()
            alertBox.setText(
                "You may need to run this program as an Administrator. If it doesn't work please close this program, and run it by right clicking and choose 'Run As Administrator' "
            )
            alertBox.show()
        #get the MS AppData directory to store data in
        homedir = "{}\\".format(
            shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0))
        if not os.path.isdir("{0}{1}".format(homedir, "SelfRestraint")):
            os.mkdir("{0}{1}".format(homedir, "SelfRestraint"))
        homedir = homedir + "\\SelfRestraint\\"

    updater = checkForUpdates()
    updater.check()
    donate = checkDonation()
    form = MainForm()
Example #58
0
    def openRemote(self):
        try:
            #QMessageBox.about(self.dlg, "Remote Projects", "Open Remote Projects...")
            local = []
            remote = []
            #build list of remote index
            url = "https://raw.githubusercontent.com/sopac/pacsafe-projects/master/{0}/index.txt".format(
                self.countryList[self.cv].lower())

            request = urllib2.Request(url,
                                      headers={'User-Agent': 'Mozilla/5.0'})
            response = urllib2.urlopen(request, timeout=100)
            #response = urllib2.urlopen(url)
            for l in response:
                if l.strip().endswith(".qgs"):
                    #print l.strip()
                    remote.append(l.strip())

            #build local list
            path = os.path.join(self.dataPath,
                                self.countryList[self.cv].upper())
            for f in os.listdir(path):
                if f.endswith(".qgs"):
                    local.append(f.strip())

            #compare list
            flist = local + remote
            flist = list(set(flist))
            #print flist
            getlist = []
            for f in flist:
                if f not in local:
                    getlist.append(f)

            msg = "There are no new remote projects available for {0}.".format(
                self.cv)
            sync = False

            if len(getlist) > 0:
                sync = True
                diff = len(getlist)
                msg = "There are " + str(
                    diff
                ) + " new project(s) available for {0}.\r\nClick Ok To Synchronise.".format(
                    self.cv)

            QMessageBox.about(self.dlg, "Remote Projects", msg)

            if sync == True:
                #sync/download new layers
                for n in getlist:
                    print n
                    p_url = "https://raw.githubusercontent.com/sopac/pacsafe-projects/master/{0}".format(
                        self.countryList[self.cv]) + n
                    request = urllib2.Request(
                        url, headers={'User-Agent': 'Mozilla/5.0'})
                    tf = urllib2.urlopen(request, timeout=100)
                    #tf = urllib2.urlopen()
                    with open(path + "/" + n, "wb") as lf:
                        lf.write(tf.read())

                #refresh project listing
                self.dlg.listWidget.clear()
                for f in os.listdir(path):
                    if f.endswith(".qgs"):
                        f = f.replace(".qgs", "")
                        f = f.replace("_", " ")
                        f = f.title()
                        item = QListWidgetItem(f)
                        self.dlg.listWidget.addItem(item)
                QMessageBox.about(self.dlg, "Remote Projects",
                                  ("Remote Projects Synchronised.\r\n"
                                   "Please Reopen PacSAFE Project Opener."))
                self.dlg.close()

        except:
            e = sys.exc_info()[0]
            e = traceback.format_exc()
            QMessageBox.critical(
                None, 'Error!',
                "Error Occurred, Ensure Internet Connectivity.\r\n" + str(e),
                QMessageBox.Abort)
    def new_config(self):
        dialog = ExpandingInputDialog(get_main_window())
        dialog.setModal(True)
        dialog.setWindowTitle('New Config File')
        dialog.setLabelText('Enter name for new openHAB config file:')
        dialog.setInputMode(QInputDialog.TextInput)
        dialog.setOkButtonText('Create')

        if dialog.exec_() != QDialog.Accepted:
            return

        name = dialog.textValue()

        # check that new name is valid as filename
        if len(name) == 0 or name == '.' or name == '..' or '/' in name:
            QMessageBox.critical(
                get_main_window(), 'New Config File Error',
                'A config file name cannot be empty, cannot be one dot [.], cannot be two dots [..] and cannot contain a forward slash [/].'
            )
            return

        endswith_items = name.endswith('.items')
        endswith_sitemap = name.endswith('.sitemap')
        endswith_rules = name.endswith('.rules')
        endswith_persist = name.endswith('.persist')
        endswith_script = name.endswith('.script')
        endswith_transform = name.endswith('.transform')

        if not endswith_items and not endswith_sitemap and not endswith_rules and not endswith_persist and not endswith_script and not endswith_transform:
            QMessageBox.critical(
                get_main_window(), 'New Config File Error',
                'A config file name has to end with .items, .sitemap, .rules, .persist, .script or .transform.'
            )
            return

        if name in [
                '.items', '.sitemap', '.rules', '.persist', '.script',
                '.transform'
        ]:
            QMessageBox.critical(
                get_main_window(), 'New Config File Error',
                '.items, .sitemap, .rules, .persist, .script and .transform cannot be used as config file names.'
            )
            return

        if endswith_items:
            if self.image_version.number < (1, 10):
                target_path = posixpath.join('/', 'etc', 'openhab',
                                             'configurations', 'items', name)
            else:
                target_path = posixpath.join('/', 'etc', 'openhab2', 'items',
                                             name)
        elif endswith_sitemap:
            if self.image_version.number < (1, 10):
                target_path = posixpath.join('/', 'etc', 'openhab',
                                             'configurations', 'sitemaps',
                                             name)
            else:
                target_path = posixpath.join('/', 'etc', 'openhab2',
                                             'sitemaps', name)
        elif endswith_rules:
            if self.image_version.number < (1, 10):
                target_path = posixpath.join('/', 'etc', 'openhab',
                                             'configurations', 'rules', name)
            else:
                target_path = posixpath.join('/', 'etc', 'openhab2', 'rules',
                                             name)
        elif endswith_persist:
            if self.image_version.number < (1, 10):
                target_path = posixpath.join('/', 'etc', 'openhab',
                                             'configurations', 'persistence',
                                             name)
            else:
                target_path = posixpath.join('/', 'etc', 'openhab2',
                                             'persistence', name)
        elif endswith_script:
            if self.image_version.number < (1, 10):
                target_path = posixpath.join('/', 'etc', 'openhab',
                                             'configurations', 'scripts', name)
            else:
                target_path = posixpath.join('/', 'etc', 'openhab2', 'scripts',
                                             name)
        elif endswith_transform:
            if self.image_version.number < (1, 10):
                target_path = posixpath.join('/', 'etc', 'openhab',
                                             'configurations', 'transform',
                                             name)
            else:
                target_path = posixpath.join('/', 'etc', 'openhab2',
                                             'transform', name)

        def cb_open(red_file):
            red_file.release()

            def select_new():
                index = -1

                for config in self.configs:
                    if config != None and config.display_name == name:
                        index = config.index

                if index >= 0:
                    self.combo_config.setCurrentIndex(index)

            self.refresh_all_configs(select_new)

        def cb_open_error(error):
            if isinstance(error, REDError
                          ) and error.error_code == REDError.E_ALREADY_EXISTS:
                QMessageBox.critical(
                    get_main_window(), 'New Config File Error',
                    'Config file {0} already exists.'.format(name))
            else:
                QMessageBox.critical(
                    get_main_window(), 'New Config File Error',
                    'Could not create config file {0}:\n\n{1}'.format(
                        name, error))

        async_call(REDFile(self.session).open,
                   (target_path, REDFile.FLAG_WRITE_ONLY | REDFile.FLAG_CREATE
                    | REDFile.FLAG_EXCLUSIVE, 0o644, 0, 0),
                   cb_open,
                   cb_open_error,
                   report_exception=True)
Example #60
0
            resp = urllib2.urlopen(getCapa)
            response = resp.read()
        except urllib2.URLError, e:
            QMessageBox.critical(None, self.tr("URL Error!"),
                                 '{0}\nReason: {1}'.format(e.args, e.reason))
            return None
        except urllib2.HTTPError, e:
            QMessageBox.critical(None, self.tr("HTTP Error!"),
                                 '{0}\nReason: {1}'.format(e.code, e.msg))
            return None

        try:
            myDom = parseString(response)
        except:
            QMessageBox.critical(
                None, self.tr("Parse Error!"),
                self.tr('Invalid GetCapabilities response: \n{0}').format(
                    response))
            return None

        qgsIndexDict = dict()
        count = 0

        for tileMap in myDom.getElementsByTagName("Layer"):
            qgsIndexDict[tileMap.getElementsByTagName("Name")
                         [0].firstChild.nodeValue] = count
            count += 1

        tileMatrixSet = '{0}-wmsc-{1}'.format(
            self.wmtsDict[layerName], qgsIndexDict[self.wmtsDict[layerName]])
        return 'crs=EPSG:4326&dpiMode=7&featureCount=10&format=image/png&layers={0}&styles=&url=http://www.geoportal.eb.mil.br/mapcache'.format(
            self.wmtsDict[layerName])