def __init__(self, world, parent=None): super().__init__(parent) self.info_text = [] self.performance = 0 self._animal_brush = QBrush(QColor(74, 172, 225)) self._food_brush = QBrush(QColor(100, 100, 100)) self._food_bitten_brush = QBrush(QColor(180, 140, 100)) self._mammoth_brush = QBrush(QColor(50, 50, 200)) self._animal_pen = Qt.NoPen self._selected_animal_pen = QPen(QColor(255, 180, 0), 3) self.selected_animal = None self.constants_window = None self.neural_network_viewer_window = None self.population_graph_window = None self.graphics_window = None self.loader_window = None self.setupUi(self) self.horizontalLayout.insertWidget(0, self.draw_widget) snapshot_dir = QDir('./snapshots/') snapshot_dir.mkpath('.') self.snapshot_directory_combobox.addItem(snapshot_dir.absolutePath()) self.world = world self.draw_widget.paintEvent = self.on_draw_widget_paintEvent self.draw_widget.mousePressEvent = self.on_draw_widget_mousePressEvent self.draw_widget.mouseMoveEvent = self.on_draw_widget_mouseMoveEvent self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.timer.start(self.TIMER_INTERVAL) self._prev_time = time.perf_counter()
def __load(self): """ Private slot to load the available scripts into the manager. """ scriptsDir = QDir(self.scriptsDirectory()) if not scriptsDir.exists(): scriptsDir.mkpath(self.scriptsDirectory()) if not scriptsDir.exists("requires"): scriptsDir.mkdir("requires") self.__disabledScripts = \ Preferences.getHelp("GreaseMonkeyDisabledScripts") from .GreaseMonkeyScript import GreaseMonkeyScript for fileName in scriptsDir.entryList(["*.js"], QDir.Files): absolutePath = scriptsDir.absoluteFilePath(fileName) script = GreaseMonkeyScript(self, absolutePath) if script.fullName() in self.__disabledScripts: script.setEnabled(False) if script.startAt() == GreaseMonkeyScript.DocumentStart: self.__startScripts.append(script) else: self.__endScripts.append(script)
def scan_for_csl_styles(self) -> dict: """Scans <app data>/csl_styles subdirectories for csl styles. Returns a dictionary with information about the styles that were found""" # Get all files in the csl_styles directory path = self.get_appdata_path() + "/csl_styles" directory = QDir(path) # Create directory if it doesn't exist if not directory.exists(): try: directory.mkpath(path) except Exception: print(f"Failed to create path: {path}") return dict() entries = directory.entryList(QDir.Files) # Iterate over files styles = dict() for entry in entries: if entry.endswith(".csl"): filepath = path + "/" + entry title = self.extract_csl_style_name(filepath) identifier = common.generate_identifier(title) if title is not None: styles[identifier] = {"name": title, "path": filepath} return styles
def __load(self): """ Private slot to load the available scripts into the manager. """ scriptsDir = QDir(self.scriptsDirectory()) if not scriptsDir.exists(): scriptsDir.mkpath(self.scriptsDirectory()) if not scriptsDir.exists("requires"): scriptsDir.mkdir("requires") self.__disabledScripts = Preferences.getWebBrowser( "GreaseMonkeyDisabledScripts") from .GreaseMonkeyScript import GreaseMonkeyScript for fileName in scriptsDir.entryList(["*.js"], QDir.Files): absolutePath = scriptsDir.absoluteFilePath(fileName) script = GreaseMonkeyScript(self, absolutePath) if not script.isValid(): del script continue self.__scripts.append(script) if script.fullName() in self.__disabledScripts: script.setEnabled(False) else: collection = WebBrowserWindow.webProfile().scripts() collection.insert(script.webScript()) self.__jsObject.setSettingsFile( os.path.join(Utilities.getConfigDir(), "web_browser", "greasemonkey_values.ini")) ExternalJsObject.registerExtraObject("GreaseMonkey", self.__jsObject)
def accept(self) -> None: """Checks if a specified directory is empty. If it isn't warns the user. If the directory doesn't exist attempts to create it""" accept = True path = self.ui.LocationLineEdit.text() directory = QDir(path) if directory.exists(): if not directory.isEmpty(): reply = QMessageBox.question(self, "Create project?", "The directory you specified is not empty." + "Are you sure that you want to create the project there?", QMessageBox.Yes | QMessageBox.No) if reply == QMessageBox.No: accept = False else: try: directory.mkpath(self.ui.LocationLineEdit.text()) except OSError as e: accept = False QMessageBox.critical(self, "Error", f"Failed to create project folder: {str(e)}") self.path = self.ui.LocationLineEdit.text() self.authors = self.ui.AuthoursLineEdit.text() self.project_type = self.ui.ProjectTypeComboBox.currentText() self.title = self.ui.TitleLineEdit.text() if accept: super().accept()
def create_project_structure(base_dir): base_qdir = QDir(base_dir) base_qdir.mkpath('normalizado/heStain') base_qdir.mkpath('train/print') base_qdir.mkpath('train/mitosis') base_qdir.mkpath('train/candidates') base_qdir.mkpath('test/mitosis') base_qdir.mkdir('anotations')
def getSettingsFile(): appPath = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) appDir = QDir(appPath) if not appDir.exists(): logger.debug('Creating app directory') appDir.mkpath(appDir.absolutePath()) else: logger.debug('App directory already exists') if appDir.setCurrent(appDir.absolutePath()): logger.debug('Changing cwd to app data directory') else: logger.debug('Changing cwd to app data directory failed') return QFile('settings.json')
def get_appdata_path(self) -> str: """Returns path to the directory, where app specific data is stored (i.e. styles, colors, templates etc). If the directory doesn't exist, creates it""" path = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) dir = QDir(path) # Create directory if it doesn't exist if not dir.exists(path): try: dir.mkpath(path) except Exception: print(f"Failed to create app data directory at path: {path}") return QStandardPaths.writableLocation(QStandardPaths.AppDataLocation)
def scan_for_color_schemas(self) -> dict: """Scans <app data>/color_schemes subdirectories for color schemas. Returns a dictionary with information about the color schemes that were found""" # Get the list of all subdirectories path = self.get_appdata_path() + "/color_schemas" directory = QDir(path) # Create directory if it doesn't exist if not directory.exists(path): try: directory.mkpath(path) except Exception: print(f"Failed to create path: {path}") subdirectories = directory.entryList(QDir.Dirs | QDir.NoDotAndDotDot) schemas = dict() # Iterate over subdirectories to check if they contain color schemas for subdirectory in subdirectories: directory.cd(subdirectory) entries = directory.entryList(QDir.Files) # Check if schema file is present if "schema.toml" in entries: schema_info = dict() filepath = path + "/" + subdirectory + "/" + "schema.toml" # Try to parse color schema try: schema = toml.load(filepath) name = schema["Schema name"] schema_info["name"] = name schema_info["path"] = filepath schemas[name] = schema_info except Exception as e: print( f"Failed to parse color schema at path: {filepath}. Error: {str(e)}" ) return schemas
def tempDirCreate(self, basedir, name=None): tmpdir = QDir(basedir) if not tmpdir.exists(): return uid = name if name else str(uuid.uuid4()) path = tmpdir.absoluteFilePath(uid) if tmpdir.mkpath(path): return path
def import_css_style_from_file(self, filepath: str, style_name: str) -> None: """Imports a css style from a file""" # Generate style identifier used_identifiers = set( self.get_setting_value("Render/Css_styles").keys()) style_identifier = common.generate_identifier( style_name, used_identifiers=used_identifiers, placeholder="Style") try: # Create directory for the style and copy it style_path = self.get_appdata_path( ) + "/css_styles/" + style_identifier directory = QDir(self.get_appdata_path()) directory.mkpath(style_path) new_path = style_path + "/style.css" QFile.copy(filepath, new_path) except Exception: print(f"Failed to copy css style to path: {style_path}") return styles = self.get_setting_value("Render/Css_styles") style_info = { "identifier": style_identifier, "name": style_name, "path": new_path } try: # Generate description.toml file_handle = open(style_path + "/description.toml", "w+") toml.dump(style_info, file_handle) file_handle.close() except Exception as e: print(f"Failed to create style description. Error: {str(e)}") return # Add style to settings manager styles[style_identifier] = style_info self.set_setting_value("Render/Css_styles", styles)
def new_campaign(self): dialog = QFileDialog(self) dialog.setDirectory(helper.one_up(self.current_dir)) dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.setFileMode(QFileDialog.AnyFile) dialog.setOption(QFileDialog.ShowDirsOnly) dialog.setWindowTitle('Select folder name') if dialog.exec_(): directory = dialog.selectedFiles()[0] qdir = QDir(directory) if not qdir.exists(): self.current_dir = qdir.path() for folder_name in resource.folders: qdir.mkpath('./' + folder_name) helper.save_json_data( '{}/{}/health{}'.format(self.current_dir, resource.health_stat.folder, resource.health_stat.ext), resource.health_stat.default) qdir.mkpath('./.settings/std') qdir.mkpath('./.settings/debug') resource.create_config_files(self.current_dir, qdir.dirName()) self.refresh_tree_view() else: helper.display_error('Directory for campaign already exists.' ) # This shouldn't happen
def create_project(directory_path: str) -> None: """Creates a new project at given path""" try: directory = QDir(directory_path) directory.mkdir(".manuwrite") directory.mkdir("images") directory.mkdir("notes") directory.mkdir("data") directory.mkpath(".manuwrite/render") file = QFile() file.setFileName(directory_path + "/.manuwrite/project.toml") file.open(QFile.ReadWrite) project_settings = copy.deepcopy(defaults.project_settings) project_settings["Absolute path"] = {"type": "str", "value": directory_path} file.write(toml.dumps(project_settings).encode()) file.close() except OSError: raise ProjectError("Error creating project files")
def __init__(self, parent=None): super().__init__(parent) self.info_text = [] self.performance = 0 self._animal_brush = QBrush(QColor(74, 172, 225)) self._food_brush = QBrush(QColor(100, 100, 100)) self._food_bitten_brush = QBrush(QColor(180, 140, 100)) self._mammoth_brush = QBrush(QColor(50, 50, 200)) self._animal_pen = Qt.NoPen self._selected_animal_pen = QPen(QColor(255, 180, 0), 3) self.selected_animal = None self.constants_window = None self.neural_network_viewer_window = None self.population_graph_window = None self.graphics_window = None self.setupUi(self) self.horizontalLayout.insertWidget(0, self.draw_widget) snapshot_dir = QDir('./snapshots/') snapshot_dir.mkpath('.') self.snapshot_directory_combobox.addItem(snapshot_dir.absolutePath()) world_constants = WorldConstants() self.draw_widget.setFixedWidth(world_constants.WORLD_WIDTH) self.draw_widget.setFixedHeight(world_constants.WORLD_HEIGHT) self.world = world.World(constants=world_constants, save_genealogy=False) self.mammoth_analyzer = MammothAnalyzer(self.world) self.draw_widget.paintEvent = self.on_draw_widget_paintEvent self.draw_widget.mousePressEvent = self.on_draw_widget_mousePressEvent self.draw_widget.mouseMoveEvent = self.on_draw_widget_mouseMoveEvent self.timer = QTimer(self) self.timer.timeout.connect(self.on_timer_timeout) self.timer.start(self.TIMER_INTERVAL) self._prev_time = time.clock()
def scan_for_css_styles(self) -> dict: """Scans <app data>/css_styles subdirectories for css styles. Returns a dictionary with information about the styles that were found""" # Get the list of all subdirectories path = self.get_appdata_path() + "/css_styles" directory = QDir(path) if not directory.exists(): try: directory.mkpath(path) except Exception: print(f"Failed to create path: {path}") return dict() subdirectories = directory.entryList(QDir.Dirs | QDir.NoDotAndDotDot) styles = dict() # Iterate over subdirectories to check if they contain styles for subdirectory in subdirectories: directory.cd(subdirectory) entries = directory.entryList(QDir.Files) # Check if necessary files are present if "description.toml" in entries and "style.css" in entries: # Parse description try: style_info = toml.load(path + "/" + subdirectory + "/" + "description.toml") style_info[ "path"] = path + "/" + subdirectory + "/" + "style.css" styles[style_info["identifier"]] = style_info except Exception as e: print( f"Failed to parse css style at path: {path + '/' + subdirectory}. Error: {str(e)}" ) return styles
def check_path(path: str): """ Checks if path exists. If not, creates one. :param path: Path to check. """ check_dir = QDir(path) if not check_dir.exists(): if Tools.is_verbose(): print("Not exists '%s'." % path) if not check_dir.mkpath(".") and Tools.is_verbose(): print("Could not create '%s'" % path) elif Tools.is_verbose(): print("Created '%s'" % path) elif Tools.is_verbose(): print("Exists '%s'." % path)
def saveStamp(self, stamp): # make sure we have a stamps directory prefs = preferences.Preferences.instance() stampsDirectory = prefs.stampsDirectory() stampsDir = QDir(stampsDirectory) if (not stampsDir.exists() and not stampsDir.mkpath(".")): qDebug("Failed to create stamps directory" + stampsDirectory) return filePath = stampsDir.filePath(stamp.fileName()) file = QSaveFile(filePath) if (not file.open(QIODevice.WriteOnly)): qDebug("Failed to open stamp file for writing" + filePath) return stampJson = stamp.toJson(QFileInfo(filePath).dir()) file.write(QJsonDocument(stampJson).toJson(QJsonDocument.Compact)) if (not file.commit()): qDebug() << "Failed to write stamp" << filePath
def veritabaniBaglan(): veritabani = QSqlDatabase.database() if not veritabani.isValid(): veritabani = QSqlDatabase.addDatabase("QSQLITE") if not veritabani.isValid(): logger.error("Veritabanı Eklenemedi !") yaz_dir = QDir() if not yaz_dir.mkpath("."): logger.error("Yazılabilir dizin oluşturulamadı !") # Erişilebilir bir veritabanı dosyası oluşturulmuştur. dosyaAdi = "{}/chat-database.sqlite3".format(yaz_dir.absolutePath()) # Veritabanı mevcut değilse open() fonksiyonu SQLite'ı oluşturacaktır. veritabani.setDatabaseName(dosyaAdi) if not veritabani.open(): logger.error("Veritabanı Açılamadı") QFile.remove(dosyaAdi)
def saveDirectory(self, dirName): """ Public method to save the search engine definitions to files. @param dirName name of the directory to write the files to (string) """ dir = QDir() if not dir.mkpath(dirName): return dir.setPath(dirName) from .OpenSearchWriter import OpenSearchWriter writer = OpenSearchWriter() for engine in list(self.__engines.values()): name = self.generateEngineFileName(engine.name()) fileName = dir.filePath(name) file = QFile(fileName) if not file.open(QIODevice.WriteOnly): continue writer.write(file, engine)
def Dir(dir_path, create=True): """ Take dir path, return absolute path, or False if error. Create new folder by default. """ METHOD_NAME = f"Blister.Dir" if type(dir_path) != type(str()): print(f"{METHOD_NAME}: Invalid input type {type(dir_path)}. String only.", end='\n') return False dir_info = QFileInfo(dir_path) if (dir_info.exists() and (not dir_info.permission(QFile.WriteUser))): print(f"{METHOD_NAME}: Writing in this dir is not permitted:\n\t{dir_info.absoluteFilePath()}", end='\n') return False if ((not dir_info.exists()) and (not create)): print(f"{METHOD_NAME}: This dir does not exist [creating new is forbidden]:\n\t{dir_info.absoluteFilePath()}", end='\n') return False if ((not dir_info.exists()) and create): result = QDir.mkpath(QDir(), dir_info.absoluteFilePath()) if not result: print(f"{METHOD_NAME}: Creating new dir was failed:\n\t{dir_info.absoluteFilePath()}", end='\n') return False else: print(f"{METHOD_NAME}: New dir was created:\n\t{dir_info.absoluteFilePath()}", end='\n') return dir_info.absoluteFilePath()
def createDirectory(self): path = self.model.filePath(self.rootIndex()) directory = QDir() directory.setPath(path) directory.mkpath("New Folder")
def __init__(self): super(TileImages, self).__init__() self.images_list = [] self.images_number = False self.images_panda = False self.images_folder = IMG_FOLDER_NAME + QDir.separator() path_dir = QDir() if path_dir.exists(IMG_FOLDER_NAME): self.images_number = True file_list = [] for idx in range(16): file_path = self.images_folder + "number_" + str(idx) + ".png" if not QFile(file_path).exists(): self.images_number = False file_list = [] break try: img = Image.open(file_path) image_width, image_height = img.size # Get image dimensions if image_width != IMG_SIZE or image_height != IMG_SIZE: resize_slice = Image.open(file_path) resize_slice = resize_slice.resize( (IMG_SIZE, IMG_SIZE), Image.ANTIALIAS) resize_slice.save(os.path.join(os.getcwd(), file_path)) file_list.append(file_path) except IOError: self.images_number = False file_list = [] break self.images_list.append(file_list) if self.images_number: self.tile_images = True self.images_in_use = [] for img in self.images_list[0]: self.images_in_use.append(img) self.images_panda = True file_list = [] for idx in range(16): file_path = self.images_folder + "panda_" + str(idx) + ".png" if not QFile(file_path).exists(): self.images_panda = False file_list = [] break try: img = Image.open(file_path) image_width, image_height = img.size # Get image dimensions if image_width != IMG_SIZE or image_height != IMG_SIZE: resize_slice = Image.open(file_path) resize_slice = resize_slice.resize( (IMG_SIZE, IMG_SIZE), Image.ANTIALIAS) resize_slice.save(os.path.join(os.getcwd(), file_path)) file_list.append(file_path) except IOError: self.images_panda = False file_list = [] break self.images_list.append(file_list) else: path_dir.mkpath(IMG_FOLDER_NAME) self.actionPandaBabies.setEnabled(False)
def create_folder(): new_id = CreateResourceDialog.get_new_id('folder') if new_id is not None and new_id.strip() != '': qdir = QDir(folder_location) qdir.mkpath('./' + new_id)
def __init__(self): super(Homepage, self).__init__() self.path = QDir('C:/Speedtest_Save') if not QDir.exists(self.path): print("Folder is not Exisiting! Please Wait till it create New.......") #if the folder doesn't exist it throws the message dir = QDir() newfolder = 'C:/SpeedTest_Save' #Creating the new folder dir.mkpath(newfolder) self.myfile = 'C:/SpeedTest_Save' + '/Speedtest_results.csv' #saving the file self.isChanged = False self.setStyleSheet(design(self)) self.speedtestExec = "C:/Users/jagan/speedtest-cli.exe" #executable file path for the speedtest self.cmd = '' print("Cmd started") self.list = [] print("list started") self.date = "" print("date started") self.time = "" print("time started") self.download = "" print("download started") self.upload = "" print("upload started") self.ping = "" print("Ping started") self.server = "" print("Server started") self.process = QProcess(self) print("Process Started") self.process.started.connect(lambda: self.showMessage("Speed Test Has Been Started")) #showing the test messages print("Test Started") print("Test Completed") self.process.finished.connect(self.processFinished) self.process.readyRead.connect(self.processOut) self.tableview = QTableWidget() print("Table creation success") self.tableview.setColumnCount(6) print("Process Started") self.setHeaders() print("Process Started for the headers") self.tableview.verticalHeader().setVisible(False) print("Process Started") self.tableview.horizontalHeader().setVisible(False) print("Process Started") self.tableview.setSelectionBehavior(QAbstractItemView.SelectRows) print("Process Started") self.setCentralWidget(self.tableview) self.setWindowIcon(QIcon.fromTheme('network')) self.toolbarcreation() self.createStatusBar() self.readSettings() print("read setting started") self.combofillbox() self.title = "frame" self.setMinimumSize(440, 220)
def test_standard(self): qdir = QDir(self.current_dir) qdir.mkpath('./.run') file_location = self.current_dir + '/.run/std.trpg' export.export_to_file(self.current_dir, file_location) dialog = ConsoleDialog(file_location).exec_()