Example #1
0
 def accept(self):
     """Función de aceptación del dialogo. 
     Avisa al usuario si los datos han sido introducidos incorrectamente, y genera"""
     if self.lineEdit1.text():
         from Driza.excepciones import VariableExisteException
         sobreescritura = self.checkBox1.isChecked()
         solofiltrado = False
         if sobreescritura:
             if self.checkBox2.isChecked():
                 solofiltrado = True
         try:
             self.__idu.ana_var_expresion(self.lineEdit1.text().latin1(), self.comboBox1.currentText().latin1(), \
                     "NA", self.lineEdit2.text(),self.textEdit1.text().latin1(), \
                     permitirsobreescritura=sobreescritura, solofiltrados=solofiltrado)
         except (SyntaxError,NameError):
             #La expresión no es correcta, mostramos un mensaje de error
             LOG.exception("Excepción al añadir la variable con la expresión")
             QErrorMessage(self, "error").message(u"La expresión no es correcta")
             self.__idu.borrar_var(self.lineEdit1.text().latin1()) #Borrar la variable que está a medias
         except (ZeroDivisionError,OverflowError):
             QErrorMessage(self, "error").message(u"La expresión genera un desbordamiento")
         except VariableExisteException:
             QMessageBox.warning(self, u"atención", u"La variable ya existe")
         except TypeError:
             QErrorMessage(self, "error").message(u"El tipo de variable no coincide con el existente")
             LOG.exception("Excepción al añadir la variable con la expresión")
         else:
             DialogoCrevar.accept(self)
             self.parent().grid.myUpdate()
     else:
         returncode = QMessageBox.warning(self, 'Atencion', \
                 'No has rellenado todos los campos', \
                 'Volver al dialogo', 'Salir', '', 0, 1 )
         if returncode == 1:
             self.reject()
Example #2
0
 def __guardar_como(self):
     """Abre un diálogo pidiendo el nombre de archivo y guarda en dicho archivo"""
     filtro = ""
     for fmt in SL.extensiones_fichero:
         filtro = filtro+ "%s files (*.%s);;" % (fmt, fmt.lower())
     filename = QFileDialog.getSaveFileName(QString.null, filtro, self)
     filename = str(filename)
     if filename:
         from Driza.excepciones import FicheroExisteException, FicheroTipoDesconocidoException
         import re
         extension = re.compile('.*\..*')
         if not extension.match(filename):
             filename += ".driza"
         try:
             self.__gestorproyectos.guardar(filename)
         except FicheroExisteException, fichero:
             returncode = QMessageBox.information(self, 'Atencion:', 'El fichero' + fichero.fichero + ' ya existe' , 'Sobreescribir', 'Otro nombre', 'Cancelar', 0, 1)
             if returncode == 0:
                 self.__gestorproyectos.guardar(filename, True)
                 self.__idu.establecer_original()
                 self.__myUpdate()
             elif returncode == 1:
                 self.__guardarcomo()
         except FicheroTipoDesconocidoException:
             QMessageBox.warning(self, u'Atención', u'La extensión del fichero es incorrecta.\nPruebe con otra extensión')
             self.__gestorproyectos.fichero = None
Example #3
0
 def __insertar_registro(self):
     """Inserta un registro, devolviendo un mensaje si ha habido un error"""
     try:
         self.grid.insertar_reg()
     except AssertionError:
         QMessageBox.warning(self, u'Atención', u'Error en la inserción')
         LOG.exception("excepcion capturada al insertar")
Example #4
0
 def __actualizar_reg_interfazdatos(self, row, col, valor):
     """actualiza un dato en interfazdatos,recogiendo la excepcion en caso de error """
     LOG.debug("Actualizando datos de la interfaz:" + str(row) + "," + str(col))
     try:
         self.__idu[row][col] = valor
     except ValueError:
         QMessageBox.warning(self, 'Atención', u'El dato no es válido')
Example #5
0
    def slotAcceptData(self):
        tabForm=self.tabs[0][0]
        rec = self.tabs[0][1]
        for field, fieldDef in tabForm.fieldList:
            if fieldDef.readonly:
                continue
            elif fieldDef.relation <> None: #combobox
                if field == "usernr":
                    rec.updateUser()
                else:
                    rec.setFieldValue(rec.getDescriptorColumnName(field),
                                      tabForm.getFieldText(field))
                    fieldDef.default = tabForm.getFieldValue(field)
                    rec.setFieldValue(field, tabForm.getFieldValue(field))
            else:
                rec.setFieldValue(field, tabForm.getFieldValue(field))
            #print "Type ", type(getattr(rec, field))
        if self.mode == constants.INSERT:
            try:
                rec.insert()
                self.mode = constants.UPDATE
            except dbexceptions.dbError, dberr:
                QMessageBox.information(self, "Kura Error while inserting"
                                        , dberr.errorMessage)
                return False
            self.emit(PYSIGNAL("sigAcceptNewData"), (rec,))

            self.mode = constants.UPDATE
