def managematcharmies(): user_id = users_service.user_id() if not user_id: return redirect("/") if users_service.get_csrf_token() != request.form["csrf_token"]: abort(403) op_type = request.form["operation_type"] match_id = request.form["match_id"] if (op_type == "attach"): army_name = request.form["army_name"].strip() army_size = request.form["army_size"].strip() army_side = request.form["force"] if not (utils.validate_input(army_name, 3, 64) & utils.validate_input(army_size, 3, 6)): return redirect("/match/" + match_id) if not army_side: return redirect("/match/" + match_id) new_or_existing_id = armies_service.create_new(army_name, army_size, user_id) if (new_or_existing_id != None): matches_service.add_army_to_match(match_id, new_or_existing_id, army_side) return redirect("/match/" + match_id) if (op_type == "detach"): army_id = request.form["army_id"] matches_service.remove_army_from_match(match_id, army_id) return redirect("/match/" + match_id)
def managearmyunits(): user_id = users_service.user_id() if not user_id: return redirect("/") if users_service.get_csrf_token() != request.form["csrf_token"]: abort(403) op_type = request.form["operation_type"] army_id = request.form["army_id"] if (op_type == "attach"): unit_name = request.form["unit_name"].strip() unit_points = request.form["unit_points"].strip() if not (utils.validate_input(unit_name, 3, 64) & utils.validate_input(unit_points, 1, 4)): return redirect("/army/" + army_id) new_or_existing_id = units_service.create_new(unit_name, unit_points, user_id) if (new_or_existing_id != None): armies_service.add_unit_to_army(army_id, new_or_existing_id) return redirect("/army/" + army_id) if (op_type == "detach"): unit_id = request.form["unit_id"] armies_service.remove_unit_from_army(army_id, unit_id) return redirect("/army/" + army_id)
def armies(): user_id = users_service.user_id() if not user_id: return redirect("/") user_armies = armies_service.get_user_armies(user_id) user_hidden_armies = armies_service.get_user_hidden_armies(user_id) if request.method == "GET": return render_template("armies.html", armies=user_armies, hidden_armies=user_hidden_armies, message="") if request.method == "POST": if users_service.get_csrf_token() != request.form["csrf_token"]: abort(403) army_name = request.form["army_name"].strip() army_size = request.form["army_size"].strip() if not (utils.validate_input(army_name, 3, 64) & utils.validate_input(army_size, 3, 6)): return render_template( "armies.html", armies=user_armies, hidden_armies=user_hidden_armies, message= "Army name must be 3-64 and army size between 3-6 characters, and contain only numbers or letters" ) armies_service.create_new(army_name, army_size, user_id) return redirect("/armies")
def units(): user_id = users_service.user_id() if not user_id: return redirect("/") user_units = units_service.get_user_units(user_id) user_hidden_units = units_service.get_user_hidden_units(user_id) if request.method == "GET": return render_template("units.html", units=user_units, hidden_units=user_hidden_units, message="") if request.method == "POST": if users_service.get_csrf_token() != request.form["csrf_token"]: abort(403) unit_name = request.form["unit_name"].strip() unit_points = request.form["unit_points"].strip() if not (utils.validate_input(unit_name, 3, 64) & utils.validate_input(unit_points, 1, 4)): return render_template( "units.html", units=user_units, hidden_units=user_hidden_units, message= "Unit name must be 3-64 and unit points cost between 1-4 characters, and contain only numbers or letters" ) units_service.create_new(unit_name, unit_points, user_id) return redirect("/units")
def register(): if request.method == "GET": return render_template("register.html", message="") if request.method == "POST": message = "" username = request.form["username"].strip() password = request.form["password"].strip() if not (utils.validate_input(username, 3, 32) & utils.validate_input(password, 3, 32)): return render_template( "register.html", message= "Username and password must be 3-32 characters and contain only letters and numbers." ) if users_service.register(username, password): message = users_service.login(username, password) if message == "Success": return redirect("/matches") else: return render_template("index.html", message="Logging in user failed") else: return render_template("register.html", message="Username already taken")
def matches(): if not users_service.user_id: return redirect("/") returned_matches = matches_service.get_user_matches( users_service.user_id()) if request.method == "GET": return render_template("matches.html", matches=returned_matches, message="") if request.method == "POST": if users_service.get_csrf_token() != request.form["csrf_token"]: abort(403) match_name = request.form["match_name"].strip() match_size = request.form["match_size"].strip() if not (utils.validate_input(match_name, 3, 64) & utils.validate_input(match_size, 3, 6)): return render_template( "matches.html", matches=returned_matches, message= "Match name must be 3-64 and match size between 3-6 characters, and contain only numbers or letters" ) if (matches_service.create_new(match_name, match_size, users_service.user_id())): return redirect("/matches") else: return render_template("matches.html", matches=returned_matches, message="Invalid match name or size.")
def lru_fibonacci(n): utils.validate_input(n) if n in (1, 2): return 1 return lru_fibonacci(n - 1) + lru_fibonacci(n - 2)
def execute(self, balance): print( '------------------------------------------------------------------------', end='') while True: super().welcome(self.name, balance) print( 'Note: there are no jokers in this deck of cards (total: 52 cards).' ) inpt = input( 'Please enter the amount of money you want to bet (default is 10.00): ' ) bet = validate_input(inpt, 'bet', balance=balance) if bet == 'quit': break print( 'Choose which player you want to be (Player 1 draws first, Player 2 draws next)' ) inpt = input('Enter "1" or "2": ') player = validate_input(inpt, 'player') if player == 'quit': break first_draw = self.cards[r.randint(0, len(self.cards) - 1)] self.cards.remove(first_draw) second_draw = self.cards[r.randint(0, len(self.cards) - 1)] # Let user know it's executing wait_msg('Drawing cards from a deck', 5, 0.5) num1 = self.parse_card(first_draw) num2 = self.parse_card(second_draw) win = None if player == 1: print("\nYou (player 1) have drawn: {}".format(first_draw)) t.sleep(1.5) print('The computer (player 2) has drawn: {}'.format( second_draw)) t.sleep(1.5) if num1 > num2: win = True elif num1 < num2: win = False balance += super().get_result(win, bet) else: print('\nThe computer (player 1) has drawn: {}'.format( first_draw)) t.sleep(1.5) print("You (player 2) have drawn: {}".format(second_draw)) t.sleep(1.5) if num1 < num2: win = True elif num1 > num2: win = False balance += super().get_result(win, bet) print( '------------------------------------------------------------------------' ) return balance
def dict_fibonacci(n): utils.validate_input(n) if n in (1, 2): return 1 if n not in dict_cache: dict_cache[n] = dict_fibonacci(n - 1) + dict_fibonacci(n - 2) return dict_cache[n]
def no_cache_fibonacci(n): utils.validate_input(n) if n in (1, 2): return 1 if n > 30: n = 30 # just for it not to take forever... return no_cache_fibonacci(n - 1) + no_cache_fibonacci(n - 2)
def pymemcache_fibonacci(n): utils.validate_input(n) if n in (1, 2): return 1 f = client.get("p" + str(n)) if f is None: f = pymemcache_fibonacci(n - 1) + pymemcache_fibonacci(n - 2) client.set("p" + str(n), str(f)) return int(f)
def tls_bmemcached_fibonacci(n): utils.validate_input(n) if n in (1, 2): return 1 f = tls_client.get("b" + str(n)) if f is None: f = tls_bmemcached_fibonacci(n - 1) + tls_bmemcached_fibonacci(n - 2) tls_client.set("b" + str(n), str(f)) return int(f)
def index(): if request.method == "GET": return render_template("index.html", message="") if request.method == "POST": username = request.form["username"].strip() password = request.form["password"].strip() if not (utils.validate_input(username, 3, 32) & utils.validate_input(password, 3, 32)): return render_template("index.html", message="Incorrect username or password!") message = users_service.login(username, password) if message == "Success": return redirect("/matches") else: return render_template("index.html", message=message)
def create_new_game_api(self, request): """ Create a new game. Requires an exiting user""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'There is no user with that name!') try: history_record = [ HistoryRecord(play_sequence=1, action='Game created', user_entry=" ", result=" ", current_game="", game_over=False, game_won=False, game_cancelled=False) ] game = Game.create_new_game_models(user.key, request.answer, request.strikes, history_record) Score.create_new_score_models(user, game) except ValueError: raise endpoints.BadRequestException( 'You really need a positive number of strikes') input_validation = validate_input(game.answer) if input_validation[0] is True: return game.to_form('Have fun playing Hangman!') else: raise endpoints.BadRequestException(input_validation[1])
def play_turn_api(self, request): """ Process user input""" game = get_by_urlsafe(request.urlsafe_game_key, Game) score = Score.query(Score.game == game.key).get() user = User.query(game.user == User.key).get() user_guess = request.guess.upper() """ Validate game status""" if game.game_over is True: msg = "This game is already over!" raise endpoints.BadRequestException(msg) # Validate user input input_validation = validate_input(request.guess, 1) if input_validation[0] is False: raise endpoints.BadRequestException(input_validation[1]) else: answer_valid = validate_guess(game, user_guess) if answer_valid is True: game_state = handle_right_answer(user, game, score, user_guess) else: game_state = handle_wrong_answer(user, game, score, user_guess) return game_state.get('game').to_form(game_state.get('msg'))
def account_activate(): """ Account Manager handler for AJAX - Activate Account Accept all Terms and Conditions applicable to the account :input data: {'username': <username>, 'password': <password>} :return dict: { 'status': <status_code>, 'msg': <response msg> } :return int: Status code """ logging.debug("Account activation requested") raw_data = request.get_json() template = {'required': ('username', 'password')} data = utils.validate_input(template, raw_data) # Verify the given credentials candlepin.account.verify(data['username'], data['password']) # Accept all necessary Terms and Conditions org_id = candlepin.utils.get_orgid(data['username']) r = candlepin.account.accept_terms(data['username'], data['password'], org_id=org_id) if r['failed']: raise RuntimeError("Failed to accept some Ts&Cs for account '{0}': {1}" "".format(data['username'], r['failed'])) msg = ("Terms and Conditions for account '{0}' were successfully accepted" "".format(data['username'])) return dumps({'status': '200', 'msg': msg}), 200
def delete(self, store_id): store = validate_input(store_id=store_id) if store.items.first() is not None: return {'message': 'This store still contains some items.'}, 400 store.delete_from_db() return {'message': 'Store deleted.'}, 200
def put(self, store_id, item_id): item = validate_input(store_id=store_id, item_id=item_id) data = Item.parser.parse_args() item.name = data['name'] item.price = data['price'] item.save_to_db() return item.json(), 200
def account_new(): """ Account Manager handler for AJAX - New Account :input data: { 'username': <account's username>, 'password': <account's password>, 'first_name': <optional>, 'last_name': <optional> } :return dict: {'status': <status_code>, 'msg': <response data>} :return int: Status code """ data = request.get_json() template = { 'required': ('username', 'password'), 'optional': ('first_name', 'last_name') } create_data = utils.validate_input(template, data) # Create user candlepin.account.create_new(**create_data) # NOTE: Account is inactive by default response = { 'status': '200', 'msg': "Account '{0}' created".format(data['username']) } return dumps(response), 200
def subscriptions_refresh(): """ Account Manager handler for AJAX - Refresh Subscriptions for Account :input data: { 'username': <account's username>, 'password': <account's password> } :return dict: {'status': <status_code>, 'msg': <response data>} :return int: Status code """ logging.debug("Refresh requested") raw_data = request.get_json() template = {'required': ('username', 'password')} data = utils.validate_input(template, raw_data) # Verify the account is available and active candlepin.account.verify(data['username'], data['password']) # Initiate the refresh candlepin.subscription.refresh_pools(data['username']) response = { 'status': '200', 'msg': "Pools for '{0}' refreshed successfully".format(data['username']) } return dumps(response), 200
def execute(self, balance): print( '------------------------------------------------------------------------', end='') while True: super().welcome(self.name, balance) inpt = input( 'Please enter the amount of money you want to bet (default is 10.00): ' ) bet = validate_input(inpt, 'bet', balance=balance) if bet == 'quit': break inpt = input('Please enter your guess ("odd" or "even"): ') guess = validate_input(inpt, 'odd_or_even') if guess == 'quit': break outcome = '' win = None # Let user know it's executing wait_msg('Rolling dies', 5, 0.4) die1 = r.randint(1, 6) die2 = r.randint(1, 6) die_sum = die1 + die2 if die_sum % 2 == 0: outcome = 'even' else: outcome = 'odd' print('\nDice #1: {}'.format(die1)) t.sleep(1.5) print('Dice #2: {}'.format(die2)) t.sleep(1.5) print('The sum: {}, which is {}!'.format(die_sum, outcome)) t.sleep(1.5) if outcome == guess: win = True else: win = False balance += super().get_result(win, bet) print( '------------------------------------------------------------------------' ) return balance
def match(match_id): if not users_service.user_id: return redirect("/") selected_match = matches_service.find_match(match_id) involvedForces = matches_service.find_match_armies(match_id) force1 = involvedForces[0] force2 = involvedForces[1] if request.method == "GET": return render_template("match.html", match=selected_match, force1=force1, force2=force2, message="") if request.method == "POST": if users_service.get_csrf_token() != request.form["csrf_token"]: abort(403) match_name = request.form["match_name"].strip() match_size = request.form["match_size"].strip() if not (utils.validate_input(match_name, 3, 64) & utils.validate_input(match_size, 3, 6)): return render_template( "match.html", match=selected_match, force1=force1, force2=force2, message= "Match name must be 3-64 and match size between 3-6 characters, and contain only numbers or letters" ) if matches_service.update_match(match_id, match_name, match_size, users_service.user_id()): return redirect("/match/" + str(match_id)) else: return render_template("match.html", match=selected_match, force1=force1, force2=force2, message="Invalid match name or size.")
def main(argv=None): log.config_logging(getattr(logging, 'INFO', None)) argv = argv or sys.argv image_tags_file, output_file, args = validate_input(argv, 'python') t_start = time.time() PatchArtifactRunner(PatchArtifactPythonTask, image_tags_file, _COPY_DIR, output_file, args, workers=args.workers).run() t_end = time.time() log.info('Running patch took {}s'.format(t_end - t_start))
def main(): args = sys.argv utils.validate_input(args) sub_matrix_path, seqs_paths = utils.split_input(args) sub_matrix = utils.read_scoring_matrix(sub_matrix_path) alphabet = utils.read_alphabet(sub_matrix_path) seqs_dict = utils.get_seqs(seqs_paths) i = 0 for id1, seq1 in seqs_dict.items(): j = 0 for id2, seq2 in seqs_dict.items(): if i < j: timestart = datetime.now() hsps = utils.find_hsps(k, T, sub_matrix, seq1, seq2, alphabet) msps = utils.extend_hsps_to_msps(hsps, sub_matrix, seq1, seq2, X) graph = utils.gen_graph(msps) score = utils.runDAG(graph) timedelta = datetime.now() - timestart utils.update_output_file(id1, id2, score) print(f"({id1}, {id2}):\t{timedelta}\t msps: {len(msps)}") j += 1 i += 1
def execute(self, balance): print( '------------------------------------------------------------------------', end='') while True: super().welcome(self.name, balance) inpt = input( 'Please enter the amount of money you want to bet (default is 10.00): ' ) bet = validate_input(inpt, 'bet', balance=balance) if bet == 'quit': break inpt = input('Please enter your guess ("heads" or "tails"): ') guess = validate_input(inpt, 'coin_guess') if guess == 'quit': break num = r.randint(0, 1) outcome = '' win = None # Let user know it's executing wait_msg('Flipping', 5, 0.7) if num == 0: outcome = 'heads' else: outcome = 'tails' print("It's " + outcome + '!') t.sleep(1) if outcome == guess: win = True else: win = False balance += super().get_result(win, bet) print( '------------------------------------------------------------------------' ) return balance
def main(argv=None): log.config_logging(getattr(logging, 'INFO', None)) argv = argv or sys.argv image_tags_file, output_file, args = validate_input(argv, 'maven') # Remains empty if run outside of reproducer pipeline repr_metadata_dict = dict() # Task JSON path will be an empty string by default if args.task_json: log.info('Writing pairs to reference dict from ReproducedResultsAnalyzer JSON') repr_metadata_dict = get_repr_metadata_dict(args.task_json, repr_metadata_dict) t_start = time.time() PatchArtifactRunner(PatchArtifactMavenTask, image_tags_file, _COPY_DIR, output_file, repr_metadata_dict, args, workers=args.workers).run() t_end = time.time() log.info('Running patch took {}s'.format(t_end - t_start))
def run(self): print(r"We are running...") os.help() keep_running = True while keep_running: user_input = input("[A,S,t,p#,d#,c#,P#,D#,C#]: ").strip() while not validate_input(user_input): user_input = input("Not valid! Try again: ") # We know this is valid now.... if user_input == "A": pcb = PCB() self.readyQueue.add_pcb_to_readyqueue(pcb) print("Added process %d " % pcb.pid) elif user_input == "S": selection = input("[r,d,p,c]: ") while not validate_input_snapshot(selection): selection = input("Invalid input! [r,d,p,c]: ") if selection == "r": self.snapshot(readyQ=True) elif selection == "d": self.snapshot(diskQ=True) elif selection == "p": self.snapshot(printerQ=True) elif selection == "c": self.snapshot(cdrwQ=True) else: print("If we get here...fail me.") elif match(r"^[PDCpdc]{1}\d+$", user_input): if user_input[0].islower(): self.syscall(user_input) elif user_input[0].isupper(): self.interrupt(user_input) else: print("If you see this message...dock points!") elif parse_if_terminate_syscall(user_input): if self.readyQueue.queue_len() > 0: pcb = self.readyQueue.pop() print("Terminated Process %d " % pcb.pid) else: print("No process is currently in the CPU.") elif do_we_quit(user_input): print("This always happens...was it me??!! I love you anyways...") keep_running = False # break out.
def add(text, links, **kwargs): """ Call class on module level, initialize like this, get back the class and operate on this object instead of the class directly import anchorman a = anchorman.add(text, links) """ success, values = validate_input((text, links)) if success: text, links = values else: raise ValueError(values) a = Anchorman(text, links, **kwargs) a.add() return a
def main(argv=None): log.config_logging(getattr(logging, 'INFO', None)) argv = argv or sys.argv image_tags_file, output_file, args = validate_input(argv, 'python') repr_metadata_dict = dict( ) # This arg for PatchArtifactRunner only used in Java at the moment t_start = time.time() PatchArtifactRunner(PatchArtifactPythonTask, image_tags_file, _COPY_DIR, output_file, repr_metadata_dict, args, workers=args.workers).run() t_end = time.time() log.info('Running patch took {}s'.format(t_end - t_start))
def main(args): """App's main""" #start_time = time.time() #stime = strftime("%a %b %d %H:%M %Y", gmtime()) if len(sys.argv) > 1: with open(args.filename, buffering=-1) as data_file: data = data_file.read() json_status, json_string = utl.is_json(data) if json_status: keylist = json_string.keys() if utl.validate_input(**json_string): for rules in json_string['RuleList']: my_cls = cmn.GCP() my_cls.process(**rules) else: print "Provided json doesn't contain all the necessary keys" else: print "Provided json is not valid"
def main(argv=None): argv = argv or sys.argv image_tags_file, output_file = validate_input(argv, _print_usage) artifact_list = list() with open(image_tags_file, "r") as file: for line in file: image_tag = line.strip() artifact = bugswarmapi.find_artifact(image_tag).json() res = False if artifact["lang"] == "Python": res = python_filter(artifact) elif artifact["lang"] == "Java": res = java_filter(artifact) if res: artifact_list.append(image_tag) with open(output_file, "w+") as file: for art in artifact_list: file.write("{}\n".format(art))
def main(): # User's money money = 100.00 # All the games available games = {1:'Flip a Coin!', 2:'Cho-Han', 3:'Poker Game', 4:'Mini Roulette'} # Welcome message print('\n★☆★☆★☆ Welcome to Games of Chance ★☆★☆★☆') print('You have $100 to start!') print('(You can exit the program at any time by entering "exit".)') while True: check_balance(money) # Print out main menu print('【Main Menu】') print('Your current balance is ${:.2f}'.format(money)) print('(You can exit the program at any time by entering "exit".)') print('The current available games are:') for index in games: print(' {}. {}'.format(index, games[index])) # Prompt the user to select a game inpt = input('Please make your selection by entering the index of the game: ') selection = validate_input(inpt, 'game', num_games=len(games)) if selection == 'quit': return # Execute the selected game if games[selection] == 'Flip a Coin!': cf = CoinFlip() money = cf.execute(money) elif games[selection] == 'Cho-Han': chohan = ChoHan() money = chohan.execute(money) elif games[selection] == 'Poker Game': poker = PlayCards() money = poker.execute(money) elif games[selection] == 'Mini Roulette': roulette = Roulette() money = roulette.execute(money)