def outputIndexAs(self): widget = QApplication.focusWidget() extensions = [] for extension, desc in EXPORT_EXTENSIONS.items(): extensions.append("{} (*{})".format(desc, extension)) with Lib.Qt.DisableUI(*self.window.widgets(), forModalDialog=True): form = QFileDialog( self.window, "Output As — {}".format(QApplication.applicationName())) form.setNameFilters(extensions) form.setAcceptMode(QFileDialog.AcceptSave) form.setDirectory(self.state.outputPath) form.selectFile(str(pathlib.Path(self.state.model.filename).stem)) if form.exec_(): filename = form.selectedFiles()[0] extension = form.selectedNameFilter() if filename: # Must have some extension if not re.match(r"^.*[.].+$", filename): if extension: filename += EXTENSION_EXTRACT_RX.sub( r"\1", extension) else: filename += ".rtf" self._outputIndex(filename, widget) Lib.restoreFocus(widget)
def import_wallet(self): dlg = QFileDialog(self.new_wallet_ui, "Select Import Wallet File") dlg.setFileMode(QFileDialog.ExistingFile) wallet_filename = None if dlg.exec_(): wallet_filename = dlg.selectedFiles()[0] else: return new_wallet_file = os.path.join(wallet_dir_path, self.get_new_wallet_file_name()) if wallet_filename: wallet_key_filename = wallet_filename + '.keys' if not os.path.exists(wallet_key_filename): QMessageBox.warning(self.new_wallet_ui, \ 'Import Wallet',\ """Error: Key file does not exist!<br> Are you sure to select correct wallet file?<br><br> Hint: Wallet file often ends with .bin""") return False try: copy2(wallet_filename, os.path.join(wallet_dir_path, new_wallet_file)) copy2(wallet_key_filename, os.path.join(wallet_dir_path, \ new_wallet_file + '.keys')) except IOError, err: self._detail_error_msg("Importing Wallet", "Error importing wallet!", str(err)) self.ui.reset_wallet() return False
def on_browse(self): current_path = self.files_model.rootPath() file_dialog = QFileDialog(self, 'Select a Folder', current_path) file_dialog.setFileMode(QFileDialog.Directory) file_dialog.setOption(QFileDialog.ShowDirsOnly) if file_dialog.exec_(): self.on_change_root_path(file_dialog.selectedFiles()[0])
def on_browse(self, *_): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.DirectoryOnly) dialog.setViewMode(QFileDialog.Detail) dialog.setDirectory(self.le_output.text()) if dialog.exec_(): self.le_output.setText(dialog.selectedFiles()[0])
def seleccionarUI(self): dialogo = QFileDialog(None) dialogo.setFileMode(QFileDialog.ExistingFile) dialogo.setNameFilter('Interfaz(*.ui)') if dialogo.exec_(): global Ruta_archivoUI Ruta_archivoUI = dialogo.selectedFiles()[0] self.rutaEntrada_lineEdit.setText(Ruta_archivoUI)
def open_file(parent, filter): dialog = QFileDialog() dialog.setAcceptMode(QFileDialog.AcceptOpen) dialog.setFilter(QDir.Files) dialog.setFileMode(QFileDialog.ExistingFile) dialog.setNameFilter(filter) res = dialog.exec() if res: return dialog.selectedFiles()[0]
def ask_path(self): """Show a dialog ask config['NUKE']. """ dialog = QFileDialog() filename, selected_filter = dialog.getSaveFileName(filter='*.html') selected_filter = selected_filter[1:] if filename: if not filename.endswith(selected_filter): filename += selected_filter self.lineEdit.setText(filename)
def actionReadReport(self): if not os.path.isdir('./report'): os.mkdir('./report') filedialog = QFileDialog(self) files = filedialog.getOpenFileNames(self, u"读取报告", "report/", "PDF Files (*.pdf)") filename = files[0] if filename: import win32api win32api.ShellExecute(0, 'open', filename[0], '', '', 1)
def seleccionarPY(self): dialogo = QFileDialog(None) dialogo.setFileMode(QFileDialog.AnyFile) dialogo.setNameFilter('Archivo Python(*.py)') dialogo.setAcceptMode(QFileDialog.AcceptSave) dialogo.setDefaultSuffix('py') if dialogo.exec_(): global Ruta_archivoPY Ruta_archivoPY = dialogo.selectedFiles()[0] self.rutaSalida_lineEdit.setText(Ruta_archivoPY)
def save(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setDefaultSuffix("avi") dialog.setDirectory(os.getcwd()) dialog.setNameFilter(self.tr("Video Files [.avi] (*.avi)")) if dialog.exec_(): output_file_name = dialog.selectedFiles()[0] correlate(self.clip_filename, self.audio_filename, output_file_name)
def cmdSfoglia_click(self): """Evento che gestisce il tasto per sfogliare il percorso""" dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.AnyFile) dialog.setNameFilter("SQLite db (*.db)") dialog.setViewMode(QFileDialog.Detail) if dialog.exec_(): fileNames = dialog.selectedFiles() self.myWidget.txtPercorso.setText(fileNames[0]) self.InitTable()
def cmd_getPath(self): defaultPath = self.lineEdit.text() dialog = QFileDialog(self) dialog.setDirectory(defaultPath) fileName = dialog.getOpenFileName()[0] fileName = fileName.replace('\\', '/') if fileName: self.lineEdit.setText(fileName) self.save_lineEdit_info() self.parentWidget().w_textEditor.load_leftScript() self.parentWidget().w_textEditor.load_convertedText()
def browseFile(self): dialog = QFileDialog() # if the current node is a reader if self._type == "OpenFile": self._file = dialog.getOpenFileName(None, self._message, self._directory) # else it's a writer elif self._type == "SaveFile": self._file = dialog.getSaveFileName(None, self._message, self._directory) else: logging.error("Error : Unknown type of dialog") return self._file = self._file[0]
def select_path_clicked(): dialog = QFileDialog() path = dialog.getExistingDirectory() config['save_folder_path'] = path config['backup_folder_path'] = os.path.join(path, "backups") config['remote_folder_path'] = os.path.join(path, "remote") if not os.path.exists(config['backup_folder_path']): os.mkdir(config['backup_folder_path']) update_save_list() save_config()
def choose_save_dir(self): fname = QFileDialog(self, FILEBROWSER_SAVE_FOLDER_TITLE) fname.setFileMode(QFileDialog.Directory) looking_label = QFileDialog.DialogLabel(QFileDialog.LookIn) filename_label = QFileDialog.DialogLabel(QFileDialog.FileName) filetype_label = QFileDialog.DialogLabel(QFileDialog.FileType) fname.setLabelText(looking_label, FILEBROWSER_SAVE_FOLDER_LOOKIN) fname.setLabelText(filename_label, FILEBROWSER_SAVE_FOLDER_FOLDERNAME) fname.setLabelText(filetype_label, FILEBROWSER_SAVE_FOLDER_FOLDERTYPE) fname.setOption(QFileDialog.ShowDirsOnly) if fname.exec_(): filename = fname.selectedFiles()[0] self.save_folder_editline.setText(filename)
def __init__(self): """ Constructs the main window. """ super(MainWindow, self).__init__() self.setupUi(self) self.actionAboutpySUMO.triggered.connect(self._showAboutBox_) self.infolog = InfoLog() self.log = logging.getLogger('.' + __name__) self.setCentralWidget(None) callback = partial(self._addWidget_, "TextEditorWidget", self.menuTextEditorWidgets) self.actionTextEditorWidget.triggered.connect(callback) callback = partial(self._addWidget_, "DocumentationWidget", self.menuDocumentationWidgets) self.actionDocumentationWidget.triggered.connect(callback) callback = partial(self._addWidget_, "HierarchyWidget", self.menuHierarchyWidgets) self.actionHierarchyWidget.triggered.connect(callback) callback = partial(self._addWidget_, "GraphWidget", self.menuGraphWidgets) self.actionGraphWidget.triggered.connect(callback) self.newOntologyAction.triggered.connect(self._newOntology_) self.openLocalOntologyAction.triggered.connect( self._openLocalOntology_) self.openRemoteOntologyAction.triggered.connect( self._openRemoteOntology_) self.createStatusBar() self.ontologyAdded.connect(self.notifyOntologyAdded) self.clearHistoryAction.triggered.connect( self._ClearRecentOntologiesHistory_) self.widgets = list() # unique instances. self.fileChooser = QFileDialog(self) self.dialog = QPrintDialog() self.userLayout = LayoutManager(self) filepath = pysumo.CONFIG_PATH + "/settings.ini" exist = False try: with open(filepath) as f: f.close() exist = True except IOError: pass self.settings = PySumoSettings(self, filepath) if not exist: self.settings.loadDefaults() self.optionDialog = OptionDialog(self, self.settings) self.actionSettings.triggered.connect(self._showOptionDialog_) # restore and show the view. self.userLayout.restoreLayout() self.show()
def destination_chooser(self): """Show folder chooser dialog and update lblDestPath with path selected. Input: None Output: None""" dialog = QFileDialog() dialog.setFileMode(QFileDialog.Directory) dialog.setOption(QFileDialog.ShowDirsOnly) dialog.exec_() self.lblDestPath.setEnabled(True) self.lblDestPath.setText( os.path.abspath(dialog.directory().absolutePath())) self.update_table_view() self.copyButton.setEnabled(True)
def open_file(self): """ saves the file """ dialog = QFileDialog(self) dialog.setNameFilter("Image Files (*.png *.jpg *.bmp)") dialog.setStyleSheet('color:black;') name = '' if dialog.exec_(): name = dialog.selectedFiles() if name: self.image_data = open(name[0], 'rb').read() self.pixmap = QPixmap(name[0]) self.image_label.setPixmap( self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation))
def new_picture(self): dialog = QFileDialog() if (dialog.exec_()): filename = dialog.selectedFiles()[0] # print "ok {}".format(filename) f = open(filename,"rb") bytes = f.read(-1) f.close() image = QImage.fromData(QByteArray(bytes)) if image: # save as buffer(bytes) pixmap = QPixmap.fromImage(image.convertToFormat(QImage.Format_RGB16, Qt.MonoOnly).scaledToHeight(128)) self.set_pixmap_as_icon(pixmap)
def importF(self): fileBrowser = QFileDialog() fileBrowser.setFileMode(QFileDialog.Directory) fileBrowser.setViewMode(QFileDialog.Detail) fileBrowser.setOption(QFileDialog.ShowDirsOnly, True) if fileBrowser.exec_(): dir = fileBrowser.selectedFiles() else: print "Cancelled" return print "Copying data from " + str(dir[0]) files = os.listdir(str(dir[0])) copyOn = True print files for file in files: copyOn = True if file.endswith(".json"): if os.path.exists( os.path.join(json_reader.buildPath("data"), file)): if popup( "File " + file[:len(file) - 5] + " already exists. Overwrite?", "Warning"): os.remove(json_reader.buildPath("data/" + file)) else: copyOn = False if copyOn: print "Copying valid file " + file copy(os.path.join(str(dir[0]), file), json_reader.buildPath("data")) if "_link" not in file: try: #Ugly AF json_reader.readOne(file[:len(file) - 5]) json_reader.writeCharNames(file[:len(file) - 5]) except: print "Not a Character" try: json_reader.readP(file[:len(file) - 5]) json_reader.writePerNames(file[:len(file) - 5]) except Exception as e: print "Not a Persona" print e print "Successfully copied files" popup("Files imported successfully!", "Information")
def __init__(self, dict_results): headers = [ "File", "scan", "m/z", "Intensity", "Resolving Power", "Baseline", "Noise", "Charge" ] filedialog = QFileDialog() arquivo_out = filedialog.getSaveFileName(\ None, "Export to Excel", "", "*.xls")[0] if arquivo_out == str(u''): pass else: self.write_results(arquivo_out, dict_results, headers)
def getBasePath(self): if int(cmds.about(v=1)) < 2017: import shiboken from PySide.QtGui import QFileDialog, QWidget, QDialog else: import shiboken2 as shiboken from PySide2.QtWidgets import QFileDialog, QWidget, QDialog winName = "dialog_getDirectory" mayaWin = shiboken.wrapInstance( long(maya.OpenMayaUI.MQtUtil.mainWindow()), QWidget) existing_widgets = mayaWin.findChildren(QDialog, winName) if existing_widgets: map(lambda x: x.deleteLater(), existing_widgets) dialog = QFileDialog(mayaWin) dialog.setObjectName(winName) dialog.setDirectory(os.path.splitext(cmds.file(q=1, sceneName=1))[0]) choosedFolder = dialog.getExistingDirectory() if choosedFolder: self.lineEdit.setText(choosedFolder) self.cmd_loadList()
def export(self): fileBrowser = QFileDialog() fileBrowser.setFileMode(QFileDialog.Directory) fileBrowser.setViewMode(QFileDialog.Detail) fileBrowser.setOption(QFileDialog.ShowDirsOnly, True) if fileBrowser.exec_(): dir = fileBrowser.selectedFiles() else: print "Cancelled" return print "Copying data to " + str(dir[0]) + "/exportdata" try: copytree(json_reader.buildPath("data"), str(dir[0]) + "/exportdata") except Exception as e: print e popup( "Error in copying files. There is a file in the selected directory that has the same name as a Story Creator file.\n\nFiles are copied to " + str(dir[0]) + "/exportdata" + ". Please ensure this directory does not already exist.", "Critical") return print "Successfully copied files" popup("Files exported successfully!", "Information")
def set_backup_directory(self): dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.Directory) dialog.setOption(QFileDialog.ShowDirsOnly, True) dialog.setWindowTitle("Please select a backup directory") if configuration.get("Backup", "backup_directory"): dialog.setDirectory(configuration.get("Backup", "backup_directory")) if dialog.exec_(): mainlog.debug(dialog.selectedFiles()) directory = dialog.selectedFiles()[0] self._log("Testing the backup directory") try: f = open(os.path.join(directory, "test_file"), "w") f.write("TestBackup") f.close() except Exception as ex: box = QMessageBox( QMessageBox.Warning, "Unable to write into the backup directory", u"I can't write in the backup directory you selected. Have I the necessary permissions on that directory ({})? The error was : {}" .format(directory, str(ex))) box.exec_() return self.backup_directory_edit.setText(directory) configuration.set("Backup", "backup_directory", directory) self._log("Saving the backup directory in the configuration") configuration.save() dialog.close()
def open_existing_wallet(self): current_wallet_password, result = self._custom_input_dialog(self.ui, \ "Wallet Password", "Current wallet password:"******"Incorrect Wallet Password", "Wallet password is not correct!") return dlg = QFileDialog(self.ui, "Open Wallet File", wallet_dir_path, "Wallet files (*.bin)") dlg.setFileMode(QFileDialog.ExistingFile) wallet_filename = None if dlg.exec_(): wallet_filename = dlg.selectedFiles()[0] else: self.on_open_existing_wallet_complete_event.emit() return if not wallet_filename: return wallet_key_filename = wallet_filename + '.keys' if not os.path.exists(wallet_key_filename): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Key file does not exist!<br> Please make sure to select correct wallet file""") return if os.path.normpath(os.path.dirname( wallet_filename)) != os.path.normpath(wallet_dir_path): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Only wallet files at default location are available for opening.<br> You can import wallet via 'New... > Import' feature instead.""") return if os.path.basename(wallet_filename) == os.path.basename( self.ui.wallet_info.wallet_filepath): QMessageBox.warning(self.ui, \ 'Open Wallet File',\ """Error: Cannot open the same wallet!""") return while True: wallet_password, result = self._custom_input_dialog(self.ui, \ "Wallet Password", "Enter wallet password for opening:", QLineEdit.Password) if result: if not wallet_password: QMessageBox.warning(self.ui, \ 'Wallet Password',\ "You must provide password to open wallet") continue else: break else: return self.ui.stop_update_wallet_info_timer() self.on_open_existing_wallet_start_event.emit() current_wallet_filename = self.ui.wallet_info.wallet_filepath try: ret = self.ui.wallet_rpc_manager.rpc_request.stop_wallet() if ret['status'] == "ERROR": error_message = ret['message'] QMessageBox.critical(self.ui, \ 'Error Closing Current Wallet',\ "Error: %s" % error_message) raise Exception(error_message) self.ui.wallet_rpc_manager.set_ready(False) self.ui.run_wallet_rpc() while not self.ui.wallet_rpc_manager.is_ready(): self.app_process_events(0.1) ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet( os.path.basename(wallet_filename), wallet_password) if ret['status'] == "ERROR": error_message = ret['message'] QMessageBox.critical(self.ui, 'Error Opening Wallet', error_message) raise Exception(error_message) self.ui.reset_wallet(False) self.ui.wallet_info.wallet_password = hashlib.sha256( wallet_password).hexdigest() self.ui.wallet_info.wallet_filepath = wallet_filename self.ui.wallet_info.is_loaded = True self.ui.wallet_info.save() while not self.ui.wallet_rpc_manager.is_ready(): self.app_process_events(0.1) except Exception, err: log(str(err), LEVEL_ERROR) ret = self.ui.wallet_rpc_manager.rpc_request.open_wallet( os.path.basename(current_wallet_filename), current_wallet_password) self.ui.wallet_info.wallet_password = hashlib.sha256( current_wallet_password).hexdigest() self.ui.wallet_info.wallet_filepath = current_wallet_filename self.ui.wallet_info.is_loaded = True self.ui.wallet_info.save() self.on_open_existing_wallet_complete_event.emit()
def readFileButtonClicked(self): if not os.path.isdir('./DigitalSheet'): os.mkdir('./DigitalSheet') filedialog = QFileDialog(self) files = filedialog.getOpenFileNames(self, u"读取文档", "DigitalSheet/", "excel Files (*.csv)") filename = files[0] if filename: try: file = open(filename[0], 'r') data = file.read().split('\n')[:-1] #关闭文件 file.close() self.exist_axis = [] axis_num = [] interval = [] check = [] #提取第一行中的报告值 _result = [i for i in data[0].split(",")] if _result[0] == 'startest': for i, j in enumerate( ['SERIAL', 'TYPE', 'TRIGGER', 'PERSON', 'DATE'], 1): self.report[j] = _result[i] self.report['TRIGGER'] = self.getText( self.report['TRIGGER']) self.report['TYPE'] = self.getText(self.report['TYPE']) for i, j in enumerate(_result[6].split('&'), 1): self.report['PRESS'][i] = j for i, j in enumerate(_result[7].split('&'), 1): self.report['DIGITAL'][i] = j self.report['ACCELERATION'] = _result[8] self.report['SPEED'] = _result[9] self.report['DELAY'] = _result[10] self.report['SHOOT'] = _result[11] self.report['OPEN'], self.report['BLEED'] = _result[ 12].split('&') self.report['DEEP'] = _result[13] elif _result[0] == 'time': for i in ['SERIAL', 'TYPE', 'TRIGGER', 'PERSON', 'DATE']: self.report[i] = '**' for i in range(1, 7): self.report['PRESS'][i] = '**' for i in range(1, 5): self.report['DIGITAL'][i] = '**' for i in [ 'ACCELERATION', 'SPEED', 'DELAY', 'SHOOT', 'OPEN', 'BLEED', 'DEEP' ]: self.report[i] = '**' #注意第一列为x轴 for i in data[1].split(",")[1:]: interval.append(int(i)) for i, j in enumerate(data[2].split(',')[1:]): if j == "True": self.exist_axis.append(i) axis_num.append((i, interval[i])) check.append(True) else: check.append(False) #print check self.curve_window.produceAxis(self.exist_axis) for i in axis_num: self.curve_window.setTicker(i[0], i[1]) self.lcd_window.check(check[0:6], check[6:10], check[10]) self.group_speed_trigger = [check[10]] #数据区域 curve_data = ','.join(data[3:]).split(',') #todo 是否实数化 #for i, j in enumerate(curve_data): # curve_data[i] = float(j) for i in range(14): self.lines_data[i] = curve_data[i::14] for i, j in enumerate(self.exist_axis): self.curve_window.drawLine2D(i, self.lines_data[0], self.lines_data[j + 1], self.color_sheet[j]) self.curve_window.setXFull(float(self.lines_data[0][0]), float(self.lines_data[0][-1])) self.curve_window.updateDraw() self.curve_window._init_View() self.actionOrder("read") #print 'ok' except Exception, e: QMessageBox.critical(self, u"文档读取失败", u'文档格式有误或不存在\n' + str(e), QMessageBox.Ok, QMessageBox.NoButton)
def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setGeometry(0, 0, 1500, 1000) self.move( QApplication.desktop().screenGeometry().center() - self.rect().center()) self.show() # Main layout self.layout = QHBoxLayout() self.setLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) titles = odict([ ["Presets", odict([["preset", "Presets"]])], ["Cosmological Model", odict([ ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Hubble parameter constraint"], ["matter", "Matter sector"], ["neutrinos", "Neutrinos and other extra matter"], ["dark_energy", "Lambda / Dark energy"], ["bbn", "BBN"], ["reionization", "Reionization history"]])], ["Data sets", odict([ ["like_cmb", "CMB experiments"], ["like_bao", "BAO experiments"], ["like_sn", "SN experiments"], ["like_H0", "Local H0 measurements"]])], ["Sampler", odict([["sampler", "Samplers"]])]]) self.combos = odict() for group, fields in titles.items(): group_box = QGroupBox(group) self.layout_options.addWidget(group_box) group_layout = QVBoxLayout(group_box) for a, desc in fields.items(): self.combos[a] = QComboBox() if len(fields) > 1: label = QLabel(desc) group_layout.addWidget(label) group_layout.addWidget(self.combos[a]) self.combos[a].addItems( [text(k, v) for k, v in getattr(input_database, a).items()]) # PLANCK NAMES CHECKBOX TEMPORARILY DISABLED # if a == "theory": # # Add Planck-naming checkbox # self.planck_names = QCheckBox( # "Keep common parameter names " # "(useful for fast CLASS/CAMB switching)") # group_layout.addWidget(self.planck_names) # Connect to refreshers -- needs to be after adding all elements for field, combo in self.combos.items(): if field == "preset": combo.currentIndexChanged.connect(self.refresh_preset) else: combo.currentIndexChanged.connect(self.refresh) # self.planck_names.stateChanged.connect(self.refresh_keep_preset) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python", "citations"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)
def restore_backup(self): self._clear_log() self._log("Restore procedure started") url = self.url_edit.text() psql_path = configuration.get("Commands", "psql") if not psql_path: self._log_error( "The Commands/psql path is not set in the server.cfg") self._log("Please fix the configuration file (on the right)") return if not configuration.get("Commands", "pg_restore"): self._log_error( "The Commands/pg_restore path is not set in the server.cfg") self._log("Please fix the configuration file (on the right)") return if not configuration.get("Backup", "backup_directory"): self._log( "The Backup/backup_directory path is not set in the server.cfg" ) self._log("I'm setting it myself.") configuration.set("Backup", "backup_directory", get_data_dir()) configuration.set("DocumentsDatabase", "documents_root", os.path.join(get_data_dir(), "documents")) configuration.save() self.edit_config.load_configuration() login_clt, password_clt, dummy, dummy, dummy = self._extract_db_params_from_url( configuration.get("Database", "url")) login_adm, password_adm, dbname, host, port = self._extract_db_params_from_url( configuration.get("Database", "admin_url")) self._log("{} / {}".format(login_adm, password_adm)) full_path_backup = None d = "" if configuration.get("Backup", "backup_directory"): d = configuration.get("Backup", "backup_directory") if platform.system() == "Windows": if configuration.get("Backup", "backup_directory"): d = configuration.get("Backup", "backup_directory") # Using the static method gives a more native FileDialog. # with support for network backup_file = QFileDialog.getOpenFileName( self, _("Please select a backup file"), d, "{} database backup (*.pgbackup)".format( configuration.get("Globals", "name")))[0] if not backup_file: self._log("Restore aborted") return full_path_backup = backup_file if not os.path.isdir(full_path_backup): self._log( "{} is not a directory, so I'll go up a level".format( full_path_backup)) full_path_backup = os.path.dirname(full_path_backup) if not os.path.isdir(full_path_backup): self._log_error( "{} is not a directory either. Aborting restore.". format(full_path_backup)) return elif platform.system() == "Linux": d = AskWindowsShare(None) d.exec_() if d.result() == QDialog.Accepted: # //192.168.0.6/postgresqlbackup script_path = "/tmp/horse_mount.sh" script = open(script_path, "w") script.write("""#!/bin/bash echo "Creating transfer directory" mkdir /tmp/backup_win echo "Unmounting previous transfer directory (can fail)" umount /tmp/backup_win echo "Mouting the backup directory" mount -t cifs -ousername={},password={} {} /tmp/backup_win """.format(d.user.text().strip(), d.password.text().strip(), d.address.text().strip())) script.close() import stat os.chmod(script_path, stat.S_IEXEC | stat.S_IWRITE | stat.S_IREAD) cmd = [ 'gksudo', '--sudo-mode', '--message', 'Allow Koi to connect to the backup server.', script_path ] # gksudo seems to like to have the DISPLAY set. So I basically copy # it from the calling environment. ret, dummy, dummy = self._run_shell( cmd, {'DISPLAY': os.environ.get('DISPLAY')}) if ret > 0: self._log_error( "The mount operation failed. Please review the parameters you've given." ) self._log_error( "Network address : {}, windows user name : {}".format( d.address.text() or "?", d.user.text() or "?")) return full_path_backup = "/tmp/backup_win" else: dialog = QFileDialog(self) dialog.setFileMode(QFileDialog.Directory) dialog.setNameFilters(['Koi database backup (*.pgbackup)']) dialog.setWindowTitle("Please select a backup file") if configuration.get("Backup", "backup_directory"): dialog.setDirectory( configuration.get("Backup", "backup_directory")) if dialog.exec_(): full_path_backup = dialog.selectedFiles()[0] else: self._log_error( "Without proper source directory, I can't continue !") return else: self._log_error("Unsupported operating system") # At this poitn full_path_backup is the path to the backup # directory of Horse that we want to restore. # It is different than the current backup directory. if full_path_backup: full_restore(configuration, full_path_backup, backup_file, True, mainlog) self._log_success("Backup successfully restored !")
def __init__(self, app, ui, config, parent=None): super(MainWindow, self).__init__(parent) print('\n---------- GAVLab RTK Survey ----------') def setupMOOS(): # manual threading is only necessary if reading messages from moos # roslaunch automatically configures threads - ros is superior to moos self.comm_arch = 'moos' try: MainWindow.viz_ip = config['ip'] MainWindow.viz_port = config['port'] except: pass self.thread = MainWindow.VizThread() self.moos_widget = MoosWidget(config['moos']) self.requestPosition.connect(self.moos_widget.onPositionRequested) self.moos_widget.sendPosition.connect(self.receivePosition) print('MOOS setup') def setupROS(): self.comm_arch = 'ros' # ... print('ROS setup') # Determine Comm arch if config['ros']: import rospy, roslib roslib.load_manifest('survey_gui') setupROS() elif config['moos']: from moos_comm import MoosWidget, MOOSPositionWarning, MOOSConnectionWarning setupMOOS() else: raise Exception('Need a config file with comm architecture') self.app = app # reference to the Qt Application self.ui = ui self.ui.setupUi(self) self.config = config # Table self.table_model = TableModel() self.ui.tableView.setModel(self.table_model) self.ui.tableView.horizontalHeader().setStretchLastSection(True) # output self.output_file_dialog = QFileDialog() self.output_file = None self.header = '## GAVLab Survey - Recorded %s\n' + \ '## All data in ECEF (m): X Y Z Description\n' self.manual_dialog = QtGui.QDialog() self.pos_data = array([None] * 3) # latest self.pos_data_good = False self.std_dev_threshold = config["std_dev_threshold"] if not self.std_dev_threshold: # blank string --> accept first position received and record self.std_dev_threshold = inf # Signals/Slots self.ui.actionExit.triggered.connect(self.app.closeAllWindows) self.ui.recordButton.clicked.connect(self.onRecordRequested) self.ui.actionManual_Entry.triggered.connect(self.addManualPoint) self.ui.actionWrite.triggered.connect(self.writeToFile) # Number cruncing states (iterative) self._sum = array([0.0] * 3) self._2sum = array([0.0] * 3)
def __init__(self): super(MainWindow, self).__init__() self.setWindowTitle("Cobaya input generator for Cosmology") self.setGeometry(0, 0, 1500, 1000) self.move( QApplication.desktop().screen().rect().center() - self.rect().center()) self.show() # Main layout self.layout = QHBoxLayout() self.setLayout(self.layout) self.layout_left = QVBoxLayout() self.layout.addLayout(self.layout_left) self.layout_output = QVBoxLayout() self.layout.addLayout(self.layout_output) # LEFT: Options self.options = QWidget() self.layout_options = QVBoxLayout() self.options.setLayout(self.layout_options) self.options_scroll = QScrollArea() self.options_scroll.setWidget(self.options) self.options_scroll.setWidgetResizable(True) self.layout_left.addWidget(self.options_scroll) self.atoms = odict() titles = odict([ ["preset", "Presets"], ["theory", "Theory code"], ["primordial", "Primordial perturbations"], ["geometry", "Geometry"], ["hubble", "Constaint on hubble parameter"], ["baryons", "Baryon sector"], ["dark_matter", "Dark matter"], ["dark_energy", "Lambda / Dark energy"], ["neutrinos", "Neutrinos and other extra matter"], ["bbn", "BBN"], ["reionization", "Reionization history"], ["cmb_lensing", "CMB lensing"], ["cmb", "CMB experiments"], ["sampler", "Samplers"]]) for a in titles: self.atoms[a] = { "group": QGroupBox(titles[a]), "combo": QComboBox()} self.layout_options.addWidget(self.atoms[a]["group"]) self.atoms[a]["layout"] = QVBoxLayout(self.atoms[a]["group"]) self.atoms[a]["layout"].addWidget(self.atoms[a]["combo"]) self.atoms[a]["combo"].addItems( [text(k,v) for k,v in getattr(input_database, a).items()]) # Connect to refreshers -- needs to be after adding all elements for a in self.atoms: if a == "preset": self.atoms["preset"]["combo"].currentIndexChanged.connect( self.refresh_preset) continue self.atoms[a]["combo"].currentIndexChanged.connect(self.refresh) # Add Planck-naming checkbox and connect to refresher too self.planck_names = QCheckBox("Keep common names") self.atoms["theory"]["layout"].addWidget(self.planck_names) self.planck_names.stateChanged.connect(self.refresh) # RIGHT: Output + buttons self.display_tabs = QTabWidget() self.display = {} for k in ["yaml", "python"]: self.display[k] = QTextEdit() self.display[k].setLineWrapMode(QTextEdit.NoWrap) self.display[k].setFontFamily("mono") self.display[k].setCursorWidth(0) self.display[k].setReadOnly(True) self.display_tabs.addTab(self.display[k], k) self.layout_output.addWidget(self.display_tabs) # Buttons self.buttons = QHBoxLayout() self.save_button = QPushButton('Save', self) self.copy_button = QPushButton('Copy to clipboard', self) self.buttons.addWidget(self.save_button) self.buttons.addWidget(self.copy_button) self.save_button.released.connect(self.save_file) self.copy_button.released.connect(self.copy_clipb) self.layout_output.addLayout(self.buttons) self.save_dialog = QFileDialog() self.save_dialog.setFileMode(QFileDialog.AnyFile) self.save_dialog.setAcceptMode(QFileDialog.AcceptSave)