Example #6
0
 def __buscar(self):
     """ Funcion busca la cadena de texto introducida por el usuario en la tabla que este activa, seleccionando el primer registro válido que encuentre"""
     if not self.lineEdit1.text().latin1():
         return
     if self.parent().grid.currentPageIndex() == 0: 
         tablaactual = self.parent().grid.table1
     else: 
         tablaactual = self.parent().grid.table2
     fila = tablaactual.currentRow()
     columna = tablaactual.currentColumn()
     textoabuscar = self.lineEdit1.text().latin1()
     LOG.debug("Busqueda de " + textoabuscar)
     resultado = self.__buscarinterno(tablaactual, textoabuscar, fila, columna)
     if resultado:
         LOG.debug("Resultado encontrado en la primera columna")
         tablaactual.clearSelection()
         tablaactual.setCurrentCell(resultado[0], resultado[1])
         self.accept()
         return
     codigoretorno = QMessageBox.warning(self, 'Atencion', 'No he encontrado nada', '¿Continuar desde el principio?', 'Salir', '', 0, 1)
     if codigoretorno == 1:
         self.reject()
         return
     resultado = self.__buscarinterno(tablaactual, textoabuscar)
     if resultado:
         tablaactual.clearSelection()
         tablaactual.setCurrentCell(resultado[0], resultado[1])
         self.accept()
         return
     codigoretorno = QMessageBox.warning(self, 'Atencion', 'No he encontrado nada', 'Otra busqueda', 'Salir', '', 0, 1)
     if codigoretorno == 1:
         self.reject()
     else:
         self.lineEdit1.clear()
     return
 def setSource(self, url):
     #action, key, filename = split_url(url)
     action, name = split_url(url)
     filehandler = self.app.game_fileshandler
     if action == 'cleanup':
         filehandler.cleanup_game(name)
     elif action == 'prepare':
         filehandler.prepare_game(name)
     elif action == 'edit':
         dlg = EditGameDataDialog(self, name)
         dlg.show()
     elif action == 'set_title_screenshot':
         self.select_title_screenshot(name)
     elif action == 'open_weblink':
         # get gamedata from doc object
         # to keep from excessive xml parsing
         gamedata = self.doc.gamedata
         cmd = self.app.myconfig.get('externalactions', 'launch_weblink')
         # for these url's, the name is the site
         weblink_url = gamedata['weblinks'][name]
         if '%s' in cmd:
             os.system(cmd % weblink_url)
         else:
             os.system("%s '%s'" % (cmd, weblink_url))
         # now we reset the name variable to reset the page properly
         name = gamedata['name']
     else:
         QMessageBox.information(self, '%s is unimplemented.' % action)
     # refresh the page
     self.set_game_info(name)
     # need to emit signal here for mainwin to pick up
     # this method is ugly
     if action in ['cleanup', 'prepare', 'edit']:
         mainwin = self.parent().parent()
         mainwin.refreshListView()
Example #8
0
    def __modificacion_t_var(self, fila, columna):
        """Funcion a que conecta con la introduccion de nuevos datos en la tabla de variables"""
        if columna == 1 and (self.table2.text(fila, columna).latin1() == self.__idu.var(fila).tipo):
            return # Se ha solicitado un cambio de tipo al propio tipo
        self.__portero.guardar_estado()
        if fila >= self.__idu.n_var(): #Es una nueva variable
            #Variables intermedias (creadas con los valores por defecto)
            for valorintermedio in range (self.__idu.n_var(), fila):
                self.__insertar_variable()
                self.__mostrar_var(valorintermedio)
            self.__insertar_variable()
        #Variable modificada
        variable = self.__idu.var(fila)
        if columna == 1:   # El usuario quiere cambiar el tipo
            textoencuestion = self.table2.text(fila, columna).latin1() 
            #preguntar el tipo de conversion
            metododeseado = self.__preguntar_conversion(variable, textoencuestion)
            if metododeseado:
                variable, columna = self.__agenteconversion(variable, textoencuestion, metododeseado) #Pareja variable-list
                self.__idu.establecer_var(fila, variable, columna)
                self.__mostrar_t_reg()  
        else: #Restos de campos (Texto)
            from Driza.excepciones import VariableExisteException
            try:
                self.__idu.modificar_var(variable, columna, str(self.table2.text(fila, columna).latin1()))
            except VariableExisteException:
                QMessageBox.warning(self, u'Atención', u'El nombre de variable ya existe')
            except NameError:
                QMessageBox.warning(self, u'Atención', u'Nombre de variable Erróneo')

        self.__mostrar_var(fila)
        #En todos los casos, actualizamos el titulo de la tabla de datos
        self.__mostrar_titulo_t_reg()
