Example #1
0
    def doActionAbout(self):
        f = open(os.path.join(GURU_ROOT, 'guru', 'guru_about.html'))

        file_contents = f.read()

        message_text = file_contents % (platform.python_version(), QT_VERSION_STR, PYSIDE_VERSION_STR, platform.system())
        QMessageBox.about(self, "About Guru", message_text)
Example #2
0
 def check_barcode(self, txt):
     if len(txt) == self.edBarcode.maxLength():
         db = Db_Instance("obook_barcode_search").get_instance()
         try:
             if db.open():
                 query = QSqlQuery(db)
                 query.prepare("SELECT * FROM book WHERE barcode = :barcode")
                 query.bindValue(":barcode", txt)
                 query.exec_()
                 if query.next():
                     self.add_book_from_record(query.record())
                     self.edBarcode.clear()
                 else:
                     raise RecordNotFoundException
             else:
                 raise DbUnavailableException
         except RecordNotFoundException:
             message = unicode("Código de barra inválido!\n\n"""
                           "O código informado não corresponde a nenhum livro cadastrado".decode('utf-8'))
             QMessageBox.critical(self, "Seareiros - Livraria", message)
         except DbUnavailableException:
             self.log.error(db.lastError().text())
             message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8'))
             QMessageBox.critical(self, "Seareiros - Livraria", message)
         self.edBarcode.setFocus()
Example #3
0
    def doActionSageServer(self):
        server_list_dialog = ServerListDlg(self)

        #Get a reference to the WorksheetController associated to this window.
        wsc = self.webViewController().worksheet_controller

        #Select the server associated to this window, if there is one.
        if wsc and wsc.server_configuration:
            server_list_dialog.selectServer(wsc.server_configuration)

        #Show the dialog.
        server_list_dialog.exec_()

        #It's possible that the user will delete all of the servers. It's not clear how to cleanly handle this case.
        #We choose to give the user a choice to fix the situation.
        while not ServerConfigurations.server_list:
            #No servers?
            message_text = "Guru needs a Sage server configured in order to evaluate cells. " \
                            "Add a Sage server configuration in the server configuration dialog?"
            response = QMessageBox.question(self, "Sage Not Configured", message_text, QMessageBox.Yes, QMessageBox.No)
            if response == QMessageBox.No:
                return
            server_list_dialog.exec_()

        #Execution only reaches this point if there exists a server.
        server_name = server_list_dialog.ServerListView.currentItem().text()
        if wsc:
            new_config = ServerConfigurations.getServerByName(server_name)
            try:
                wsc.useServerConfiguration(new_config)
            except Exception as e:
                QMessageBox.critical(self, "Error Switching Servers", "Could not switch servers:\n%s" % e.message)
Example #4
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.serviceProvider = 0
        self.popupMenu = None
        self.mapControlButtons = []
        self.mapControlTypes = []
        self.markerObjects = []
        self.setWindowTitle(self.tr('Map Viewer Demo'))

        self.routingManager = None
        self.mapManager = None
        self.mapWidget = None
        self.markerIcon = None
        self.slider = None

        manager = QNetworkConfigurationManager()

        canStartIAP = manager.capabilities() & QNetworkConfigurationManager.CanStartAndStopInterfaces

        configuration = manager.defaultConfiguration()

        if not configuration.isValid or (not canStartIAP and configuration.starte() != QNetworkConfiguration.Active):
            QMessageBox.information(self, self.tr('Map Viewer Demo'),
                                    self.tr('Available Access Points not found.'))
            return

        self.session = QNetworkSession(configuration, self)
        self.session.opened.connect(self.networkSessionOpened)
        self.session.error.connect(self.error)

        self.session.open()
        self.session.waitForOpened()

        self.setProvider('nokia')
        self.setupUi()
Example #5
0
 def on_addTagsButton_clicked(self):
     if len(self.tagsInput.text()) == 0:
         QMessageBox.critical(self, u'错误', u'请至少输入一个类别')
     else:
         tags = set(self.tagsInput.text().split())
         self.selectedTag.addItems(list(tags-set(self.tags)))
         self.tags.extend(tags)
Example #6
0
    def mouseReleaseEvent(self, event):
        super().mouseReleaseEvent(event)

        pos = event.pos()
        x, y = pos.x() // self.cell_size, pos.y() // self.cell_size

        # Нельзя изменять дефолтную ячейку
        try:
            if not self.def_num_matrix[x][y]:
                if event.button() == Qt.LeftButton:
                    self.matrix[x][y] = self.matrix[x][y] + 1 if self.matrix[x][y] < 9 else 0
                elif event.button() == Qt.RightButton:
                    self.matrix[x][y] = self.matrix[x][y] - 1 if self.matrix[x][y] > 0 else 9
                elif event.button() == Qt.MiddleButton:
                    self.matrix[x][y] = 0

                # Получим список решения этой судоку
                for solution in self.sudoku_solutions:
                    if solution == self.matrix:
                        QMessageBox.information(None, 'Победа', 'Совпало, мать его!')
                        break

                self.update()

        except IndexError:
            pass
  def importNominalPositions(self):
    fn, filt = QFileDialog.getOpenFileName(self, "Open Excel File", "",
        "Excel Files(*.xls)")
    if not fn:
      return
    try:
      wb = xlrd.open_workbook(fn)
    except:
      QMessageBox.critical(self, "Invalid Excel file", "Pyrite could not "
          "parse the selected Excel file. Make sure it is the .xls not "
          ".xlsx format.")
      return

    dlg = ExcelRegionSelector(self, wb.sheet_names())
    dlg.exec_()
    if dlg.result() != QDialog.Accepted:
      return
    xRow = dlg.xRow
    xCol = dlg.xCol
    yRow = dlg.yRow
    yCol = dlg.yCol
    count = dlg.count
    sheetName = dlg.sheetName

    sheet = wb.sheet_by_name(sheetName)
    # load the nominal positions
    for i in range(count):
      pos = (float(sheet.cell(xRow + i, xCol).value),
          float(sheet.cell(yRow + i, yCol).value))
      self._nominalData.append(pos)
    self._nominalDataLoaded = True
    self.updateNominalPositionPreview()
    self.updateGenerateEnabled()
