def Admin(self, handler, query): #Read config file new each time in case there was any outside edits config = ConfigParser.ConfigParser() config.read(config_file_path) shares_data = [] for section in config.sections(): if not (section.startswith('_tivo_') or section.startswith('Server')): if not (config.has_option(section, 'type')): shares_data.append( (section, dict(config.items(section, raw=True)))) elif config.get(section, 'type').lower() != 'admin': shares_data.append( (section, dict(config.items(section, raw=True)))) subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template( file=os.path.join(SCRIPTDIR, 'templates', 'settings.tmpl')) t.container = cname t.server_data = dict(config.items('Server', raw=True)) t.server_known = buildhelp.getknown('server') t.shares_data = shares_data t.shares_known = buildhelp.getknown('shares') t.tivos_data = [ (section, dict(config.items(section, raw=True))) for section in config.sections() \ if section.startswith('_tivo_')] t.tivos_known = buildhelp.getknown('tivos') t.help_list = buildhelp.gethelp() handler.wfile.write(t)
def Admin(self, handler, query): #Read config file new each time in case there was any outside edits config = ConfigParser.ConfigParser() config.read(config_file_path) shares_data = [] for section in config.sections(): if not(section.startswith('_tivo_') or section.startswith('Server')): if not(config.has_option(section,'type')): shares_data.append((section, dict(config.items(section, raw=True)))) elif config.get(section,'type').lower() != 'admin': shares_data.append((section, dict(config.items(section, raw=True)))) subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template(file=os.path.join(SCRIPTDIR,'templates', 'settings.tmpl')) t.container = cname t.server_data = dict(config.items('Server', raw=True)) t.server_known = buildhelp.getknown('server') t.shares_data = shares_data t.shares_known = buildhelp.getknown('shares') t.tivos_data = [ (section, dict(config.items(section, raw=True))) for section in config.sections() \ if section.startswith('_tivo_')] t.tivos_known = buildhelp.getknown('tivos') t.help_list = buildhelp.gethelp() handler.wfile.write(t)
def remove_customized_motion_window(self): self.removeCustomizedMotionWindow = Toplevel(self.window) self.removeCustomizedMotionWindow.geometry("420x360+100+100") self.removeCustomizedMotionWindow.resizable(False, False) label = Label( self.removeCustomizedMotionWindow, text="Caution: Once you delete an exercise, it is gone forever.", ) label.grid(sticky="W", row=0, column=0, pady=5, padx=5) config = ConfigParser() config.read('config.ini') customizedExercisesDict = dict(config.items('customized')) customizedExercises = list(customizedExercisesDict.keys()) self.customizedExercisesOption = StringVar() self.customizedExercisesOption.set(customizedExercises[0]) customizedExercisesOptionMenu = OptionMenu( self.removeCustomizedMotionWindow, self.customizedExercisesOption, *customizedExercises) customizedExercisesOptionMenu.config(width=18) customizedExercisesOptionMenu.grid(row=1, column=0, pady=5, padx=0) deleteButton = Button(self.removeCustomizedMotionWindow, text="Delete", command=self.delete_customized_exercise) deleteButton.grid(row=1, column=1, pady=5, padx=0)
def remove_extremity_window(self): self.removeExtremityWindow = Toplevel(self.window) self.removeExtremityWindow.geometry("420x360+100+100") self.removeExtremityWindow.resizable(False, False) label = Label( self.removeExtremityWindow, text="Caution: Once you delete a trigger, it is gone forever.", ) label.grid(sticky="W", row=0, column=0, pady=5, padx=5) config = ConfigParser() config.read('config.ini') extremityDict = dict(config.items('extremity')) extremities = list(extremityDict.keys()) self.extremityOption = StringVar() self.extremityOption.set(extremities[0]) extremityOptionMenu = OptionMenu(self.removeExtremityWindow, self.extremityOption, *extremities) extremityOptionMenu.config(width=18) extremityOptionMenu.grid(row=1, column=0, pady=5, padx=0) deleteButton = Button(self.removeExtremityWindow, text="Delete", command=self.delete_extremity) deleteButton.grid(row=1, column=1, pady=5, padx=0)
def get_config(self): config = { 'upsampling': self.upsampling, 'output_size': self.output_size, 'data_format': self.data_format } base_config = super(BilinearUpsampling, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def getPellet(self): """I read Pellet's location from ../config/pellet.conf""" import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open('config/pellet.conf')) for name, value in config.items("Pellet"): if name == 'pelletcmd': return value
def get_config(self): config = { 'output_dim': self.output_dim, 'mode': self.mode, 'supports_masking': self.supports_masking, 'transitions': tf.keras.backend.eval(self.transitions) } base_config = super(CRF, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def get_config(self): config = { 'lr': float(K.get_value(self.lr)), 'momentum': float(K.get_value(self.momentum)), 'decay': float(K.get_value(self.decay)), 'nesterov': self.nesterov } base_config = super(SimpleSGD, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def read_yaml_settings(path): settings = {} if path.is_file(): config = read_yaml(path) if config is None: return None if isinstance(config, list): return config for key, value in config.items(): settings[key] = '' if value is None else value return settings
def migrateOldConfig(self): #Legacy support code import ConfigParser, ast config = ConfigParser.ConfigParser() if os.path.exists(self.getOldConfigFile()): with codecs.open(self.getOldConfigFile(), "r", "utf8") as fp: config.readfp(fp) if not config.has_section("__SYSTEM__"): config.add_section("__SYSTEM__") self.settings = dict(config.items("__SYSTEM__")) for name in config.sections(): if name != "__SYSTEM__": dat = dict(config.items(name)) if dat["program"] and dat["program"].startswith("["): args = ast.literal_eval(dat["program"]) else: args = shlex.split(str(dat["program"])) dat["program"] = args[0] if "\\\\" in dat["program"]: dat["program"] = ast.literal_eval('"'+dat["program"]+'"') dat["arguments"] = args[1:] self.shortcutData[name] = dat
def mail_setup(): global mail mail = smtp.mailSMTP() config = mail.get_config() setconfig = {} for mkey, dict in config.items(): for key, value in dict.items(): if gcfg.get_cfg('frontend', key): setconfig[key] = gcfg.get_cfg('frontend', key) else: setconfig[key] = value mail.set_min_config(setconfig)
def add_computer(self, config): """ Adds a tracked computer. :arg dict config: configuration dictionary of the computer to be added :returns: computer id assigned to added computer :rtype: string """ defaults = {"max": 10, "beat_interval": 3.0, "first_beat": 5.0, "kernels": {}} comp_id = str(uuid.uuid4()) cfg = dict(defaults.items() + config.items()) req = self.context.socket(zmq.REQ) client = self._setup_ssh_connection(cfg["host"], cfg["username"]) code = "python '%s/receiver.py'"%(os.getcwd(),) ssh_stdin, ssh_stdout, ssh_stderr = client.exec_command(code) stdout_channel = ssh_stdout.channel # Wait for untrusted side to respond with the bound port using paramiko channels # Another option would be to have a short-lived ZMQ socket bound on the trusted # side and have the untrusteed side connect to that and send the port failure = True from time import sleep for i in xrange(10): if stdout_channel.recv_ready(): port = stdout_channel.recv(1024) failure = False break; sleep(0.5) retval = None if failure: print "Computer %s did not respond, connected failed!"%comp_id else: addr = "tcp://%s:%s"%(cfg["host"], port) req.connect(addr) req.send("handshake") response = req.recv() if(response == "handshake"): self._clients[comp_id] = {"socket": req, "ssh": client} self._comps[comp_id] = cfg print "ZMQ Connection with computer %s at port %s established." %(comp_id, port) else: print "ZMQ Connection with computer %s at port %s failed!" %(comp_id, port) retval = comp_id return retval
def read_yaml(path): settings = {} if path.is_file(): with path.open() as yamlfile: try: config = yaml.safe_load(yamlfile) except: fatal(f'Failed to parse {path}.') if config is None: return None if isinstance(config, list): return config for key, value in config.items(): settings[key] = '' if value is None else value return settings
def delete_extremity(self): config = ConfigParser() config.read('config.ini') for item in config.items('extremity'): if item[0] == self.extremityOption.get(): config.remove_option('extremity', item[0]) config.write(open('config.ini', 'w')) inputs = ConfigParser() inputs.read('current_inputs.ini') for item in inputs.items('extremity'): if item[0] == self.extremityOption.get(): inputs.remove_option('extremity', item[0]) inputs.write(open('current_inputs.ini', 'w')) self.removeExtremityWindow.destroy() self.profileWindow.destroy() self.profile_window() self.profileNotebook.select(1)
def __init__(self, config, database): config = json.load(open(config, 'rb')) self.database = database valid_keys = ['name', 'identifiers', 'entities'] for k, v in config.items(): if k in valid_keys: setattr(self, k, v) # Append any source-specific entities found in the config file to # the standard list if self.entities is None: self.entities = Source.ENTITIES else: self.entities.update(Source.ENTITIES)
def apply(base, config): # print("base={}".format(base)) # print("config={}".format(config)) if isinstance(config, dict): for key, value in config.items(): if not key.startswith('__'): # and not callable(value): if isinstance(base, dict): if isinstance( value, dict ) and key in base and base[key] is not None: Configurator.apply(base[key], value) else: # print("base[{}]={}".format(key, value)) base[key] = value else: if isinstance(value, dict) and hasattr( base, key) and getattr(base, key) is not None: Configurator.apply(getattr(base, key), value) else: # print("base.{}={}".format(key, value)) setattr(base, key, value)
def checkRequired(parsed): log.log(log.DEBUG, 'Checking required fields') if not 'doc-tag' in parsed: log.log(log.ERROR, 'No tag specified') return (1, 'No tag specified') tag = parsed['doc-tag'][0].split('-', 1) event_type = tag[0] if config.has_section('fields-' + event_type): items = config.items('fields-' + event_type) for i in items: if i[0] == 'required': required_fields = i[1].split(', ') for field in required_fields: if not field in parsed: log.log(log.ERROR, 'Required field "' + field + '" is missing') return (1, 'Required field "' + field + '" is missing') elif i[0] == 'optional': return (0, '') #optional_fields = i[1].split(', ') #for field in optional_fields: # if field in parsed: # pass else: log.log(log.ERROR, 'Unknown definition in config: ' + repr(i)) return (1, 'Unknown definition in config: ' + repr(i)) else: log.log(log.ERROR, 'Event type not specified in config file. Adding section. All fields will be added as optional. Fix this soon.') config.add_section('fields-' + event_type) oldkey = '' for key in parsed: if oldkey == '': newkey = key else: newkey = oldkey + ', ' + key config.set('fields-' + event_type, 'optional', newkey) oldkey = config.get('fields-' + event_type, 'optional') config.write() return (0, '')
def delete_customized_exercise(self): config = ConfigParser() config.read('config.ini') for item in config.items('customized'): if item[0] == self.customizedExercisesOption.get(): config.remove_option('customized', item[0]) config.write(open('config.ini', 'w')) inputs = ConfigParser() inputs.read('current_inputs.ini') for item in inputs.items('customized'): print(item[0]) if item[0] == self.customizedExercisesOption.get(): inputs.remove_option('customized', item[0]) inputs.write(open('current_inputs.ini', 'w')) dirpath = "models/customized/" + self.customizedExercisesOption.get() if os.path.exists(dirpath) and os.path.isdir(dirpath): shutil.rmtree(dirpath) self.removeCustomizedMotionWindow.destroy() self.profileWindow.destroy() self.profile_window()
def gen_cfg(config): """ config.items() -> (<section>, <dict of values>) """ for key, val in config.items(): write_cfg(val, key)
#!/usr/bin/python # Import custom logger to initialize logging system. This must be done before # anything tries to use logging. import cube_logger import config import word_app import tabletop table = tabletop.Tabletop() colors = list(config.items('COLORS')) letters = ["E", "T", "A", "N", "S"] for i, letter in enumerate(letters): color = colors[i % len(colors)] cube = table.make_cube(color=config.get('COLORS', 'CUBE_RED')) # Start the letter app. app = word_app.WordGameLetter(letter) cube.run_app(app) # Create the checker cube. checker_cube = table.make_cube(color=config.get('COLORS', 'CUBE_GOLD')) app = word_app.WordGameChecker() checker_cube.run_app(app) table.run()
def get_config(self): config = { 'attention_dim': self.attention_dim } base_config = super(AttLayer, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def get_config(self): config = {"momentum": self.momentum, "axis": self.axis} base_config = super(Scale, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def profile_window(self): self.eventTypes = ["keypress", "mouse", "brightness"] self.mouseEvents = [ "click", "move-left", "move-right", "move-up", "move-down" ] if (self.appStatus != 0): self.stop() self.profileWindow = Toplevel(self.window) self.profileWindow.geometry('+100+100') self.profileWindow.resizable(False, False) profileSettingsFrame = Frame(self.profileWindow) profileSettingsFrame.pack(fill=X, side=BOTTOM) self.profileNotebook = ttk.Notebook(profileSettingsFrame) self.profileNotebook.pack(pady=15) self.profileExerciseFrame = Frame(self.profileNotebook, width=500, height=1000) self.profileExtremityFrame = Frame(self.profileNotebook, width=500, height=1000) self.profileExerciseFrame.pack(fill="both", expand=1) self.profileExtremityFrame.pack(fill="both", expand=1) self.defaultProfiles = [] self.customizedProfiles = [] self.extremityProfiles = [] config = ConfigParser() config.read('config.ini') currentInputs = ConfigParser() currentInputs.read('current_inputs.ini') defaultExercisesDict = dict(config.items('default')) currentDefaultInputsDict = dict(currentInputs.items('default')) customizedExerciseDict = dict(config.items('customized')) currentCustomizedInputsDict = dict(currentInputs.items('customized')) extremityTriggersDict = dict(config.items('extremity')) extremityTriggerInputsDict = dict(currentInputs.items('extremity')) rowCount = 0 defaultLabel = Label(self.profileExerciseFrame, text="DEFAULT", font=('Helvetica', 18, 'bold')) defaultLabel.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 for key in defaultExercisesDict: checkBoxVar = IntVar() if (int(currentDefaultInputsDict.get(key))) == 1: checkBoxVar.set(1) else: checkBoxVar.set(0) checkBox = Checkbutton(self.profileExerciseFrame, text=key, variable=checkBoxVar) checkBox.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) if ('+' in defaultExercisesDict.get(key)): eventType = defaultExercisesDict.get(key).split('+')[0] eventContent = defaultExercisesDict.get(key).split('+')[1] else: eventType = defaultExercisesDict.get(key) eventContent = None eventTypeOption = StringVar() eventTypeOption.set(eventType) eventTypeOption.trace( "w", lambda *args, row=rowCount, eventTypeOptionInstance= eventTypeOption: self.default_event_type_changed( eventTypeOptionInstance, row, *args)) eventTypeOptionMenu = OptionMenu(self.profileExerciseFrame, eventTypeOption, *self.eventTypes) eventTypeOptionMenu.config(width=18) eventTypeOptionMenu.grid(row=rowCount, column=1, pady=5, padx=0) if eventType == "keypress": keyLabel = Label(self.profileExerciseFrame, text=eventContent, background='light grey') keyLabel.grid(sticky="W", row=rowCount, column=2, pady=5, padx=5) keyLabel.bind("<Button-1>", self.key_map) self.defaultProfiles.append( (checkBoxVar, checkBox, eventTypeOption, keyLabel)) elif eventType == "mouse": mouseEventOption = StringVar() mouseEventOption.set(eventContent) mouseEventTypeOptionMenu = OptionMenu( self.profileExerciseFrame, mouseEventOption, *self.mouseEvents) mouseEventTypeOptionMenu.config(width=18) mouseEventTypeOptionMenu.grid(row=rowCount, column=2, pady=5, padx=0) self.defaultProfiles.append( (checkBoxVar, checkBox, eventTypeOption, mouseEventOption)) elif eventType == "brightness": self.defaultProfiles.append( (checkBoxVar, checkBox, eventTypeOption)) rowCount += 1 customizedLabel = Label(self.profileExerciseFrame, text="CUSTOMIZED", font=('Helvetica', 18, 'bold')) customizedLabel.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 for key in customizedExerciseDict: checkBoxVar = IntVar() if (int(currentCustomizedInputsDict.get(key))) == 1: checkBoxVar.set(1) else: checkBoxVar.set(0) checkBox = Checkbutton(self.profileExerciseFrame, text=key, variable=checkBoxVar) checkBox.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) if ('+' in customizedExerciseDict.get(key)): eventType = customizedExerciseDict.get(key).split('+')[0] eventContent = customizedExerciseDict.get(key).split('+')[1] else: eventType = customizedExerciseDict.get(key) eventContent = '' eventTypeOption = StringVar() eventTypeOption.set(eventType) eventTypeOption.trace( "w", lambda *args, row=rowCount, eventTypeOptionInstance= eventTypeOption: self.customized_event_type_changed( eventTypeOptionInstance, row, *args)) eventTypeOptionMenu = OptionMenu(self.profileExerciseFrame, eventTypeOption, *self.eventTypes) eventTypeOptionMenu.config(width=18) eventTypeOptionMenu.grid(row=rowCount, column=1, pady=5, padx=0) if eventType == "keypress": keyLabel = Label(self.profileExerciseFrame, text=eventContent, background='light grey') keyLabel.grid(sticky="W", row=rowCount, column=2, pady=5, padx=5) keyLabel.bind("<Button-1>", self.key_map) self.customizedProfiles.append( (checkBoxVar, checkBox, eventTypeOption, keyLabel)) elif eventType == "mouse": mouseEventOption = StringVar() mouseEventOption.set(eventContent) mouseEventTypeOptionMenu = OptionMenu( self.profileExerciseFrame, mouseEventOption, *self.mouseEvents) mouseEventTypeOptionMenu.config(width=18) mouseEventTypeOptionMenu.grid(row=rowCount, column=2, pady=5, padx=0) self.customizedProfiles.append( (checkBoxVar, checkBox, eventTypeOption, mouseEventOption)) elif eventType == "brightness": self.customizedProfiles.append( (checkBoxVar, checkBox, eventTypeOption)) rowCount += 1 addNewCustomizedButton = Button( self.profileExerciseFrame, text="Add a new customized exercise", command=self.add_customized_motion_window) addNewCustomizedButton.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 removeCustomizedButton = Button( self.profileExerciseFrame, text="Delete existed customized exercise", command=self.remove_customized_motion_window) removeCustomizedButton.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 initialConfigtLabel1 = Label(self.profileExerciseFrame, text="INITIAL CONFIGURATION", font=('Helvetica', 18, 'bold')) initialConfigtLabel1.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 initialConfigtLabel2 = Label( self.profileExerciseFrame, text="Initial configuration is necessary if this is your " "first time using the Exercise Module", wraplengt=400, justify=LEFT, font=('Helvetica', 10)) initialConfigtLabel2.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 if not config.has_section('roi'): initialConfigtLabel3 = Label(self.profileExerciseFrame, text='Initial Config not completed', fg='red', justify=LEFT, font=('Helvetica', 10)) else: initialConfigtLabel3 = Label(self.profileExerciseFrame, text='Initial Config completed', fg='green', justify=LEFT, font=('Helvetica', 10)) initialConfigtLabel3.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 initialConfigButton = Button(self.profileExerciseFrame, text="Initial Configuration", command=self.initial_config_window) initialConfigButton.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount = 0 extremityLabel = Label(self.profileExtremityFrame, text="DEFAULT", font=('Helvetica', 18, 'bold')) extremityLabel.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 for key in extremityTriggersDict: checkBoxVar = IntVar() if (int(extremityTriggerInputsDict.get(key))) == 1: checkBoxVar.set(1) else: checkBoxVar.set(0) checkBox = Checkbutton(self.profileExtremityFrame, text=key, variable=checkBoxVar) checkBox.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) if (len(extremityTriggersDict.get(key).split('+')) == 3): pos = extremityTriggersDict.get(key).split('+')[0] eventType = extremityTriggersDict.get(key).split('+')[1] eventContent = extremityTriggersDict.get(key).split('+')[2] else: pos = extremityTriggersDict.get(key).split('+')[0] eventType = extremityTriggersDict.get(key).split('+')[1] eventContent = '' posLabel = Label(self.profileExtremityFrame, text=pos, background='light grey') posLabel.grid(sticky="W", row=rowCount, column=1, pady=5, padx=5) posLabel.bind("<Button-1>", self.change_trigger_pos_window) eventTypeOption = StringVar() eventTypeOption.set(eventType) eventTypeOption.trace( "w", lambda *args, row=rowCount, eventTypeOptionInstance= eventTypeOption: self.extremity_event_type_changed( eventTypeOptionInstance, row, *args)) eventTypeOptionMenu = OptionMenu(self.profileExtremityFrame, eventTypeOption, *self.eventTypes) eventTypeOptionMenu.config(width=18) eventTypeOptionMenu.grid(row=rowCount, column=2, pady=5, padx=0) if eventType == "keypress": keyLabel = Label(self.profileExtremityFrame, text=eventContent, background='light grey') keyLabel.grid(sticky="W", row=rowCount, column=3, pady=5, padx=5) keyLabel.bind("<Button-1>", self.key_map) self.extremityProfiles.append((checkBoxVar, checkBox, posLabel, eventTypeOption, keyLabel)) elif eventType == "mouse": mouseEventOption = StringVar() mouseEventOption.set(eventContent) mouseEventTypeOptionMenu = OptionMenu( self.profileExtremityFrame, mouseEventOption, *self.mouseEvents) mouseEventTypeOptionMenu.config(width=18) mouseEventTypeOptionMenu.grid(row=rowCount, column=3, pady=5, padx=0) self.extremityProfiles.append( (checkBoxVar, checkBox, posLabel, eventTypeOption, mouseEventOption)) elif eventType == "brightness": self.extremityProfiles.append( (checkBoxVar, checkBox, posLabel, eventTypeOption)) rowCount += 1 addNewExtremityButton = Button(self.profileExtremityFrame, text="Add a new extremity trigger", command=self.add_extremity_window) addNewExtremityButton.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) rowCount += 1 removeExtremityButton = Button( self.profileExtremityFrame, text="Delete existed extremity triggers", command=self.remove_extremity_window) removeExtremityButton.grid(sticky="W", row=rowCount, column=0, pady=5, padx=5) self.profileNotebook.add(self.profileExerciseFrame, text="Exercise") self.profileNotebook.add(self.profileExtremityFrame, text="Extremity") self.instructionLabel2 = Label( profileSettingsFrame, text= 'Click APPLY to save the settings.\nClick \'X\' on the upper right corner to close' ' the page.', font=("Courier", 10)) self.instructionLabel2.config(anchor=CENTER) self.instructionLabel2.pack() apply_button = Button(profileSettingsFrame, text="APPLY", command=self.apply_profile).pack()
def get_config(self): config = {"name": self.__class__.__name__, 'hp_lambda': K.get_value(self.hp_lambda)} base_config = super(GradientReversal, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def getDSN(): return DSN_FORMAT % dict(config.items("repository"))
def items(self, vars_=None): log.debug('context get items: %s, section: %s' % (self.inifile, self.section)) return config.items(self.inifile, self.section, vars_)
def getDbDSN(): config.loadConfig() return DB_DSN_FORMAT % dict(config.items("repository"))
def get_config(self): config = { 'hid_dim': self.hid_dim, } base_config = super(FeedForward, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def get_config(self): config = {'pool_size': self.pool_size, 'num_rois': self.num_rois} base_config = super(RoiPoolingConv, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def get_config(self): config = { 'eps': self.eps, } base_config = super().get_config() return dict(list(base_config.items()) + list(config.items()))
def getVirtualPathConfig(config_path): items = config.items(config_path, 'DEFAULT') return dict( items )
def init_logging(): formatter = logging.Formatter('%(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) log.setLevel(logging.DEBUG) log.addHandler(handler) if __name__ == '__main__': init_logging() try: self, mountpoint = sys.argv except: raise SystemExit('Usage: %s <mountpoint>' % sys.argv[0]) bithorde = Client(parseConfig(config.items('BITHORDE')), autoconnect=False) bithorde.connect() mount_point_created = None if not os.path.exists(mountpoint): os.mkdir(mountpoint) mount_point_created = mountpoint def cleanup(remove_mountpoint): if remove_mountpoint: os.rmdir(remove_mountpoint) atexit.register(cleanup, mount_point_created) try: print("Entering llfuse")
parser.add_option("-l", "--level", dest="level", default="0", help="permissions will be updated to this level (r = read, w = write, p = deny / purge entry from database. You may chain these flags together, eg. rw or rwx") parser.add_option("--purge", dest="purge", action="store_true", help="Remove all permission entries for the specified user") parser.add_option("--check", dest="check_perms", action="store_true", help="List the user's permissions for the specified modules") parser.add_option("-f", "--force", dest="force", action="store_true", help="Action will be forced regardless of any concerns") parser.add_option("-p", "--pretend", dest="pretend", action="store_true") (options, args) = parser.parse_args() configfile = os.path.expandvars(options.configfile) config = ConfigParser.RawConfigParser() config.read(configfile) print "Read config from file: %s" % configfile man = module_manager.ModuleManager() couch_engine = dict(config.items("server")).get("couch_engine", "couchdb") couch_config = config.items(couch_engine) man.set_database( twentyc.database.ClientFromConfig( couch_engine, couch_config, "modules" ) ) if config.has_option("xbahn", "username") and config.has_option("xbahn", "password"): xbahn_user = config.get("xbahn", "username") xbahn_pass = config.get("xbahn", "password") else: xbahn_user = None xbahn_pass = None
def get_config(self): config = {'output_dim': self.output_dim} base_config = super(SWAP, self).get_config() return dict(list(base_config.items()) + list(config.items()))
def main(pid, env_name, seed, sticky_actions, frame_stack, screen_size, wrapper, **cfg): # Create agent-directory config_string = f"env_name={env_name}:" \ f"seed={seed}:" \ f"sticky_actions={sticky_actions}:" \ f"sticky_actions={frame_stack}:" \ f"wrapper={wrapper}:" \ f"screen_size={screen_size}:" for param in cfg: config_string += param + "=" + str(cfg[param]) + ":" agent_dir = os.path.join("agents", config_string) os.makedirs(agent_dir) # Initialize utils and specify reporting params logger = Logger(agent_dir, reward_history_len=episodic_reward_history_len, debug_history_len=debug_history_len) # FIX SEEDING np.random.seed(seed) random.seed(seed) # Create env if wrapper == "rainbow": env = create_atari_environment(game_name=env_name, sticky_actions=sticky_actions, screen_size=screen_size, frame_stack=frame_stack, seed=seed) elif wrapper == "spr": from envs.spr import AtariEnv env = AtariEnv(game=env_name, seed=seed, repeat_action_probability=0, obv_size=screen_size, episodic_lives=False, fire_on_reset=True) agent = AKR2Agent(env=env, seed=seed, agent_dir=agent_dir, logger=logger, **cfg) observation = env.reset() old_s = None old_a = None t = 0 # Get variable being tested compare_var = "lr" from config import config for k, v in config.items(): if type(v) is list and k != "seed" and k != "env_name": compare_var = k for step in trange( total_steps + 1, position=pid, desc=f"Env={env_name[:5]}.{seed}, {compare_var}={cfg[compare_var]}" ): if step % eval_freq == 0 and step: logger.end_epoch(step) if debug_freq and step % debug_freq == 0 and step: logger.write_debug_info(step) # Get state from current observation, quantize normalize etc. s = agent.obv2state(observation) a, qsa, approx = agent.choose_action(s) if t > 0: agent.receive_timestep(s=old_s, a=old_a, r=reward, t=t, q_dash=qsa, old_qsa=old_q, old_approx=old_approx) observation, reward, done, life_lost = env.step(a) logger.log_reward(reward) old_s = s old_a = int(a) old_q = qsa old_approx = approx t += 1 if done or life_lost: agent.receive_timestep(s=s, a=int(a), r=reward, t=t, q_dash=0, old_qsa=qsa, old_approx=approx) t = 0 agent.end_episode() old_s = None old_a = None if done: logger.end_episode() observation = env.reset() # Eval run: if step in eval_intervals: tmp = logger.reward_history logger.reward_history = deque(logger.reward_history, maxlen=20) for e in range(20): o = env.reset() d = False while not d: s = agent.obv2state(o) a, *_ = agent.choose_action(s) o, reward, d, _ = env.step(a) logger.log_reward(reward) logger.end_episode() logger.end_epoch(step) logger.reward_history = deque(tmp, maxlen=episodic_reward_history_len) env.reset()