def __init__(self, d): for a, b in d.items(): if isinstance(b, (list, tuple)): setattr(self, a, [config(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, a, config(b) if isinstance(b, dict) else b)
def get_configs(_state_trees, Cs, mus, dcf_mode): #c1,mu1, c2 = None, mu2 = None): if len(Cs) == 1: # Config is simple configuration = config(mut_state=Cs[0], other_states=[], cn_props={Cs[0]: [ mus[0], ]}, desc_set=[], dcf_mode=dcf_mode) return [ configuration, ], [ [(1, 1, 0), (1, 1, 1)], ] else: state_trees = _state_trees[tuple(set(Cs))] configurations = [] alltrees = [] for state_tree_full in state_trees: saved_tree = [tuple(s) for s in state_tree_full] state_tree = set([tuple(s) for s in state_tree_full]) # Identify mutation state for c in Cs: try: num_states_c = sum([ 1 for s in state_tree if s[0] == c[0] and s[1] == c[1] ]) except: print(state_tree) print(Cs) print(mus) raise if num_states_c == 0: continue elif num_states_c == 2: mut_state = c # Don't break out of this here because we still want to skip this # state tree if not all states are in it # Identify the descendant set of mut_state desc_set = get_desc_set(state_tree_full, mut_state) other_states = [ s for s in state_tree if s[0] != mut_state[0] or s[1] != mut_state[1] ] cn_props = {c: [ mu, ] for c, mu in zip(Cs, mus)} configuration = config(mut_state=mut_state, other_states=other_states, cn_props=cn_props, desc_set=desc_set, dcf_mode=dcf_mode) configurations.append(configuration) alltrees.append(saved_tree) return configurations, alltrees
def key_charLCD(): print('Waiting for key press') while threads_running: for action in config()['keyActions']['charLCD']: if lcd().is_pressed(action['keyCode']): lcd().clear() lcd_setText(action['lcdMessage']) c = action['lcdColor'] lcd().set_color(c[0], c[1], c[2]) for oscAction in action['OSC']: send_osc(oscAction) for otherAction, args in action['Actions'].items(): get_function(otherAction)(*args) time.sleep(config()['settings']['debounceTime'])
def start_server(serverName): listenIP = config()['settings']['listenIP'] listenPort = config()['oscServers'][serverName]['responsePort'] d = dispatcher.Dispatcher() for string, fn in config( )['oscServers'][serverName]['responseCallback'].items(): d.map(string, get_function(fn)) global servers servers = {} print("Starting server on {}, port {}".format(listenIP, listenPort)) server = osc_server.ThreadingOSCUDPServer((listenIP, listenPort), d) servers[serverName] = server server_thread = threading.Thread(target=server.serve_forever) server_thread.start()
def test(config_file): """Test the account-manager svr. """ config(config_file) address = (config.config_tcp_svr_addr, config.config_tcp_svr_port) svr = AccountManagerSvr(address, AMRequestHandler) sa = svr.socket.getsockname() print "account-manager Tcp Server Serving on ", sa[0], " port ", sa[1], " ..." svr.serve_forever()
def populate_documents(): file = r'csv_files/Document.csv' sql_insert = """INSERT INTO DOCUMENT (TITLE, PDATE, PUBLISHERID) VALUES(%s, %s, %s)""" conn = None try: params = config() # connect to the PostgreSQL database conn = psycopg2.connect(**params) cursor = conn.cursor() df = pd.read_csv(file, parse_dates=['PDATE']) for index, row in df.iterrows(): cursor.execute(sql_insert, (row['TITLE'], row['PDATE'], row['PUBLISHERID'])) conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: cursor.close() conn.close() print("Table populated. Connection closed.")
def connect(): """ Connect to the PostgreSQL database server """ conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.cursor() # execute a statement print('PostgreSQL database version:') cur.execute('SELECT version()') # display the PostgreSQL database server version db_version = cur.fetchone() print(db_version) # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.')
def getBackLinks(self, url): _repository = [] try: _config = config() _config.google() _source = url.replace('https', '').replace('http', '').replace( ':', '').replace('//', '').replace('www.', '') if _source.find('/') != -1: _source = _source[:_source.find('/')] _url = _config.google_settings['externallinks'].replace( '[URL]', url).replace('[BASE_URL]', _source) _html = self.external_links(_url, 'GOOGLE') try: for _link in _html.backlinks: if _link not in _repository: _repository.append(_link) print("Total Links = %i" % len(_repository)) except: print("Error Extracting Google Data.") _repository = 'ERROR' except urllib.request.URLError as e: print("Error: %s" % e.reason) except ValueError as v: print("Non urllib Error: %s" % v) return _repository
def populate_confproc(): file = r'csv_files/confprocee.csv' sql_insert = """INSERT INTO PROCEEDINGS (DOCID, CDATE, CLOCATION, CEDITOR) VALUES(%s, %s, %s, %s)""" conn = None try: params = config() # connect to the PostgreSQL database conn = psycopg2.connect(**params) cursor = conn.cursor() df = pd.read_csv(file, parse_dates=['CDATE']) for index, row in df.iterrows(): cursor.execute( sql_insert, (row['DOCID'], row['CDATE'], row['CLOCATION'], row['CEDITOR'])) conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: cursor.close() conn.close() print("Table populated. Connection closed.")
def setup(): # Configure signal handler for a clean exit def signal_handler(signal, frame): lcd().clear() lcd().set_color(0.0, 0.0, 0.0) for port, server in servers.items(): server.shutdown() global threads_running threads_running = False for t in keyThreads: t.join(1000) os._exit(0) signal.signal(signal.SIGINT, signal_handler) lcd_setText("Press play") # Import modules required for OSC responses # First import base module f, filename, description = imp.find_module("modules") module = imp.load_module("modules", f, filename, description) for imp_mod in config()['importModules']: try: f, filename, description = imp.find_module(imp_mod, [filename]) module = imp.load_module(imp_mod, f, filename, description) importedModules[imp_mod] = module print("Successfully loaded {} from {}".format(imp_mod, filename)) except ImportError as err: print("Could not import: {} error {}".format(imp_mod, err))
def insert_to_database_record(key, title, description, salary, location, company, url): """ Connect to the PostgreSQL database server """ conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params, sslmode="require") # create a cursor cur = conn.cursor() # execute a statement # display the PostgreSQL database server version sql = "INSERT INTO jobs(jobkey, jobname, descrip, salary, location, companyname, url) VALUES(%s, %s, %s, %s, %s, %s, %s);" data = (key, title, description, salary, location, company, url) cur.execute(sql, data) conn.commit() # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.')
def connect(): conn = None try: params = config() print('Connecting to database..') conn = psycopg2.connect(**params) # Create a cursor cur = conn.cursor() """sql to be executed""" sql = 'CREATE TABLE IF NOT EXISTS RATINGS(' \ 'UserID INT PRIMARY KEY NOT NULL,' \ 'MovieID INT NOT NULL,' \ 'Rating INT NOT NULL' \ ')'; print('PostgreSQL database :') cur.execute(sql) db_query = cur.fetchone() print(db_query) cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connect closed')
def set_config_rules(): if request.form.getlist('tag_groups_to_assign') and request.form.getlist( 'chosen_config_rule_ids'): selected_tag_groups = list() selected_tag_groups = request.form.getlist('tag_groups_to_assign') selected_config_rules = list() selected_config_rules = request.form.getlist('chosen_config_rule_ids') config_rule_id = selected_config_rules[0] tag_groups = get_tag_groups(region) tag_group_key_values = dict() tag_groups_keys_values = dict() tag_count = 1 for group in selected_tag_groups: # A Required_Tags Config Rule instance accepts up to 6 Tag Groups if tag_count < 7: tag_group_key_values = tag_groups.get_tag_group_key_values( group) key_name = "tag{}Key".format(tag_count) value_name = "tag{}Value".format(tag_count) tag_groups_keys_values[key_name] = tag_group_key_values[ 'tag_group_key'] tag_group_values_string = ",".join( tag_group_key_values['tag_group_values']) tag_groups_keys_values[value_name] = tag_group_values_string tag_count += 1 config_rules = config(region) config_rules.set_config_rules(tag_groups_keys_values, config_rule_id) updated_config_rule = config_rules.get_config_rule(config_rule_id) return render_template('updated-config-rules.html', updated_config_rule=updated_config_rule) else: return redirect(url_for('find_config_rules'))
def getLinks(self, query): # Obtain Configuration Settings _config = config() _config.bing() try: # Keywords _keywords = [] for _synonyms in wordnet.synsets(query): for _s in _synonyms.lemmas(): _s = _s.name().replace('_', ' ') if _s not in _keywords: _keywords.append(_s) if len(_keywords) == 0: _keywords.append(query) # Set Repository Structure _name = os.getcwd() + '\\BING\\' + query + '_' + time.strftime( "%Y%m%d%H%M%S") + ".data" _file = open(_name, "w") _file.write( 'index\turl\tdescription\tdiv\th1\th2\th3\th4\th5\th6\tinbound_links\tkeywords\toutbound_links\tp\troot\tspan\ttitle\n' ) _file.close() # Direct Call _html = self.extract_links(_config.bing_settings['url'] + query, 'BING') _indexValue = 0 _page = 1 _maxPages = 6 while _html.next != '' and _page < _maxPages: for _entry in _html.links: _indexValue += 1 if '.pdf' not in _entry: print("Searching: %s" % _entry.get('url')) _indexes = sorted( self.extract_indexes(_entry.get('url'), _keywords).items()) if _indexes: _file = open(_name, 'a') _file.write( str(_indexValue) + '\t' + _entry.get('url')) for _index in _indexes: _file.write('\t' + str(_index[1])) _file.write('\n') _file.close() if _html.next != '': print("Next: %s" % _html.next) print("Page: %i" % _page) _html = self.extract_links(_html.next, 'BING') print("Pausing for 3 seconds") time.sleep(3) _page += 1 except request.URLError as e: print("Error: %s" % e.reason) except ValueError as v: print("Non urllib Error: %s" % v)
def __init__(self): self.quit = False self.config = config() #FIXME: actually this is a list of modules # logs is an awful name self.logs = [] self.__connect_signals() self.__write_pid()
def main(): fundo, tela, clock = config() musica = pygame.mixer.Sound("BGM/Firelink Shrine.wav") grupo = RenderUpdates() personagem = Hero(20, 290, "dante", grupo) pygame.font.init() frase = Text(40, 'Quem eh voce e oque faz aqui?', 'carolingia.ttf') lx = [b for b in range(-4, 76)] l1 = [-10] l2 = [6] parede = [x for x in range(-10, 16)] iniciarConversa = [43, 0] teclas = { K_LEFT: False, K_RIGHT: False, K_UP: False, K_DOWN: False, K_RETURN: False, 27: False } # obs 27 = tecla 'esc' musica.play() fundo = fundo.convert() pygame.display.flip() while True: clock.tick(FPS) for e in pygame.event.get([KEYUP, KEYDOWN]): valor = (e.type == KEYDOWN) if e.key in teclas.keys(): teclas[e.key] = valor if teclas[27]: # tecla ESC pygame.quit() sys.exit() if teclas[K_LEFT]: personagem.move("LEFT") if teclas[K_RIGHT]: personagem.move("RIGHT") if teclas[K_UP]: personagem.move("UP") if teclas[K_DOWN]: personagem.move("DOWN") if personagem.px == iniciarConversa[ 0] and personagem.py == iniciarConversa[1]: tela.blit(frase.frases, (200, 500)) pygame.display.flip() #print(personagem.px, personagem.py) grupo.clear(tela, fundo) pygame.display.update(grupo.draw(tela))
def load_model_config(config_folder): curr_dir = Path(config_folder) file_path = curr_dir.parent / config_folder / 'config.json' with file_path.open() as f: config1 = config(json.load(f)) # print("retrieved configuraiton", config1.modelconfig.__dict__) return config1.modelconfig
def flash_(sqlsession): error, errors = models.Token.flash(request.form.get('token_id'), config('flash_device')) if error: for e in errors: flash(e[1], 'danger') else: flash('Flashed token successfully.', 'success') return redirect(url_for('token.view', id=request.form.get('token_id')))
def getBackLinks(self, url): _repository = {} _page = 1 _iteration = "&first=[ITERATION_STEP]&FORM=PORE" _MAX = 100 try: print("Page %i" % _page) _config = config() _config.bing() _source = url.replace('https', '').replace('http', '').replace( ':', '').replace('//', '').replace('www.', '') if _source.find('/') != -1: _source = _source[:_source.find('/')] _url = _config.bing_settings['externallinks'].replace( '[URL]', url).replace('[BASE_URL]', _source) _base = _url _html = self.external_links(_url, 'BING') _repository = _html.backlinks print("Page %i Contains %i Links" % (_page, len(_html.backlinks))) while _html.next != '' and len(_html.backlinks) > 0 and len( _html.backlinks[0]) > 0: # Will go maximum 100 pages deep in search ... 1000 links approximately if _MAX - _page == 0 or len(_html.backlinks) == 0: break time.sleep(3) _html = self.external_links( _base + _iteration.replace("[ITERATION_STEP]", str(len(_repository) + 1)), 'BING') _page += 1 print("Page %i Contains %i Links" % (_page, len(_html.backlinks))) _new = False for _link in _html.backlinks: if _link not in _repository: _repository.append(_link) _new = True # Stop if no new links were found if not _new: break print("Total Links = %i" % len(_repository)) except request.URLError as e: print("Error: %s" % e.reason) except ValueError as v: print("Non urllib Error: %s" % v) return _repository
def main(): args = get_normalize_args() if args.config: config(args) if args.run_all: run_all(args) if args.fragment_picker: fragment_picker(args) if args.abinitio_relax: abinitio_relax(args) if args.postprocess: postprocess(args) if args.score: score(args) if args.cluster: cluster(args) if args.pick: pick(args) if args.setup_only: setup(args)
def activate(sqlsession, token): if type(token) == int: token = sqlsession.query(models.Token).filter_by(id=token).first() if token: for date in config('semester_end_dates'): date = helpers.str_to_date(date) if date <= helpers.today(): continue token.expiry_date = date return date return False
def build(self): # Configure self.state = 'configure' self.bld.database[self.name] = 0 # mark this package as not built self.logfile = os.path.join(self.logdir, self.name + "-conf.log") remove_file(self.logfile) # remove any old sources os.system("/bin/rm -rf %s" % self.bdir) self.build_start_time = time.time() if config(self.name, 'Build') == '': inst = self.installed() if inst: # Check to see if this is a python package # that is already in our build lib directory. path = python_path(self.name) if os.path.commonprefix([path, self.libdir]) != self.libdir: print 'Using installed package %s%s%s' %\ (colors['BOLD'], self.name, colors['NORMAL']) self.bld.database[self.name] = self.build_start_time self.bld.database[self.name + '-status'] = 'installed' return # get new sources self.unpack_srcs() os.chdir(self.bdir) run_commands(self.name, 'before') pmess("CONF", self.name, self.bdir) self.pstatus(self._configure()) # Build self.state = 'build' self.logfile = os.path.join(self.logdir, self.name + "-build.log") remove_file(self.logfile) pmess("BUILD", self.name, self.bdir) os.chdir(self.bdir) self.pstatus(self._build()) # Install self.state = 'install' self.logfile = os.path.join(self.logdir, self.name + "-install.log") remove_file(self.logfile) pmess("INSTALL", self.name, self.blddir) os.chdir(self.bdir) self.pstatus(self._install()) self.bld.database[self.name] = self.build_start_time self.bld.database[self.name + '-status'] = self.status() debug('database[%s] = %s' % (self.name, self.build_start_time)) debug( 'database[%s] = %s' % (self.name + '-status', self.bld.database[self.name + '-status'])) run_commands(self.name, 'after')
def main(): fundo, tela, clock = config() musica = pygame.mixer.Sound("BGM/Firelink Shrine.wav") grupo = RenderUpdates() personagem = Hero(20, 290, "dante", grupo) pygame.font.init() frase = Text(40, 'Quem eh voce e oque faz aqui?', 'carolingia.ttf') lx = [b for b in range(-4, 76)] l1 = [-10] l2 = [6] parede = [x for x in range(-10, 16)] iniciarConversa = [43, 0] teclas = {K_LEFT: False, K_RIGHT: False, K_UP: False, K_DOWN: False, K_RETURN: False, 27: False} # obs 27 = tecla 'esc' musica.play() fundo = fundo.convert() pygame.display.flip() while True: clock.tick(FPS) for e in pygame.event.get([KEYUP, KEYDOWN]): valor = (e.type == KEYDOWN) if e.key in teclas.keys(): teclas[e.key] = valor if teclas[27]: # tecla ESC pygame.quit() sys.exit() if teclas[K_LEFT]: personagem.move("LEFT") if teclas[K_RIGHT]: personagem.move("RIGHT") if teclas[K_UP]: personagem.move("UP") if teclas[K_DOWN]: personagem.move("DOWN") if personagem.px == iniciarConversa[0] and personagem.py == iniciarConversa[1]: tela.blit(frase.frases, (200, 500)) pygame.display.flip() #print(personagem.px, personagem.py) grupo.clear(tela, fundo) pygame.display.update(grupo.draw(tela))
def build(self): # Configure self.state = 'configure' self.bld.database[self.name] = 0 # mark this package as not built self.logfile = os.path.join(self.logdir, self.name + "-conf.log") remove_file(self.logfile) # remove any old sources os.system("/bin/rm -rf %s" % self.bdir) self.build_start_time = time.time() if config(self.name, 'Build') == '': inst = self.installed() if inst: # Check to see if this is a python package # that is already in our build lib directory. path = python_path(self.name) if os.path.commonprefix([path,self.libdir]) != self.libdir: print 'Using installed package %s%s%s' %\ (colors['BOLD'], self.name, colors['NORMAL']) self.bld.database[self.name] = self.build_start_time self.bld.database[self.name + '-status'] = 'installed' return # get new sources self.unpack_srcs() os.chdir(self.bdir) run_commands(self.name, 'before') pmess("CONF", self.name, self.bdir) self.pstatus(self._configure()) # Build self.state = 'build' self.logfile = os.path.join(self.logdir, self.name + "-build.log") remove_file(self.logfile) pmess("BUILD", self.name, self.bdir) os.chdir(self.bdir) self.pstatus(self._build()) # Install self.state = 'install' self.logfile = os.path.join(self.logdir, self.name + "-install.log") remove_file(self.logfile) pmess("INSTALL", self.name, self.blddir) os.chdir(self.bdir) self.pstatus(self._install()) self.bld.database[self.name] = self.build_start_time self.bld.database[self.name + '-status'] = self.status() debug('database[%s] = %s' % (self.name, self.build_start_time)) debug('database[%s] = %s' % (self.name + '-status', self.bld.database[self.name + '-status'])) run_commands(self.name, 'after')
def find_config_rules(): #Get the Tag Group names & associated tag keys tag_group_inventory = dict() tag_groups = get_tag_groups(region) tag_group_inventory = tag_groups.get_tag_group_names() #Get the AWS Config Rules config_rules_ids_names = dict() config_rules = config(region) config_rules_ids_names = config_rules.get_config_rules_ids_names() return render_template('find-config-rules.html', tag_group_inventory=tag_group_inventory, config_rules_ids_names=config_rules_ids_names)
def save_data(self, widget=None): cfg = config() cfg.write_data([self.basic_table.get_swivel_option(), \ self.basic_table.get_touch_toggle(), \ self.basic_table.get_hingevalue_toggle(), \ self.adv_table.get_before_tablet(), \ self.adv_table.get_after_tablet(), \ self.adv_table.get_before_normal(), \ self.adv_table.get_after_normal(), \ self.adv_table.get_isnotify_button(), \ self.adv_table.get_isnotify_timeout(), \ self.adv_table.get_waittime(), \ self.adv_table.get_autostart(), \ self.adv_table.get_debug_log(), \ self.version])
def home(): clear_screen() print(LAUNCHER_MENU) while True: """ OPTIONS 1. View Configuration 2. Start Bot 3. Reset Configuration 4. Setup (Use if bot cannot run when Starting)""" try: u_i = int(input("Please enter the option number > ")) except: print("Invalid Input. Try again.") pass if u_i == 1: config() elif u_i == 2: start() elif u_i == 3: reset_config() elif u_i == 4: setup() else: print("Input not recognised.")
def load_xml(self): cfg = config() data = cfg.load_xml() self.basic_table.set_swivel_option(data[0]) self.basic_table.set_touch_toggle(data[1]) self.basic_table.set_hingevalue_toggle(data[2]) self.adv_table.set_before_tablet(data[3]) self.adv_table.set_after_tablet(data[4]) self.adv_table.set_before_normal(data[5]) self.adv_table.set_after_normal(data[6]) self.adv_table.set_isnotify_button(data[7]) self.adv_table.set_isnotify_timeout(data[8]) self.adv_table.set_waittime(data[9]) self.adv_table.set_autostart(data[10]) self.adv_table.set_debug_log(data[11]) self.version = data[12]
def connect_run_close(): conn = None try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor() for sql in query(): cur.execute(sql) conn.commit() msg = cur.statusmessage #print msg cur.close() except (Exception, psycopg2.DatabaseError) as error: print error finally: if conn is not None: conn.close()
def connect(db_id, db_cnpj, db_name, db_email): conn = None try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor() cur.execute(insert) conn.commit() count = cur.rowcount print(count, "Record inserted successfully into companies table") cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close()
def open(sqlsession, id): id = int(id) user = sqlsession.query( models.User).filter_by(username=session['username']).first() device = None if id == 0: if user.default_device: device = user.default_device else: id = int(config('default_door_device')) if id > 0 and not device: device = sqlsession.query(models.Device).filter_by(id=id).first() if device: access_granted = False if user.level > 9000: access_granted = True else: for token in user.tokens: if token in device.tokens: access_granted = True if not access_granted: flash('No access on device with id %s' % id, 'danger') else: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((config.api_host, config.api_port)) temporary_token = helpers.generate_token() q = Query() q.create_register_webui(config.webui_token, temporary_token) s.send(q.to_command()) q.create_open(temporary_token, device.pubkey) s.send(q.to_command()) q.create_unregister(temporary_token) s.send(q.to_command()) s.close() flash('%s has been opened.' % device.name, 'success') except Exception as e: flash('Failed to access device %s' % device.name, 'danger') else: flash('Could not find device with id %s' % id, 'danger') return redirect(request.referrer)
def __init__(self): """init all stuff and signals""" #从xml文件中读取数据,并链接必要的信号 self.builder=gtk.Builder() self.file=sys.path[0]+"/run.glade" self.builder.add_from_file(self.file) self.builder.connect_signals(self) for widget in self.builder.get_objects(): if issubclass(type(widget),gtk.Buildable): name=gtk.Buildable.get_name(widget) setattr(self,name,widget) #创建一个Terminal的实例,并且添加到登录管理的标签页中 self.myterm=MyTerm() self.vbox6.add(self.myterm.terminal) #创建一个treeview的实例 self.stInstance=serverTree(self.treestore,self.treeview) #创建一个cfInstance实例 self.cfInstance=config() #创建一个pyScan的实例 self.pInstance=pyScan() #创建ListStore用来在增加server时补全显示group的信息 #从及时输入的信息和xml中获取信息 self.liststore=gtk.ListStore(str) self.entrycompletion.set_model(self.liststore) self.addservergroupentry1.set_completion(self.entrycompletion) self.entrycompletion.set_text_column(0) if os.path.isfile('./server.xml'): for child in ET.parse('server.xml').getroot(): self.liststore.append([child.tag]) #获取statusbar的id self.context_id=self.statusbar.get_context_id("Linux Server") #显示所有窗体 self.window.set_size_request(800,500) self.window.show_all() #先暂时关闭这个用来显示硬盘图形信息的image控件 self.fulltextimage.hide()
def data_feeder(args, PAD_TOKEN=-99, shuffle=True): conf = config(args.dataset) if args.encoder_type == 'MLP': stack_count = int(input('Enter number of frames to be stacked \n')) else: stack_count = None my_dataset = RoboDataset( dataset=args.dataset, encoder_type=args.encoder_type, stack_count=stack_count, PAD_TOKEN=PAD_TOKEN, MAX_LENGTH=conf.MAX_LENGTH) dataloader = DataLoader(my_dataset, batch_size=conf.batch_size, \ shuffle=shuffle, num_workers=1) return dataloader
def open(sqlsession, id): id = int(id) user = sqlsession.query(models.User).filter_by(username=session['username']).first() device = None if id == 0: if user.default_device: device = user.default_device else: id = int(config('default_door_device')) if id > 0 and not device: device = sqlsession.query(models.Device).filter_by(id=id).first() if device: access_granted = False if user.level > 9000: access_granted = True else: for token in user.tokens: if token in device.tokens: access_granted = True if not access_granted: flash('No access on device with id %s' % id, 'danger') else: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((config.api_host, config.api_port)) temporary_token = helpers.generate_token() q = Query() q.create_register_webui(config.webui_token, temporary_token) s.send(q.to_command()) q.create_open(temporary_token, device.pubkey) s.send(q.to_command()) q.create_unregister(temporary_token) s.send(q.to_command()) s.close() flash('%s has been opened.' % device.name, 'success') except Exception as e: flash('Failed to access device %s' % device.name, 'danger') else: flash('Could not find device with id %s' % id, 'danger') return redirect(request.referrer)
def __init__(self): """init all stuff and signals""" #从xml文件中读取数据,并链接必要的信号 self.builder = gtk.Builder() self.file = sys.path[0] + "/run.glade" self.builder.add_from_file(self.file) self.builder.connect_signals(self) for widget in self.builder.get_objects(): if issubclass(type(widget), gtk.Buildable): name = gtk.Buildable.get_name(widget) setattr(self, name, widget) #创建一个Terminal的实例,并且添加到登录管理的标签页中 self.myterm = MyTerm() self.vbox6.add(self.myterm.terminal) #创建一个treeview的实例 self.stInstance = serverTree(self.treestore, self.treeview) #创建一个cfInstance实例 self.cfInstance = config() #创建一个pyScan的实例 self.pInstance = pyScan() #创建ListStore用来在增加server时补全显示group的信息 #从及时输入的信息和xml中获取信息 self.liststore = gtk.ListStore(str) self.entrycompletion.set_model(self.liststore) self.addservergroupentry1.set_completion(self.entrycompletion) self.entrycompletion.set_text_column(0) if os.path.isfile('./server.xml'): for child in ET.parse('server.xml').getroot(): self.liststore.append([child.tag]) #获取statusbar的id self.context_id = self.statusbar.get_context_id("Linux Server") #显示所有窗体 self.window.set_size_request(800, 500) self.window.show_all() #先暂时关闭这个用来显示硬盘图形信息的image控件 self.fulltextimage.hide()
def sys_log(self, cmd, show=False): "Execute a system call and log the result." # get configuration variable e = config(self.name, self.state) e = e.replace('BUILDDIR', self.blddir) e = e.replace('SRCDIR', self.sdir) e = e.replace('TMPBDIR', self.bdir) e = e.replace('LOGDIR', self.logdir) cmd = cmd + " " + e debug(cmd) f = None if self.logfile != '': f = open(self.logfile, 'a') print >> f, "EXECUTING:", cmd p = Popen(cmd, shell=True, stderr=PIPE, stdout=PIPE) pid = p.pid plist = [p.stdout, p.stderr] done = 0 while not done: rr, wr, er = select(plist, [], plist) if er: print 'er=',er for fd in rr: data = os.read(fd.fileno(), 1024) if data == '': plist.remove(fd) if plist == []: done = 1 else: if fd == p.stderr: print >>f, data, if show: cprint('DYELLOW', data, False) else: if show: print data, print >>f, data, if f: f.close() try: return os.waitpid(pid, 0)[1] except: return 0
def __init__(self, logname='', outdir='./', loglevel='DEBUG'): self.log = os.path.realpath(logname) with open(self.log, 'rb') as logfile: self.loglines = logfile.readlines() self.logger = logConf(debuglevel=loglevel) self.logger.logger.info('init flow') self.config = config() self.logutils = logutils() logbasename = os.path.basename(logname) # get prefix, get timestamp prefix = logbasename.split('.')[0] self.version = self.config.getversion() #output is in one extra dir self.outdir = os.path.dirname(logname) + '/output' self.logutils.mkdirp(self.outdir) self.trimlog = self.outdir + '/' + prefix + '_' +self.logger.timestamp +'_media.log' with open(self.trimlog, 'a+')as trimlog: trimlog.truncate() self.excel = self.outdir + '/' + prefix + '_' +self.logger.timestamp +'_statictics.xlsx' #final eventmsg should be processed self.eventmsgs = list() #pid should be a verbose list self.pids = list() #call list self.calllist = list() #call number self.callnum = 0 #Do we really need this F*cking global flag self.incall = False self.curcall = None
def load(self): with open(config().get('train', 'tfidf_result_path'), 'rb') as fp: model = pickle.load(fp) logger.info("read " + self.__class__.__name__ + " train result") self.vectorizer = model.vectorizer self.selector = model.selector
if (len(line)+l)<breadth: line += (word+' ') else: print head, line line = word+' ' print head,line if __name__ == '__main__': import util,config cfgstruct = (\ ('address', 'a', '0.0.0.0', 'IP address to bind'), \ ('port', 'p', 0x2121, 'TCP port to bind'), \ ('mdsaddress', 'M', '127.0.0.1', 'meta data server address'), \ ('mdsport', 'm', 0x26505, 'meta data server TCP port'), \ ('vg', 'g', 'SANGroup', 'name of volume group for use exclusively by SoftSAN'),\ ('volprefix', 'z', 'lv_softsan_', 'prefix of volume name'),\ ('logging-level', 'l', 'info', 'logging level, can be "debug", "info", "warning", "error" or "critical"'), \ ('logging-file', 'f', 'stdout', 'logging appends to this file'),\ ('config', 'c', 'Chunkserver.conf', 'config file'),\ ('help', 'h', False, 'this help'),\ ) configure, noOpt_args = config(cfgstruct) print configure,'00000000000000000' if configure['help']==True: config.usage_print(cfgstruct) exit(0) confobj = util.Object(configure)
use_vfs = True use_romfs = True use_fcfs = False use_spiffs = False use_fatfs = False use_eth = False def __getattr__( self, key ): if self.__dict__.has_key( key ): return self.__dict__[key] else: self.__dict__[key] = None # visit unknown attribute return None hal_config = config() # called from SConstruct # search in 'halXXXXX' directory for 'config.py' # the config script must include a basic build environment object 'env' # if load_(hal/mcush/freertos) switch is set (default), .c/.h codes will be included def loadHalConfig( haldir, *args, **kwargs ): global hal_config assert isinstance(haldir, str) # check if haldir/root/config.py exists if haldir.startswith('hal'): haldir = haldir[3:] root = _findRoot() if root is None: raise Exception("ROOT not defined") config = join(root, 'hal'+haldir, 'config.py')
import re import email as email_lib from msnlib.msnlib import * import msnlib.msncb as msncb from msnlib.ftp import MsnFTP from utils import * import users; import cmds; from config import * m = msnd() # msn descriptor m.cb = msncb.cb() # callbacks conf = config() # configuration usrs = conf.usrs usrs['config'] = users.ConfigUser(m, conf) def cb_msg(md, type, tid, params, sbd): "Message received callback" msncb.cb_msg(md, type, tid, params, sbd) email = tid.split(" ")[0] if email not in usrs: usrs[email] = users.RealUser(md, email, conf) else: usrs[email].updatemd(md) msg = email_lib.message_from_string(params)
def main(): background, screen, clock = config() #================================ #Criação de objetos musica = pygame.mixer.Sound("BGM/hark_the_sound.wav") #from https://alumni.unc.edu/article.aspx?sid=9630 Audio archive group = RenderUpdates() personagem = Heroi(20, 290,['nome','sobrenome','classe'],listImagens, group) npc = Npcs(650, 280, ['sprites/devilL.png'], group) npc2 = Npcs(675, 240, ["sprites/devilR.png"], group) npc3 = Npcs(675, 340, ["sprites/devilL.png"], group) pygame.font.init() frase = Textos(40, 'Nyeh nyeh nyeh!!', 'fonts/carolingia.ttf') #=================================== lx = [b for b in range(-15, 30)] l1 = [-30] l2 = [30] #parede esquerda parede = [x for x in range(-10, 16)] #colisaoParedeLateral = Eventos(parede, -2) #=================================== iniciarConversa = [52,6,36,-20,55,-10] keys = {K_LEFT: False, K_RIGHT: False, K_UP: False, K_DOWN: False, K_RETURN: False, 27: False} # obs 27 = key 'esc' musica.play() background = background.convert() pygame.display.flip() while True: clock.tick(FPS) for e in pygame.event.get([KEYUP, KEYDOWN]): valor = (e.type == KEYDOWN) if e.key in keys.keys(): keys[e.key] = valor if keys[27]: # key ESC pygame.quit() sys.exit() if personagem.py in l1: #player in the top MPD(keys,personagem) MPR(keys,personagem) MPL(keys,personagem) elif personagem.py in l2: #player in the bottom MPT(keys,personagem) MPR(keys,personagem) MPL(keys,personagem) else: MPU(keys,personagem) MPD(keys,personagem) MPL(keys,personagem) MPR(keys,personagem) if personagem.px == iniciarConversa[0] and personagem.py == iniciarConversa[1]: import squirrel squirrel.main() if personagem.px == iniciarConversa[2] and personagem.py == iniciarConversa[3]: import flippy flippy.main() if personagem.px == iniciarConversa[4] and personagem.py == iniciarConversa[5]: import wormy wormy.main() print(personagem.px, personagem.py) group.clear(screen, background) pygame.display.update(group.draw(screen))
def dump(self): with open(config().get('train', 'tfidf_result_path'), 'wb') as fp: pickle.dump(self, fp) logger.info("write " + self.__class__.__name__ + " train result")
def regenerate_config(apps, config_file, groups, bind_http_https, ssl_certs, templater): compareWriteAndReloadConfig(config(apps, groups, bind_http_https, ssl_certs, templater), config_file)
def getcurdef(config, curdef = None): if curdef: return 'CURR_%s' % curdef else: return 'CURR_%s' % config('CURRENCY')
def MPB(): global filaF if teclas[K_DOWN]: personagem.image = pygame.image.load(listaImagensFrente[filaF]) personagem.converterImagem() personagem.mover(0, 10) personagem.py += 1 filaF += 1 if filaF > 2: filaF = 0 #======================= fundo, tela, clock = config() #================================ #Criação de objetos musica = pygame.mixer.Sound("BGM/Firelink Shrine.wav") grupo = RenderUpdates() personagem = Personagem(20, 290, grupo) npc = Npcs(650, 280, 'sprites/personagem2.png', grupo) npc2 = Npcs(675, 240, "sprites/personagem.png", grupo) npc3 = Npcs(675, 340, "sprites/personagem.png", grupo) pygame.font.init() frase = Textos(40, 'Quem eh voce e oque faz aqui?', 'carolingia.ttf') #=================================== lx = [b for b in range(-4, 76)]
def formatprice(config, price, currency, curdef = None, fmt = '%.2f', rnd = False): price = getprice(config, price, currency, curdef) return (formatnumber(fmt % price), config(getcurdef(config, curdef), 2))
def getprice(config, price, currency, curdef = None): curdef = getcurdef(config, curdef) rate = config('CURR_%s' % currency) ratedef = config(curdef) rate = float(rate) / float(ratedef) return float(price) * rate
sys.exit(2) # # set logger and config objects # if (log_file == None) or (config_file == None): print "Invalid log file/config file specified" usage() sys.exit(1) logger = logger(log_file) if logger.read_error == 1: print "Unable to open log file for writing" sys.exit(1) config = config(config_file) config.parse_and_validate() if config.read_error == 1: logger.toboth("Unable to open config file for reading") sys.exit(1) if config.config_status == CONFIG_INVALID: logger.toboth("Config file is having some lines in invalid format, \ please check") sys.exit(1) if config.valid_lines == 0: logger.toboth("No valid lines in config file") sys.exit(1) common = common(logger, host, port, config, ca=ca_file, cipher=cipher_value) ssl_config_obj_list = copy.deepcopy(config.config_obj_list) sLib = LibTLS(debugFlag, config_obj_list = ssl_config_obj_list, comm = common)
# -*- coding: utf-8 -*- import subprocess from control import * from optimize import * from numpy import * import util from config import * import logging conf = config('path_config.cfg') cur_counter = str(conf.get_and_set_run_counter()) logger = logging.getLogger('madelon' + cur_counter) hdlr = logging.FileHandler(conf.get_run_log_path('MADELON')+'madelon' + cur_counter + '.log') formatter = logging.Formatter('%(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) # Find the paths command_path = conf.get_command_path() file_path = conf.get_file_path()+"madelon" + cur_counter + ".net" data_file = conf.get_data_path('MADELON')+'combined.data.sel' test_data_file = conf.get_data_path('MADELON')+'combined_valid.data.sel' MADELON_spec = netspec(file_path, command_path, data_file, test_data_file) MADELON_spec.num_input_units = 38 MADELON_spec.num_hidden_layers = 2
(len(WEIGHTS), N)) else: WEIGHTS = [1 for x in INPUT_FILES] except Exception as e: if len(sys.argv) > 1: if type(e) == IndexError: sys.stderr.write("Not enough input arguments.\n") elif type(e) == ValueError: sys.stderr.write("Incorrect form of weight provided: \"" + e.message[e.message.index(":")+2:] + "\".\n") else: sys.stderr.write(e.message + "\n") sys.stderr.write(USAGE) sys.exit(1) # Configurations globals().update(config(LANGUAGE_CODE, CORPUS, KWLIST_ID)) sys.stdout = codecs.getwriter("utf-8")(sys.stdout) sys.stderr = codecs.getwriter("utf-8")(sys.stderr) # Load keyword list and build result detection list kwlist = parseKwList(KWLIST_FILE) outList = DetList(kwlist) outList.kwlistFilename = os.path.basename(KWLIST_FILE) outList.language = LANGUAGE # Load input detection lists inLists = [] for i in range(N): sys.stderr.write("Loading input detection list %s (weight = %.6f) ...\n" % (INPUT_FILES[i], WEIGHTS[i])) inLists.append(DetList(kwlist)) inLists[-1].readXml(INPUT_FILES[i], removeZeroScore = True)
""" blogeng.py - Model functions for MVC Blog Engine """ import web, os, sys, datetime # Set path to custom modules, get the config rootdir = os.path.abspath(os.path.dirname(__file__)) + '/' sys.path.append(rootdir) from config import * config = config(rootdir) # Set up database object db = web.database(dbn='mysql', db=config.db, user=config.user, pw=config.pw) # Get all posts def getPosts(): return db.select('posts', order='id DESC') # Get specified post def getPost(postid): return db.select('posts', where='id=$postid', vars=locals())[0] # Add new post def addPost(title, body): db.insert('posts', date=datetime.datetime.utcnow(), title=title, body=body) # Delete specified post def delPost(postid): # Better delete attached comments too
# -*- coding=utf-8 -*- # author: [email protected] # pyinstaller mparserui.spec from lib.logConf import logConf from easygui import * from mflow_parser import * from config import * from datetime import * logger = logConf() config = config() title = 'media engine log parser version: ' + str(config.getversion()) buttonboxmsg = 'Please select a main log:' ylogstring = 'Open a main log' choices = [ylogstring, 'Exit'] choice = buttonbox(buttonboxmsg, title = title, choices = choices) if choice != 'Exit': if choice == ylogstring: mainlog = fileopenbox() if not mainlog: msgbox('please relaunch and open a correct log.') exit() else: mflow = mflow(logname=mainlog) starttime = datetime.now() mflow.parse() mflow.exportexcel() endtime = datetime.now()