def __init__(self, app, hostname='localhost', port=9000, pidfile='/var/run/decanter.pid', development=False): self.app = app self.hostname = hostname self.port = int(port) self.pidfile = pidfile self.config = Config() if 'timezone' in self.config: os.environ['TZ'] = self.config.timezone if 'memfile_max' in self.config: bottle.Request.MEMFILE_MAX = self.config.memfile_max # remove all default bottle plugins bottle.uninstall(True) bottle.debug(self.config.debug) # install plugins self.install_plugins(config=self.config) if self.config.debug or not development: stdout = os.popen('tty').read().strip() stderr = os.popen('tty').read().strip() if not development: super(Decanter, self).__init__(pidfile, stdout=stdout, stderr=stderr)
def main(): args = parse_args() cfg = Config(args.cfg) dataset = cfg.get_dataset('test') height, width = cfg['datasets']['test']['parameters']['img_size'] print('Using resolution {}x{}'.format(width, height)) if not args.view: video = create_video(args.out, width, height) # add_cover_img(video, args.cover) with open(args.pred, "rb") as pred_file: predictions = pickle.load(pred_file) for idx, pred in tqdm(zip(range(len(dataset)), predictions), total=len(dataset)): if idx < 2200: continue if idx > 3000: break det_pred, cls_pred = pred assert det_pred.shape[0] == 1 # batch size == 1 frame = dataset.draw_annotation(idx, pred=det_pred[0].cpu().numpy(), cls_pred=cls_pred[0].cpu().numpy() if cls_pred is not None else None) assert frame.shape[:2] == (height, width) if args.view: cv2.imshow('frame', frame) cv2.waitKey(0) else: video.write(frame) if not args.view: video.release() print('Video saved as {}'.format(args.out))
def __init__(self, dhcp_leases_file, port_type, config_path=None): self.log = logger.getlogger() self.cfg = Config(config_path) self.dhcp_leases_file = dhcp_leases_file self.port_type = port_type self.inv = Inventory(cfg_file=config_path) self.log.debug('Add ports, port type: {}'.format(self.port_type))
def setUp(self): config = Config() config.pkgdir = 'test/data/res/packages' config.schema = 'res/itemschema.json' config.localedir = 'test/data/res' self.app = Application() self.app.setup(config)
def save_mask(cfg_path, output_path): cfg = Config(cfg_path) frequency = get_anchors_use_frequency(cfg, split='train', t_pos=30., t_neg=35.) torch.save(frequency, output_path)
def enable_deployer_gateway(config_path=None, remove=False): """Configure or remove NAT record for PXE Network gateway Args: remove (bool, optional): True(default)= configure NAT record if it does not already exist. False = Remove NAT record if it exists. """ cfg = Config(config_path) log = logger.getlogger() if not remove: log.info('Configure NAT record for PXE network gateway') else: log.info('Remove NAT record for PXE network gateway') type_ = cfg.get_depl_netw_client_type() dev_label = cfg.get_depl_netw_client_device() bridge_ipaddr = cfg.get_depl_netw_client_brg_ip() netprefix = cfg.get_depl_netw_client_prefix() for i, dev in enumerate(dev_label): if cfg.get_depl_gateway() and type_[i] == "pxe": _create_nat_gateway_rule( bridge_ipaddr[i] + "/" + str(netprefix[i]), remove)
def __init__(self, config_path=None, name=None): self.log = logger.getlogger() self.cfg = Config(config_path) self.cont_package_path = gen.get_container_package_path() self.cont_id_file = gen.get_container_id_file() self.cont_venv_path = gen.get_container_venv_path() self.cont_scripts_path = gen.get_container_scripts_path() self.cont_python_path = gen.get_container_python_path() self.cont_os_images_path = gen.get_container_os_images_path() self.cont_playbooks_path = gen.get_container_playbooks_path() self.depl_package_path = gen.get_package_path() self.depl_python_path = gen.get_python_path() self.depl_playbooks_path = gen.get_playbooks_path() if name is True or name is None: for vlan in self.cfg.yield_depl_netw_client_vlan('pxe'): break self.name = '{}-pxe{}'.format(self.DEFAULT_CONTAINER_NAME, vlan) else: self.name = name self.client = docker.from_env() try: self.image = self.client.images.get('power-up') except docker.errors.ImageNotFound: self.image = None try: self.cont = self.client.containers.get(self.name) except docker.errors.NotFound: self.cont = None
def main() -> None: """ TODO """ config = Config( basename="trellod", api_key=None, api_secret=None, oauth_token=None, oauth_token_secret=None, ) if config.api_key is None: config.set(**authorize()) client = login(config) board_name = None board = select_board(client, board_name) # lists = select_lists(board) lists = board.open_lists() filename = f"Trello {board.name.strip()}.xlsx" dump_trello(filename, lists) # download_images_in_lists(lists) webbrowser.open(f"file://{Path(filename).resolve()}")
def main(): parser = make_argument_parser() args = parser.parse_args() logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=args.loglevel) config = Config() if sys.platform in ('linux2', 'darwin') and args.syslog: from logging.handlers import SysLogHandler handler = SysLogHandler(address=get_syslog_address()) log.addHandler(handler) if args.config_file: config.load_config(args.config_file) if args.get: log.debug("getting %s", args.get) section, option = args.get.split(".", 1) v = config.get(section, option) if v is not None: print v exit(0) elif not args.taskdir: parser.error("taskdir required") if not os.path.exists(args.taskdir): log.error("%s doesn't exist", args.taskdir) exit(1) runner(config, args.taskdir, args.times) if args.halt_after and config.halt_task: halt_cmd = os.path.join(args.taskdir, config.halt_task) log.info("finishing run with halt task: %s" % halt_cmd) run_task(halt_cmd, os.environ, config.max_time)
def run(self, global_args): local_args = self._local_args config = Config() env_args = [{ 'map_name': local_args.map_name } for _ in range(local_args.env_num)] env_args[0]['visualize'] = local_args.visualize with tf.device(self.tf_device(global_args)): agent = A2C(network_creator=network_creator(config), lr=local_args.lr, td_step=local_args.td_step, ent_coef=local_args.ent_coef, v_coef=local_args.v_coef) with agent.create_session(**self.tf_sess_opts(global_args)): env = ParallelEnvs.new(mode=local_args.mode, env_num=local_args.env_num, env_args=env_args) obs_adapter = ObservationAdapter(config) act_adapter = ActionAdapter(config) env_runner = EnvRunner(agent=agent, env=env, train=global_args.train, observation_adapter=obs_adapter, action_adapter=act_adapter, epoch_n=local_args.epoch, step_n=local_args.td_step, logdir=local_args.logdir) env_runner.run()
def __init__(self): self.config_file = "c:/test-av/conf/vmware.conf" self.conf = Config(self.config_file) self.cmd = Command(self.conf.path, self.conf.host, self.conf.user, self.conf.passwd) self.dst_dir = "c:/Users/avtest/Desktop"
def download_os_images(config_path=None): """Download OS installation images""" log = logger.getlogger() os_images_path = get_os_images_path() + "/" os_image_urls_yaml_path = os_images_path + OS_IMAGES_URLS_FILENAME cfg = Config(config_path) os_image_urls = yaml.load(open(os_image_urls_yaml_path), Loader=AttrDictYAMLLoader).os_image_urls for os_profile in cfg.yield_ntmpl_os_profile(): for os_image_url in os_image_urls: if check_os_profile(os_profile) in os_image_url.name: for image in os_image_url.images: dest = os_images_path if 'filename' in image: dest += image.filename else: dest += image.url.split("/")[-1] if not os.path.isfile(dest): log.info('Downloading OS image: %s' % image.url) wget.download(image.url, out=dest) print('') sys.stdout.flush() log.info('Verifying OS image sha1sum: %s' % dest) sha1sum = _sha1sum(dest) if image.sha1sum != sha1sum: msg = ('OS image sha1sum verification failed: %s' % dest) log.error(msg) raise UserException(msg)
def main(): api = DeviantArtAPI() args = cmd.main_parser() config = Config(args.f) if args.l: config.print() if args.s: config.save_dir = args.s if args.t: api.threads = args.t if args.option == 'artwork': if args.a: config.add_users(args.a) if args.d: config.delete_users(args.d) if args.c: config.clear_users(args.c) download_users(api, config, args.option) elif args.option == 'ranking': params = { 'order': args.order, 'type': args.type, 'content': args.content, 'category': args.category, 'limit': args.n, 'dir_path': config.save_dir } download_users(api, config, args.option, **params) elif args.option == 'collections': params = {'dir_path': config.save_dir} download_users(api, config, args.option, **params) config.update()
def start(): """ Start one of the processes based on command line arguments. """ parser = create_parser() args = parser.parse_args() config = Config() setup(config, args) if args.cmd == 'self-play': from agz_commands import self_play return self_play.start(config) elif args.cmd == 'optimize': from agz_commands import optimize return optimize.start(config) elif args.cmd == 'evaluate': from agz_commands import evaluate return evaluate.start(config) elif args.cmd == 'supervised': from agz_commands import supervised return supervised.start(config) elif args.cmd == 'game': from game import game return game.start(config)
def main(): parser = ArgumentParser( description='Test program for testing tallylight plugins') parser.add_argument('-c', '--config', type=FileType('r'), help='Use a specific config file') args = parser.parse_args() config = Config(cmd_line_config=args.config) plugin_cls = PLUGINS.get(config.get('light', 'plugin'), None) if plugin_cls is None: print('No plugin selected, control will not work!') exit(1) plugin = plugin_cls(config) try: while True: print('Tally light on. Press ENTER to turn off, ^C to stop.') plugin.tally_on() input() print('Tally light off. Press ENTER to turn on, ^C to stop.') plugin.tally_off() input() except KeyboardInterrupt: pass
def get_symbols_cheaper_than(price): res = {} try: cfg = Config() dir_quote = cfg['paths']['quotes'] symbols = os.listdir(dir_quote) except Exception as e: raise Exception('Could not read dir:', dir_quote) for s_file in os.listdir(dir_quote): # For each quote, find cheap ones try: symbol = s_file.split('.')[0] fname = dir_quote + '/' + s_file if os.stat(fname).st_size > 1: with open(fname) as f: price_found = json.load(f)['c'] if float(price_found) <= float(price): res[symbol] = price_found except Exception as e: print('Unable to read %s' % s_file) for k, v in sorted(res.items()): # Sort by symbol res[k] = v return res
def __init__(self): self.warrior = TaskWarrior() self.config = Config() self.default_limit = self.config.get_default_filter() self.limit = self.default_limit self.show_annotations = [] self.walker = urwid.SimpleListWalker([]) self.list_box = ScrollingListBox(self.walker) self.view = urwid.Frame(urwid.AttrWrap(self.list_box, 'body')) self.refresh() def update_header(): limit = ' | ' + self.limit if self.limit else '' header_text = ['tasky.α', ('dim', limit)] self.view.set_header(urwid.AttrMap(urwid.Text(header_text), 'head')) update_header() loop = urwid.MainLoop(self.view, Tasky.palette, unhandled_input=self.keystroke) self.loop = loop urwid.connect_signal(self.walker, 'modified', update_header) loop.screen.set_terminal_properties(colors=256) loop.run()
def download_os_images(config_path=None): """Download OS installation images""" log = logger.getlogger() cfg = Config(config_path) os_images_path = get_os_images_path() + "/" os_image_urls = get_os_image_urls() for os_profile in cfg.yield_ntmpl_os_profile(): for os_image_url in os_image_urls: if check_os_profile(os_profile) in os_image_url['name']: for image in os_image_url['images']: dest = os_images_path if 'filename' in image: dest += image['filename'] else: dest += image['url'].split("/")[-1] if not os.path.isfile(dest): log.info(f"Downloading OS image: {image['url']}") wget.download(image['url'], out=dest) print('') sys.stdout.flush() log.info('Verifying OS image sha1sum: %s' % dest) if image['sha1sum'] != sha1sum(dest): msg = ('OS image sha1sum verification failed: %s' % dest) log.error(msg) raise UserException(msg)
def __init__(self): self.wheel_motors = Wheel_Motors() self.direction = Direction() self.config = Config(self.CONFIG_FILE()) self.position = Position(self.config) self.mvt_state = enum.Mvt_State.IDLE self.direction_state = enum.Direction_State.STRAIGHT
def load_config(path): if not os.path.isfile(path): main_logger.log_console("Config file does not exists '%s'" % path, status="~") return None config = Config(path) if not config.load(): return None return config
def monitaur(): print_banner() config = Config() parser = ArgumentHandler() arguments = parser.parse(sys.argv[1:]) start_monitor(config)
def __init__(self): self.config = Config() self.menu_item = JMenuItem('Insert Mole payload') self.menu_item.addActionListener(self) # Check to see if we can reach the token server if not token_server_health_check(self.config): raise Exception('Token Server Unavailable: %s://%s' %(self.config.token_protocol, self.config.token_server))
def run_around_tests(): # Code that will run before each test, as we need to # set the configuration to an empty dictionary: global empty_config empty_config = Config(None, {}) # A test function will be run at this point yield
def setUp(self): config = Config() config.guipkg = 'test/data/res/packages/gui.pkg' config.scriptspkg = 'test/data/res/packages/scripts.pkg' config.localedir = 'test/data/res' config.schema = 'res/itemschema.json' self.app = Application() self.app.setup(config)
def __init__(self, log=False): self.result = [] self.opts = Config('test.conf').get_default() self.opts['chat_proto'] = ['MOCK'] self.opts['username'] = '******' self.opts['password'] = '******' self.opts['nick_name'] = 'BOT:NICK' self.opts['cmd_prefix'] = 'BOT:PREFIX' self.opts['rooms'] = [{ 'room': 'MOCK_ROOM', 'nick': None, 'pass': None }] self.opts['only_direct'] = False self.opts['recon_wait'] = 0 self._SibylBot__finished = False self._SibylBot__reboot = False self.last_cmd = {} self.plugins = ['sibylbot'] self.hooks = { x: {} for x in [ 'chat', 'init', 'down', 'con', 'discon', 'recon', 'rooms', 'roomf', 'msg', 'priv', 'group', 'status', 'err', 'idle' ] } self.hooks['chat']['MOCK'] = lambda m, a: 'HOOK_CHAT' self.hooks['init']['MOCK'] = lambda: 'HOOK_INIT' self.hooks['down']['MOCK'] = lambda: 'HOOK_DOWN' self.hooks['con']['MOCK'] = lambda: 'HOOK_CON' self.hooks['discon']['MOCK'] = lambda e: 'HOOK_DISCON' self.hooks['recon']['MOCK'] = lambda: 'HOOK_RECON' self.hooks['rooms']['MOCK'] = lambda r: 'HOOK_ROOMS' self.hooks['roomf']['MOCK'] = lambda r, e: 'HOOK_ROOMF' self.hooks['msg']['MOCK'] = lambda m, c: 'HOOK_MSG' self.hooks['priv']['MOCK'] = lambda m, c: 'HOOK_PRIV' self.hooks['group']['MOCK'] = lambda m, c: 'HOOK_GROUP' self.hooks['status']['MOCK'] = lambda m: 'HOOK_STATUS' self.hooks['idle']['MOCK'] = lambda: 'HOOK_IDLE' if log: logging.basicConfig( filename='test.log', format= '%(asctime).19s | %(name)-8.8s | %(levelname).3s | %(message)s', level=logging.DEBUG) self.log = logging.getLogger('bot') self.protocol = MockProtocol(self, logging.getLogger('protocol')) else: self.log = MockLog() self.protocol = MockProtocol(self, self.log) self._SibylBot__run_hooks('init')
def __init__(self): config = Config() self.config = config logger = self._prepare_logger(config.log_path) tweet_api = TwitterAPI(config.consumer_key, config.consumer_secret, config.access_token_key, config.access_token_secret) safe_api = SafeTwitter(logger, config.min_rate_limit_search, config.min_rate_limit_post, tweet_api) self.scanner = ContestScanner(safe_api) self.retweeter = ReTweeter(safe_api, config.keywords_fav, config.keywords_follow)
def get_quotes(): # List quotes from disk try: cfg = Config() except Exception as e: raise Exception('Could not read config') l = sorted(os.listdir(cfg['paths']['quotes'])) l = [ el.replace('.json', '') for el in l ] return l
def __init__(self): self.options = {} self.cfg = Config() self.cur_page = int(self.cfg.get('control')['indexpage']) self.page = 0 self.base_url = 'http://terms.naer.edu.tw/search/' self.proxy_switch = False self.proxies = self.get_proxy() self.result = self.get()
def main(config_path=None): cfg = Config(config_path) for sw_info in cfg.yield_sw_data_access_info(): switch = SwitchFactory.factory(sw_info[1], sw_info[2], sw_info[3], sw_info[4], mode='active') switch.clear_mac_address_table()
def run(self): conf = Config(data=self.data).get() vagrantfile_path = os.path.join(self.vagrantdir, "Vagrantfile") GenerateVagrantFile(template_path="Vagrantfile", vagrantfile_path=vagrantfile_path, config=conf) self.cmd.append('up') return self._run_command()