def main():
    if not os.path.exists(os.path.expanduser("~/.pyqlogger")):
        os.mkdir(os.path.expanduser("~/.pyqlogger"))
    settings = Settings.Settings.load()
    UI.prepareModule(settings)
    app = UI.API.KQApplication(sys.argv, None)
    stat = UI.API.prepareCommandLine()
    pic = QPixmap(150, 50)
    pic.fill()
    loginsplash = QSplashScreen(pic)
    pixmap = QPixmap("splash.png")
    splash = QSplashScreen(pixmap)
    splash.show()
    splash.message("Loading forms...", alignflag)
    qApp.processEvents()
    load_forms(splash, app, settings)
    splash.message("Loading plugins...", alignflag)
    qApp.processEvents()
    manager = Manager.load(__FORMS__["Main"]["Impl"])
    del splash
    acc = None
    pwd = None
    if settings.AutoLogin:  # check if we have auto login info
        acc = settings.accountByName(settings.AutoLogin)
        pwd = acc.Password

    while True:
        if not acc:
            wnd = __FORMS__["Login"]
            if wnd["Impl"].init(settings, __FORMS__, manager):
                if wnd["Class"].exec_loop() == QDialog.Accepted:
                    acc = wnd["Impl"].acc
                    pwd = str(wnd["Impl"].edtPassword.text())
        if not acc or not pwd:
            break
        else:
            (acc.Password, oldpwd) = (pwd, acc.Password)
            acc.init()
            loginsplash.show()
            loginsplash.message("Logging in...", Qt.AlignCenter)
            logres = acc.login()
            loginsplash.hide()
            acc.Password = oldpwd
            if not logres:
                QMessageBox.warning(None, "Failed!", """Cannot login!""")
                acc = None
            else:
                wnd = __FORMS__["Main"]
                acc.init()
                wnd["Impl"].init(settings,__FORMS__, acc, pwd,\
                                 manager)
                app.setMainWidget(wnd["Class"])
                wnd["Class"].show()
                #splash.finish(wnd["Class"])
                app.exec_loop()
                if wnd["Impl"].reload:
                    acc = None
                else:
                    break
def main():
    if not os.path.exists(os.path.expanduser("~/.pyqlogger")):
        os.mkdir(os.path.expanduser("~/.pyqlogger"))    
    settings = Settings.Settings.load()
    UI.prepareModule(settings)
    app =  UI.API.KQApplication(sys.argv, None)
    stat = UI.API.prepareCommandLine()    
    pic = QPixmap ( 150, 50)
    pic.fill()
    loginsplash = QSplashScreen( pic )
    pixmap = QPixmap( "splash.png" )
    splash = QSplashScreen( pixmap )
    splash.show()
    splash.message( "Loading forms...",alignflag )
    qApp.processEvents()
    load_forms(splash,app,settings)
    splash.message( "Loading plugins...",alignflag )
    qApp.processEvents()
    manager = Manager.load(__FORMS__["Main"]["Impl"])
    del splash
    acc = None
    pwd = None
    if settings.AutoLogin: # check if we have auto login info
        acc = settings.accountByName(settings.AutoLogin)
        pwd = acc.Password

    while True:
        if not acc:
            wnd = __FORMS__["Login"]
            if wnd["Impl"].init(settings,__FORMS__,manager):
                if wnd["Class"].exec_loop() == QDialog.Accepted:
                    acc = wnd["Impl"].acc
                    pwd = str(wnd["Impl"].edtPassword.text())
        if not acc or not pwd:
            break
        else:
            (acc.Password,oldpwd) = (pwd,acc.Password)            
            acc.init()
            loginsplash.show()
            loginsplash.message( "Logging in...",Qt.AlignCenter)            
            logres = acc.login()
            loginsplash.hide()
            acc.Password = oldpwd
            if not logres:
                QMessageBox.warning(None,"Failed!","""Cannot login!""")
                acc = None
            else:
                wnd = __FORMS__["Main"]
                acc.init()
                wnd["Impl"].init(settings,__FORMS__, acc, pwd,\
                                 manager)
                app.setMainWidget(wnd["Class"])
                wnd["Class"].show()
                #splash.finish(wnd["Class"])
                app.exec_loop()
                if wnd["Impl"].reload:
                    acc = None
                else:
                    break