Example #8
0
def create_window(window_class, **kwargs):
    """Create a QT window in Python, or interactively in IPython with QT GUI
    event loop integration.
    """
    global app

    app = get_app_qt4(sys.argv)
    app.references = set()

    net = None
    fname = None
    if len(sys.argv) > 1:
        fname = sys.argv[1]
        if os.path.exists(fname):
            net = read_pickle(fname)
        else:
            QMessageBox.critical(
                        None, "Error opening file %s", fname,
                        QMessageBox.Ok, QMessageBox.NoButton)

    window = window_class(net, fname)
    app.references.add(window)
    window.show()

    start_event_loop_qt4(app)
    return window
Example #9
0
 def _isCloseOk(self):
     
     doc = self.document
     
     if doc.saved:
         return True
     
     else:
         # current document has unsaved changes
         
         if doc.filePath is None:
             prefix = 'This document'
         else:
             fileName = os.path.basename(doc.filePath)
             prefix = 'The document "{:s}"'.format(fileName)
             
         box = QMessageBox()
         box.setText(prefix + ' has unsaved changes.')
         box.setInformativeText('Would you like to save them before closing?')
         box.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
         box.setDefaultButton(QMessageBox.Save)
         
         result = box.exec_()
         
         if result == QMessageBox.Save:
             return self._onSave()
         
         elif result == QMessageBox.Cancel:
             return False
         
         else:
             return True
Example #10
0
    def fetched_usages(self, reply):
        self.updateButton.setEnabled(True)
        self.progressBar.setHidden(True)

        if reply.error() == QNetworkReply.NoError:
            if not self.usage_model.parse(str(reply.readAll())):
                title = "Parsing error"
                message = self.usage_model.error
            else:
                title = None
                self.tree_model.deleteLater()
                self.tree_model = TreeModel(self.usage_model.usage)
                self.treeView.setModel(self.tree_model)
                self.show_lastupdate()
                self.write_usage()
        elif reply.error() in [QNetworkReply.AuthenticationRequiredError,
                               QNetworkReply.ContentAccessDenied]:
            title = "Authentication error"
            message = "Please check your account credentials."
        else:
            title = "An error occured"
            message = reply.errorString() \
                    + ".\nPlease check your internet connection."

        if title:
            QMessageBox.critical(self, title, message)
        reply.deleteLater()
Example #11
0
def merge_pdf(destination=None, pdf_files=None):
	try:
		output = PdfFileWriter()
		inputs = []
		for pdf_file in pdf_files:
			reader_pdf_file = PdfFileReader(open(pdf_file, 'rb'))
			inputs.append(reader_pdf_file)

		for input_pdf in inputs:
			for page in input_pdf.pages:
				output.addPage(page)

		output_stream = open(destination, 'wb')
		output.write(output_stream)
		output_stream.close

		# merger = PdfFileMerger()
		# for pdf_file in pdf_files:
		# 	merger.append(open(pdf_file, 'rb'))
		
		# merger.write(open(destination), 'wb')

		QMessageBox.information(main, 'Success!', 'PDFs have been merged to ' + destination )
	except:
		QMessageBox.critical(main, 'Error!', 'Critical error occured.\n\n%s' % traceback.format_exc())
Example #12
0
	def beginScan(self):
		global infectionsList
		global infectedFiles
		global infectionsList
		self._theMainWindow.theScan.theScanProgress.theShowScanResults.tableWidget.clear()
		self.isCleanScan = False
		global scanPath
		global abnormalTermination
		global scanParameters
		self.getScanSettings()
		infectedFiles = []
		infectionsList = []
		abnormalTermination = 0
		self._theMainWindow.theScan.theScanProgress.btnExitScan.setText(langmodule.terminateScan)
		#print("Scan path is: " + str(scanPath))
		if scanPath == None:
			QMessageBox.information(None, langmodule.attention, langmodule.noFilesChosen, 
								 QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)
			return -1
		
		# preparing to start scan in a new thread
		self.theScanWorker = utilities.scanWorker(scanPath, scanParameters)
		#self.theScanWorker.finished.connect(self.onScanFinish)
		self.theScanWorker.sigWriteScan.connect(self.printToWidget)
		self.theScanWorker.sigScanTerminated.connect(self.onScanFinish)
		
		self._theMainWindow.theScan.theScanProgress.textScanProg.clear()
		self._theMainWindow.theScan.theScanProgress.show()
		self.theScanWorker.start()
			
		#preparing to store scan event in a new thread
		self.theSQLITEWorker = utilities.sqliteWorker()
		self.theSQLITEWorker.finished.connect(self.onSQLiteFinish)
Example #13
0
	def insert(self):
		p = self.aFileModel.insert()
		if p:
			msgDuplBox = QMessageBox()
			msgDuplBox.setText('\n'.join(p) + 
				"\n\n...file(s) already being tracked.")
			msgDuplBox.exec_()
