def start_window(): # 開始画面のレイアウト作成 layout = [[sg.Text('ping結果ファイルの削除')], [sg.Text('保存期間の過ぎたping結果ファイルを、毎日決められた時刻に削除します')], [sg.Text('事前にファイル保存期間と削除時刻を設定してください。\n')], [sg.Text('現在設定されている保存期間は' + config.get('settings', 'delete') + '日、削除時刻は' + config.get('settings', 'deltime') + 'です。')], [sg.Text('設定完了後、[実行]ボタンを押してください。')], [sg.Text('削除プログラムを中断するにはこのウインドウを閉じてください。')], [sg.Button('設定メニューへ', size=(20, 2), border_width=4)], [sg.Button('実行', size=(20, 2), border_width=4)], [sg.Button('キャンセル', size=(20, 2), border_width=4)]] window = sg.Window('ping監視システム', layout) while True: # Event Loop event, values = window.read() if event in (None, 'キャンセル'): sys.exit() elif event == '設定メニューへ': import settings as st st.settings() start_window() elif event == '実行': msg1 = 'ファイル削除を実行します。' sg.popup(msg1) # 毎日一定の時刻に古いログファイルを削除する deltime = config.get('settings', 'deltime') schedule.every().day.at(deltime).do(delete_files) while True: schedule.run_pending() time.sleep(59)
def put_user(): if not request.json: abort_msg(400, 'Expected JSON parameters') if 'password' in request.json: passwd = request.json['password'] if not passwd: passwd = utils.generatePassword(20) _db = db.connect(settings.settings()) db.update(_db, 'users', 'pass="******"' % (passwd), where='name="%s"' % auth.username()) data = {'user': auth.username(), 'password': passwd} return jsonify(data) if 'api_key' in request.json: apikey = utils.generateApiKey() _db = db.connect(settings.settings()) db.update(_db, 'users', 'apikey="%s"' % (apikey), where='name="%s"' % auth.username()) data = {'user': auth.username(), 'api_key': apikey} return jsonify(data) abort_msg(400, 'Expected "password" or "api_key"')
def configParsing(): configs = [] # 0 = theme, 1 = sender email, 2 = payment receiver, 3 = account number, 4 = member classes, 5 = bank BIC save_path = os.getenv("APPDATA") + "\\Haukiposti" completeName = os.path.join(save_path, "haukiposticonfig.ini") config = configparser.ConfigParser() try: config.read(completeName) configs.append(config["haukiposti"]["theme"]) configs.append(config["haukiposti"]["email"]) configs.append(config["haukiposti"]["paymentreceiver"]) configs.append(config["haukiposti"]["accountnumber"]) configs.append(config["haukiposti"]["memberclasses"]) configs.append(config["haukiposti"]["bank"]) logging.info("Settings retrieved succesfully.") except: configs.append("reddit") configs.append("") configs.append("") configs.append("") configs.append("") configs.append("") logging.error("No settings file.") sg.PopupOK("Ohjelma ei pystynyt löytämään asetustiedostoa.\nViemme sinut ensin asetuksiin, jotta voit laittaa ne kuntoon.") settings.settings(configs) configs = updateConfig(configs) return configs
def start_window(): # 開始画面のレイアウト作成 layout = [[sg.Text('ping監視システム')], [sg.Text('初めて使う場合はまず設定を行ってください。')], [sg.Text('設定完了後、[ping監視実行]ボタンを押してください。')], [sg.Text('ping監視を中断するにはこのウインドウを閉じてください。')], [sg.Button('設定メニューへ', size=(20, 2), border_width=4)], [sg.Button('ping監視実行', size=(20, 2), border_width=4)], [sg.Button('キャンセル', size=(20, 2), border_width=4)]] window = sg.Window('ping監視システム', layout) while True: # Event Loop event, values = window.read() if event in (None, 'キャンセル'): sys.exit() elif event == '設定メニューへ': import settings as st st.settings() start_window() elif event == 'ping監視実行': msg1 = 'ping監視を実行します。' sg.popup(msg1) schedule.every(config.getint('settings', 'interval')).minutes.do(run_ping()) while True: schedule.run_pending() time.sleep(1) window.close()
def __init__(self,s3conn=None,bucket=None): if not s3conn: s3conn = S3.AWSAuthConnection(settings('AWS_ACCESS_KEY_ID'),settings('AWS_SECRET_ACCESS_KEY')) self.s3conn = s3conn if not bucket: bucket = settings('APP_BUCKET') self.bucket = bucket
def test_setters_and_signals(self): """ Checks the singleton properties of settings as well as setters, signals and save behavior. """ s = settings.settings() s2 = settings.settings() changed = defaultdict(lambda: False) def track_changed(onwhat, name): def slot(): changed[name] = True getattr(onwhat, name + "_changed").connect(slot) track_changed(s, "main_window_geometry") track_changed(s, "main_window_state") s.main_window_geometry = QtCore.QByteArray("hi") self.assertTrue(changed["main_window_geometry"]) self.assertEqual(s2.main_window_geometry, QtCore.QByteArray("hi")) s.main_window_state = QtCore.QByteArray("there") self.assertTrue(changed["main_window_state"]) self.assertEqual(s2.main_window_state, QtCore.QByteArray("there")) s.save() self.assertEqual(self.settings_mock.values["main_window_geometry"], QtCore.QByteArray("hi")) self.assertEqual(self.settings_mock.values["main_window_state"], QtCore.QByteArray("there"))
def define_network(): sets = settings.settings() if 'network_name' not in sets: return False inf = infra.provider(settings.settings()) net = inf.network(sets['network_name']) if net is not None and net.name() == sets['network_name']: if not net.isActive(): net.create() network_info(net) return True if 'network_ip' not in sets: print ('ERROR: No IP for network') return False net_xml = inf.defineNatNetwork(sets['network_name'], sets['network_ip']) net = inf.createNetwork(net_xml) if net is not None and net.name() == sets['network_name']: network_info(net) return True print ('Failed to setup network: %s' % (sets['network_name'])) return False
def start(): display.fill(white) message('Racecar Dodge', lobsterL, -75) message('By Shaunak Warty', lobsterS, 0) message('Press any key to start', lobsterS, 50) gear = pygame.image.load(r'Images\gear.png') gearRect = gear.get_rect(topright=(dispWD - 3, 3)) display.blit(gear, gearRect) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: end() elif event.type == pygame.KEYUP: main() start() elif event.type == pygame.MOUSEBUTTONUP: mouse = pygame.mouse.get_pos() if gearRect.collidepoint(mouse): settings() start() clock.tick(10)
def createMachine(self, res): extras = [] extra = '' base = '' inf = infra.provider(settings.settings()) volume = self.get_volume_from_image(res['image'], utils.generateID() + '_', resize=res['size']) if volume: base = os.path.basename(res['image']) extras.append(inf.fileStorage(volume)) cdrom = self.get_cdrom_image(res['cdrom']) if cdrom: if not base: base = os.path.basename(cdrom) extras.append(inf.cdromStorage(cdrom)) image_extra_loader = None if volume or cdrom: item = cdrom if volume: item = volume image_extra_loader = self.image_extra_config(os.path.basename(item), res['name']) image_extra_userdata = {} if image_extra_loader is not None: print ('Found image loader: %s' % (image_extra_loader.base())) extra_device = image_extra_loader.extraDeviceConfig(inf) if extra_device: extras.append(extra_device) image_extra = image_extra_loader.extra() if image_extra: extra += image_extra image_extra_userdata = image_extra_loader.userdata() # TODO: Support other features if 'network_name' in settings.settings(): extras.append(inf.defineNetworkInterface(settings.settings()['network_name'])) extradevices = '\n'.join(extras) dom_xml = inf.customDomain(res['name'], res['cpus'], res['memory'], extradevices=extradevices, extra=extra) dom = inf.createDomain(dom_xml) dom_res = dom.create() _db = db.connect(settings.settings()) config_data = json.dumps(image_extra_userdata) config_data = config_data.replace('\'', '\\\'') db.update(_db, 'machines', 'config=\'%s\'' % (config_data), where='id="%s"' % (res['name']))
def get_volume_from_image(self, image, prefix='', resize=''): img = images.provider(settings.settings()) vol = images.volume_provider(settings.settings()) try: src_img = img.get(image) return vol.copyFrom(src_img, prefix=prefix, resize=resize) except Exception as e: print ('ERROR: %s' % (e)) return ''
def nereden(self): dosya = QFileDialog.getOpenFileName(self, "", settings().value("Genel/Yol").toString()) if dosya == "": pass elif QFile.exists(dosya): from os.path import abspath, dirname settings().setValue("Genel/Yol", abspath(dirname(str(dosya)))) self.neredenEdit.setText(dosya) else: QMessageBox.warning(self, self.trUtf8("Hata!"), self.trUtf8("Böyle bir dosya mevcut değil!"))
def nereye(self): dosya = QFileDialog.getSaveFileName(self, "", settings().value("Genel/Yol").toString()) if not dosya == "": if dosya[-3:] == "001": self.nereyeEdit.setText(dosya) from os.path import abspath, dirname settings().setValue("Genel/Yol", abspath(dirname(str(dosya)))) return self.nereyeEdit.setText(dosya+".001") from os.path import abspath, dirname settings().setValue("Genel/Yol", abspath(dirname(str(dosya))))
def machine_del(machine_id): user = auth.username() _db = db.connect(settings.settings()) if user == 'admin': res = db.select(_db, 'machines', where='id=\'%s\'' % machine_id) else: res = db.select(_db, 'machines', where='id=\'%s\' AND owner=\'%s\'' % (machine_id, user)) if not res: abort_msg(400, 'Machine "%s" not found' % (machine_id)) res = res[0] inf = infra.provider(settings.settings()) dom = inf.getDomain(res[0]) if not dom or dom is None: abort(400) if dom.isActive(): dom.destroy() flags = 0 if dom.hasManagedSaveImage(): flags |= libvirt.VIR_DOMAIN_UNDEFINE_MANAGED_SAVE if dom.snapshotNum() > 0: flags |= VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA vol_provider = images.volume_provider(settings.settings()) vols = inf.deviceItems(dom, 'disk') error_msg = '' try: dom.undefineFlags(flags) except: error_msg = 'ERROR: Undefining domain: %s' % macine_id print(error_msg) error_msg += vol_provider.removeVolumes(vols) _db = db.connect(settings.settings()) db.delete(_db, 'machines', where='id=\'%s\'' % machine_id) data = {'removed': machine_id} if error_msg: data['error'] = error_msg return jsonify(data)
def put_machine(machine_id): if not request.json: abort_msg(400, 'Expected JSON input') user = auth.username() _db = db.connect(settings.settings()) if user == 'admin': res = db.select(_db, 'machines', where='id=\'%s\'' % machine_id) else: res = db.select(_db, 'machines', where='id=\'%s\' AND owner=\'%s\'' % (machine_id, user)) if not res: abort_msg(400, 'Machine "%s" not found' % (machine_id)) res = res[0] inf = infra.provider(settings.settings()) dom = inf.getDomain(res[0]) if not dom or dom is None: abort_msg(400, 'Machine "%s" not in backedn' % (machine_id)) if 'operation' not in request.json: abort_msg(400, 'No operation defined') data = {} if request.json['operation'] == 'reboot': data['result'] = dom.reboot() elif request.json['operation'] == 'reset': data['result'] = dom.reset() elif request.json['operation'] == 'shutdown': data['result'] = dom.shutdown() elif request.json['operation'] == 'start': st = dom.state()[0] if st in [0, 4, 5, 6]: data['result'] = dom.create() else: abort_msg(400, 'Can\'t start, invalid state: %s' % (inf.domState(dom))) elif request.json['operation'] == 'forceoff': data['result'] = dom.destroy() elif request.json['operation'] == 'suspend': data['result'] = dom.suspend() elif request.json['operation'] == 'resume': data['result'] = dom.resume() else: abort_msg(400, 'Unknown operation: %s' % (request.json['operation'])) data[request.json['operation']] = machine_id return jsonify(data)
def run_game(): pygame.init() ai_settings = settings() pygame.mouse.set_visible(0) screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") ship = Ship(ai_settings, screen) alien = Alien(ai_settings, screen) bullets = Group() secondaries = Group() aliens = Group() bombs = Group() gf.create_fleet(ai_settings, screen, ship, aliens) stats = GameStats(ai_settings) ai_settings.soundin.play() while True: gf.check_events(ai_settings, screen, ship, bullets, secondaries, bombs) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, ship, aliens, bullets, secondaries, bombs) gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets, secondaries, bombs) screen.blit(ai_settings.background, [0, 0]) gf.update_screen(ai_settings, screen, ship, bullets, secondaries, aliens, bombs)
def __init__(self): pygame.init() self.settings = settings() self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) pygame.display.set_caption("Alien Invasion") self.ship = ship(self)
def getFontLocation(fontName: str): s = settings() s.ReadSettings() if s.fontLocationMap is None: return None if fontName in s.fontLocationMap: return s.fontLocationMap[fontName]
def __init__(self, city): self.urlPath = "http://www.flickr.com/map?place_id=" self.flickrPlaces = dict() self.flickrPlaces["istambul"] = "6NGXevKbAphp2QAz" self.flickrPlaces["london"] = ".2P4je.dBZgMyQ" self.flickrPlaces["new+york"] = "hVUWVhqbBZlZSrZU" self.flickrPlaces["tokio"] = "V5QAdQebApgw_9XH" self.flickrPlaces["barcelona"] = "2HQ7FIeeBJ_vRb8" self.flickrPlaces["paris"] = "bV4EOqafAJnqoz4" self.flickrPlaces["berlin"] = "sRdiycKfApRGrrU" self.flickrPlaces["mexicodf"] = "MuLDKdiYAJo.QrA" self.flickrPlaces["rome"] = "xbTF9RCeA51vjuk" self.flickrPlaces["praha"] = "UEddssmbAZwXVqZt7g" self.flickrPlaces["moscou"] = "ZLXvFuGbAJ6JI5bc" self.flickrPlaces["san+francisco"] = "kH8dLOubBZRvX_YZ" self.flickrPlaces["new+delhi"] = "7gGxOnGbApgQ3.2i2g" self.flickrPlaces["vienna"] = "wL4AEK2cBJ0UQdc" self.flickrPlaces["rosario"] = "vzJ2RFBSUbveaB0" self.flickrPlaces["buenos+aires"] = "SG5jj75SUbqEFrc" self.flickrPlaces["sau+paulo"] = "ou6W9HJTUL1op5q6RA" self.flickrPlaces["adelaide"] = "xTgz9S9QUrMLZbpQ" #http://www.flickr.com/places/info/466862 self.settings = settings() self.setCity(city) self.managerDB = managerDB() self.flickr = flickrapi.FlickrAPI(self.settings.flickr_api_key, self.settings.flickr_api_secret) self.lastRhythm = 0 self.minimHistoric = 10
def menu(main, win, LETTER_FONT): while True: play_button = pygame.Rect(170, 300, 150, 50) play_button_text = LETTER_FONT.render('Play', 1, BLACK) settings_button = pygame.Rect(335, 300, 150, 50) settings_button_text = LETTER_FONT.render('Settings', 1, BLACK) quit_button = pygame.Rect(500, 300, 150, 50) quit_button_text = LETTER_FONT.render('Quit', 1, BLACK) image = pygame.image.load("images/logo.png") for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if settings_button.collidepoint(event.pos): difficulty = settings(win, LETTER_FONT) if play_button.collidepoint(event.pos): main(difficulty) if quit_button.collidepoint(event.pos): pygame.quit() quit() win.fill(WHITE) win.blit(image, (150, 100)) pygame.draw.rect(win, PURPLE, play_button) win.blit(play_button_text, (210, 310)) pygame.draw.rect(win, BLUE, settings_button) win.blit(settings_button_text, (355, 310)) pygame.draw.rect(win, LIGHT_BLUE, quit_button) win.blit(quit_button_text, (540, 310)) pygame.display.update()
def run_game(): #inicializa o jogo e cria um objeto para a tela pygame.init() ai_settings = settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) #cria a janela do pygame em pixels pygame.display.set_caption("Allien Invasion") # Cria o botao play play_button = Button(ai_settings, screen, "Play") #Cria uma instancia para armazenar dados estatisticos do jogo e cria painel de pontuacao stats = GameStats(ai_settings) sb = Scorebord(ai_settings, screen, stats) #cria uma espaconave, um grupo de projeteis e um grupo de alienigenaas ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() gf.create_fleet(ai_settings, screen, ship, aliens) #inicia o laço principal do jogo e vai ficar rodando aqui em loop infinito ate evento que pare while True: gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def game_end(main, win, image, LETTER_FONT): while True: play_again_button = pygame.Rect(130, 250, 160, 50) play_again_button_text = LETTER_FONT.render('Play Again', 1, BLACK) settings_button = pygame.Rect(305, 250, 160, 50) settings_button_text = LETTER_FONT.render('Settings', 1, BLACK) exit_button = pygame.Rect(480, 250, 160, 50) exit_button_text = LETTER_FONT.render('Exit', 1, BLACK) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: if settings_button.collidepoint(event.pos): difficulty = settings(win, LETTER_FONT) if play_again_button.collidepoint(event.pos): main(difficulty) if exit_button.collidepoint(event.pos): pygame.quit() quit() win.fill(WHITE) win.blit(image, (100, 150)) pygame.draw.rect(win, PURPLE, play_again_button) win.blit(play_again_button_text, (140, 260)) pygame.draw.rect(win, BLUE, settings_button) win.blit(settings_button_text, (330, 260)) pygame.draw.rect(win, LIGHT_BLUE, exit_button) win.blit(exit_button_text, (530, 260)) pygame.display.update()
def POST(self): from constants import jsonsep from json import dumps from settings import settings from traceback import format_exc from instaDatabase import InstaDatabase from instaAPI import InstaAPI, VerifyComplete web.header("Content-Type", "application/json; charset=UTF-8") try: sign = web.input().get("sign") if sign is None or not isinstance(sign, str) or len(sign) == 0: d = {"code": -1, "msg": "sign is needed."} return dumps(d, ensure_ascii=False, separators=jsonsep) code = web.input().get("code") if code is None or not isinstance(code, str) or len(code) == 0: d = {"code": -2, "msg": "code is needed."} return dumps(d, ensure_ascii=False, separators=jsonsep) db = InstaDatabase() InstaAPI(db, None, None, code, sign) d = {"code": -3, "msg": "Unknown Error."} except VerifyComplete: d = {"code": 0, "msg": "Verify Complete."} except: web.HTTPError('500 Internal Server Error') d = {"code": -500, "msg": "Internal Server Error"} try: s = settings() s.ReadSettings() if s.debug: d["detail"] = format_exc() except: pass return dumps(d, ensure_ascii=False, separators=jsonsep)
def __init__(self): self.config = settings() pathToData = self.config.users_token self.connection = sqlite3.connect(pathToData, check_same_thread=False) self.cursor = self.connection.cursor() self.cursor.execute('''CREATE TABLE if not exists users (chatID COUNTER CONSTRAINT PrimaryKey PRIMARY KEY, token Text(100) NOT NULL)''')
def generate_alarm(): p = subprocess.Popen(["df", "-h"], stdout=subprocess.PIPE) output = p.communicate()[0] info = ServerInfo() a = settings() subject = "Veriteknik - Disk Usage Alert" msg = """ <h2>Disk usage report</h2> <pre> Server Time: <b>{now}</b> Threshold: <b>%{thres}</b> Hostname: <b>{hostname}</b> External IP Address: <b>{ip}</b> CPU Temperature: <b>{cpu_temp}</b> Celsius ----------------------------------- {df} </pre> """.format(thres=a.threshold, df=output, hostname=info.hostname, ip=info.ip, cpu_temp=info.cpu_temp, now=info.now) msg = msg.replace("\n", "<br>") mail = MailObject(a.hostname, a.sender, a.receivers, subject, msg, a.port, a.username, a.password)
def __init__(self, command_prefix="!"): self.settings = settings.settings() self.spoiler_mask = '[Spoiler removed react with 🔍 to show]' bot.Bot.__init__(self, command_prefix=command_prefix, owner_id=self.settings.owner, case_insensitive=True)
def post_user(): if auth.username() != 'admin': abort_msg(400, 'Access denied, admin needed!') if not request.json: abort_msg(400, 'Expected JSON parameters') if 'user' not in request.json: abort_msg(400, 'Value for "user" not defined') user = request.json['user'] passwd = '' if 'password' in request.json: passwd = request.json['password'] if user == 'admin': abort_msg(400, 'Can\'t create admin') _db = db.connect(settings.settings()) res = db.select(_db, 'users', where='name=\'%s\'' % user) if res: abort_msg(400, 'User \"%s\" already exists' % user) if not passwd: passwd = utils.generatePassword(20) db.insert(_db, 'users', [user, passwd, utils.generateApiKey()]) data = {'user': request.json['user'], 'password': passwd} return jsonify(data)
def run_game(): init() uni_settings = settings() screen = display.set_mode(uni_settings.screen_size) display.set_caption('Universe') while True: screen.fill(uni_settings.black) gf.check_events() # gf.orbit(screen) # G.solar_system(screen, uni_settings, uni_settings.earth_angle, uni_settings.moon_angle, uni_settings. # mercury_angle, uni_settings.venus_angle,uni_settings.mars_angle, uni_settings.jupiter_angle, # uni_settings.saturn_angle, uni_settings.uranus_angle, uni_settings.neptune_angle) # G.rotating_solar_system(uni_settings) for i in range(1, num_stellar + 1): stellar_data = G.read_data('data.txt', i) stellar = Planet(screen, stellar_data[1], stellar_data[2], stellar_data[3], stellar_data[5]) temp = stellar.generate_planet('clockwise', [0, 0]) G.rotating_random_system('data.txt', i, stellar_data[4], stellar_data[5]) for i in range(1, num_planet + 1): print(i) planet_data = G.read_planet_data('planet_data.txt', i) planet = Planet(screen, planet_data[1], [temp[0], temp[1]], planet_data[3], planet_data[5]) planet.generate_planet('clockwise', [120, 120]) G.rotating_random_planet('planet_data.txt', i, planet_data[4], planet_data[5]) display.flip()
def closeEvent(self, event): s = settings() # Save layout s.main_window_geometry = self.saveGeometry() s.main_window_state = self.saveState() event.accept()
def FormatChangeLog(changelog, name, connection): localsettings = settings.settings(False) localsettings.GetSettings() output = name + "\n\n" count = 0 for a in changelog.split("$$$"): date = a.split("%%%")[0] userid = a.split("%%%")[1] try: action = "SELECT Name FROM user WHERE ID = " + str(userid) results = db.SendSQL(action, connection) username = results[0][0] except: username = localsettings.dictionary["userdeleted"][localsettings.language] output = output + date + " - " + username + "\n" count = count + 1 if count == 10: break return output.strip()
def __init__(self, screen): # {{{ ## curses options curses.curs_set(0) cui.color.setColor() self.stdscr = screen self.stdscr.keypad(1) self.settings = settings() self.initSrvlst() self.initMenus() self.focusedWidget = self.srvlst panel.update_panels() curses.doupdate() self.startQuery() ## Main Loop -- have to catch all quit events here while True: key = self.stdscr.getch() if key in cui.KEY_QUIT: self.quit() break if key in cui.KEY_LAUNCH and self.focusedWidget == self.srvlst: self.launch() self.quit() break else: self.handleInput(key) curses.doupdate() # }}}
def run_game(): # 定义全局变量 global ship # 初始化并创建一个窗口对象 pygame.init() ai_settings = settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # 创建按钮 play_button = Button(ai_settings, screen, "PLAY") # 储存信息 stats = Gamestats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) ship = ship(ai_settings, screen) # 储存子弹编组 bullets = Group() # 创建外星人群 aliens = Group() gf.create_fleet(ai_settings, screen, ship, aliens) # 游戏主循环 while True: gf.check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, ship, aliens, bullets) gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets) gf.undate_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
def authed_get_url(self,path): path = path.strip('/') # Normalize path by dropping extra begin/end slashes auth_gen = S3.QueryStringAuthGenerator(settings('AWS_ACCESS_KEY_ID'),settings('AWS_SECRET_ACCESS_KEY'), is_secure=False) #PP_BUCKET) # if not expires: # expires = datetime.datetime.now() + datetime.timedelta(0,60*10) # In 10 min # auth_gen.set_expires(expires) uri = auth_gen.get(self.bucket,path) # We actually want to `unquote` the `/` char to allow for prettier key URLs #i = uri.index('?') #lside = uri[:i].replace('%2F','/') #rside = uri[i:] return uri
def load_channels_from_settings(self): try: common.dbg_log('channel_list::load_channels_from_settings', 'enter_function') self.Data = [] set = settings.settings() xmldoc = set.parse() if xmldoc != None: category = xmldoc.getElementsByTagName('category') for node_cat in category: setting = node_cat.getElementsByTagName('setting') for node_set in setting : if 'id' in node_set.attributes.keys() and not node_set.getAttribute('id').find('channel_sep_'): offset = len('channel_sep_') index = node_set.getAttribute('id')[offset:] enabled = common.__addon__.getSetting('channel_enable_'+index) if enabled == 'true': oname = node_set.getAttribute('label') uname = common.__addon__.getSetting('channel_name_'+index) icon = common.__addon__.getSetting('channel_icon_'+index) chn = channel(index, oname, uname, icon, common.correction) self.Data.append(chn) common.dbg_log('channel_list::load_channels_from_settings', oname.encode('utf-8') + '(' + index + ')') common.dbg_log('channel_list::load_channels_from_settings', 'exit_function') except Exception, e: common.dbg_log('channel_list::load_channels_from_settings', 'ERROR: (' + repr(e) + ')', common.logErorr)
def rekonfiguruj(self): # metoda do zmiany ustawien w programie self.ust.p_sr = self.ust.p_pr self.ust.p_w = self.ust.p_pr self.ust.headers = [] self.ust.ostat_zapis = self.ust.p_pr self.sett = settings(self.ust) # wylacz niepotrzebne ustawienia self.sett.g_ref_lineEdit.setEnabled(False) self.sett.g_working_lineEdit.setEnabled(False) self.sett.g_headers.clear() self.sett.g_headers.setEnabled(False) przyciski = [ self.sett.g_toHeaders, self.sett.g_upHeader, self.sett.g_downHeader, self.sett.g_delHeader, self.sett.g_firstHeader, self.sett.g_lastHeader, self.sett.g_working_choose, self.sett.g_ref_choose, ] for przycisk in przyciski: przycisk.setEnabled(False) self.sett.exec_() if self.sett.restart: self.defpol = [';'.join([x, self.ust.defpol[x]]) for x in self.ust.defpol_index] self.resetujMetadane()
def runGrader(settingsFile="settings.json", submissionFile="submission.s", outputFile="output.txt", concatFile="concat.s", autograderOutput="graderResults.txt", ShowAll=False, printResults=True, IO=None): try: _ShowAll = sys.argv[1] except: _ShowAll = False # overrides json "show" and shows the StudentOutputs of every test _ShowAll = _ShowAll or ShowAll if IO is None: io = settings(settingsFile) else: io = IO runMips = concat(IO=io, sfile=submissionFile, concatFile=concatFile) autograder(IO=io, _ShowAll=_ShowAll, runMips=runMips, outputDest=outputFile, concatFile=concatFile, autograderOutput=autograderOutput, printResults=printResults)
def FormatChangeLog(changelog, name, connection): localsettings = settings.settings(False) localsettings.GetSettings() output = name + "\n\n" count = 0 for a in changelog.split("$$$"): date = a.split("%%%")[0] userid = a.split("%%%")[1] try: action = "SELECT Name FROM user WHERE ID = " + str(userid) results = db.SendSQL(action, connection) username = results[0][0] except: username = localsettings.dictionary["userdeleted"][ localsettings.language] output = output + date + " - " + username + "\n" count = count + 1 if count == 10: break return output.strip()
def genItemList(username: str, d: dict, li: list, typ: int) -> List[RSSItem]: s = settings() s.ReadSettings() ser = s.RSSProxySerects r = [] for i in li: t = RSSItem(typ) url = f"https://www.tiktok.com/@{username}/video/{i['id']}" t.link = url t.author = i['author']['nickname'] t.guid = url t.comments = url desc = escape(i['desc']) vurl = None for k in ['downloadAddr', 'playAddr']: if k in i['video']: if i['video'][k] is not None: vurl = i['video'][k] break cover = None for k in ['originCover', 'reflowCover']: if k in i['video']: cover = i['video'][k] break if vurl is not None: vurl = genUrl(vurl, ser, d, "https://www.tiktok.com/") if cover is not None: cover = genUrl(cover, ser) if vurl is not None: p = f' poster="{escapeQuote(cover)}"' if cover is not None else '' desc += f'<video src="{escapeQuote(vurl)}"{p} controls="controls">' t.description = desc r.append(t) return r
def post(self, **params): module = self.get_argument('module', 'missing') if module == 'missing': self.clear() self.set_status(404) self.finish("<html><body>Missing function call</body></html>") return else: Log.Debug('Recieved a post call for module: ' + module) if module == 'logs': self = logs().reqprocessPost(self) elif module == 'settings': self = settings().reqprocessPost(self) elif module == 'pms': self = pms().reqprocessPost(self) elif module == 'findMedia': self = findMedia().reqprocessPost(self) elif module == 'wt': self = wt().reqprocessPost(self) elif module == 'scheduler': self = scheduler().reqprocessPost(self) elif module == 'jsonExporter': self = jsonExporter().reqprocessPost(self) else: self.clear() self.set_status(412) self.finish('Unknown module call') return
def OnInit(self): # wx.InitAllImageHandlers() self.connected = False self.settings = settings.settings() # Crée la frame principale self.frame = frame.frame(None, self, App.title) self.frame.Show(True) self.SetTopWindow(self.frame) self.score = frame_score.frame_score(self.frame) self.score.Show(False) self.son = son.son() self.tour_on = False self.t1 = wx.Timer(self) self.reliquat = reliquat.reliquat() self.onExit = False # Appelle la frame de connexion au début d = dlgconn.dlgconnframe(self) d.ShowModal() if not d.nick: return False self.nick = d.nick self.host = d.host self.port = d.port self.lance_net() return True
def fetch_new_pages(tree): global something_new, urls_to_open classes = """.topic_unread a, .topic_unread_mine a, .topic_unread_locked a, .topic_unread_locked_mine a, .topic_unread_hot a, .topic_unread_hot_mine a, .sticky_unread a, .sticky_unread_locked_mine a, .sticky_unread_mine a, .announce_unread a, .announce_unread_locked a, .announce_unread_locked_mine a, .announce_unread_mine a, .global_unread a, .global_unread_locked a, .global_unread_locked_mine a, .global_unread_mine a""" unread_pages = tree.cssselect(classes) for unread_page in unread_pages: new_url = settings("FORUM_URL") + unread_page.get("href")[2:] urls_to_open.append(new_url) print(new_url) sys.stdout.flush() something_new = True
def __init__(self): pygame.init() # Set up the music self.shoot_sound = pygame.mixer.Sound('music/8bit.wav') pygame.mixer.music.load('music/09 - Cherry Bomb.mp3') pygame.mixer.music.play(-1, 0.0) self.music_playing = True self.settings = settings() self.scene = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height), 0, 32) pygame.display.set_caption('Space Invader') self.fleet = Fleet(self.settings, self.shoot_sound) self.ship = Ship(self.settings) self.start_screen = start_screen( self.scene, Vector2(self.settings.screen_width, self.settings.screen_height), self.settings) self.high_score_screen = high_score_screen(self.scene, self.settings) self.game_over_screen = game_over_screen(self.settings, self.scene) # Set up the music self.shoot_sound = pygame.mixer.Sound('music/8bit.wav') pygame.mixer.music.load('music/09 - Cherry Bomb.mp3') pygame.mixer.music.play(-1, 0.0) self.music_playing = True self.new_game = True self.show_scores = False self.game_over = False self.round_count = 1 self.scene_count = 0
def __init__(self, basepath, username, project, *args, **kwargs): self._xmlparser = ET.XMLParser(load_dtd = True) self._xmlparser.resolvers.add(PrefixResolver()) self._htmlparser = ET.HTMLParser(encoding='utf-8') try: self._app_config = settings() self._appdir = os.path.join(self._app_config['InstallSettings']['installdir'],"kolekti") except : self._app_config = {'InstallSettings':{'installdir':os.path.realpath( __file__), 'kolektiversion':"0.7"}} self._appdir = os.path.dirname(os.path.realpath( __file__ )) if basepath is not None: if basepath[-1]==os.path.sep: basepath = basepath[:-1] self._basepath = basepath self._username = username self._project = project self._path = os.path.join(basepath, username, project) self.project_settings = self.get_project_config(self._path) self._version = self.project_settings.get('version')
def test_default_configuration(self): """ Checks the default configuration and presence of all properties. """ s = settings.settings() self.assertEqual(s.main_window_geometry, QtCore.QByteArray()) self.assertEqual(s.main_window_state, QtCore.QByteArray())
def main(command): log_proc = S3LogProcessor(settings('LOG_BUCKET'), settings('LOG_BUCKET_PREFIX'), db) usage_meter = UsageMeter() if command == 'nuke': print "Resetting log markers, Removing all usage events" db.usage_events.remove() log_proc.reset_log_marker() if command == 'nuke' or command == 'reset': print "resetting mapreduce markers" usage_meter.reset() if command == 'update': # Pull updates from S3 logs print "Process Amazon logs" log_proc.process_new_logs() # Update usage stats in DB print "Calculate usage from logs" usage_meter.update()
def ShowChangeLog(name, changelog, connection): localsettings = settings.settings(False) localsettings.GetSettings() changelog = FormatChangeLog(changelog, name, connection) output = wx.MessageDialog(None, changelog, localsettings.dictionary["changelog"][localsettings.language], wx.OK) output.ShowModal()
def __getlnk(self): params = settings() if(params.getSettings()): try: lnk = MySQLdb.connect(params.host,params.user,params.password,params.db) return lnk except Exception, e: print e
def front(): s = session(request) authed = s.get('authenticated') if not authed: return redirect('/login') pile = authed['piles'][0] if not pile: return abort(404,'Your user account (%s) does not have a Pile associated with it. Please report this error!' % user_ent['email']) return redirect('http://'+settings('CONTENT_DOMAIN') +'/app#'+pile['name'])
def __init__(self): __settings = settings.settings(self.default_cli()) self.templates = __settings.templates self.variables = __settings.variables self.passwords = __settings.passwords self.projectDir = os.path.dirname(os.path.abspath(__file__)) self.blocks_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), __settings.blocks_path) self.templates_directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), __settings.templates_path)
def test_error_handling(self): s = SettingsMock() s.status_value = QtCore.QSettings.FormatError self.assertRaises(Exception, settings.setup_settings, s) s = SettingsMock() settings.setup_settings(s) s.status_value = QtCore.QSettings.AccessError self.assertRaises(Exception, settings.settings().save)
def stage(): """Stage all the necessary static files!""" staged_dir = os.path.join(settings("DIRNAME"), "staged") staged_static_dir = os.path.join(staged_dir, "static") orig_static_dir = os.path.join(settings("DIRNAME"), "static") # Stage the app if not os.path.isdir(staged_dir): os.mkdir(staged_dir) app_html = template("app", app_meta=app_meta()) open(os.path.join(staged_dir, "app"), "w").write(app_html) # Stage the static files! if not os.path.isdir(orig_static_dir): print "Couldn't find the static files dir" return if os.path.isdir(staged_static_dir): shutil.rmtree(staged_static_dir) shutil.copytree(orig_static_dir, staged_static_dir)
def test_existing_settings(self): """ Tests whether existing settings are picked up but the Settings class. """ my_settings_mock = SettingsMock({"main_window_geometry": QtCore.QByteArray("foo")}) settings.setup_settings(my_settings_mock) self.assertEqual(settings.settings().main_window_geometry, QtCore.QByteArray("foo")) self.assertEqual(settings.settings().main_window_state, QtCore.QByteArray()) settings.settings().save() self.assertEqual(my_settings_mock.values["main_window_geometry"], QtCore.QByteArray("foo")) self.assertEqual(my_settings_mock.values["main_window_state"], QtCore.QByteArray())
def getapp(): session_opts = { "session.type": "file", 'session.cookie_expires': True, 'session.auto': True, 'session.data_dir': os.path.join(settings("DIRNAME"),"cache"), } app = bottle.default_app() app = SessionMiddleware(app, session_opts) bottle.debug(True) return app
def __init__(self,gatherer,bucket=None): if not bucket: bucket = settings('APP_BUCKET') self.bucket = bucket self.gatherer = gatherer self.store = S3Store() try: f = open('deploy_tracker.pickle','r') self.change_tracker = pickle.load(f) except IOError: self.change_tracker = {}
def refreshContent(self): self.s = settings() self.ui.qmlFolderLbl.setText( self.s.qmlDir ) self.styles = glob.glob( os.path.join( self.s.qmlDir, "*.qml" )) self.mapLayers = QgsMapLayerRegistry.instance().mapLayers() self.ui.layerCbx.clear() self.ui.layerCbx.insertItems(0, [ l.name() for l in self.mapLayers.values()]) self.ui.qmlList.clear() self.ui.qmlList.insertItems(0, [os.path.split(n)[1] for n in self.styles]) self.iface.mapCanvas().refresh()
def __init__(self): self.config = settings() self.logger = logging.getLogger('BotLogger.RequestSender') self.logger.setLevel(logging.DEBUG) fh = logging.FileHandler(self.config.log) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) self.logger.addHandler(fh) self.matching = dict() self.CNNstyles = [] self.loadMatching()
def CheckDBConnection(): localsettings = settings.settings(False) success = False try: localsettings.GetSettings() connection = db.GetConnection(localsettings) connection.close() success = True except: pass return success
def initGui(self): self.newSearchAction = QAction(QIcon(":/plugins/qsearch/icons/search.png"),"new search", self.iface.mainWindow()) QObject.connect(self.newSearchAction, SIGNAL("triggered()"), self.newSearch) self.iface.addToolBarIcon(self.newSearchAction) self.iface.addPluginToMenu("&qSearch", self.newSearchAction) # settings self.uisettings = settings(self.iface) self.uisettingsAction = QAction(QIcon(":/plugins/qsearch/icons/settings.png"), "settings", self.iface.mainWindow()) QObject.connect(self.uisettingsAction, SIGNAL("triggered()"), self.uisettings.exec_) self.iface.addPluginToMenu("&qSearch", self.uisettingsAction) # help self.helpAction = QAction(QIcon(":/plugins/qsearch/icons/help.png"), "Help", self.iface.mainWindow()) QObject.connect(self.helpAction, SIGNAL("triggered()"), lambda: QDesktopServices.openUrl(QUrl("https://github.com/3nids/qsearch/wiki"))) self.iface.addPluginToMenu("&qSearch", self.helpAction)
def parseLogs(self): idRunner = 1; for fobj in self.findLogs(): g = re.match(self.LOG_RE, fobj) gamedate = [] gamedate.append(g.group(0)) gamedate.append(g.group(1)) gamedate.append(g.group(2)) gamedate.append(g.group(3)) gamedate.append(g.group(4)) gamedate.append(g.group(5)) gamedate.append(g.group(6)) absolute_path = self.LOG_DIR + fobj gameMetaData = utils().get_status_from_logs(absolute_path, gamedate, idRunner) idRunner += 1 if settings().enableDebugKeenObjects: print json.dumps(gameMetaData) if settings().enableKeen: self.client.add_event("game", gameMetaData)
def app_meta(): return { 'BUCKET_NAME':settings('APP_BUCKET'), 'AWS_ACCESS_KEY_ID':settings('AWS_ACCESS_KEY_ID'), 'APP_DOMAIN':settings('APP_DOMAIN'), 'FILE_POST_URL':settings('FILE_POST_URL'), 'APP_BUCKET_ACL':settings('APP_BUCKET_ACL'), 'CONTENT_DOMAIN':settings('CONTENT_DOMAIN'), }