Example #11
0
 def __copiar(self):
     """Funcion que copia y borra la seleccion"""
     try:
         self.__copiar_privado()
     except AssertionError:
         QMessageBox.warning(self, u'Atención', 'Las operaciones de copiado, cortado y pegado no han sido implementadas')
     else:
         self.grid.borrar_seleccion() 
 def btnFetchUrl_clicked(self):
     bc = BloggerClient(str(self.editHost.text()), str(self.editLogin.text()), str(self.editPassword.text()))
     try:
         url = bc.getHomepage(self.blogs[unicode(self.comboBlogs.currentText())]['id'])
         if url:
             self.editURL.setText(url)
     except Exception, inst:
         print "btnFetchUrl_clicked: %s" % inst
         QMessageBox.critical(self, "Error", "Couldn't fetch blog's URL!")
Example #13
0
	def FindgiFTexec(self):
		self.config.OptionList["giFTexecLoc"] = ""
		for x in self.pathArray:
			if os.access(x, os.X_OK):
				self.config.OptionList["giFTexecLoc"] = x
				break
		if len(self.config.OptionList["giFTexecLoc"]) == 0: ## Binary not found
			QMessageBox.warning(self.win, "giFT executable not found!", "LokiPoki couldn't find your 'giFT' server binary.  \nPlease press \"ok\" to select it manually.")
			filename= str(QFileDialog.getOpenFileName("giFT", "giFT", self.win, "Find giFT executable"))
			self.config.OptionList["giFTexecLoc"] = filename
Example #14
0
 def __init__(self, swappers):
     QMessageBox.__init__(self)
     decorateWindow(self, m18n("Swap Seats"))
     self.setText(
         m18n("By the rules, %1 and %2 should now exchange their seats. ",
              swappers[0].name, swappers[1].name))
     self.yesAnswer = QPushButton(m18n("&Exchange"))
     self.addButton(self.yesAnswer, QMessageBox.YesRole)
     self.noAnswer = QPushButton(m18n("&Keep seat"))
     self.addButton(self.noAnswer, QMessageBox.NoRole)
Example #15
0
 def __dacerca_de(self):
     """Mensaje acerca de"""
     from Driza import VERSION
     separador = "\n----------------------------------\n"
     betatesters = u"Carlos Mestre Gonzalez\n Luis de Bethencourt Guimerá"
     iconos = "Iconos del Tango Desktop Project: http://tango.freedesktop.org/"
     ristra = u"Driza %s es una interfaz estadística\n (C) Néstor Arocha Rodríguez - Tutorizado por Inmaculada luengo Merino\n Distribuido bajo licencia GPL" +\
             separador + "Betatesters:\n" + betatesters + separador +\
             u" Mantenedor del paquete .deb:\n Luis de Bethencourt Guimerá"+ separador + iconos
     QMessageBox.about(self, "Acerca de Driza", ristra % (VERSION))
Example #16
0
 def __init__(self, swappers):
     QMessageBox.__init__(self)
     decorateWindow(self, i18n("Swap Seats"))
     self.setText(
         i18n("By the rules, %1 and %2 should now exchange their seats. ",
              swappers[0].name, swappers[1].name))
     self.yesAnswer = QPushButton(i18n("&Exchange"))
     self.addButton(self.yesAnswer, QMessageBox.YesRole)
     self.noAnswer = QPushButton(i18n("&Keep seat"))
     self.addButton(self.noAnswer, QMessageBox.NoRole)
Example #17
0
    def addChildDataTypesSlot(self):
        """ Adds the selected data types from the list of available data types to the list of child data types. """

        if self._relationTypeView.mySelectedAvailableDataTypeList == []:
            QMessageBox.information(self._parentFrame, self._parentFrame.tr("DataFinder: No Selection"),
                                          "Please select a Data Type to add!",
                                          self._parentFrame.tr("OK"), "", "",
                                          0, -1)
        else:
            self._relationTypeModel.addChildDataTypes(self._relationTypeView.mySelectedAvailableDataTypeList)
            self._relationTypeView.setButtonsState(True)