Example #14
0
	def handleMainWindowEmits(self, param):
		#print(param)
		if param == "SCAN":
			self._theMainWindow.theScan.clear()
			self._theMainWindow.theScan.theSelect.clear()
			self._theMainWindow.theScan.show()
		elif param == "UPDATE":
			self._theMainWindow.theUpdate.show()
		elif param == "HISTORY":
			self._theMainWindow.theHistory.show()
			# populating combo boxes
			availMal = utilities.populateMalware()
			modelMalware = utilities.malwareModel(availMal)
			self._theMainWindow.theHistory.comMalware.setModel(modelMalware)
			availDBs = utilities.populateVirusDBs()
			modelDBs = utilities.virusDBModel(availDBs)
			
			#populating date fields
			self.curDateList = date.today().isoformat().split('-')
			self.curQDate = QDate(int(self.curDateList[0]), int(self.curDateList[1]), int(self.curDateList[2]))
			self._theMainWindow.theHistory.comStartDate.setDate(self.curQDate )
			self._theMainWindow.theHistory.comEndDate.setDate(self.curQDate )
			
			self._theMainWindow.theHistory.comDatabase.setModel(modelDBs)
			
		else:
			QMessageBox.critical(None, langmodule.attention, langmodule.applicationError, 
								 QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)
 def do_it(self):
     QMessageBox.information(
         self, 'Do it!', 'The input was {0}'.format(self.edit.text()))
     number = float(self.edit.text())
     QMessageBox.information(
         self, 'Do it!', 'Convert to a double and add something: '
         '{0} + 2.5 = {1}'.format(number, number+2.5))
Example #16
0
    def convert(self):
        ''' Converts the input file and writes to the output file. '''

        input_path = self.input_path.text()
        # Should be set below when opening input the file.
        output_path = self.output_path.text()

        try:
            input_path, output_path = validate(input_path, output_path)
        except OutputExistsError as e:
            # E128 Technically this should be indented more, but I feel that
            # hurts readability in this case.
            overwrite = QMessageBox.warning(self,
                self.tr('JWPCE conversion'),
                self.tr('The output file already exits. Overwrite it?'),
                QMessageBox.Yes | QMessageBox.No)  # noqa: E128

            if overwrite == QMessageBox.No:
                return

        except ValidateError as e:
            QMessageBox.warning(self,
                                self.tr('JWPCE conversion'),
                                self.tr(str(e)),
                                QMessageBox.Ok)
            return

        # TODO - add in some kind of progress indicator?
        contents = read_file(input_path)
        write_file(output_path, contents)

        QMessageBox.information(self,
                                self.tr('JWPCE conversion'),
                                self.tr('The conversion is complete.'),
                                QMessageBox.Ok)
def tratarRetornoModem(iRetorno, Janela):

    RetornoMetodo = ''
    if (iRetorno == 0):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno 0 - Erro de comunicação, não foi possível enviar o método.'
    elif (iRetorno == 1):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno 1 - Operação realizada com sucesso!!'
    elif (iRetorno == -1):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno -1 - Erro na comunicação da serial.'
    elif (iRetorno == -2):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno -2 - Modem retornou erro.'
    elif (iRetorno == -3):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno -3 - Modem retornou caractere(s) inválido(s).'
    elif (iRetorno == -4):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno -4 - Modem não conectado na rede GSM.'
    elif (iRetorno == -5):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno -5 - Modem retornou NO CARRIER.'
    elif (iRetorno == -6):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno -6 - Modem retornou NO DIALTONE.'
    elif (iRetorno == -7):
        RetornoMetodo = 'Tratamento de Retorno - DarumaFramework Python/Qt','Retorno -7 - Modem retornou BUSY.'

    if (iRetorno > 1):
        QMessageBox.information(Janela,'Tratamento de Retorno - DarumaFramework Python/Qt',' O nivel de sinal é: ' + str(iRetorno))
    else:
        QMessageBox.information(Janela, 'Tratamento Retorno - Genérico','Retorno do Método: ' + str(RetornoMetodo))
Example #18
0
 def onAbout(self):
     aboutMsg = 'TFTP Until Dinner\n\nCopyright Huw Lewis 2014'
     aboutMsg += '\n\nA TFTP Server implemented in Python; User interface in Qt and PySide (LGPL)'
     aboutMsg += '\n\nLicensed under MIT license. See http://opensource.org/licenses/MIT'
     aboutMsg += '\n\ntftpudGui: https://github.com/javert/tftpudGui'
     aboutMsg += "\nTftpud: https://github.com/javert/tftpud"
     QMessageBox.about(self, 'TFTPUD', aboutMsg)
Example #19
0
	def extractToText(self):
		try:
			now = datetime.now().isoformat().split('T')
			filename='scanLog_' + now[0][0:10] + '_' + now[1][0:8] + '.txt'
			flags = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
			folder = QFileDialog.getExistingDirectory(self._theMainWindow.theHistory.theResults, langmodule.chooseFolderToStoreText, homeDir, flags)
			print(filename)
			print(manager._resultsToPrint)
			path = folder + '/' + filename
			with open(path, 'w') as file:
				file.write(langmodule.userTitle + '\t\t\t' + langmodule.noOfResultsTitle  + '\t\t' + langmodule.scanDateTimeTitle + '\n') # linux specific newline - not portable!
				file.write("----------------------------------------------------------------------------------" + '\n') # linux specific newline - not portable!
				for inlist in manager._resultsToPrint:
					file.write(inlist[0] + '\t\t\t')
					file.write(inlist[1] + '\t\t\t\t\t')
					file.write(inlist[2] + '\n') # linux specific newline - not portable!
				file.close()	
		except IOError as error:
			print(str(error)[0:13])
			if "Permission denied" in str(error):
				QMessageBox.critical(None, langmodule.attention, langmodule.noAccessRightsInFolder, 
								 QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)
		except Exception:
			QMessageBox.critical(None, langmodule.attention, langmodule.errorStoringFile, 
								 QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton)
