def main(): from characters import Character init() import menu import howtoplay import unlocker main_menu = [ ("Dwarf versus Dwarf", menu.entry(play_game, False)), ("Arcade Mode", menu.entry(play_arcade_game, False)), ("Setup", menu.entry(setup, False)), ("How to Play", menu.entry(howtoplay.init, False)), ("Quit Game", menu.break_menu)] if config.getboolean("unlock", "unlocker"): main_menu.insert(3, ("View Unlocks", menu.entry(unlocker.init, False))) if config.getboolean("unlock", "single"): main_menu.insert(2, ("Single Player", menu.entry(play_single_game, False))) if config.getboolean("unlock", "cpuversus"): main_menu.insert(2, ("Dwarf versus Robot", menu.entry(play_ai_game, False))) # if len(Character.arcade) != 8: # main_menu = [main_menu[0]] + main_menu[2:] menu.Menu(main_menu) quit()
def run(self): try: self.setup() self.feedback.play('intro').get() if config.getboolean('main', 'emulator'): from gi.repository import Gtk import emulator window = emulator.EmulatorWindow() window.connect('delete-event', Gtk.main_quit) window.show_all() Gtk.main() else: main_loop = GObject.MainLoop() main_loop.run() except KeyboardInterrupt: pass except Exception, e: logger.exception(e) self._play_error() holdoff = config.getfloat('main', 'error_holdoff_time') if holdoff > 0: logger.info('Waiting %.2fs before exiting' % holdoff) time.sleep(holdoff) self.teardown() return 1
def read_scores(self): self._images = [] secs = [] for c in range(1, 10, 2): sec = "scores-versus-%d" % c name = "Top Scores: Best %d/%d" % (c / 2 + 1, c) secs.append((sec, name)) if config.getboolean("unlock", "single"): secs.append(("scores-single", "Top Scores: Single Player")) secs.append(("scores-versus-arcade", "Top Scores: Arcade")) for sec, name in secs: img = pygame.Surface([420, 110], SRCALPHA, 32) img.fill([0, 0, 0, 0]) t = textfx.shadow(name, 26) img.blit(t, t.get_rect(midtop = [210, 0])) for i in range(1, 4): parts = config.get(sec, str(i)).split(",") score = parts.pop() name = ",".join(parts) tl = textfx.shadow(name, 30) tr = textfx.shadow(score, 30) img.blit(tl, tl.get_rect(topleft = [10, 25 * i])) img.blit(tr, tr.get_rect(topright = [415, 25 * i])) self._images.append(img) self.image = self._images[0] self.rect = self.image.get_rect(midtop = [400, 440])
def _extract_params(): params = {'storage_duration': '12H'} for name, default_value in params.items(): if not config.has_option('database', name): service_logger.warning("Not found '{name}' in database section, using default value: '{default_value}'." .format(name=name, default_value=default_value)) value = default_value else: value = config.get('database', name) params[name] = value params['database_dir'] = config.get('database', 'database_dir') params['listen_host'] = config.get('server', 'listen_host') params['listen_port'] = config.getint('server', 'listen_port') params['white_host'] = config.get('server', 'white_host') params['white_port'] = config.get('server', 'white_port') # Https configures. if config.has_option('security', 'tls') and config.getboolean('security', 'tls'): params['server_cert'] = config.get('security', 'server_cert') params['server_key'] = config.get('security', 'server_key') params['ca'] = config.get('security', 'ca') with open(os.path.join(global_vars.CURRENT_DIRNAME, 'certificate/pwf'), mode='r') as f: params['cert_pwd'] = f.read().strip() return params
def yt_download(link, metadata): download_location = output + '/' + metadata['Event'] + '/' + metadata[ 'Artist'] + " @ " + metadata['Event'] + '.%(ext)s' # Check config file if mp3 is needed, otherwise download mp3/m4a. Note: mp3 conversion make the scrape slow as f**k. if config.getboolean('DEFAULT', 'force_mp3'): ydl_opts = { 'outtmpl': download_location, 'format': 'bestaudio/best', 'quiet': 'true', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', }], } else: ydl_opts = { 'outtmpl': download_location, 'quiet': 'true', 'format': 'bestaudio/best', } # Download the shit with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([link]) print(download_location)
def music(self): if not config.getboolean('Sound', 'enabled'): return try: pygame.mixer.music.fadeout(5000) except: error('Music error') debug(sys.exc_info())
def music(self): if not config.getboolean('Sound', 'enabled'): return try: pygame.mixer.music.load(resource.file_path('mutate_title.ogg')) pygame.mixer.music.play() except: error('Unable to play music') debug(sys.exc_info())
def music(self): if not config.getboolean('Sound', 'enabled'): return try: pygame.mixer.music.load(resource.file_path('gurdonark_-_Little_Penguin.ogg')) pygame.mixer.music.play(-1) except: error('Unable to play music') debug(sys.exc_info())
def toggle_fs(): flags = 0 fs = config.getboolean("settings", "fullscreen") ^ True if "linux" not in sys.platform: if fs: flags ^= FULLSCREEN pygame.display.set_mode([800, 600], flags) else: pygame.display._toggle_fullscreen() config.set("settings", "fullscreen", str(fs))
def check_tls_protocol(): try: context = config.getboolean('security', 'tls') if context: protocol = 'https' else: protocol = 'http' return protocol except Exception as e: agent_logger.error("[security] part must exists in configure file.") raise
def setup(menu_, platform, pos, key): import menu config_menu = [ (config.get_matches(), menu.entry(config.set_matches)), (config.get_speed(), menu.entry(config.set_speed)), (config.get_rotup(), menu.entry(config.set_rotup)), (config.get_space(), menu.entry(config.set_space)), ("Back", menu.break_menu) ] if config.getboolean("unlock", "cpuversus"): config_menu.insert(2, (config.get_ai(), menu.entry(config.set_ai))) if config.getboolean("unlock", "combat"): config_menu.insert(-1, (config.get_combat(), menu.entry(config.set_combat))) try: menu.Menu(config_menu) except menu.MenuExit: pass return True
def _update_name_tag_highlight_states(self): speaker_names = self.state['speaker_names'] if config.getboolean('EVERYONE_ALWAYS_SPEAKS_TEST_MODE'): speaker_names = self._name_tags_by_name.keys() non_speaker_names = set( self._name_tags_by_name.keys()) - set(speaker_names) for name in speaker_names: self._name_tags_by_name[name].highlight() for name in non_speaker_names: self._name_tags_by_name[name].dehighlight()
def _extract_params(): """ Check if the agent parameter is valid, if the parameter is valid, then return parameters dict, otherwise exit process. :return: agent parameters dict. """ params = {} host = config.get('server', 'host') listen_port = config.get('server', 'listen_port') params['host'] = host params['listen_port'] = listen_port default_params = { 'sink_timer_interval': '10S', 'source_timer_interval': '10S', 'channel_capacity': 1000 } for parameter, default in default_params.items(): try: if parameter == 'channel_capacity': agent_parameter_value = config.getint('agent', parameter) params[parameter] = agent_parameter_value else: agent_parameter_value = config.get('agent', parameter) params[parameter] = TimeString( agent_parameter_value).to_second() except Exception as e: agent_logger.error( "An error ({error}) occurs when acquiring {parameter}," " using default value: {default_value}.".format( parameter=parameter, error=e, default_value=default)) params[parameter] = default_params[parameter] params['db_host'] = config.get('agent', 'db_host') params['db_port'] = config.get('agent', 'db_port') params['db_type'] = config.get('agent', 'db_type') # Https configures. if config.has_option('security', 'tls') and config.getboolean( 'security', 'tls'): params['agent_cert'] = os.path.realpath( config.get('security', 'agent_cert')) params['agent_key'] = os.path.realpath( config.get('security', 'agent_key')) params['ca'] = os.path.realpath(config.get('security', 'ca')) pwd_file = os.path.join(global_vars.CURRENT_DIRNAME, 'certificate/pwf') with open(pwd_file, mode='r') as f: params['cert_pwd'] = f.read().strip() return params
def POST(self): url = config.get("usertrack", "wufoo_url") user = config.get("usertrack", "wufoo_user") fields = { 'name': 'Field6', 'company': 'Field3', 'email': 'Field4', 'edition': 'Field8', 'version': 'Field10', 'build': 'Field12', 'accountId': 'Field14', 'uniqueServerId': 'Field16', 'instanceId': 'Field18', 'region': 'Field19', 'instanceType': 'Field21' } payload = {} instanceData = instance_utils.getInstanceData() or {} for datum in instanceData: if datum in fields: payload[fields[datum]] = instanceData[datum] data = json.loads(web.data()) if 'email' in data and len(data['email']): sendWelcomeEmail(data['email']) for datum in data: payload[fields[datum]] = data[datum] payload[fields["uniqueServerId"]] = config.get("usertrack", "htm-it_id") if config.getboolean("usertrack", "send_to_wufoo"): requests.post(url=url, data=payload, auth=(user, '')) for (fieldName, field) in fields.iteritems(): log.info("{TAG:WUFOO.CUST.REG} %s=%s" % (fieldName, payload.get(field))) return web.HTTPError(status="204", data="No Content")
def _actual_main(self): if ((active_window_title() == 'Among Us' or active_window_title().startswith('nametag_') and self.gms.is_voting_or_end_phase_of_meeting()) or config.getboolean('SHOW_TAGS_OUTSIDE_OF_GAME')): if not self._just_was_in_meeting: self._restore_name_to_colour_matching() if self._just_ocrd_name_to_slot: self._just_ocrd_name_to_slot = False self._arrange_tags_based_on_ocrd_name_to_slot_matching() self._update_name_tags() self._show_all_tags() else: if self._just_was_in_meeting: self._save_name_to_colour_matching() self._hide_all_tags() self._just_was_in_meeting = self.gms.is_voting_or_end_phase_of_meeting( )
def send(self): addresses = [] for header_name in ("To", "Cc", "Bcc"): for header in self.get_all(header_name, []): addresses.append(email.utils.parseaddr(decode(header))[1]) del self["Bcc"] name, address = email.utils.parseaddr(u"Guillaume Ayoub <*****@*****.**>".encode("utf-8")) if name: name = email.header.Header(name, "utf-8").encode() self["From"] = email.utils.formataddr((name, address)) else: self["From"] = address self["Date"] = email.utils.formatdate(time.time(), True) self["X-Mailer"] = "Mailanie %s" % config.get("mailanie", "version") server = config.get("smtp", "server") port = config.getint("smtp", "port") if config.getboolean("smtp", "ssl"): client = smtp.SMTP_SSL(server, port) else: client = smtp.SMTP(server, port) login = config.get("smtp", "login") if login: password = config.get("smtp", "password") client.login(login, password) name = config.get("smtp", "name") address = config.get("smtp", "address") if name: sender = "%s <%s>" % (name, address) else: sender = address client.sendmail(sender, addresses, self.as_string()) sent_folder = mailanie.mailbox.get_folder(config.get("mailbox", "sent")) sent_folder.add(self)
def setup(self): self.components = [ Component('feedback', player.FeedbackPlayer, assets_base_path=config.get('feedback_player', 'assets_base_path'), volume=config.getfloat('feedback_player', 'volume')) ] if not config.getboolean('main', 'emulator'): self.components.append(Component('smc', smc.SMC, port=config.get('smc', 'serial_port'))) self.components += [ Component('playlist', playlist.PlaylistFetcher), Component('stations_pool', stationspool.StationsPool, base_url=config.get('stations_pool', 'base_url'), auth_code=get_auth_code()), Component('player', player.StreamPlayer), Component('main_controller', MainController, plumbing=self) ] for component in self.components: component.start() self.__dict__[component.tag] = component.proxy
def init(): if os.name == 'posix': # We need to force stereo in many cases. try: mixer.pre_init(44100, -16, 2) except pygame.error: pass pygame.init() config.init(rc_file) os.chdir(angrydd_path) pygame.display.set_caption("Angry, Drunken Programmers") try: pygame.display.set_icon(pygame.image.load("angrydd.png")) except pygame.error: pass pygame.mouse.set_visible(False) if config.getboolean("settings", "fullscreen"): flags = FULLSCREEN else: flags = 0 pygame.display.set_mode([800, 600], flags) import game import menu import boxes import characters boxes.TickBox.sound = load.sound("tick.wav") boxes.TickBox.sound.set_volume(0.3) boxes.BreakBox.sound = load.sound("break.wav") boxes.BreakBox.sound.set_volume(0.3) boxes.Special.sound = load.sound("select-confirm.wav") boxes.Special.sound.set_volume(0.5) game.FallingBoxes.rotate_sound = load.sound("rotate.wav") game.FallingBoxes.rotate_sound.set_volume(0.2) menu.Menu.bg = load.image("menu-bg.png").convert() characters.init() mixer.music.load(os.path.join("music", "intro.ogg")) mixer.music.play(-1)
def main(): import sys from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] server_dir") parser.add_option("--changepw", action="store_true", dest="changepw", help="Prompt for administrator password change and exit") parser.add_option("--foreground", action="store_true", dest="foreground", help="Run WeBIAS in foreground (without daemonization)") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") config.load_config(args[0]) if options.changepw: auth.set_admin_pw() sys.exit(0) from cherrypy.process.plugins import Daemonizer, PIDFile, DropPrivileges # DropPrivileges(cherrypy.engine, umask=0022, uid=1044, gid=1000).subscribe() PIDFile(cherrypy.engine, config.get('Server', 'pid_file')).subscribe() cherrypy.engine.signal_handler.subscribe() auth.CleanupUsers(cherrypy.engine).subscribe() data.SAEnginePlugin(cherrypy.engine).subscribe() reports.ReportSender(cherrypy.engine).subscribe() statistics.DBLogPlugin(cherrypy.engine).subscribe() cherrypy.tools.db = data.SATool() conf = { 'tools.db.on': True, 'tools.hit_recorder.on': True, 'tools.error_recorder.on': True, 'tools.sessions.on': True, 'tools.clean_session.on': True, 'log.screen': False, 'tools.protect.on': True, 'tools.protect.allowed': ['any'] } try: conf['log.access_file'] = config.get('Server', 'access_log') except config.NoOptionError: cherrypy.engine.log( 'Filename of access log for WeBIAS server not set. Logging will be performed only to standard output.' ) try: conf['log.error_file'] = config.get('Server', 'error_log') except config.NoOptionError: cherrypy.engine.log( 'Filename of error log for WeBIAS server not set. Logging will be performed only to standard output.' ) mediaconf = { # 'tools.staticdir.on': True, 'tools.protect.on': False, 'tools.staticredirect.on': True, 'tools.staticredirect.section': '/media', 'tools.staticredirect.redirect_section': '/media-base', 'tools.staticredirect.dir': os.path.join(config.server_dir, 'media') } mediabaseconf = { 'tools.staticdir.on': True, 'tools.staticdir.dir': os.path.join(pkg_resources.resource_filename('webias', 'data'), 'media') } webias = WeBIAS() cherrypy.tree.mount(webias, config.get('Server', 'root'), config={ '/': conf, '/media': mediaconf, '/media-base': mediabaseconf }) cherrypy.config.update({ 'session_filter.on': True, "session_filter.timeout": 600000 }) cherrypy.engine.templateProcessor = template.TemplateProcessor() if config.getboolean('Server', 'proxy'): cherrypy.config.update({ 'tools.proxy.on': True, 'tools.https_filter.on': True, 'server.thread_pool': 100, "server.socket_port": config.getint('Server', 'server_port'), 'server.socket_host': config.get('Server', 'server_host') }) else: cherrypy.server.unsubscribe() try: server1 = cherrypy._cpserver.Server() server1.socket_port = config.getint('Server', 'server_ssl_port') server1._socket_host = config.get('Server', 'server_host') server1.thread_pool = 100 server1.ssl_module = 'builtin' server1.ssl_certificate = config.get('Server', 'ssl_cert') server1.ssl_private_key = config.get('Server', 'ssl_key') server1.ssl_certificate_chain = config.get('Server', 'ssl_cert_chain') server1.subscribe() except config.NoOptionError as e: webias.no_SSL = True cherrypy.engine.log( 'Option ' + e.option + ' not set and WeBIAS is not acting as a proxy. SSL will be disabled, and all connections will be unencrypted. DO NOT USE THIS CONFIGURATION IN THE PRODUCTION ENVIRONMENT.' ) server2 = cherrypy._cpserver.Server() server2.socket_port = config.getint('Server', 'server_port') server2._socket_host = config.get('Server', 'server_host') server2.thread_pool = 100 server2.subscribe() if not options.foreground: cherrypy.process.plugins.Daemonizer(cherrypy.engine).subscribe() cherrypy.engine.start() cherrypy.engine.block()
"dealer", config.get("accountant", "cashier_export"), config.getint("accountant", "cashier_export_base_port")) session = db.make_session() bitcoin_conf = config.get("cashier", "bitcoin_conf") log.msg('connecting to bitcoin client') bitcoinrpc = {'BTC': BitcoinRpc(bitcoin_conf, 1)} compropago = Compropago(config.get("cashier", "compropago_key")) cold_wallet_period = config.getint("cashier", "cold_wallet_period") sendmail = Sendmail(config.get("administrator", "email")) minimum_confirmations = config.getint("cashier", "minimum_confirmations") alerts_proxy = AlertsProxy(config.get("alerts", "export")) bitgo_config = { 'use_production': not config.getboolean("cashier", "testnet"), 'client_id': config.get("bitgo", "client_id"), 'client_secret': config.get("bitgo", "client_secret") } bitgo = BitGo(**bitgo_config) bitgo_private_key_file = config.get("cashier", "bitgo_private_key_file") cashier = Cashier( session, accountant, bitcoinrpc, compropago, cold_wallet_period=cold_wallet_period, sendmail=sendmail, minimum_confirmations=minimum_confirmations, alerts=alerts_proxy,
import traceback from contextlib import contextmanager from sqlalchemy import create_engine, Column, String, Integer, ForeignKey from sqlalchemy.orm import sessionmaker, relationship import config from .model import BASE, User, ApiKey, Warehouse, WarehouseACE, Location, Reference, Category, Article, Tag, roles from . import queries ENGINE = create_engine(config.get("sqlalchemy", "url"), echo=config.getboolean("sqlalchemy", "echo")) SESSION = sessionmaker(bind=ENGINE) @contextmanager def Session(): try: session = SESSION() yield session session.commit() except Exception: traceback.print_exc() session.rollback() finally: session.close()
def init(*args): em = EventManager() screen = pygame.display.get_surface() move_snd = load.sound("select-move.wav") index = 0 # The format is up to three paragraphs per screen, displayed # left, right, left, texts = [ ["In Angry, Drunken Dwarves, you are an angry, drunken dwarf. Why " "are you so angry? Who knows. But you've decided to take your " "aggression out on other dwarves, by dropping gems on their " "heads.", "Multicolored gems will fall from the top of the screen. You " "should try to arrange them into groups by color. The arrow keys " "or a/d and j/l will move them left and right. s or k will make " "then fall faster, and q/e and u/o will rotate them.", "As gems reach the bottom, they will land and sit in place. If you " "put enough gems of the same color in a rectangle shape, they will " "merge and form a crystal." ], ["Less common are break gems. When you drop a break gem on a gem " "or crystal of the same color, it will destroy any gems of that " "color adjacent to it. Crystals are worth much more than an equal " "number of regular gems.", "When you destroy gems on your side, it will drop counter gems " "onto your opponent. These are harder to destroy, but turn into " "regular gems after a few turns. You can try to cancel an incoming " "attack by breaking gems yourself, but you'll need to break twice " "as many as are coming.", "Rarer is the diamond. When you drop a diamond onto something, " "it will destroy all gems of that color on your side, even " "counter gems! Be careful though, because a crystal " "destroyed by a diamond isn't worth any more than normal gems." ], ["Each dwarf has a drop gem pattern, and an attack strength. The drop " "pattern is a display of what kinds of gems will be dropped when " "you attack your opponent. Small attacks will drop the same " "row over and over, which will probably help them!", "The attack strength is a measurement of how strong your drop " "pattern is; drops with weirder patterns are harder to plan " "against. Before gems are dropped, they are multiplied by this " "attack strength, and so the damage is scaled up or down.", "For the most devestating results, try chaining attacks together, " "so breaking some gems results in even more breaking afterwards. " "Breaking many crystals in a chain can result in huge drops." ] ] drop = pygame.Surface([64, 64]) drop.blit(load.block("blue"), [0, 0]) drop.blit(load.block("yellow"), [0, 32]) drop.blit(load.block("green"), [32, 0]) drop.blit(load.block("red"), [32, 32]) crystal = load.gem("green", 4, 3) breaks = pygame.Surface([64, 64]) breaks.blit(load.block("red", "-crash"), [0, 0]) breaks.blit(load.block("green", "-crash"), [0, 32]) breaks.blit(load.block("yellow", "-crash"), [32, 0]) breaks.blit(load.block("blue", "-crash"), [32, 32]) counters = pygame.Surface([64, 64]) counters.blit(textfx.lettered_box("5", "green"), [0, 0]) counters.blit(textfx.lettered_box("4", "blue"), [32, 0]) counters.blit(textfx.lettered_box("3", "red"), [0, 32]) counters.blit(textfx.lettered_box("2", "yellow"), [32, 32]) chain = pygame.Surface([64, 96]) chain.blit(load.block("blue", "-crash"), [0, 64]) chain.blit(load.block("green"), [32, 64]) chain.blit(load.block("green", "-crash"), [32, 32]) chain.blit(load.block("blue"), [32, 0]) # Followed by up to three images per screen, right, left, right. images = [ [None, drop, crystal], [breaks, counters, load.block("diamond")], [Character.arcade[4].drop.render(), None, chain], ] if config.getboolean("unlock", "single"): texts.append([ "In single player mode, rather than competing against someone " "else, you're racing the clock. You have to clear a certain " "number of blocks in a certain number of turns, or the ones " "left get dumped on you.", "Your field is also twice as big. So it sounds easy, right? " "Well, to start with, you've got three new colors of gems to " "contend with: orange, purple, and cyan.", "If that wasn't bad enough, the number of gems you have to clear " "goes up much faster than the number of turns you have " "to do it, so build up those crystals early and save them." ]) newcols = pygame.Surface([64, 64]) newcols.blit(load.block("orange"), [16, 0]) newcols.blit(load.block("cyan"), [0, 32]) newcols.blit(load.block("purple"), [32, 32]) counts = pygame.Surface([130, 100]) box = Character.default.border([40, 40]) text1 = textfx.shadow("new:", 20) text2 = textfx.shadow("turns:", 20) num1 = textfx.shadow("122", 30) num2 = textfx.shadow("10", 30) counts.blit(box, [0, 20]) counts.blit(box, [70, 20]) counts.blit(text1, text1.get_rect(center = [30, 38])) counts.blit(text2, text2.get_rect(center = [100, 38])) counts.blit(num1, [12, 45]) counts.blit(num2, [87, 45]) images.append([None, newcols, counts]) if config.getboolean("unlock", "combat"): texts.append([ "Combat blocks look like normal gems with a special symbol " "in the middle. These gems don't form crystals, but otherwise " "break like normal colored gems. When you break one of these, " "you 'pick up' the special attack in it.", "To use the attack, press start (enter/2). There are five basic " "attacks; from left to right: make your opponent's field blink, " "clear your own field of all blocks,", "flip your opponent's screen upside down, disable the 'next' " "indicator, drop some gray blocks, or reverse your opponent's " "controls. Blink, flip, and reverse last for a few " "seconds. Scramble lasts 10 turns."]) blink = load.block("blue") clear = load.block("red") rev = load.block("yellow") flip = load.block("green") gray = load.block("red") scram = load.block("purple") blink.blit(SpecialSprite.load(BLINK), [6, 6]) flip.blit(SpecialSprite.load(FLIP), [6, 6]) clear.blit(SpecialSprite.load(CLEAR), [6, 6]) rev.blit(SpecialSprite.load(REVERSE), [6, 6]) gray.blit(SpecialSprite.load(GRAY), [6, 6]) scram.blit(SpecialSprite.load(SCRAMBLE), [6, 6]) img1 = pygame.Surface([64, 32]) img2 = pygame.Surface([64, 64]) img1.blit(blink, [0, 0]) img1.blit(clear, [32, 0]) img2.blit(flip, [0, 0]) img2.blit(scram, [32, 0]) img2.blit(gray, [0, 32]) img2.blit(rev, [32, 32]) images.append([None, img1, img2]) wipes.wipe_in(render_help_page(texts[index], images[index])) cont = True screen.blit(render_help_page(texts[index], images[index]), [0, 0]) img = textfx.shadow("Enter: Menu - Left/Right: Turn Page (%d/%d)" % (index + 1, len(images)), 18) screen.blit(img, [785 - img.get_width(), 10]) pygame.display.update() while cont: oldindex = index for ev in em.wait(): if ev.type == QUIT: cont = False elif ev.type == PLAYER: if ev.key == CONFIRM: cont = False elif ev.key == UP or ev.key == LEFT: index = (index - 1) % len(texts) move_snd.play() elif ev.key in [DOWN, RIGHT, ROT_CC, ROT_CW]: index = (index + 1) % len(texts) move_snd.play() if oldindex != index: screen.blit(render_help_page(texts[index], images[index]), [0, 0]) img = textfx.shadow("Enter: Menu - Left/Right: Turn Page (%d/%d)" % (index + 1, len(images)), 18) screen.blit(img, [785 - img.get_width(), 10]) pygame.display.update() return True
accountant = AccountantProxy("dealer", config.get("accountant", "cashier_export"), config.getint("accountant", "cashier_export_base_port")) session = db.make_session() bitcoin_conf = config.get("cashier", "bitcoin_conf") log.msg('connecting to bitcoin client') bitcoinrpc = {'BTC': BitcoinRpc(bitcoin_conf, 1)} compropago = Compropago(config.get("cashier", "compropago_key")) cold_wallet_period = config.getint("cashier", "cold_wallet_period") sendmail=Sendmail(config.get("administrator", "email")) minimum_confirmations = config.getint("cashier", "minimum_confirmations") alerts_proxy = AlertsProxy(config.get("alerts", "export")) bitgo_config = {'use_production': not config.getboolean("cashier", "testnet"), 'client_id': config.get("bitgo", "client_id"), 'client_secret': config.get("bitgo", "client_secret")} bitgo = BitGo(**bitgo_config) bitgo_private_key_file = config.get("cashier", "bitgo_private_key_file") cashier = Cashier(session, accountant, bitcoinrpc, compropago, cold_wallet_period=cold_wallet_period, sendmail=sendmail, minimum_confirmations=minimum_confirmations, alerts=alerts_proxy, bitgo=bitgo, bitgo_private_key_file=bitgo_private_key_file, testnet=config.getboolean("cashier", "testnet"), )
return flask.Response(response=j, status=200, content_type=u"application/json") def api_error(code, msg): return flask.jsonify(code=code, error_message=msg) def api_do(req, func): try: o = func(req) resp = api_ok(o) return resp except APIError, e: return api_error(e.code, e.message) except BaseException, e: if config.getboolean(u"misc", u"debug", False): raise e else: return api_error(E_UNKNOWN, u"Unknown error") def _make_upload_html(file_field=u"file"): return ( u"""<!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form action="" method="post" enctype="multipart/form-data"> <p><input type="file" name="%s"> <input type="submit" value="Upload!"> </form> """
#!/usr/bin/python __author__ = '*****@*****.**' import config import gv __import__('purchaser_controllers') __import__('account_controllers') __import__('publisher_controllers') wsgi_server = config.get(u'web', u'wsgi_server', u'') if wsgi_server.lower() == u'tornado': print u'Tornado start' from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop server = HTTPServer(WSGIContainer(gv.app)) server.listen(config.getint(u'web', u'port'), address=config.get(u'web', u'host', u'')) IOLoop.instance().start() else: print u'Flask start' gv.app.run(host=config.get(u'web', u'host', u'0.0.0.0'), port=config.getint(u'web', u'port', 6789), debug=config.getboolean(u'misc', u'debug', False))
for line in bhup_out.splitlines(): try: proto, _ = line.split(':', 1) except ValueError: continue if proto == 'magnet': return magnet.objectFromMagnet(line.strip().decode('utf8'), fullPath=unicode(file)) return None if __name__ == '__main__': import cliopt usage = "usage: %prog [options] file1/dir1 [file2/dir2 ...]\n" \ " An argument of '-' will expand to filenames read line for line on standard input." parser = cliopt.OptionParser(usage=usage) parser.add_option("-l", "--upload_link", action="store_true", dest="upload_link", default=config.getboolean('BITHORDE', 'upload_link'), help="Upload as a linked asset, instead of adding it to cache-dir. NEEDS appropriate bithorded-config.") parser.add_option("-L", "--no-links", action="store_false", dest="export_links", default=True, help="When done, don't immediately export links to links-directory") parser.add_option("-T", "--no-txt", action="store_false", dest="export_txt", default=True, help="When done, don't immediately publish txt-format index") parser.add_option("-t", "--tag", action="append", dest="tags", help="Define a tag for these uploads, such as '-tname:monkey'") parser.add_option("-s", "--strip-path", action="store_const", dest="sanitizer", default=sanitizedpath, const=path.basename, help="Strip name to just the name of the file, without path") parser.add_option("-f", "--force", action="store_true", dest="force", default=False, help="Force upload even of assets already found in sync in index")
def __init__(self, rand, colors, single): self.rand = rand self.combat = (config.getboolean("settings", "combat") and not single) self.colors = colors
content_type=u'application/json') def api_error(code, msg): return flask.jsonify(code=code, error_message=msg) def api_do(req, func): try: o = func(req) resp = api_ok(o) return resp except APIError, e: return api_error(e.code, e.message) except BaseException, e: if config.getboolean(u'misc', u'debug', False): raise e else: return api_error(E_UNKNOWN, u'Unknown error') def _make_upload_html(file_field=u'file'): return u"""<!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form action="" method="post" enctype="multipart/form-data"> <p><input type="file" name="%s"> <input type="submit" value="Upload!"> </form> """ % file_field
def _cursor_execute(cursor, sql, params=None): cursor.execute(sql, params) if config.getboolean(u'misc', u'debug', False): print cursor._last_executed
def __init__(self, config, filename): self.log = logging.getLogger('main') self.cursor_create() self.consumers = [] self.dataset = {} self.filename = filename # config defaults rows = config.getint('general/rows', 3) self.fullscreen = config.getboolean('general/fullscreen', False) # Create window and get widget handles. builder = gtk.Builder() builder.add_from_file(join(dirname(__file__),'main.ui')) builder.connect_signals(self) self.window = builder.get_object('main') self.notebook = builder.get_object('notebook1') self.area = builder.get_object('area') # Setup keyboard shortcuts gtk.accel_map_add_entry("<visualizer>/quit", gtk.accelerator_parse("q")[0], gtk.gdk.CONTROL_MASK) self.accel_group = gtk.AccelGroup() self.accel_group.connect_by_path("<visualizer>/quit", self.quit) self.window.add_accel_group(self.accel_group) # guess resolution size = (800,600) if self.fullscreen: dgd = gtk.gdk.display_get_default() gsd = dgd.get_default_screen() size = (gsd.get_width(), gsd.get_height()) # setup visualizer self.log.debug('Creating canvas') self.visualizer = Canvas(size=size, rows=rows) self.visualizer.connect('motion_notify_event', self.cursor_show) self.area.pack_start(self.visualizer) self.window.show_all() if self.fullscreen: self.window.fullscreen() self.notebook.set_show_tabs(False) self.visualizer.window.set_cursor(self.cursor) # Process events so window is fully created after this point. gtk.main_iteration(True) while gtk.events_pending(): gtk.main_iteration(False) # parse rest of config. self.log.debug('Parsing config') self.parse_config(config) # Setup statistics self.stats = Statistics() self.add_consumer(self.stats) gobject.timeout_add(1000, self.update_stats) # retrieve datasets from consumers self.load_dataset() if len(self.consumers) > 0: print 'Available consumers' print '-------------------' for con in self.consumers: print ' *', con print if len(self.dataset) > 0: print 'Available datasets' print '------------------' for k,v in self.dataset.iteritems(): print ' * %s: %s' % (k, v) print # Initialize plugins. Must be done after fullscreen-mode so variables depending on size will work. self.visualizer.dataset = self.dataset # fulhack self.visualizer.init_all_plugins() # Setup signal and event handling signal(SIGHUP, self.handle_sighup) signal(SIGINT, self.handle_sigint) gobject.idle_add(self.expire)
def init(*args): em = EventManager() disp = pygame.Surface([800, 600]) disp.fill([0, 0, 0]) font = textfx.WrapFont(30, 760) bg = Character.default.border([780, 100]).convert() bg.set_alpha(256) disp.blit(bg, [0, 0]) t = font.render( "Welcome to the unlock screen! As you do more in this " "game, new features will sometimes appear. By playing the " "game at least once, you've managed to unlock this unlock " "screen, for example. Keep practicing, and more things will " "appear..." ) disp.blit(t, t.get_rect(midleft=[20, 60])) if config.getboolean("unlock", "single"): bg.set_alpha(256) disp.blit(bg, [0, 120]) t = font.render( "Congratulations! By scoring over 20,000 points in a 2/3 versus " "match, you've unlocked single player mode. It's a lot " "harder, so you should practice your crystal building and " "combo setups." ) disp.blit(t, t.get_rect(midleft=[20, 180])) else: bg.set_alpha(127) disp.blit(bg, [0, 120]) if config.getboolean("unlock", "unixbros"): bg.set_alpha(256) disp.blit(bg, [0, 240]) t = font.render( "By breaking a crystal of over 16 gems, you've unlocked two more " "characters - The Yuniks brothers. Both encourage a very " "unique style of attacks. Go check them out." ) disp.blit(t, t.get_rect(midleft=[20, 300])) else: bg.set_alpha(127) disp.blit(bg, [0, 240]) if config.getboolean("unlock", "combat"): bg.set_alpha(256) disp.blit(bg, [0, 360]) t = font.render( "By getting at least a 4 chain, you've unlocked combat " "mode. If this is on, special attack rocks might appear in " "versus mode, that have strange effects on the other " "player. Enable it in the setup menu." ) disp.blit(t, t.get_rect(midleft=[20, 420])) else: bg.set_alpha(127) disp.blit(bg, [0, 360]) if config.getboolean("unlock", "cpuversus"): bg.set_alpha(256) disp.blit(bg, [0, 480]) t = font.render( "You've made it at least halfway through arcade mode! " "You can now practice against any dwarf, on any " "of the AI levels." ) disp.blit(t, t.get_rect(midleft=[20, 540])) else: bg.set_alpha(127) disp.blit(bg, [0, 480]) wipes.wipe_in(disp) pygame.display.update() quit = False while not quit: for ev in em.wait(): quit = quit or ev.type == QUIT or (ev.type == PLAYER and ev.key in [ROT_CC, ROT_CW, CONFIRM]) return True