Example #18
0
    def removeChildDataTypesSlot(self):
        """ Removes the selected data type from the list of parent data types. """

        if self._relationTypeView.mySelectedChildDataTypeList == []:
            QMessageBox.information(self._parentFrame, self._parentFrame.tr("DataFinder: No Selection"),
                                          "Please select a Data Type to remove!",
                                          self._parentFrame.tr("OK"), "", "",
                                          0, -1)
        else:
            self._relationTypeModel.removeChildDataTypes(self._relationTypeView.mySelectedChildDataTypeList)
            self._relationTypeView.setButtonsState(True)
 def btnFetchUrl_clicked(self):
     bc = BloggerClient(str(self.editHost.text()),
                        str(self.editLogin.text()),
                        str(self.editPassword.text()))
     try:
         url = bc.getHomepage(self.blogs[unicode(
             self.comboBlogs.currentText())]['id'])
         if url:
             self.editURL.setText(url)
     except Exception, inst:
         print "btnFetchUrl_clicked: %s" % inst
         QMessageBox.critical(self, "Error", "Couldn't fetch blog's URL!")
 def btnRefresh_clicked(self):
     if str(self.editUrl.text()):
         try:
             img = urllib2.urlopen(str(self.editUrl.text())).read()
             pic = QPixmap()
             pic.loadFromData(img)
             if not str(self.editWidth.text()):
                 self.editWidth.setText(str(pic.width()))
             if not str(self.editHeight.text()):
                 self.editHeight.setText(str(pic.height()))
             self.previewImage.setPixmap(pic)
         except:
             QMessageBox.warning(self, "Warning", "Cannot open the image url!")
Example #21
0
    def removeAttributeSlot(self):
        """ Removes selected rows/attributes. """

        if self._dataTypeView.propertyTable.currentSelection() == -1:
            QMessageBox.information(self._parentFrame, self._parentFrame.tr("DataFinder: No Selection"),
                                          "Please select a row to remove!",
                                          self._parentFrame.tr("OK"), "", "",
                                          0, -1)
        else:
            for index in self._dataTypeView.mySelectedRowList:
                self._dataTypeView.propertyTable.removeRow(index)
            self._dataTypeModel.myPropertyList = self._dataTypeView.myPropertyList
            self._dataTypeView.setButtonsState(True)
 def select_title_screenshot(self, name):
     if self.select_title_screenshot_dlg is None:
         file_filter = "*.png|PNG Images\n*|All Files"
         path = self.app.dosbox.get_capture_path(name)
         dlg = QFileDialog(path, file_filter, self, 'select_title_screenshot_dlg', True)
         dlg.connect(dlg, SIGNAL('okClicked()'), self.title_screenshot_selected)
         dlg.connect(dlg, SIGNAL('cancelClicked()'), self.destroy_select_title_screenshot_dlg)
         dlg.connect(dlg, SIGNAL('closeClicked()'), self.destroy_select_title_screenshot_dlg)
         dlg.game_name = name
         dlg.show()
         self.select_title_screenshot_dlg = dlg
     else:
         # we shouldn't need this with a modal dialog
         QMessageBox.information(self, opendlg_errormsg)
Example #23
0
 def __cortar(self):
     """Copia, borra la seleccion y su contenido"""
     from Driza.excepciones import SeleccionIncorrectaException
     try:
         self.grid.verificar_seleccion_registros()
         self.__portero.guardar_estado()
         self.__copiar_privado()
     except SeleccionIncorrectaException:
         QMessageBox.warning(self, u'Atención', 'Solo se permite cortar registros')
     except AssertionError:
         QMessageBox.warning(self, u'Atención', 'Las operaciones de copiado, cortado y pegado no han sido implementadas')
     else:
         self.grid.borrar_seleccion(borrardatos=True)
         self.grid.myUpdate()
Example #24
0
    def removeAttributeSlot(self):
        """ Removes selected rows/attributes. """

        if self._dataTypeView.propertyTable.currentSelection() == -1:
            QMessageBox.information(
                self._parentFrame,
                self._parentFrame.tr("DataFinder: No Selection"),
                "Please select a row to remove!", self._parentFrame.tr("OK"),
                "", "", 0, -1)
        else:
            for index in self._dataTypeView.mySelectedRowList:
                self._dataTypeView.propertyTable.removeRow(index)
            self._dataTypeModel.myPropertyList = self._dataTypeView.myPropertyList
            self._dataTypeView.setButtonsState(True)
Example #25
0
    def _set_name(self, newname):
        name = self.name
        if newname == name:
            return
        if not re.match('^[a-zA-Z]\w*$', newname):
            QMessageBox.information(None, "grafit", 
                        "<b>Illegal column name</b><p>Column names must start with a letter and consist "
                        "of letters, numbers and underscore (_)<p>")
            return
        if newname in self.worksheet.column_names and name != newname:
            QMessageBox.information(None, "grafit", 
                        "<b>A column with this name already exists</b><p>Please choose another name<p>")
            return

        self.rename___(self.worksheet.name, self.name, newname).do().register()
