def setupProducerConfig(self): global sampleConfig, streamName if self.options['--config_file']: self.config = libconf.load(self.options['--config_file']) else: self.config = libconf.loads(sampleConfig) self.config['general']['log_path'] = self.runDir if self.options['--verbose']: self.config['general']['log_level'] = 'all' self.config['produce']['streams'][0]['source'][ 'name'] = self.sourcePipe # customize other things, if options are available if self.options['--video_size']: # TODO logger.debug("will setup video size here") if self.options['--bitrate']: # TODO logger.debug("will setup bitrate here") if self.options['--stream_name']: streamName = self.options['--stream_name'] self.config['produce']['streams'][0]['name'] = self.options[ '--stream_name'] if self.options['--thread_name']: self.config['produce']['streams'][0]['threads'][0][ 'name'] = self.options['--thread_name'] # save config to a temp file self.configFile = os.path.join(self.runDir, 'producer.cfg') with io.open(self.configFile, mode="w") as f: libconf.dump(self.config, f) logger.debug("saved config to %s" % self.configFile)
def DumpMethod(FilePath: str, Config: dict) -> None: FilePath = os.path.expanduser(FilePath) assert os.path.exists( FilePath), "Cannot find the configfile {}".format(FilePath) f = io.open(FilePath, 'w') libconf.dump(Config, f) f.close()
def setupConsumerConfig(self): global sampleConfig, streamName if self.options['--config_file']: self.config = libconf.load(self.options['--config_file']) else: self.config = libconf.loads(sampleConfig) self.config['general']['log_path'] = self.runDir if self.options['--verbose']: self.config['general']['log_level'] = 'all' streamPrefix = self.options['<stream_prefix>'] if self.options['--instance_name']: utils.ndnrtcClientInstanceName = self.options[ '--instance_name'] self.basePrefix = streamPrefix if streamPrefix.endswith( utils.ndnrtcClientInstanceName) else os.path.join( streamPrefix, utils.ndnrtcClientInstanceName) self.config['consume']['streams'][0][ 'base_prefix'] = self.basePrefix self.sinkPipe = os.path.join(self.runDir, 'sink') self.config['consume']['streams'][0]['sink'][ 'name'] = self.sinkPipe if self.options['--stream_name']: streamName = self.options['--stream_name'] self.config['consume']['streams'][0]['name'] = self.options[ '--stream_name'] if self.options['--thread_name']: self.config['consume']['streams'][0][ 'thread_to_fetch'] = self.options['--thread_name'] self.configFile = os.path.join(self.runDir, 'consumer.cfg') with io.open(self.configFile, mode="w") as f: libconf.dump(self.config, f) logger.debug("saved config to %s" % self.configFile)
def write_config_file(self, file_path): try: f = open(file_path, 'w') libconf.dump(self.output, f) self.output = dict() # erase output dictionary except Exception as e: print 'Failed to write to file ', e raise
def test_dump(): example_file = os.path.join(CURDIR, 'test_e2e.cfg') with io.open(example_file, 'r', encoding='utf-8') as f: c = libconf.load(f, includedir=CURDIR) with open('test_e2e_copy.cfg', 'w+') as f: libconf.dump(c, f) with io.open('test_e2e_copy.cfg', 'r', encoding='utf-8') as f: c_dumped = libconf.load(f, includedir=CURDIR) assert c == c_dumped
def WriteInputFile(self, FileName='gitrInput.cfg', Folder='', OverWrite=False): FileName = os.path.abspath(os.path.join(Folder,FileName)) print('Writing input config into {} ...'.format(FileName)) if os.path.exists(FileName): if not OverWrite and not click.confirm('File {} exists.\n Do you want to overwrite it?'.format(FileName), default=True): return with io.open(FileName,'w') as f: libconf.dump(self.Input,f)
def test_dump_roundtrip(): example_file = os.path.join(CURDIR, 'test_e2e.cfg') with io.open(example_file, 'r', encoding='utf-8') as f: c = libconf.load(f, includedir=CURDIR) with io.StringIO() as f: libconf.dump(c, f) f.seek(0) c_dumped = libconf.load(f, includedir=CURDIR) assert c == c_dumped
def ModConfig(self): """修改系统配置信息: 成功返回True,否则False。""" try: f = io.open(self.File_Path, 'w', encoding='utf-8') except: logging.error(u'解析配置文件异常 : %s' % traceback.format_exc()) return False else: with f: libconf.dump(self.CfgInfo, f) return True
def serialize_jobs(self): # Make a backup of the job file if os.path.exists(config.HELHEIMR_CONFIG_FILE_SCHEDULED_JOBS): bak = config.HELHEIMR_CONFIG_FILE_SCHEDULED_JOBS + '.bak' rsp = common.safe_shell_output( 'cp', config.HELHEIMR_CONFIG_FILE_SCHEDULED_JOBS, bak) if rsp.success: _logger.info(f'Made a backup of the job file at {bak}.') else: _logger.error( f'Cannot backup the job file {config.HELHEIMR_CONFIG_FILE_SCHEDULED_JOBS}: {rsp.output}' ) _ = translation.translator_fx() broadcast.error(_( 'Cannot backup the scheduled jobs, please check the log.'), source=broadcast.SRC_SCHEDULER) self._condition_var.acquire() # Each job class (e.g. periodic heating) has a separate group within the configuration file: # Periodic heating jobs: phjs = [j for j in self.jobs if isinstance(j, PeriodicHeatingJob)] # Sort them by at_time: phds = [j.to_dict() for j in sorted(phjs, key=lambda j: j.at_time)] # Periodic non-heating jobs: pnhjs = [ j.to_dict() for j in self.jobs if isinstance(j, NonHeatingJob) ] self._condition_var.release() try: lcdict = { type(self).JOB_LIST_CONFIG_KEY_PERIODIC_HEATING: tuple(phds), type(self).JOB_LIST_CONFIG_KEY_PERIODIC_NON_HEATING: tuple(pnhjs) } with open(config.HELHEIMR_CONFIG_FILE_SCHEDULED_JOBS, 'w') as f: libconf.dump(lcdict, f) _logger.info( f'Successfully serialized the job list to {config.HELHEIMR_CONFIG_FILE_SCHEDULED_JOBS:s}.' ) return True except: err_msg = traceback.format_exc(limit=3) _logger.error('Error while serializing:\n' + err_msg) return False
def WriteGeomFile(self, FileName='gitrGeom.cfg', Folder='', GeoDim='3D', OverWrite=False): FileName = os.path.abspath(os.path.join(Folder, FileName)) print('Writing geometry config into {} ...'.format(FileName)) self.CheckGeomInput() if os.path.exists(FileName): if not OverWrite and not click.confirm( 'File {} exists.\n Do you want to overwrite it?'.format( FileName), default=True): return with io.open(FileName, 'w') as f: libconf.dump(self.ConvertGeomInput(), f)
def write_hal_config_file(file_name, dict): with open(file_name, 'w') as f: print('Writing HAL configuration into file:', file_name) libconf.dump(dict, f)
def main(argv): usage = "Usage: convert_theme.py <input theme dir> <output theme.zip>" if len(argv) < 2: print(usage) return -1 in_dir = Path(argv[0]) if not in_dir.is_dir(): print("Invalid input directory") return -1 tmp_dir = Path("tmp_convert") if not tmp_dir.exists(): tmp_dir.mkdir() try: icon = Image.open(Path(in_dir, "icon.png")) icon = icon.resize((256, 256)).convert("RGB") icon.save(Path(tmp_dir, "icon.jpg")) except FileNotFoundError: pass cfg_info = {"info": {}} try: xml_info = ET.parse(Path(in_dir, "meta.xml")).getroot() name = xml_info.find("name") if name is None: cfg_info["info"]["name"] = in_dir.name else: cfg_info["info"]["name"] = name.text author = xml_info.find("coder") if author is None: cfg_info["info"]["author"] = "Unspecified Author" else: cfg_info["info"]["author"] = author.text version = xml_info.find("version") if version is None: cfg_info["info"]["version"] = "1.0" else: cfg_info["info"]["version"] = version.text with Path(tmp_dir, "info.cfg").open("w") as f: libconf.dump(cfg_info, f) except FileNotFoundError: pass try: with zipfile.ZipFile(Path(in_dir, "theme.zip"), "r") as zf: try: cfg_styles = {"styles": {}} with zf.open("theme.xml") as f: xml_styles = ET.parse(f).getroot() norm_text_col = xml_styles.find("font_color") if norm_text_col is not None: cfg_styles["styles"][ "normal_text_color"] = color_from_elem( norm_text_col) prog_grad = xml_styles.find("progress_gradient") if prog_grad is not None: main_col = [ prog_grad.find("upper_left"), prog_grad.find("upper_right") ] main_col = [ color_from_elem(x) for x in main_col if x is not None ] main_col = int(sum(main_col) / len(main_col)) grad_col = [ prog_grad.find("lower_left"), prog_grad.find("lower_right") ] grad_col = [ color_from_elem(x) for x in grad_col if x is not None ] grad_col = int(sum(grad_col) / len(grad_col)) cfg_styles["styles"][ "remote_bar_main_color"] = main_col cfg_styles["styles"][ "remote_bar_grad_color"] = grad_col with Path(tmp_dir, "styles.cfg").open("w") as f: libconf.dump(cfg_styles, f) except KeyError: pass for old_name, (new_name, new_size) in asset_names.items(): try: with zf.open(old_name, "r") as f: im = Image.open(f) im = im.resize(new_size) im.save(Path(tmp_dir, new_name)) except KeyError: pass except FileNotFoundError: pass res = gen_theme.main([tmp_dir, argv[1]]) if res != 0: return res shutil.rmtree(tmp_dir) return 0
def create_profile(self, config): config[self.profile] = {} with open(self.config_directory + self.config_name, "w+") as f: libconf.dump(config, f) f.close()
def create_config(): config = {"default_profile": "tdbot", "tdbot": {}} with open(CONFIG_DIRECTORY + "/config", "w+") as f: libconf.dump(config, f) f.close()
def create_swdesc_file(images, path): """Create a sw-description file for an update payload.""" with open(str(path), mode="wt") as f: libconf.dump(_generate_swdesc(images), f)
def main(): parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter, description='''Generate (signed) swu-update file, based on information from a template sw-description.''') parser.add_argument("template", metavar="TEMPLATE", help="sw-description template (sw-decription.in)") parser.add_argument("--debug", action="store_true", dest="debug", default=False, help="Enable various features for debugging") parser.add_argument("-k", "--key", dest="key", help="""pkcs11 uri or file name of the key used for signing the update""") parser.add_argument("-o", "--output", dest="output", default="firmware.swu", help="filename of the resulting update file") parser.add_argument("-C", "--chdir", dest="chdir", help="""directory where the sw-update cpio archive is built""") parser.add_argument("-L", "--libdir", dest="libdirs", action="append", default=['.'], help="""add path where files (e.g. images and scripts) are searched""") opt = parser.parse_args() # make all paths absolute swdescription_in = os.path.abspath(opt.template) if opt.key: keyfile = os.path.abspath(opt.key) opt.output = os.path.abspath(opt.output) opt.libdirs = [os.path.abspath(p) for p in opt.libdirs] if not opt.chdir: temp = TemporaryDirectory() opt.chdir = temp.name os.chdir(opt.chdir) fp = codecs.open(swdescription_in, 'r', 'utf-8') cc = libconf.load(fp, filename=swdescription_in) for i in find_key('images', cc.software): handle_image(i, opt) for i in find_key('scripts', cc.software): handle_script(i, opt) for i in find_key('files', cc.software): handle_script(i, opt) fp = codecs.open('sw-description', 'w', 'utf-8') libconf.dump(cc, fp) fp.close() files = ['sw-description'] if opt.key: if os.path.isfile(keyfile): logging.warning("""Please consider providing a pkcs11 uri instead of a key file.""") sign_cmd = 'openssl dgst -sha256 \ -sign "%s" sw-description \ > sw-description.sig' % keyfile else: sign_cmd = 'openssl dgst -sha256 \ -engine pkcs11 \ -keyform engine \ -sign "%s" sw-description \ > sw-description.sig' % opt.key # Preventing the malloc check works around Debian bug #923333 if os.system('MALLOC_CHECK_=0 ' + sign_cmd) != 0: print('failed to sign sw-description') files.append('sw-description.sig') for i in find_key('images', cc.software): if 'filename' in i: files.append(i.filename) for i in find_key('scripts', cc.software): if 'filename' in i: files.append(i.filename) for i in find_key('files', cc.software): if 'filename' in i: files.append(i.filename) swfp = open(opt.output, 'wb') cpio_cmd = 'paxcpio' cpio_opt = '-L' if not shutil.which(cpio_cmd): cpio_cmd = 'cpio' cpio_opt = '--dereference' cpio = Popen([cpio_cmd, '-ov', '-H', 'crc', cpio_opt], stdin=PIPE, stdout=swfp) files_for_cpio = [] for i in files: if i not in files_for_cpio: files_for_cpio.append(i) for n in files_for_cpio: if cpio_cmd == 'cpio' and os.path.getsize(n) > (2 << 30): logging.warning( '''%s is greater than 2GiB. %s will have a bad checksum with GNU cpio. Install paxcpio or configure SWUpdate with DISABLE_CPIO_CRC.''', n, opt.output) cpio.stdin.write(bytes(n + '\n', 'utf-8')) cpio.stdin.close() cpio.wait() swfp.close() print('finished')
def makeGeom(inFile='d3drzZ.csv', filename="gitrD3DGeometry2DWringsPy.cfg", plot=1): float_format = "%.6f" rzZ = np.loadtxt(inFile, dtype='float', delimiter=',') Z = rzZ[:, 2] Z = np.append(Z, 0) x1 = rzZ[:, 0] x2 = rzZ[1:, 0] x2 = np.append(x2, rzZ[0, 0]) z1 = rzZ[:, 1] z2 = rzZ[1:, 1] z2 = np.append(z2, rzZ[0, 1]) slope = (z2 - z1) / (x2 - x1) tol = 1.0e-9 vertical_lines = np.where(abs(x2 - x1) < tol) horizontal_lines = np.where(abs(z2 - z1) < tol) intercept = -slope * x1 + z1 print('x1 z1 ', x1[0:3], z1[0:3]) print('x2 z2 ', x2[0:3], z2[0:3]) print('slope intercept', slope[0:3], intercept[0:3]) slope[vertical_lines] = np.sign(z2[vertical_lines] - z1[vertical_lines]) * 1.0e12 intercept[vertical_lines] = 1.0e12 print('slope intercept', slope[0:3], intercept[0:3]) slope[horizontal_lines] = 0 inDir = np.ones(x1.size + 1) reverseDir = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 19, 21, 25, 37, 38, 39, 47, 48, 49, 50, 51, 52, 54 ] inDir[reverseDir] = -1 intercept[horizontal_lines] = z1[horizontal_lines] print('slope intercept', slope[0:3], intercept[0:3]) line_length = np.sqrt( np.multiply(x2 - x1, x2 - x1) + np.multiply(z2 - z1, z2 - z1)) surface = np.zeros(x1.size + 1) w_indices = np.where(Z > 0) w_indices = w_indices[0] w_indices2 = np.append(w_indices[1:len(w_indices)], w_indices[0]) geom_indices = np.where(np.subtract(w_indices2, w_indices) == 1) surface[w_indices[geom_indices]] = 1 if plot == 1: plt.close() plt.figure(1, figsize=(6, 10), dpi=60) for i in range(len(x1)): if (slope[i] == 0.0): perpSlope = 1.0e12 else: perpSlope = math.copysign(1.0, slope[i]) / abs(slope[i]) Bx = -1.0 / math.sqrt(perpSlope * perpSlope + 1.0) By = 0.0 Bz = math.copysign(1.0, perpSlope) * math.sqrt(1.0 - Bx * Bx) plt.quiver(0.5 * (x1[i] + x2[i]), 0.5 * (z1[i] + z2[i]), Bx * inDir[i], Bz * inDir[i]) plt.text(0.5 * (x1[i] + x2[i]), 0.5 * (z1[i] + z2[i]), str(i)) if (surface[i] == 1): plot_color = 'green' surface_plot, = plt.plot([x1[i], x2[i]], [z1[i], z2[i]], linewidth=2.0, color=plot_color, label='Surface') else: plot_color = 'blue' boundary_plot, = plt.plot([x1[i], x2[i]], [z1[i], z2[i]], linewidth=2.0, color=plot_color, label='Boundary') plt.scatter(x1, z1) plt.autoscale(enable=True, axis='x', tight=True) plt.title('DIII-D W Geometry Creation', fontsize=20) plt.xlabel('r [m]', fontsize=16) plt.ylabel('z [m]', fontsize=16) plt.legend(handles=[surface_plot, boundary_plot]) print('saving geometry plot') plt.savefig('geometry.png') plt.show() fileExists = os.path.exists(filename) if not fileExists: f = open(filename, "w") f.close() with io.open(filename) as f: config = libconf.load(f) config['geom'] = {} config['geom']['x1'] = x1.tolist() config['geom']['z1'] = z1.tolist() config['geom']['x2'] = x2.tolist() config['geom']['z2'] = z2.tolist() config['geom']['slope'] = ['%.6f' % elem for elem in slope.tolist()] config['geom']['intercept'] = [ '%.6f' % elem for elem in intercept.tolist() ] config['geom']['length'] = line_length.tolist() config['geom']['Z'] = Z.tolist() config['geom']['surface'] = ['%i' % elem for elem in surface.tolist()] config['geom']['inDir'] = ['%i' % elem for elem in inDir.tolist()] config['geom']['y1'] = 0.0 config['geom']['y2'] = 0.0 config['geom']['periodic'] = 0 with io.open(filename, 'w') as f: libconf.dump(config, f)
def writeConfig(data, filePath): with io.open(filePath, 'w') as f: libconf.dump(data, f)