Example #20
0
    def addServer(self):
        dialog = EditSageServerDlg(self)

        name_collision = True #The while loop needs to run at least once.
        while name_collision:
            if not dialog.exec_():
                #The user clicked cancel.
                return

            #Fetch the data.
            new_server = dialog.getServerConfiguration()

            #Check to see if the name is in use.
            name_collision = ServerConfigurations.getServerByName(new_server["name"])
            #If the user set the name to a new name that is already in use, name_collision will
            #not be None. The loop will continue and the dialog reopened.
            if name_collision:
                #The name is already in use.
                QMessageBox.critical(self, "Name already exists", "A server configuration already exists with that name. Choose a different name.")
                dialog.txtName.selectAll()
                dialog.txtName.setFocus()

        #Add the server configuration to the list.
        ServerConfigurations.addServer(new_server)
        item = QListWidgetItem(new_server["name"], self.ServerListView)
        self.ServerListView.setCurrentItem(item)
        if new_server["default"]:
            self.updateListViewDefault()
Example #21
0
 def delete(self):
     if(self.get_item(self.tree.currentItem()).parent == None):
         QMessageBox.warning(None, 'cannot delete the root node', 'cannot delete the root node')
         return
     
     delete(self.get_item(self.tree.currentItem()))
     self.tree.currentItem().parent().removeChild(self.tree.currentItem())
Example #22
0
 def startApplication(self):
     self.m_server = QLocalServer()
     if self.m_server.listen(self.applicationName()):
         self.m_server.newConnection.connect(self.getNewConnection)
         self.mainWindow.show()
     else:
         QMessageBox.critical(None, self.tr("Error"), self.tr("Error listening the socket."))
Example #23
0
    def about(self):
        app = QApplication.instance()
        args = {'name': app.applicationName(),
                'version': app.applicationVersion()}
        title = self.trUtf8(b'{name} {version}').format(**args)
        text = self.trUtf8("""\
<h1>{name} {version}</h1>

<p>An trivial text editor implemented in Qt</p>

<p>Copyright © 2011 <a href="mailto:[email protected]">Sebastian
Wiesner</a></p>

<p>Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:<p>

<ul><li>The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.</li></ul>

<p><strong>The software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of merchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the software or the use or other dealings in the
software.</strong></p>""").format(**args)
        QMessageBox.about(self, title, text)
Example #24
0
 def change_auth(self):
     if self.app.provider.is_authenticated():
         msgBox = QMessageBox(
             QMessageBox.Critical,
             self.tr("You are trying to remove authorisation"),
             self.tr("""
             Are you sure want to remove authoristion?
             It remove all not synced changes!
             """.strip()),
             QMessageBox.Yes | QMessageBox.No
         )
         ret = msgBox.exec_()
         if ret == QMessageBox.Yes:
             self.app.provider.remove_authentication()
             self.update_tabs()
     else:
         self.ui.tabWidget.hide()
         self.ui.webView.show()
         consumer = oauth.Consumer(CONSUMER_KEY, CONSUMER_SECRET)
         client = oauth.Client(consumer, proxy_info=get_oauth_proxy('https'))
         resp, content = client.request(
             'https://%s/oauth?oauth_callback=' % HOST + urllib.quote('http://everpad/'),
         'GET')
         data = dict(urlparse.parse_qsl(content))
         url = 'http://%s/OAuth.action?oauth_token=' % HOST + urllib.quote(data['oauth_token'])
         page = AuthPage(
             data['oauth_token'], data['oauth_token_secret'], self,
         )
         self.ui.webView.setPage(page)
         page.mainFrame().load(url)
Example #25
0
 def saveRecord(self, where):
     ''' Method saves the current row in the self.mapper and moves the 
     data model cursor to a given location.
     '''
     
     if self.sppLineEdit.text() == "":
         QMessageBox.warning(self, "Warning",
             "You must enter a species name!", QMessageBox.Ok)
         return
     
     # Get the current index and submit changes to the underlying model
     row = self.mapper.currentIndex()
     self.mapper.submit()
     
     # Move the data model cursor to a given location
     if where == ObservationDialog.FIRST:
         row = 0
     elif where == ObservationDialog.PREV:
         row = 0 if row <= 1 else row - 1
     elif where == ObservationDialog.NEXT:
         row += 1
         if row >= self.model.rowCount():
             row = self.model.rowCount() - 1
     elif where == ObservationDialog.LAST:
         row = self.model.rowCount() - 1
     self.mapper.setCurrentIndex(row)
Example #26
0
    def accept(self):
        self.model.name = self.accountNameEdit.text()
        username = self.usernameEdit.text()
        password = self.passwordEdit.text()
        if not all([username, password]):
            QMessageBox.critical(self, "Username & Password",
                                "Both the username and password are required.")
            if not username:
                self.usernameEdit.setFocus()
            else:
                self.passwordEdit.setFocus()
            return
        self.model.username = username
        self.model.password = password

        try:
            self.model.capKB = int(self.capEdit.text() or 0)
        except ValueError:
            QMessageBox.critical(self, "Invalid value",
                                 "Please enter a number in KB for the capacity.")
            self.capEdit.setFocus()
            return

        self.model.start = self.fromDate.date()
        self.model.end = self.toDate.date()

        super(AccountDialog, self).accept()
Example #27
0
 def fileUnlockedEvent(self, success, decryptedFileName):
     if success == 'True':
         QMessageBox.information(self, __appname__, "File Unlocked Successfully.")
     else:
         os.remove(decryptedFileName)
         EncryptedFile.replaceWithUnlockDialog(EncryptedFile.CALLER_LOCATION, decryptedFileName)
         QMessageBox.information(self, __appname__, "Wrong password. Couldn't unlock file.")