Example #26
0
 def scenarioSelection_currentRowChanged(self, current, previous):
     if not current.isValid():
         return
     currentItem = current.internalPointer()
     previousItem = previous.internalPointer()
     if not isinstance(currentItem, FileItem):
         return
     if currentItem == previousItem:
         return
     if currentItem.object.type() != ContainerType.Scenario:
         return
     if currentItem.object == self.currentScenario:
         return
     if self.currentIsChanged():
         ret = QMessageBox.information(self,
                 self.tr("Text Changed"),
                 self.tr("Do you want to save it?"),
                 QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard)
         if ret == QMessageBox.Cancel:
             self.scenarioRestore.emit(previous)
             return
         elif ret == QMessageBox.Save:
             self.currentScenario.setText(qt.toUnicode(self.ui.textEditScenario.toPlainText()))
     self.setCurrentScenario(currentItem.object)
     self.ui.textEditScenario.setScenario(self.currentScenario)
     filepath = self.currentScenario.filePath()
     self.setWindowTitle(self.tr("%1 - Hestia [*]").arg(filepath))
Example #27
0
 def insert(self, objeto):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         insert = u'''insert into Registro (id, registro, tipo, nome, curso, data_registro, data_saida, status, observacoes) 
                      values (%d,%d,%d,"%s","%s","%s","%s",%d,"%s");''' % (
             objeto['id'],
             objeto['registro'],
             objeto['tipo'],
             objeto['nome'],
             objeto['curso'],
             objeto['data_registro'],
             objeto['data_saida'],
             objeto['status'],
             objeto['observacoes'],
         )
         cursor.execute(insert)
         banco.commit()
         return True
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             u"Erro de inserção no banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
Example #28
0
def launch_browser(browser, url, caption=None, message=None):
    if not caption: caption = "Info"
    if not message: message = "Launch web browser?"
    
    if not browser or not access(browser, X_OK):
        QMessageBox.warning(None, "Warning", "You must properly configure your web browser path in Preferences (within the Edit menu).")
        return 0


    cancel = QMessageBox.information(None, caption, message, "&Ok", "&Cancel")
    if cancel: return 0

    if sys.platform == 'win32':
        return spawnv(P_NOWAIT, browser, (" ", url))
    else:
        return spawnv(P_NOWAIT, browser, (browser, url))
Example #29
0
    def __showQuestion(self, caption, question):
        """ Ask the user a question and returns the result. """

        result = False
        answer = QMessageBox.warning(self, caption, question, QMessageBox.No, QMessageBox.Yes)
        if answer == QMessageBox.Yes:
            result = True
        return result
Example #30
0
    def _sendImage(self, path):
        global password
        import base64

        f = open(path)
        img = f.read()
        f.close()
        bimg = base64.encodestring(img)

        # resmi gönder
        ret = self.server.addImage(username, password, basename(path), bimg,
                                   False)

        if not ret:
            QMessageBox.critical(self, "HATA", u"Yeni resim eklenemedi!")
        else:
            self.fillImgList()
Example #31
0
def launch_browser(browser, url, caption=None, message=None):
    if not caption: caption = "Info"
    if not message: message = "Launch web browser?"

    if not browser or not access(browser, X_OK):
        QMessageBox.warning(
            None, "Warning",
            "You must properly configure your web browser path in Preferences (within the Edit menu)."
        )
        return 0

    cancel = QMessageBox.information(None, caption, message, "&Ok", "&Cancel")
    if cancel: return 0

    if sys.platform == 'win32':
        return spawnv(P_NOWAIT, browser, (" ", url))
    else:
        return spawnv(P_NOWAIT, browser, (browser, url))
Example #32
0
 def closeEvent(self, event):
     if self.project.isChanged():
         ret = QMessageBox.warning(self,
                 self.tr("Project changed"),
                 self.tr("Do you want to continue?"),
                 QMessageBox.Cancel | QMessageBox.Discard)
         if ret == QMessageBox.Cancel:
             event.ignore()
             return
Example #33
0
    def showQuestion(self, question):
        """ Displays the given question and returns the answer. """

        answer = QMessageBox.question(self.__generatedDialog, _creationQuestionMessage, question,
                                      QMessageBox.No, QMessageBox.Yes)
        result = False
        if answer == QMessageBox.Yes:
            result = True
        return result
Example #34
0
 def __dproyecto_modificado(self):
     """Pregunta en caso de que haya sido modificado el proyecto si desea ser guardado"""
     if not self.__idu.original():
         returncode = QMessageBox.information(self, 'Atencion:', 'El proyecto actual ha sido modificado, desea guardarlo?', 'Guardarlo', 'No guardarlo', 'Volver', 0, 1)
         if returncode == 0:
             self.__guardar()
         elif returncode == 2:
             return False
     return True
