def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) CURRENT_THEME = get_theme() context['form'] = ConfigUpdateForm(initial={'theme': CURRENT_THEME}) context['themes'] = get_themes() context['title'] = get_key("ctf_name") context['start_time'] = get_key('start_time') context['end_time'] = get_key('end_time') return context
def getBasicInfo(self): url = get_urls('url_view') timestamp_ms = get_timestamp() appkey = get_key() UAS = get_user_agents() params = {'type': 'json', 'appkey': appkey, 'id': str( self.aid), '_': '{}'.format(timestamp_ms)} # print(params) headers = {'User-Agent': random.choice(UAS)} # print(headers) try: res = requests.get(url, params=params, headers=headers) res.raise_for_status() except Exception as e: # print(e) msg = 'aid({}) get error'.format(self.aid) bilivideolog.error(msg) return None data = json.loads(res.text) # print(data) if 'mid' in data: # ('added','mid','aid','tid','cid','typename','arctype','title','pic','pages','created') related_info = (get_timestamp_s(), data['mid'], self.aid, data['tid'], data['cid'], data['typename'], data['arctype'], data['title'], data['pic'], data['pages'], data['created']) return related_info else: msg = 'aid({}) basic info request return error'.format(self.aid) bilivideolog.info(msg) return None
def arrivals(naptan, app_id=None, app_key=None): if app_id == None or app_key == None: app_id, app_key = config.get_key() payload = {'app_id': app_id, 'app_key': app_key} r = requests.get('https://api.tfl.gov.uk/StopPoint/{0}/Arrivals'.format(naptan), params=payload) json_result = r.json() timestamp = "" to_zone = dateutil.tz.tzlocal() now = datetime.datetime.now(to_zone) for arrival in json_result: eta = dateutil.parser.parse(arrival['expectedArrival']) local = eta.astimezone(to_zone) rd = relativedelta(local, now) #expectedArrival=datetime.datetime.strptime( arrival['expectedArrival'], "%Y-%m-%dT%H:%M:%SZ" ) #eta = expectedArrival.strftime('%H:%M:%S %Z') #utc = eta.replace(tzinfo=from_zone) #local = utc.astimezone(to_zone) print("Stop {1}: {2} towards {0}: {3}, {4} minutes".format(arrival['destinationName'], arrival['platformName'], arrival['lineName'], local.strftime('%H:%M'), rd.minutes)) timestamp = arrival['timestamp'] print("ts/now: {0}/{1}".format(timestamp, datetime.datetime.now().time()))
def get_previous_session(): sess = None token_key, token_secret = config.get_access_token() if token_key and token_secret: sess = session.DropboxSession(config.get_key(), config.get_secret(), ACCESS_TYPE) sess.set_token(token_key, token_secret) return sess
def __call__(self, request): if request.path.startswith(reverse('installer')): return self.get_response(request) install_status = get_key("installed") if install_status: response = self.get_response(request) return response else: return redirect(reverse("installer"))
def get_theme(): theme = cache.get("theme") if theme is not None: return theme else: theme = get_key("theme") if theme: cache.set("theme", theme) return theme else: cache.set("theme", "core") return "core"
def check_input(character): if global_var.lives <= 0: global_var.quit_flag = 1 return event = config.get_key(config.get_input()) if event == config.LEFT: character.check_left() elif event == config.RIGHT: character.check_right() elif event == config.QUIT: global_var.quit_flag = 1 return reset_scenery()
def create_new_session(): sess = session.DropboxSession(config.get_key(), config.get_secret(), ACCESS_TYPE) request_token = sess.obtain_request_token() print((sess.build_authorize_url(request_token))) print("Visit this website and press the 'Allow' button, then hit 'Enter' here: ") raw_input() access_token = sess.obtain_access_token(request_token) config.save_access_token(access_token.key, access_token.secret) return sess
def hash(): # url = "https://api.heroku.com/apps/frozen-garden-83591/config-vars" # r = requests.get(url) # values = r.json() key = config.get_key() secret = config.get_secret() clientID = config.get_clientID() nonce = int(time.time() * 1000000) + 374491605044 message = str(nonce) + clientID + key message = bytes(message, 'utf-8') byte_key = bytes(secret, 'utf-8') signature = hmac.new(byte_key, message, hashlib.sha256).hexdigest() return ({"key": key, "signature": str.lower(signature), "nonce": nonce})
def addObjectList(bd, level_name, *names): for name in names: bd.at = 0 completeName = os.path.join(dir_path + level_name, name + ".txt") file = open(completeName, "w") ob = makeObject(name) mk = objects.Marker(ob, ob.width, ob.height, 60, 30) bd.add(mk, mk.x, mk.y) while True: bd.clear(config.show_width) addobjects(bd, brick, enemy, goomba, spikey, stalker, spring, coin, cloud, specialbrick, boss, castle) bd.add(mk, mk.x, mk.y) os.system('clear') bd.show(config.show_width, config.show_height) event = config.get_key(config.get_input()) if event == config.QUIT: break elif event == config.SHOOT: bd.add(mk, mk.x, mk.y) file.write(str(mk.x) + ',' + str(mk.y) + '\n') lists[name].append(makeObject(name, mk.x, mk.y)) else: mk.move(event) bd.move(event, mk.width) bd.add(mk, mk.x, mk.y) bd.remove(mk, mk.x, mk.y) bd.at = 0
import board import objects import datetime import config from board import * from config import * ''' Main file for running the code ''' bd = board.Board() p_input = -1 while (True): global lives p_input = config.get_key(config.get_input()) if p_input == config.QUIT: # if input is q, quit the game break # Calling collision function bd.CollisionMarioPipe() bd.process_input(p_input) bd.insert() bd.printIt() flag1 = bd.CollisionMarioBrick() flag = bd.CollisionMarioEnemy() flag2 = bd.CollisionMarioSmartEnemy() bd.CollisionMarioCoin() bd.CollisionMarioSpring() if bd.youWin(): break if board.t == 0: bd.gameOver()
import darksky from twilio.rest import Client import config twilio_acct = config.get_key('twilio_acct') twilio_token = config.get_key('twilio_token') twilio_tn = config.get_key('twilio_tn') darksky_key = config.get_key('darksky') tn = config.get_key('cell_phone_tn') def send_text(forecast, tn, twilio_acct, twilio_token): text_body = f"Forecast: {forecast['summary'].lower()} High today of {forecast['apparentTemperatureHigh']}, " \ f"low of {forecast['apparentTemperatureLow']}." client = Client(twilio_acct, twilio_token) message = client.messages.create(to=tn, from_=twilio_tn, body=text_body) def main(): forecast = darksky.get_today_weather(darksky_key, config.location) send_text(forecast, tn, twilio_acct, twilio_token) if __name__ == '__main__': main()
common.restart_all() config.LIVES = 10 # if mario goes below the floor LEVEL if config.M != "" and config.M.y_pos > common.MIDS_R: raise config.DeadMario # create the scene depending on the LEVEL create_scenery.create_scene() if config.M != "": if Char != config.JUMP: create_scenery.check_floor() common.print_all() # get input from user Char = config.get_key(config.get_input()) if Char == config.QUIT: # shut down all [q] config.STAGE = "quit" common.game_over() if Char == config.START: # create a Person [m] sound.play_sound("mb_new.wav") create_scenery.create_mario() elif Char == config.BREAK: # break the loop [s] os.system("tput reset") break
def keypress(self, size: Tuple[int, int], key: str) -> str: if self.controller.editor_mode: return self.controller.editor.keypress((20, ), key) else: return super(View, self).keypress(size, get_key(key))
def main(): lives = 3 reply = input('Do want to make your own level?(y/n) ') if reply == "y": level_name = input('What do you want to name your cutom level? ') levelGenerator.makeLevel(level_name) level_name = input('Please enter level name: ') while lives: tme = 360 + int(time.time()) clearLists(specialbrick, brick, enemy, spring, coin, cloud, castle, boss) bd = board.Board(config.board_width, config.board_width) try: loadLevel(level_name, "brick", "spring", "goomba", "stalker", "spikey", "boss", "castle", "cloud", "coin", "specialbrick") except: print("No such level exists") exit() mario = objects.Player(2, 2, 54, 15) bd.at = 0 while True: bd.clear(config.show_width) levelGenerator.addobjects(bd, brick, enemy, spring, coin, cloud, specialbrick, boss, castle) bd.add(mario, mario.x, mario.y) collisionCheck.bossFight(enemy, boss, bd, mario) collisionCheck.enemyCollision(enemy, enemy, mario, bd) collisionCheck.enemyCollision(boss, boss, mario, bd) collisionCheck.updateEnemy(boss, bd, mario.x, brick, spring) collisionCheck.updateEnemy(enemy, bd, mario.x, brick, spring) collisionCheck.brickCollision(brick, mario, bd) collisionCheck.specialbrickCollision(specialbrick, mario, bd) collisionCheck.springCollision(spring, mario, bd) collisionCheck.coinCollision(coin, mario, bd) if mario.hp <= 0 or mario.y > config.show_height or int( tme - time.time()) <= 0: lives -= 1 break if mario.x >= castle[0].x: print("YOU WIN \t TOTAL SCORE:", mario.score + int(tme - time.time())) lives = 0 break os.system('tput reset') bd.show(config.show_width, config.show_height) print("LIVES:", lives, "\t", "HEALTH:", mario.hp, "\t", "SCORE:", mario.score, "\t", "TIME LEFT:", int(tme - time.time())) event = config.get_key(config.get_input()) if event == config.QUIT: lives = 0 break if mario.move(event) == "move": bd.move(event, 1) print("GAME OVER")
def init_key(inputKey): script, id = config.get_key(inputKey) global sg sg = Shotgun(server, script, id)
def __init__(self): self.key = config.get_key() self.test_user = config.get_test_user_id() self.base_api_url = "http://api.steampowered.com/" self.base_store_api_url = "http://store.steampowered.com/"
def main(): try: height, width = tuple(map(int, rd[1:3])) except BaseException: height, width = (34, 76) a = 'r' while a == 'r': try: level = int(input("Choose level [[1], 2, 3] :")) if level not in [0, 1, 2, 3]: raise Exception except BaseException: level = 1 # make the board and player bd = board.Board(height, width, level) player = people.Bomber( 5, 3, config.lives[level], config.bombs[level]) # always spawns at top left # spawning the player on the board bd.spawn(player) print("Initializing enemies, bricks ...") if not (spawn(config._enemy, config.enemies[level], bd) and spawn(config._bricks, config.bricks[level], bd)): print("Object Spawn Error") return False print("Objects spawned successfully", "Rendering board", sep="\n") sleep(1) bd.render() is_clean = False p_input = -1 # main loop which renders the game st_time = datetime.datetime.now() prev_round = datetime.datetime.now() while (datetime.datetime.now() - st_time) <= \ datetime.timedelta(seconds=config.timelimit[level]): print(config.printcc("'q' : quit | 'b' : drop bomb || Lives ", 'Gray') + config.printcc('%s' % (player.lives * '♥ '), 'Red') + config.printcc('| Bombs ', 'Gray') + config.printcc('%s' % (player.bombs * '💣 '), 'Dark Gray') + config.printcc("| T : %d " % (config.timelimit[level] - (datetime.datetime.now() - st_time).seconds), 'Gray')) try: bd.is_over(player) except Exception as exc: print(config.printcc(exc.args[0], 'Gray')) is_clean = True break p_input = config.get_key(config.get_input()) if p_input == config.QUIT: break cur_round = datetime.datetime.now() bd.process_input(player, p_input) if (cur_round - prev_round) >= datetime.timedelta(seconds=1): bd.update_frame() prev_round = cur_round bd.render() if not is_clean: print(config.printcc("TIME UP!", 'Gray')) bd.clear_storage() for c, player in enumerate(bd.players): print( config.printcc( "Player %d score : %d" % (c, player.score), 'White')) sleep(3) print( config.printcc( "Press ANY KEY to exit | Press 'r' to restart", 'Gray')) a = config._getch() system('reset')
def main(): height, width = (24, 76) quit = False won = False print("Waking up Mario ...") sleep(2) print("Yay, he woke up!") print("Now, waking up your enemies ...") a = 'r' while a == 'r': bd = board.Board(24, 400) player = person.Mario(3, height - 3, 3) # while (player.lives > 0): bd.spawn(player) ls = spawn(config._enemy, bd) # ck = spawn_coins(config._coin, bd) if ls == False: # or ck == False: print("Object Spawn Error") return False print("Objects spawned, your enemies have been born\n") print("Rendering Board ...") sleep(3) bd.render(0, 76) x = 0 p_input = -1 st_time = datetime.datetime.now() prev_round = datetime.datetime.now() while (datetime.datetime.now() - st_time) <= datetime.timedelta(seconds=100): # while a=='r': sys.stdout.write(Fore.BLUE + "'q' : quit || Lives " + Fore.RED + '%s' % (player.lives * '♥ ')) sys.stdout.write(' || ' + Fore.BLUE + "Time : %d" % (100 - (datetime.datetime.now() - st_time).seconds)) try: bd.gameover(player) except Exception as exc: print(exc.args[0]) break print(Style.RESET_ALL) p_input = config.get_key(config.get_input()) if p_input == config.QUIT: print(Fore.BLUE + "Quitting game because you're a sore loser ...") print("Resetting your clock ...") print(Style.RESET_ALL) quit = True break cur_round = datetime.datetime.now() if (cur_round - prev_round) >= datetime.timedelta(seconds=1): bd.update_frame() prev_round = cur_round if p_input == config.UP: i = 3 while i > 0: bd.process_input(player, config.UP) bd.render(x, x + 76) inter_input = config.get_key(config.get_input()) if inter_input == config.LEFT or inter_input == config.RIGHT or inter_input == config.UP: bd.process_input(player, inter_input) # sleep(0.1) i = i - 1 '''while i > 0: if i == 2: sleep(0.2) bd.process_input(player, config.DOWN) bd.render() # inter_input = config.get_key(config.get_input()) # bd.process_input(player, inter_input) # bd.render() sleep(0.1) i = i - 1''' '''while player.get_ycoords()+2 != 23: # print(player.get_ycoords()) bd.process_input(player, config.DOWN) bd.render() sleep(0.1) ''' # cur_round = datetime.datetime.now() if p_input == config.LEFT or p_input == config.RIGHT: bd.process_input(player, p_input) try: bd.gameover(player) except Exception as exc: sys.stdout.write(exc.args[0]) break for _ in bd._storage[config.types[config._enemy]]: while _.get_ycoords() + 2 != 23: res = bd.process_input(_, config.DOWN) if res == False: break while player.get_ycoords() != 23: # print(player.get_ycoords()) res = bd.process_input(player, config.DOWN) if res == False: break bd.render(x, x + 76) res = bd.process_input(player, config.DOWN) sleep(0.1) if player.get_ycoords() == 23: player.lives -= 1 try: bd.gameover(player) except Exception as exc: sys.stdout.write(exc.args[0]) break if player.get_xcoords() >= 360: won = True sys.stdout.write(Fore.RED + Style.BRIGHT + Back.BLACK + "YOU BEAT THE GAME") print(Style.RESET_ALL) break # sleep(0.1) # bd.render() """ if (cur_round - prev_round) >= datetime.timedelta(seconds=1): # bd.update_frame() # prev_round = cur_round""" bd.render(x, x + 76) if player.get_xcoords() > (x + 38): x = x + 6 bd.render(x, x + 76) if player.lives > 0 and won == False: sys.stdout.write(Fore.BLUE + "TIME'S UP\n") sleep(2) bd.clear_storage() player.score = ( 100 - (datetime.datetime.now() - st_time).total_seconds()) * 384 for player in bd.players: if quit: sys.stdout.write(Fore.RED + "PLAYER SCORE: 0") else: sys.stdout.write(Fore.RED + "PLAYER SCORE: %d" % player.score) print(Style.RESET_ALL) print("Press 'r' to RESTART") a = config._getch() system('reset')