Example #28
0
    def loadFile(self, file_name):
        #Which MainWindow object we create the new worksheet in depends on if loadFile()
        #is fired on a welcome page or not. Returns True on success.

        if self.isWelcome:
            #Use the current MainWindow object to create the worksheet.
            self.hideWelcome()
            #Set the working filename
            self.file_name = file_name
            #We set the window title.
            self.setUniqueWindowTitle()
            #Open the worksheet in the webView.
            try:
                self.webViewController().openWorksheetFile(file_name)
            except Exception as e:
                QMessageBox.critical(self, "File Open Error", "Could not open the file:\n%s" % e.message)
                self.showWelcome()
                return False

            #Set the dirty flag handler.
            self.dirty(False)
            self.connectWorksheetSignals()
            self.updateRecentFilesMenu()
        else:
            #Create a new MainWindow object to use for the new worksheet.
            main_window = MainWindow(file_name=file_name)
            main_window.show()

            main_window.activateWindow()
            main_window.raise_()

        return True
Example #29
0
 def fileLockedEvent(self, fileName):
     msgSuccess = "{0} locked successfully.".format(fileName)
     QMessageBox.information(self, __appname__, msgSuccess)
     self.lockButton.setText("Lock EXE")
     self.lockButton.setEnabled(True)
     self.groupBox.setEnabled(True)
     self.step1GroupBox.setEnabled(True)
Example #30
0
 def showStatusPopup(self):
     msgBox = QMessageBox(
         self.status.boxIcon,
         "System status",
         '<span style="color: white;">' + self.status.message + '</span>'
     )
     msgBox.exec_()
Example #31
0
    def deploySelectedTemplates(self, connect_after=False):
        '''Deploys machines using the selected templates'''
        templates = []
        for item in self._mywindow.lv_templates.selectedItems():
            templates.append(item.text())

        if len(templates) == 0:
            QMessageBox.warning(self._mywindow, "Template",
                                "Please select a template to deploy")
            return

        comment = self._mywindow.le_comment.text()
        expires = int(self._mywindow.le_expires.text())
        host = resolveHost(self._mywindow.cb_blades.currentText())

        self.deployTemplates(templates, comment, expires, host, connect_after)
Example #32
0
    def okToContinue(self):
        """
        Checks if it is ok to close the application.
        The user will be prompted to save files.

        @return: True, if it is ok to continue (e.g. close the app); False, otherwise
        @rtype: bool

        @todo: Make a smart save dialog to allow the user to save only certain files.
        """
        dirtyFilenames = []
        for filename, networkController in self.ModelControllers.items():
            if networkController.Dirty:
                dirtyFilenames.append(
                    networkController.filename)   # we don't use the filename key because it might be outdated
        if len(dirtyFilenames) == 0:    #nothing to save
            return True

        reply = QMessageBox.question(self,
                                     "BioParkin - Unsaved Changes",
                                     "Unsaved changes in these files:\n\n%s\n\nDo you want to save them?" % "\n".join(
                                         dirtyFilenames),
                                     buttons=QMessageBox.SaveAll | QMessageBox.Discard | QMessageBox.Cancel)
        if reply == QMessageBox.Cancel:
            return False
        elif reply == QMessageBox.SaveAll:
            for networkController in self.ModelControllers:
                if networkController.Dirty:
                    networkController.save()
        return True