Example #35
0
 def slotLaunchDosbox(self, game=None):
     if game is None:
         game = self.listView.currentItem().game
     if self.app.game_fileshandler.get_game_status(game):
         self.app.dosbox.run_game(game)
     else:
         title = self.game_titles[game]
         box = QMessageBox.information(self, 'UnavailableGame')
         box.setText('%s is unavailable' % title)
Example #36
0
    def __showQuestion(self, caption, question):
        """ Ask the user a question and returns the result. """

        result = False
        answer = QMessageBox.warning(self, caption, question, QMessageBox.No,
                                     QMessageBox.Yes)
        if answer == QMessageBox.Yes:
            result = True
        return result
Example #37
0
 def selectAll(self):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         selectAll = u'''select * from User;'''
         cursor.execute(selectAll)
         return cursor.fetchall()
     except Exception, e:
         warning = QMessageBox.warning(None, "Database error", "Erro da consulta no banco de dados. O erro foi:\n\n%s" % e, QMessageBox.Ok)
         return ~warning
Example #38
0
 def selectAll(self):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         selectAll = u"select * from Registro;"
         cursor.execute(selectAll)
         return cursor.fetchall()
     except Exception, e:
         warning = QMessageBox.warning(None, "Database error", u"Erro de seleção no banco de dados. O erro foi:\n\n%s" % e, QMessageBox.Ok)
         return ~warning
Example #39
0
    def showQuestion(self, question):
        """ Displays the given question and returns the answer. """

        answer = QMessageBox.question(self.__generatedDialog,
                                      _creationQuestionMessage, question,
                                      QMessageBox.No, QMessageBox.Yes)
        result = False
        if answer == QMessageBox.Yes:
            result = True
        return result
Example #40
0
 def delete(self, object):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         delete = u'''delete from Registro where ("registro" = %d);''' % object['registro']
         cursor.execute(delete)
         banco.commit()
     except Exception, e:
         warning = QMessageBox.warning(None, "Database error", u"Erro de deleção no banco de dados. O erro foi:\n\n%s" % e, QMessageBox.Ok)
         return ~warning
Example #41
0
 def btnDelAccount_clicked(self):
     res = QMessageBox.warning(None,
         self.trUtf8("Confirmation"),
         self.trUtf8("""Are you absolutely sure that you want to erase <b>all</b> data inside this account (i.e. all the blogs and posts)?"""),
         self.trUtf8("&Yes"),
         self.trUtf8("&No"),
         None,
         0, -1)
     if res == 0:
             acc = self.settings.accountByName(str(self.lbAccounts.currentText()))
             del self.settings.Accounts[self.settings.Accounts.index(acc)]
             self.settings.save()
             self.fillList()  
Example #42
0
 def selectAll(self):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         selectAll = u"select * from Registro;"
         cursor.execute(selectAll)
         return cursor.fetchall()
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             u"Erro de seleção no banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
Example #43
0
 def select(self, object):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         select = u'''select * from Registro where ("registro" = %d);''' % object[
             'registro']
         cursor.execute(select)
         return cursor.fetchall()
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             u"Erro de seleção no banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
Example #44
0
 def delete(self, object):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         delete = '''delete from User 
                     where ("cpf" = %d);''' % object['cpf']
         cursor.execute(delete)
         banco.commit()
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             "Erro ao remover do banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
 def select(self, objeto):
     try:
         banco = sqlite3.connect('banco.db')
         cursor = banco.cursor()
         delete = u'''select * from Solicitacao where ("registro" = %d);''' % objeto[
             'id']
         cursor.execute(delete)
         return cursos.fetchall()
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             "Erro da consulta no banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
 def delete(self, objeto):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         delete = u'''delete from Solicitacao 
                      where ("registro" = %d);''' % objeto['id']
         cursor.execute(delete)
         banco.commit()
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             "Erro ao remover do banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
 def btnFetchBlogs_clicked(self):
     host = str(self.editHost.text())
     login = str(self.editLogin.text())
     password = str(self.editPassword.text())
     endpoint = str(self.editEP.text())
     feedpath = str(self.editFP.text())
     postpath = str(self.editPassword.text())
     if self.comboProviders.currentItem() == 0:
         at = GenericAtomClient(host, login, password, endpoint, feedpath,
                                postpath)
     elif self.comboProviders.currentItem() == 1:
         at = BloggerClient(host, login, password)
     elif self.comboProviders.currentItem() == 2:
         at = MovableTypeClient(host, login, password)
     try:
         self.blogs = at.getBlogs()
         self.comboBlogs.clear()
         for blog in self.blogs.keys():
             self.comboBlogs.insertItem(blog)
         self.editLogin_textChanged(None)
     except Exception, inst:
         print "btnFetchBlogs_clicked: %s" % inst
         QMessageBox.critical(self, "Error",
                              "Couldn't fetch list of blogs!")
Example #48
0
 def select(self, object):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         delete = '''select * 
                     from User 
                     where ("cpf" = %d)''' % object['cpf']
         cursor.execute(delete)
         return cursor.fetchall()
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             "Erro da consulta no banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
Example #49
0
 def update(self, object):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         update = '''update User set ( "nome"="%s", "email"="%s", "login"="%s", "senha"="%s", "autenticacao"=%d, "admin"=%d ) where (cpf = %d);''' % (
             object['cpf'], object['nome'], object['email'],
             object['login'], object['senha'], object['autenticacao'],
             object['admin'])
         cursor.execute(update)
         banco.commit()
         return True
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             "Erro de atualização no banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning
    def setup(self):
        showPlusServerWidget = True
        if _platform == "linux" or _platform == "linux2" or _platform == "darwin":  #linux or linux or OS X
            message = "Attention: You are running Slicer on Linux or OS X. Do you have PlusServer installed on the current OS?"
            result = QMessageBox.question(slicer.util.mainWindow(),
                                          'ProstateTRUSNav', message,
                                          QMessageBox.Yes | QMessageBox.No)
            showPlusServerWidget = result == QMessageBox.Yes

        if _platform == "win32" or showPlusServerWidget:
            # Windows...
            plusServerCollapsibleButton = ctkCollapsibleButton()
            plusServerCollapsibleButton.text = "PlusServer"
            self.layout.addWidget(plusServerCollapsibleButton)
            self.configurationFileChooserButton = QPushButton(
                self.configurationFile)
            self.configurationFileChooserButton.connect(
                'clicked()', self.onConfigFileSelected)
            self.runPlusServerButton = QPushButton("Run PlusServer")
            self.runPlusServerButton.setCheckable(True)
            self.runPlusServerButton.connect('clicked()',
                                             self.onRunPlusServerButtonClicked)

            self.serverFormLayout = QFormLayout(plusServerCollapsibleButton)

            self.serverExecutableChooserButton = QPushButton(
                self.serverExecutable)
            self.serverExecutableChooserButton.connect(
                'clicked()', self.onServerExecutableSelected)

            hbox = QHBoxLayout()
            hbox.addWidget(self.serverExecutableChooserButton)
            self.serverFormLayout.addRow(hbox)

            hbox = QHBoxLayout()
            hbox.addWidget(self.configurationFileChooserButton)
            hbox.addWidget(self.runPlusServerButton)
            self.serverFormLayout.addRow(hbox)

        GuideletWidget.setup(self)

        # do specific setup here
        if _platform == "win32" or showPlusServerWidget:
            self.launchGuideletButton.setEnabled(False)
            self.checkExecutableAndArgument()
Example #51
0
 def update(self, object):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         update = u'''update Registro 
                      set ( "tipo"=%d, "nome"=%s, "curso"=%s, "data_registro"=%s, "status"=%d, "observacoes"=%s ) where (registro = %d);''' % (
             object['tipo'], object['nome'], object['curso'],
             object['data_registro'], object['data_saida'],
             object['status'], object['observacoes'], object['registro'])
         cursor.execute(update)
         banco.commit()
         return True
     except Exception, e:
         warning = QMessageBox.warning(
             None, "Database error",
             u"Erro na atualização do banco de dados. O erro foi:\n\n%s" %
             e, QMessageBox.Ok)
         return ~warning
Example #52
0
 def insert(self, object):
     try:
         banco = sqlite.connect('banco.db')
         cursor = banco.cursor()
         insert = '''insert into User 
         ('cpf', 'nome', 'email', 'login', 'senha', 'autenticacao', 'admin') 
         values ( '%d', '%s', '%s', '%s', '%s', '%d', '%d' );''' % (
             object['cpf'], object['nome'], object['email'],
             object['login'], object['senha'], object['autenticacao'],
             object['admin'])
         cursor.execute(insert)
         banco.commit()
         return True
     except Exception, e:
         print e
         warning = QMessageBox.warning(
             None, "Database error",
             u"Erro de inserção no banco de dados. O erro foi:\n\n%s" % e,
             QMessageBox.Ok)
         return ~warning