Example #33
0
    def accept(self):
        """
        Commit the input and dispose the dialog.
        """
        path = self.path.text()
        if not os.path.exists(path):
            os.makedirs(path)
        path += "/"
        path += self.name.text()
        path += ".kif"
        path = os.path.normpath(path)

        # create the ontology file.
        try:
            with open(path, 'x') as f:
                f.close()
        except FileExistsError:
            ret = QMessageBox.warning(
                self, "The ontology file already exists.",
                "Do you want to override the existing ontology file?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.Yes:
                with open(path, 'w') as f:
                    f.close()
            elif ret == QMessageBox.No:
                return
            else:
                raise RuntimeError
        ontology = Ontology(path, name=self.name.text(), url=self.url.text())
        # download the ontology (user must save to store ontology on disk)
        updater.update(
            ontology, lambda x: self.parent().addOntology(
                ontology, newversion=x.getvalue().decode('utf8')))
        super(OpenRemoteOntologyDialog, self).accept()
Example #34
0
    def __connectHttpServer(self):
        retCode = True
        retCode &= not self.leGraylogIP.text()
        retCode &= not self.leGraylogPort.text()

        if (not retCode):
            self.view.load(
                QUrl("http://" + self.leGraylogIP.text() + ":" +
                     self.leGraylogHttpPort.text() +
                     "/dashboards/59ef8317ac4207031e41f294"))
            self.view.show()
        else:
            QMessageBox.warning(
                self, "Error",
                "Please, fill Graylog IP and Http Port before connect!",
                QMessageBox.Ok)
Example #35
0
 def deleteXRef(self):
     widget = QApplication.focusWidget()
     self.state.maybeSave()
     item = self.state.entryPanel.xrefList.currentItem()
     if item is not None:
         xref = Xix.Util.xref_for_data(item.data(Qt.UserRole))
         from_term = self.state.model.term(xref.from_eid)
         kind = "see" if xref.kind is XrefKind.SEE else "see also"
         if xref.kind in {XrefKind.SEE, XrefKind.SEE_ALSO}:
             term = self.state.model.term(xref.to_eid)
         elif xref.kind in {
                 XrefKind.SEE_GENERIC, XrefKind.SEE_ALSO_GENERIC
         }:
             term = xref.term
             kind += " (generic)"
         with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True):
             reply = QMessageBox.question(
                 self.window, "Delete Cross-reference — {}".format(
                     QApplication.applicationName()),
                 "<p>Delete cross-reference from<br>“{}” to {} “{}”?".
                 format(from_term, kind, term),
                 QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
         if reply == QMessageBox.Yes:
             if xref.kind in {XrefKind.SEE, XrefKind.SEE_ALSO}:
                 self.state.model.deleteXRef(xref.from_eid, xref.to_eid,
                                             xref.kind)
             elif xref.kind in {
                     XrefKind.SEE_GENERIC, XrefKind.SEE_ALSO_GENERIC
             }:
                 self.state.model.deleteGenericXRef(xref.from_eid,
                                                    xref.term, xref.kind)
     Lib.restoreFocus(widget)
Example #36
0
 def msgApp(self, title, msg):
     uinfo = QMessageBox.question(self, title, msg,
                                  QMessageBox.Yes | QMessageBox.No)
     if uinfo == QMessageBox.Yes:
         return 'y'
     if uinfo == QMessageBox.No:
         return 'n'
Example #37
0
 def remove(self, res):
     """Remove resource"""
     msg_box = QMessageBox(
         QMessageBox.Critical,
         self.app.translate("ResourceEdit", "Delete Resource"),
         self.app.translate("ResourceEdit",
                            "Are you sure want to delete this resource?"),
         QMessageBox.Yes | QMessageBox.No)
     ret = msg_box.exec_()
     if ret == QMessageBox.Yes:
         self._resources.remove(res)
         self._resource_labels[res].hide()
         del self._resource_labels[res]
         self.on_change()
         if not self._resources:
             self.widget.hide()
Example #38
0
    def accept(self):
        """ 
        Commit the input and dispose the dialog.
        """
        path = self.ontologyPath.text()
        if not os.path.exists(path):
            os.makedirs(path)
        path = ''.join([path, '/', self.ontologyName.text(), '.kif'])
        path = os.path.normpath(path)

        # create the ontology file.
        try:
            with open(path, 'x') as f:
                f.close()
        except FileExistsError:
            ret = QMessageBox.warning(
                self, "The ontology file already exists.",
                "Do you want to override the existing ontology file?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            if ret == QMessageBox.Yes:
                with open(path, 'w') as f:
                    f.close()
            elif ret == QMessageBox.No:
                return
            else:
                raise RuntimeError
        ontology = Ontology(path, name=self.ontologyName.text())
        self.parent().addOntology(ontology)
        super(NewOntologyDialog, self).accept()
Example #39
0
 def close(self):
     msg = QMessageBox(
         QMessageBox.Critical, self.tr("Close without Saving"),
         self.tr("Are you sure want to close this note without saving?"),
         QMessageBox.Yes | QMessageBox.No)
     if not self.touched or msg.exec_() == QMessageBox.Yes:
         self.hide()
         self.closed = True
         self.app.settings.setValue(
             "note-geometry-%d" % self.note.id,
             self.saveGeometry(),
         )
         self.app.settings.setValue(
             "note-geometry-default",
             self.saveGeometry(),
         )
    def confirmToRemove(self, txt):
        question = QMessageBox.question(self, "Remove",
                                        "Remove '{0}'?".format(txt),
                                        QMessageBox.Yes | QMessageBox.Default,
                                        QMessageBox.No)

        return question == QMessageBox.Yes
Example #41
0
    def getItemSlotMapping(self):
        qfile = QtCore.QFile(":db/slotMap.csv")
        items = {}
        if qfile.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text):
            data = qfile.readAll()
            content = StringIO.StringIO(data)
            reader = csv.reader(content, delimiter=',')

            for row in reader:
                items[row[0].decode('utf-8')] = row[1].decode('utf-8')
            return items

        QMessageBox.critical(None, 'Database Failure',
                             'Failed to read item mappings from database',
                             QMessageBox.Ok)
        self.stop()
Example #42
0
 def delete(self):  # No need to restore focus widget
     row = self.listWidget.currentRow()
     item = self.listWidget.item(row)
     if item is None:
         return
     gid = item.data(Qt.UserRole)
     for button in self.buttons:
         button.setEnabled(False)
     deleteItem = False
     if (not self.state.model.isLinkedGroup(gid)
             or not self.state.model.groupMemberCount(gid)):
         with Lib.Qt.DisableUI(self, forModalDialog=True):
             reply = QMessageBox.question(
                 self,
                 "Delete Group — {}".format(QApplication.applicationName()),
                 "<p>Delete Group “{}”?</p>".format(item.text()),
                 QMessageBox.Yes | QMessageBox.No)
         if reply == QMessageBox.Yes:
             self.state.model.deleteGroup(gid)
             deleteItem = True
     else:
         with Lib.Qt.DisableUI(self, forModalDialog=True):
             form = Forms.DeleteOrUnlink.Form("Delete", gid, self.state,
                                              self)
             deleteItem = form.exec_()
     if deleteItem:
         item = self.listWidget.takeItem(row)
         del item
     self.updateUi()
Example #43
0
    def on_pushButtonEnviar_clicked(self):
        # Definiçao do Tamanho do Vetor de Recebimento da informação

        cStatus = create_string_buffer(100)

        iIndice = self.lineEditIndice.text().toInt()

        # Execuçao do Método de Retorno da Informação
        # trataRetorno(
        rConsultaStatusImpressoraStr_ECF_Daruma(iIndice, cStatus)
        #))

        # Devolve o retorno da DLL para o campo de texto
        QMessageBox.information(
            self, "DarumaFramework - Python/Qt",
            "Indice: " + str(iIndice) + "   Status: " + str(cStatus))
Example #44
0
 def remove(self, res):
     """Remove resource"""
     msg_box = QMessageBox(
         QMessageBox.Critical,
         self.parent.tr("You try to delete resource"),
         self.parent.tr("Are you sure want to delete this resource?"),
         QMessageBox.Yes | QMessageBox.No
     )
     ret = msg_box.exec_()
     if ret == QMessageBox.Yes:
         self._resources.remove(res)
         self._resource_labels[res].hide()
         del self._resource_labels[res]
         self.on_change()
         if not self._resources:
             self.widget.hide()
Example #45
0
    def okRead(self):
        'Pop-up a warning message.'
        reply = QMessageBox.warning(self,
                "Warning",
                '''\nFile Open and Save is possible only in Data Page!
\n\(Use SaveAs for Solution Page)''', QMessageBox.Ok)
        return True
Example #46
0
    def addEntry(self, name=None, address=None):
        """ Add an entry to the addressbook. """
        if name is None and address is None:
            addDialog = AddDialogWidget()

            if addDialog.exec_():
                name = addDialog.name
                address = addDialog.address

        address = {"name": name, "address": address}
        addresses = self.tableModel.addresses[:]

        # The QT docs for this example state that what we're doing here
        # is checking if the entered name already exists. What they
        # (and we here) are actually doing is checking if the whole
        # name/address pair exists already - ok for the purposes of this
        # example, but obviously not how a real addressbook application
        # should behave.
        try:
            addresses.remove(address)
            QMessageBox.information(self, "Duplicate Name",
                                    "The name \"%s\" already exists." % name)
        except ValueError:
            # The address didn't already exist, so let's add it to the model.

            # Step 1: create the  row
            self.tableModel.insertRows(0)

            # Step 2: get the index of the newly created row and use it.
            # to set the name
            ix = self.tableModel.index(0, 0, QModelIndex())
            self.tableModel.setData(ix, address["name"], Qt.EditRole)

            # Step 3: lather, rinse, repeat for the address.
            ix = self.tableModel.index(0, 1, QModelIndex())
            self.tableModel.setData(ix, address["address"], Qt.EditRole)

            # Remove the newAddressTab, as we now have at least one
            # address in the model.
            self.removeTab(self.indexOf(self.newAddressTab))

            # The screenshot for the QT example shows nicely formatted
            # multiline cells, but the actual application doesn't behave
            # quite so nicely, at least on Ubuntu. Here we resize the newly
            # created row so that multiline addresses look reasonable.
            tableView = self.currentWidget()
            tableView.resizeRowToContents(ix.row())
Example #47
0
 def save(self, filename=None):
     filename = filename or self.currentFilename
     if not filename:
         raise ValueError()
     try:
         encoding = sys.getfilesystemencoding()
         with open(filename, 'w', encoding=encoding) as stream:
             stream.write(self.editor.toPlainText())
     except EnvironmentError as error:
         QMessageBox.critical(self, self.trUtf8(b'Save file'), self.trUtf8(
             b'Could not save <tt>{filename}</tt>: {message}').format(
                 filename=filename, message=error.strerror))
         return False
     else:
         self.editor.document().setModified(False)
         self.currentFilename = filename
         return True
Example #48
0
 def _lockFile(self):
     fileName = self.locationLineEdit.text()
     if len(self.locationLineEdit.text()
            ) == 0 or self.locationLineEdit.text() == None:
         QMessageBox.information(self, __appname__,
                                 "Pick an exe file first to lock.")
         self.showFileDialog()
     else:
         password = self.passwordLineEdit.text()
         makeBackup = self.checkBox.isChecked()
         self.workerThread = WorkerThread(fileName, password, self.signal,
                                          makeBackup)
         self.lockButton.setText("Working")
         self.lockButton.setEnabled(False)
         self.groupBox.setEnabled(False)
         self.step1GroupBox.setEnabled(False)
         self.workerThread.start()
 def has_equal_references_shape_types(self):
     import FemMeshTools
     ref_shty = ''
     for ref in self.references:
         r = FemMeshTools.get_element(
             ref[0], ref[1]
         )  # the method getElement(element) does not return Solid elements
         # print('  ReferenceShape : ', r.ShapeType, ', ', ref[0].Name, ', ', ref[0].Label, ' --> ', ref[1])
         if not ref_shty:
             ref_shty = r.ShapeType
         if r.ShapeType != ref_shty:
             message = 'Multiple shape types are not allowed in the reference list.\n'
             FreeCAD.Console.PrintError(message)
             QMessageBox.critical(None, "Multiple ShapeTypes not allowed",
                                  message)
             return False
     return True
Example #50
0
    def removeQuestion(self, category='', who=[]):
        """Removes a section item."""

        return QMessageBox.question(
            self, self.tr('Remove'),
            self.tr("Do you want to remove item(s) {} from {}?".format(
                str(who)[1:-1], category)), QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No)
 def handleExitAction(self, show_confirmation=False):
     reply = QMessageBox.No
     if show_confirmation:
         reply=QMessageBox.question(self,'Exit %s?' % APP_NAME,
                 "Are you sure to exit %s?" % APP_NAME, QMessageBox.Yes,QMessageBox.No)
     if not show_confirmation or reply==QMessageBox.Yes:
         self.trayIcon.hide()
         QTimer.singleShot(250, self.app.quit)
Example #52
0
 def updateQuestion(self, category, xxx_todo_changeme):
     """Updates a section item."""
     (old_who, new_who) = xxx_todo_changeme
     return QMessageBox.question(
         self, self.tr('Update'),
         self.tr("Do you want to update item '{}' to '{}' in {}?".format(
             old_who, new_who, category)), QMessageBox.Yes | QMessageBox.No,
         QMessageBox.No)
Example #53
0
    def get_new_address(self):
        result = QMessageBox.question(self.add_pool_dialog, "Get New Wallet Address?", \
             "This will open Cryptonote generator in browser.<br><br>\
             Are you sure to proceed?"                                      , \
             QMessageBox.Yes | QMessageBox.No, defaultButton=QMessageBox.Yes)

        if result == QMessageBox.No: return
        self.open_link("https://wallet.evonote.com")
Example #54
0
 def on_addFilesButton_clicked(self):
     if len(self.tags) == 0:
         QMessageBox.critical(self, u'错误', u'请先添加至少一个类别')
     else:
         addedFiles = QFileDialog.getOpenFileNames(self, u'选择文件')[0]
         tag = self.selectedTag.currentText()
         for idx, filePath in enumerate(addedFiles):
             if filePath in self.files: continue
             fileName = os.path.split(filePath)[1]
             self.file_tag_map[fileName] = tag
             self.tags_files_table.insertRow(self.files_count + idx)
             self.tags_files_table.setItem(self.files_count + idx, 0,
                                           QTableWidgetItem(tag))
             self.tags_files_table.setItem(self.files_count + idx, 1,
                                           QTableWidgetItem(fileName))
         self.files.extend(addedFiles)
         self.files_count = len(self.files)
Example #55
0
 def loadConfigButtonClicked(self):
     """
     load the config
     """
     if not os.path.isdir('conf'):
         os.mkdir('conf')
     files = QFileDialog.getOpenFileName(
         self,
         u"读取配置文件",
         "conf/default.ini",
         "INI File (*.ini)",
     )
     filename = files[0]
     try:
         self.loadConfig(filename)
     except Exception, e:
         QMessageBox.information(self, u'读取失败', u'配置文档有误,请重新配置' + str(e))
Example #56
0
    def dba_help_button_clicked(self):
        s = '''
All the expression usable are:
- cst: val, val<size>, hexa
- var: eax, al ..
- load/store: @[addr], @[addr,size]
- unary: !e, -e
- binary: e1 bop e2
- restrict: {e, low, high}
- ite: if c e1 else e2

With:
- uop: [-, !(not)]
- bop: [+, -, *u, *s, /, /s, modu, mods, or, and, xor, >>(concat), lshift, rshiftu,
rshifts, lrotate, rrotate, =, <>, <=u, <u, >=u, >u, <=s, <s, >=s, >s, extu, exts]
        '''
        QMessageBox.about(self, u"DBA langage help", unicode(s))
Example #57
0
    def Check_ue_asset(self):

        # file_lists_ins = self.File_list.selectedItems()
        #
        # file_path_lists = []
        # for i in file_lists_ins:
        #     file_path_lists.append(file_dict[i.text()])
        #
        # UE4_project = self.UE4Project_path_line.text()
        # ue_lack_list = self.set.check_ue_asset(file_path_lists, UE4_project)
        # if ue_lack_list:
        #
        #     QMessageBox.information(self, "Lack Asset List", "".join(ue_lack_list))
        # else:
        #     QMessageBox.information(self, "Lack Asset List", "No assets missing ! ~")
        QMessageBox.information(self, "Lack Asset List",
                                "No assets missing ! ~")
    def search_mayaenv_path(self):
        usd = cmds.internalVar(usd=True)
        ud = '/'.join(usd.split('/')[0:-2])
        p = os.path.join(ud, 'Maya.env')

        if not os.path.exists(p):
            # searching path for environments other than English UI
            ud = '/'.join(usd.split('/')[0:-3])
            p = os.path.join(ud, 'Maya.env')
            if not os.path.exists(p):
                QMessageBox.question(
                    self, "Error",
                    "Maya.env is not detected (at: {0}), check your installation or call your system administrator."
                    .format(p), QMessageBox.Ok | QMessageBox.Default)
                raise "Maya.env is not detected"

        return p
Example #59
0
    def get_new_address(self):
        result = QMessageBox.question(self.add_pool_dialog, "Get New Wallet Address?", \
             "This will open HongbaoBlockchain/Monero/Aeon wallet generator in browser.<br><br>\
             Are you sure to proceed?"                                      , \
             QMessageBox.Yes | QMessageBox.No, defaultButton=QMessageBox.Yes)

        if result == QMessageBox.No: return
        self.open_link("https://wallet.hongbao.com")
Example #60
0
    def __init__(self, x, y, scaleFactor, text, obj, v, parent=None):
        """
        Default class constructor.

        :param `x`: TOWRITE
        :type `x`: qreal
        :param `y`: TOWRITE
        :type `y`: qreal
        :param `scaleFactor`: TOWRITE
        :type `scaleFactor`: qreal
        :param `text`: TOWRITE
        :type `text`: QString
        :param `obj`: TOWRITE
        :type `obj`: `BaseObject`
        :param `v`: TOWRITE
        :type `v`: `View`
        :param `parent`: TOWRITE
        :type `parent`: `QUndoCommand`_
        """
        super(UndoableScaleCommand, self).__init__(parent)

        self.gview = v
        self.object = obj
        self.setText(text)

        # Prevent division by zero and other wacky behavior
        if scaleFactor <= 0.0:
            self.dx = 0.0
            self.dy = 0.0
            self.factor = 1.0
            QMessageBox.critical(0, QObject.tr("ScaleFactor Error"),
                                 QObject.tr("Hi there. If you are not a developer, report this as a bug. "
                                 "If you are a developer, your code needs examined, and possibly your head too."))
        else:
            # Calculate the offset
            oldX = self.object.x()  # qreal
            oldY = self.object.y()  # qreal
            scaleLine = QLineF(x, y, oldX, oldY)
            scaleLine.setLength(scaleLine.length() * scaleFactor)
            newX = scaleLine.x2()  # qreal
            newY = scaleLine.y2()  # qreal

            self.dx = newX - oldX
            self.dy = newY - oldY
            self.factor = scaleFactor