def display(self, index = None, error = None): # Clear our terminal window call("cls") # Define our variables cur_count = 0 menu_item = self.get_menu(index or self.get_current_menu_index()) # Error Handling if(error != None): print("\n", "Error!", error, "\n") # Menu Title, set tree print("Please select an option: ({})".format(self.get_menu_name(self.get_current_menu_index()))) menu_counter = 0 for m in self._menu[menu_item]: # Increase our Counter menu_counter += 1 # Is the Menu Item a Function? m_type = None if(callable(m)): m_type = "" else: m_type = "->" # Print our Menu Item print("{0}. {1} {2}".format(menu_counter, m, m_type)) # Append the Back Option if(self.get_current_menu_index() != 0): print("{0}. {1}".format(menu_counter + 1, "Back")) # Get User Input self.get_input()
def new_name(self): # Clear our terminal window call("cls") # Get our input print("Please enter a season name (leave empty to cancel): ") input(">>> ")
def display(self, index=None, error=None): # Clear our terminal window call("cls") # Define our variables cur_count = 0 menu_item = self.get_menu(index or "main") # Error Handling if (error != None): print("\n", "Error!", error, "\n") # Menu Title, set tree print("Please select an option: ({})".format(index)) menu_counter = 0 for m in menu_item: # Get our menu name menu_name = menu_item[m] # Increase our Counter menu_counter += 1 # Is the Menu Item a Function? m_type = None if (callable(m)): m_type = "" else: m_type = "->" # Print our Menu Item print("{0}. {1} {2}".format(menu_counter, menu_name, m_type)) # Get User Input self.get_input()
def display(self, index = None): # Clear our terminal window call("cls") # Define our variables cur_count = 0 menu_item = self.get_menu(index or self.get_current_menu_index()) # Menu Title, set tree tree = "(current: " + self.get_menu_name(self.get_current_menu_index()) + ")" print("Please select an option: {}".format(tree)) menu_counter = 0 for m in self._menu[menu_item]: # Increase our Counter menu_counter += 1 # Is the Menu Item a Function? m_type = None if(callable(m)): m_type = "" else: m_type = "->" # Print our Menu Item print("{0}. {1} {2}".format(menu_counter, m, m_type)) # Get User Input self.get_input()
def clear(): """ Clears the console according to operating system specific command """ if "Windows" in system(): call("cls") else: call("clear")
def show_current_menu(shouldClear=True, error=False, errorMsg=None): cur_menu_items = Builder.get_item(Builder.current_menu()) # Should we clear our terminal window? if (shouldClear): call("cls") # Have we got an error? if (error): if (errorMsg == None): print( "\n{0}{1}Error:{2}\n{0}There was an error performing your request.{2}\n" .format(Colours.FAIL, Colours.BOLD, Colours.ENDC)) else: print("\n{2}Error:{3}\n{1}{0}.{3}\n".format( errorMsg, Colours.FAIL, Colours.BOLD, Colours.ENDC)) # Check that our Menu exists if (cur_menu_items == None): print("{}There was an error with grabbing the selected menu!{}". format(Colours.FAIL, Colours.ENDC)) print("Current menu: {}".format(Builder.current_menu())) Builder.set_current_menu("main") else: # Print menu header print("{2}{0}{3} ({4}{1}{3})".format(Builder._title, Builder.get_menu_tree(), Colours.BOLD, Colours.ENDC, Colours.GRAY)) # Print out our menu for i, (k, v) in enumerate(cur_menu_items.items(), 1): if (Builder.item_exists(k)): print("{3}{0}{4}. {1}{2}".format( i, v, (' -> ' if Builder.is_menu(k) else ''), Colours.BOLD + Colours.OKGREEN, Colours.ENDC)) else: print( Builder.notAvailable("{3}{0}{4}. {1}{2}".format( i, v, (' -> ' if Builder.is_menu(k) else ''), Colours.BOLD + Colours.OKGREEN, Colours.ENDC))) # Does this key (ref) have info? if (Builder.item_exists(k + "_info")): print(" - {0}{1}".format( Builder.get_item(k + "_info"), "" if (i == len(cur_menu_items.items()) and Builder.current_menu() is "main") else "\n")) # Print our back button print("{0}".format( "{0}b{1}. Back".format(Colours.FAIL, Colours.ENDC) if Builder. current_menu() is not "main" else "{0}x{1}. Exit and Save". format(Colours.FAIL, Colours.ENDC))) # Get input from user Builder.monitor_input()
def recalculate_mb(center, range, definition, maxRecursionDepth, buffer_size): global GENERATION_PROGRAM_PATH if buffer_size == "max": buffer_size = (2**64) - 1 call( f"{GENERATION_PROGRAM_PATH} dv {center[0]} {center[1]} {range} {definition} {maxRecursionDepth} {buffer_size}" )
def new_season(self): # Clear our terminal window call("cls") # Get our input print("Please enter a season name (leave empty to cancel): ") season_name = input("\n>>> ") if(season_name != ""): print("creating {}".format(season_name)) else: self._current_menu = "main" self.display()
def run_prog(self, out, cmd, timeout): log_msg = "Running test: %s" % self.name print(log_msg + " ...", end='', flush=True) call('echo "Running test %s" >> %s' % (self.name, out)) command = self.args.replace("$", cmd) call('echo "%s" >> %s' % (command, out)) result = Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True) kill_prog = lambda prog: prog.kill() if timeout is not 0: timer = Timer(timeout, kill_prog, [result]) try: if timeout is not 0: timer.start() res, err = result.communicate() code = result.returncode finally: if timeout is not 0: timer.cancel() if code == -9: print("\r" + log_msg + " Timeout") call('echo "Exec error: program timed out (Max: %d sec)" >> %s' % (timeout, out)) return (None, None, 3) if code < 0: print("\nCrashed") call('echo "Exec error: program crashed (Code: %d)" >> %s' % (code, out)) return (None, None, 2) return (res, code, 0)
def run_compare_to(self, out, cmd, timeout): res, code, status = self.run_prog(out, cmd, timeout) log_msg = "Running test: %s" % self.name if status != 0: return (status) command = self.args.replace("$", self.corrector) call('echo "%s" >> %s' % (command, out)) result = Popen(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True) correct_res, correct_err = result.communicate() correct_code = result.returncode if not res == correct_res: print("\r" + log_msg + " KO ") call('echo "KO, expected: %s and got: %s" >> %s' % (correct_res, res, out)) return (1) if (correct_code == 0 and code != 0) or (correct_code != 0 and code == 0): print("\r" + log_msg + " KO ") call('echo "KO, got incorrect return code: %d (expected %d)" >> %s' % (code, correct_code, out)) return (1) call('echo "OK" >> %s' % out) print("\r" + log_msg + " OK ") return (0)
def menu(): menuselection = 0 while menuselection == 0: print "[ - - - Open Source News Intel V1.0 - - - ]" print "[ + ] Please enter a valid option '1' through '7' and press enter to continue..." print "[ + ] 1. News Search (Russian Language)" print "[ + ] 2. News Search (English Language)" print "[ + ] 3. Twitter Search (Russian Language)" print "[ + ] 4. Twitter Search (English Language)" print "[ + ] 5. News & Twitter Search (Russian Language)" print "[ + ] 6. News & Twitter Search (English Language)" print "[ - ] 7. EXIT" selection = raw_input("Option: ") if selection == "1": news_search_Russian() menuselection = "99" if selection == "2": news_search_English() menuselection = "99" if selection == "3": twitter_Russian() menuselection = "99" if selection == "4": twitter_English() menuselection = "99" if selection == "5": news_search_Russian() twitter_Russian() menuselection = "99" if selection == "6": news_search_English() twitter_English() menuselection = "99" if selection == "7": print "Exiting..." sys.exit(1) menuselection = "99" if selection != "1" and selection != "2" and selection != "3" and selection != "4" and selection != "5" and selection != "6": call('cls') print "[ - ] ERROR. Incorrect option selected, please try again."
def show_current_menu(shouldClear=True, error=False, errorMsg=None): cur_menu_items = Builder.get_item(Builder.current_menu()) # Should we clear our terminal window? if (shouldClear): call("cls") # Have we got an error? if (error): if (errorMsg == None): print( "\nError:\nThere was an error performing your request.\n") else: print("\nError:\n{0}.\n".format(errorMsg)) # Check that our Menu exists if (cur_menu_items == None): print("There was an error with grabbing the selected menu!") print("Current menu: {}".format(Builder.current_menu())) Builder.set_current_menu("main") else: # Print menu header print("{0} ({1})".format(Builder._title, Builder.get_menu_tree())) # Print out our menu for i, (k, v) in enumerate(cur_menu_items.items(), 1): if (Builder.item_exists(k)): print("{0}. {1}{2}".format( i, v, (' -> ' if Builder.is_menu(k) else ''))) else: print( Builder.notAvailable("{0}. {1}{2}".format( i, v, (' -> ' if Builder.is_menu(k) else '')))) # Does this key (ref) have info? if (Builder.item_exists(k + "_info")): print(" - {0}{1}".format( Builder.get_item(k + "_info"), "" if (i == len(cur_menu_items.items()) and Builder.current_menu() is "main") else "\n")) # Print our back button if (Builder.current_menu() is not "main"): print("b. Back") # Get input from user Builder.monitor_input()
def cleanUpDockerContainer(self, instance=None): if instance == None: #print("cleaning up all docker containers") instance = subprocess.getoutput(self.sudo + ["docker", "ps", "-q"]) instance = instance.split("\n") for inst in instance: output = os.call(self.sudo + ["docker", "kill", inst]) self.dPrint(output, self.verbose, 1) else: #print("cleaning up container %s"%instance) output = os.call(self.sudo + ["docker", "kill", instance]) self.dPrint(output, self.verbose, 1)
def main(): parser = argparse.ArgumentParser() parser.add_argument("-t", "--timeout", dest="timeout", type=unsigned_int, help="Sets the timeout value (default=120)") parser.add_argument("-o", "--output", dest="trace", type=str, help="Sets the output file (default='trace')") parser.add_argument("-s", "--stop", dest="should_stop", action="store_true", help="Makes the tester stop at the first error") parser.add_argument("--setup", dest="setup", action="store_true", help="Sets up the testing environment") args = parser.parse_args() if args.setup: setup() return if not check_setup(): return if args.trace is not None: out = args.trace else: out = "trace" global should_stop, timeout should_stop = args.should_stop if timeout is not None: timeout = args.timeout call("echo -n > %s" % out) print("Compiling program") compiler = load_compilation_settings(COMPILATION_CFG) if not compile(compiler, out): print("Compilation failed") return print("Compilation successful\n\n") run_group_tests(out) call('echo "\n" >> %s' % (out)) compiler.clean(out)
def emulate_round(self, gdr = None, rnd = None, all = False, error = False): # Clear Terminal call("cls") # Get our Matches for m, match in enumerate(self.round(gdr, rnd).matches(), 1): print(match.versuses(True)) # Options if(all): return ([ "View current leaderboard", "View current prize money" ], [ partial(self.view_leaderboard, gdr, rnd), partial(self.view_prize_money, gdr) ]) if(rnd == "round_{}".format(self.season().settings()["round_count"])) else ([ "View current leaderboard" ], [ partial(self.view_leaderboard, gdr, rnd) ]) else: # Have we errored? if(error): print("\nError:\nYou entered an invalid option.") error = False # Are we on our last round? if(rnd == "round_{}".format(self.season().settings()["round_count"])): # Build Menu print("\nPlease select an option:", "\n1.", "View current leaderboard", "\n2.", "View current prize money", "\n3.", "Back to menu") option = input(">>> ") or None if(option == "1"): self.view_leaderboard(gdr, rnd) elif(option == "2" and rnd == "round_{}".format(self.season().settings()["round_count"])): self.view_prize_money(gdr) elif(option == "3"): return "SKIP" else: return self.emulate_round(gdr, rnd, all, True) else: # Build Menu print("\nPlease select an option:", "\n1.", "View current leaderboard", "\n2.", "Back to menu") option = input(">>> ") or None if(option == "1"): self.view_leaderboard(gdr, rnd) elif(option == "2"): return "SKIP" else: return self.emulate_round(gdr, rnd, all, True) # Repeat our Round return self.emulate_round(gdr, rnd, all)
def get_input(self): # Wrap this in a try/except to validate any errors with input try: # Get users input resp = int(input('\n>>> ')) # Validate some set input calls if (resp == "exit"): raise KeyboardInterrupt elif (resp == ""): return self.display(self._current_menu, "Please select a valid option!") # Validate input from current menu menu_selected = self.menu_exists(resp) if (menu_selected != None and callable(menu_selected) != True): print(menu_selected) self._current.append(menu_selected) self._current_menu = menu_selected self.display(menu_selected) elif (callable(menu_selected)): # Clear our screen call("cls") # Call our function menu_selected() # Hold the user so they can see the result (if back hasn't just been called) if (self.just_called_back == False): input("\n>>> Press <Return> to continue...") else: self.just_called_back = False # Display our menu again to stop from program termination self.display(self._current_menu) else: self.display(self._current_menu, "Please select a valid option!") except KeyboardInterrupt: self._app.exit() except ValueError: self.display(self._current_menu, "Please select a valid option!")
def twitter_English(): try: Keywords = raw_input( 'Please Enter A Keyword(s) to Search Twitter (English Only): ') #Authentication information needed to access Twitter's API #Substitue your own authentication information below CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' twitterauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) twitterauth.set_access_token(ACCESS_KEY, ACCESS_SECRET) twitterapi = tweepy.API(twitterauth) twitter_search_results = twitterapi.search( q=Keywords, count=100, lang='en', result_type="recent" ) #Returns a max of 100 recent tweets in English only. now = datetime.datetime.now() filename = now.strftime("%Y-%m-%d-%H %M") File = codecs.open("C:\\Path-To-Save-File\\ETWT-" + filename + ".txt", "w", "utf-8") #Change file path File.write("--*Twitter Search (English Language)*--" + "\r\n" + "Top Matching Tweets (Recent)" + "\r\n" + "Keyword Searched: " + Keywords + "\r\n" + "Date & Time of Search: ") File.write(now.strftime("%Y-%m-%d %H:%M")) for tweet in twitter_search_results: File.write("\r\n" + "\r\n" + "TWEET: " + tweet.text + "\r\n" + "\r\n") print "[ + ] - Twitter Searched Successfully" Exit = raw_input("Press Enter to Exit: ") except TypeError: call('cls') print "[ - ] Invalid Keyword Input. Only ASCII Characters are accepted. Please selection your option and try again." menu()
def run_group_tests(out): f = open(VALIDATION_CFG) validation = json.load(f) f.close() groups = load_groups(GROUPS_CFG) results = [] i = 0 failed = False print("Running test groups in order: %s" % (', '.join(groups))) for group_id in groups: results.append([0.0, 0]) if failed: break if not isfile(GROUPS_PATH % group_id): print("\nWarning: %s does not exist\nSkipping it\n" % (GROUPS_PATH % group_id)) continue print("\n\nRunning test group: %s\n" % group_id) call('echo "\n\nRunning test group: %s\n" >> %s' % (group_id, out)) tests = load_group_tests(GROUPS_PATH % group_id, validation) for test in tests: code = test.run(out, "./" + command, timeout) if should_stop and code is not 0: failed = True break if code is 0: results[i][0] += 1.0 / len(tests) if code is 2: results[i][1] += 1 i += 1 if not failed: print("\n\n") total = 0.0 crashes = 0 for i in range(0, len(groups)): group = groups[i] res = results[i] total += res[0] crashes += res[1] print("Result for group %s: %.f%% (%d crash)" % (group, res[0] * 100, res[1])) total /= len(groups) print("\nTotal: %.f%% (%d crash)\n" % (total * 100, crashes))
def twitter_Russian(): try: Keywords = raw_input( 'Please Enter A Keyword(s) to Search Twitter (English Only) *FOR BEST RESULTS SEARCH ONLY ONE KEYWORD*: ' ) #Using the twitter API, multiple keywords can be used per search, but searching only one for the russian language tweets is best to maximize results as cyrilic characters are not acceptable input. #Authentication information needed to access Twitter's API #Substitue your own authentication information below CONSUMER_KEY = '' CONSUMER_SECRET = '' ACCESS_KEY = '' ACCESS_SECRET = '' twitterauth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) twitterauth.set_access_token(ACCESS_KEY, ACCESS_SECRET) #Authenticates to twitter API twitterapi = tweepy.API(twitterauth) twitter_search_results = twitterapi.search( q=Keywords, lang='ru', result_type="recent" ) #Searches only russian language, recent tweets. now = datetime.datetime.now() filename = now.strftime("%Y-%m-%d-%H %M") File = codecs.open("C:\\Path-To-Save-File\\RTWT-" + filename + ".txt", "w", "utf-8") #Change file path File.write("--*Twitter Search (Russian Language)*--" + "\r\n" + "Top Matching Tweets (Recent)" + "\r\n" + "Keyword Searched: " + Keywords + "\r\n" + "Date & Time of Search: ") File.write(now.strftime("%Y-%m-%d %H:%M")) for tweet in twitter_search_results: File.write("\r\n" + "\r\n" + "TWEET: " + tweet.text + "\r\n" + "\r\n") print "[ + ] - Twitter Searched Successfully" Exit = raw_input("Press Enter to Exit: ") except TypeError: call('cls') print "[ - ] Invalid Keyword Input. Only ASCII Characters are accetped. Please select your option and try again." menu()
def view_leaderboard(self, gdr = None, rnd_name = None): # Get our Round Object rnd = self.round(gdr, rnd_name) # Clear our Terminal call("cls") # Set our header text print("View Leaderboard for '{0}', Round {1}:".format(self.name(), rnd.id())) print("—————————————————————————————————————————————————————————") srt = sort(self.season().players()[gdr], self.name()) place = 1 for i in reversed(range(len(srt))): print("#{0}: {1} — {2} — {3}".format(f"{place:02}", srt[i].name(), "{0:03d} score".format(srt[i].score(self.name(), rnd_name) if (srt[i].score(self.name(), rnd_name) != 0) else srt[i].highest_score(self.name(), False)), "{0:03d} diff score".format(int(srt[i].score(self.name(), rnd_name) * self.difficulty()) if (srt[i].score(self.name(), rnd_name) != 0) else int(srt[i].highest_score(self.name(), False) * self.difficulty())))) place += 1 # Hold User input(">>> Press <Return> to continue...")
def new_season(self): # Clear our terminal window call("cls") # Get our input print("Please enter a season name (leave empty to cancel): ") season_name = input("\n> ") if (season_name != ""): self._app.handler.add_season(season_name) print("creating {}".format(season_name)) input("...") self.load() print(":D") else: self._current_menu = "main" self.display() print("xd")
def switch(switch_num, action="toggle"): switch_val = app.config["switches"][int(switch_num)] if not "state" in switch_val: switch_val["state"] = 0 if action == "toggle": action = switch_val["state"] and "off" or "on" stype = switch_val.get("type") if stype == "command": call(switch_val["commands"][action]) if action == "on": switch_val["state"] = 1 if action == "off": switch_val["state"] = 0 elif stype == "plugin": plugin = plugin_manager.get_plugin(switch_val["plugin"]) plugin.switch(switch_val, action=action) redirect("/")
def display(self, index=None): # Clear our terminal window call("cls") cur_count = 0 menu_item = self.get_menu(index or self.get_current_menu_index()) menu_counter = 0 for m in self._menu[menu_item]: # Increase our Counter menu_counter += 1 # Is the Menu Item a Function? m_type = None if (callable(m)): m_type = "" else: m_type = "->" # Print our Menu Item print("{0}. {1} {2}".format(menu_counter, m, m_type)) # Get User Input self.get_input()
def view_prize_money(self, gdr = None): # Clear our Terminal call("cls") # Get our unique prize money thingies self.unique_prize_money() # Set our header text print("View Prize Money for '{0}':".format(self.name())) print("—————————————————————————————————————————————————————————") srt = sort(self.season().players()[gdr], self.name()) place = 1 for i in reversed(range(len(srt))): # Get the players Prize Money p_prizemoney = self._prize_money_unique[srt[i].wins(self.name())] # Print Data print("#{0}: {1} — £{2:,}".format(f"{place:02}", srt[i].name(), p_prizemoney)) place += 1 # Hold User input(">>> Press <Return> to continue...")
def spinUpDockerContainerNoWait(self, tag, hostIp, networkIP, port, view): #print("spinning docker container: %s:%s"%(hostIp, port)) instance = { "testScriptAddress": hostIp + ":" + port, "networkIpPortAddress": networkIP + ":8080" } instance["containerID"] = os.call(self.sudo + [ "docker", "run", "-p", "%s:8080" % port, "--net=%s" % self.mynet, "--ip=%s" % networkIP, "-e", "VIEW=%s" % view, "-e", "IP_PORT=%s:8080" % networkIP, "-d", tag ]) if " " in instance["containerID"]: print(instance["containerID"]) self.dPrint(instance["containerID"], self.verbose, 1) return instance
def validate_expected(self, out, cmd, timeout): res, code, status = self.run_prog(out, cmd, timeout) log_msg = "Running test: %s" % self.name if status is not 0: return (status) if not res == self.expected: print("\r" + log_msg + " KO ") call('echo "KO, expected: %s and got: %s" >> %s' % (self.expected, res, out)) return (1) if not code is self.returncode: print("\r" + log_msg + " KO ") call('echo "KO, got incorrect return code: %d (expected %d)" >> %s' % (code, self.returncode, out)) return (1) call('echo "OK" >> %s' % out) print("\r" + log_msg + " OK ") return (0)
def input_round(self, seasonId, tournamentName, roundId, genderName): # Get our Season Object season = self.get_season(seasonId) players = None # Get our Tournament Object tournament = season.tournament(tournamentName) # Ensure we have a valid Tournament object if(tournament == None): return print("Invalid Tournament Name: {}".format(tournamentName)) # Ensure we have valid round data previous_round = tournament.round(genderName, "round_{}".format(roundId - 1)) if(previous_round == None and not (roundId - 1) == 0): return print("You can only generate this round when the rounds before Round {0} for {1}, {2} have been generated or manually inputed.".format(roundId, genderName.title(), tournamentName)) # Get the available players for this particular Round if(previous_round == None): players = season.players()[genderName] else: players = previous_round.winners() # Lets loop until all of our players have been used up available_players = players.copy() # Check if this round has some data this_round = tournament.round(genderName, "round_{}".format(roundId)) if(this_round != None): # Clean up our available_players array with matches that may exist for p in this_round.players(): if(p in available_players): del available_players[available_players.index(p)] # Get our input try: tryAgain = False tryAgainError = "" # Get our caps match_cap = (len(available_players) // 2) if (previous_round == None) else (len(previous_round.winners()) // 2) # Round Cap round_cap = 3 if(genderName + "_cap" in season.settings()): round_cap = season.settings()[genderName + "_cap"] # Check if our round already exists _r = None if(this_round == None): _r = Round.Round(self.app, genderName, "round_{0}".format(roundId), tournament, match_cap) else: _r = this_round # Update Round details _r.set_previous_round(previous_round) _r.set_cap(round_cap) # Add our round to the tournament tournament.add_round(genderName, _r) while(len(available_players) != 0): # Clear the Terminal call("cls") # Print out our available players print("Available Players for input on Round {0}:\n{1}".format(roundId, ", ".join([ p.name() for p in available_players ]))) # Handle Error if(tryAgain): print("\nError:\n{0}\n".format(tryAgainError)) tryAgain = False # Match Specific Variables winnerCount = 0 plyr_one = input("Please enter Player A: ") if(plyr_one in [ p.name() for p in available_players ]): plyr_one_score = input("Please enter the score for Player A: ") if(plyr_one_score.isdigit() and int(plyr_one_score) <= _r.cap()): # Type Conversion plyr_one_score = int(plyr_one_score) # Increment our Winner Count if(plyr_one_score == _r.cap()): winnerCount += 1 # Player B plyr_two = input("Please enter Player B: ") if(plyr_two in [ p.name() for p in available_players ] and plyr_two != plyr_one): plyr_two_score = input("Please enter the score for Player B: ") if(plyr_two_score.isdigit() and int(plyr_two_score) <= _r.cap()): # Type Conversion plyr_two_score = int(plyr_two_score) # Increment our Winner Count if(plyr_two_score == _r.cap()): winnerCount += 1 # Ensure we have one winner if(winnerCount == 1): # Get Player Objects p_one = next(( p for p in available_players if(p.name() == plyr_one)), None) p_two = next(( p for p in available_players if(p.name() == plyr_two)), None) # Ensure our Player's exist if(p_one and p_two): # Add this Match to the Round _m = Match.Match(_r, p_one, p_two, plyr_one_score, plyr_two_score) _r.add_match(_m) # Pop our players from the array del available_players[available_players.index(p_one)] del available_players[available_players.index(p_two)] # Save this match straight away self.handle_save_rounds(tournament) # Hold User input("Match ({0}) successfully added. Press <Return> to continue...\n".format(_m.versuses(True))) else: # Try Again tryAgainError = "The Players seize to exist within the available player list." tryAgain = True else: # Try Again tryAgainError = "A winner was not elected for this Match." if (winnerCount == 0) else "Matches cannot be left as a draw - only one player can win." tryAgain = True else: # Try Again tryAgainError = "The score entered for Player B ({0}) is invalid.".format(plyr_two_score) tryAgain = True else: # Try Again tryAgainError = "The player you entered ({0}) does not exist.".format(plyr_two) if plyr_two != plyr_one else "Player B cannot be the same as Player A." tryAgain = True continue else: # Try Again tryAgainError = "The score entered for Player A ({0}) is invalid.".format(plyr_one_score) tryAgain = True continue else: # Try Again tryAgainError = "The player you entered ({0}) does not exist.".format(plyr_one) tryAgain = True continue # Finalise the save to our tournament self.handle_save_rounds(tournament) except KeyboardInterrupt: # Clear Terminal call("cls") # Show user what happens when they restart print("You have tried to exit the program using Ctrl + C whilst inputting matches.", "\n") print("If you load previous rounds in your next session, you will be able to continue") print("from where you left off from this session.") # Exit Program Builder._app.exit() except Exception as err: # Clear Terminal call("cls") # Show user error print("An unknown error has occured:\n{0}".format(err)) traceback.print_exc() # Exit Program Builder._app.exit() return True
#!/usr/bin/python from os import system as call from os import chdir as cd from os import environ as env from getpass import getuser as user from sys import exit print 'Building map files...' cd(env['QIE10ROOT'] + '/src') call('./remap') print 'Building the analyzer core...' call('python generate.py') cd(env['QIE10ROOT']) print 'Compiling the analyzer...' call('scram b -j 8') print 'Analyzer compiled.' print 'Installion complete.'
def overall_view(self): # Menu Selection available_tournaments = [tn for tn in self.tournaments()] selected_tournaments = [] selected_gender = False all_selected = False # Handling error = False error_msg = "" # Pick gender while (not selected_gender): # Clear Terminal call("cls") print("What gender would you like to view?") print("{0}".format(", ".join([g for g in self.players()]))) gender_input = input(">>> ") if (gender_input in [g for g in self.players()]): selected_gender = gender_input # Show Options while (not all_selected): # Clear Terminal call("cls") # Show Error if (error): print("\nError:\n{}\n".format(error_msg)) error = False print("Select tournaments you would like to migrate together:") for i, tn in enumerate(self.tournaments(), 1): if (gender_input in self.tournament(tn).rounds()): if (len(self.tournament(tn).rounds()[gender_input]) == self.settings()["round_count"]): print("{0}. {1} ({2})".format( i, tn, ("Selected" if tn in selected_tournaments else "Not Selected"))) else: print( "{0}. {1} (Not Available, this tournament is incomplete at Round {2})" .format( i, tn, len( self.tournament(tn).rounds() [gender_input]))) else: print( "{0}. {1} (Not Available, this tournament has no data)" .format(i, tn)) print("b. Back") # Print Final if (len(selected_tournaments) > 0): print("\nv. View Overall Leaderboard for {1}".format( i + 1, (", ".join(selected_tournaments) if len(selected_tournaments) != 0 else "[None Selected]"))) # Debug resp = input(">>> ") if (resp.isdigit()): got = int(resp) if (got >= 1 and got <= len(self.tournaments())): # Get tournament name from index tn = [ tn for i, tn in enumerate(self.tournaments(), 1) if (got == i) ][0] # Check if gender is valid in round (handle empty data) if (gender_input in self.tournament(tn).rounds()): # Check if tournament is available if (len(self.tournament(tn).rounds()[gender_input]) == self.settings()["round_count"]): # Toggle state of selected tournament if (available_tournaments[got - 1] in selected_tournaments): del selected_tournaments[ selected_tournaments.index( available_tournaments[got - 1])] else: selected_tournaments.append( available_tournaments[got - 1]) else: error = True error_msg = "{0} is incomplete, therefore is unavailable.".format( tn) else: error = True error_msg = "{0} has no data, therefore is unavailable.".format( tn) else: error = True error_msg = "Please input a valid option" elif (resp == "v"): all_selected = True break elif (resp == "b"): return "SKIP" else: error = True error_msg = "Please input a valid option" # Find out the sorting method selected_order = None while (selected_order == None): # Clear Terminal call("cls") # Print out options print("How would you like to sort the leaderboard?") print("1. Name") print("2. Prize Money") print("3. Score") print("4. Wins") # Get input resp = input(">>> ") if (resp.isdigit()): resp_int = int(resp) selected_order = resp_int if (resp_int >= 1 and resp_int <= 4) else None break # Check if we have selected tournaments if (selected_order != None and all_selected and len(selected_tournaments) != 0): # Clear Terminal call("cls") # Assign our players temporary "total" values for p in self.players()[selected_gender]: # This will set (and reset) variables p._total_wins = 0 p._total_prize_money = 0 p._total_score = 0 p._total_score_multiplier = 0 # Process our leaderboard data players = [] for tn in self.tournaments(): # Debug if (self._app.debug): print("Process Tournament: {}".format(tn)) # Check our tournament is within our selected tournaments if (not tn in selected_tournaments): continue # Get our tournament t = self.tournament(tn) t.unique_prize_money() # Increase players data rnd_final_name = "round_{0}".format( self.settings()["round_count"]) rnd_final = t.round(selected_gender, rnd_final_name) # Debug if (self._app.debug): print("Processing '{0}' on {1}".format(rnd_final_name, tn)) # Sort the players srt = sort(self.players()[selected_gender], tn) place = 1 for i in reversed(range(len(srt))): # Increment Score score_increment = (srt[i].score(tn, rnd_final_name) if (srt[i].score(tn, rnd_final_name) != 0) else srt[i].highest_score(tn, False)) srt[i]._total_score += score_increment srt[i]._total_score_multiplier += int(score_increment * t.difficulty()) # Increment Prize Money money_increment = t._prize_money_unique[srt[i].wins(tn)] srt[i]._total_prize_money += money_increment # Increment Match Wins wins_increment = srt[i].wins(tn) srt[i]._total_wins += wins_increment if (self._app.debug): print( "[{0}] Score [{1} -> {2}] Money [{3} -> {4}] Wins [{5} -> {6}]" .format(srt[i].name(), score_increment, srt[i]._total_score, money_increment, srt[i]._total_prize_money, wins_increment, srt[i]._total_wins)) place += 1 # Set our header text selected_order_name = ("Name" if selected_order == 1 else ( "Prize Money" if selected_order == 2 else ("Score" if selected_order == 3 else ("Wins" if selected_order == 4 else None)))) if (selected_order_name != None): print("Selected Tournaments: {0} by '{1}'".format( ", ".join(selected_tournaments), selected_order_name)) print( "—————————————————————————————————————————————————————————" ) # Name overall_place = 1 if (selected_order == 1): for p in self.players()[selected_gender]: print( "{0} — Score: {1:03d} — Score (Multiplier): {4:03d} — Wins: {2:03d} — Money: £{3:,}" .format(p.name(), p._total_score, p._total_wins, p._total_prize_money, p._total_score_multiplier)) # Handle data sorting elif (selected_order >= 2 and selected_order <= 4): srt_overall = attr_sort( self.players()[selected_gender], selected_order_name.lower().replace(" ", "_")) for i in reversed(range(len(srt_overall))): # Print Data print( "#{0}: {1} — Score: {2:03d} — Score (Multiplier): {5:03d} — Wins: {3:03d} — Money: £{4:,}" .format(f"{overall_place:02}", srt_overall[i].name(), srt_overall[i]._total_score, srt_overall[i]._total_wins, srt_overall[i]._total_prize_money, srt_overall[i]._total_score_multiplier)) overall_place += 1 else: pass else: # Shouldn't ever get here... pass return None
import os # runs setup of base environment and database installs # create core conda env environment_yml = '%s/../%s.yml' % (os.__file__, 'environment') os.call('conda env create --name oecophylla -f %s' % environment_yml) #TODO change this to os.walk os.call('find oecophylla -name "*.sh" -execdir bash {} \;')
def clear_screen(self): call("cls")
def load_rounds(self, seasonId, error = False, errorMsg = None): # Get our Season Object season = self.get_season(seasonId) # Clear Terminal call("cls") # Was there an error? if(error): if(errorMsg != None): print("\nError:\n{0}\n".format(errorMsg)) else: print("\nError:\nThere was an error performing your request.\n") # Build Our Menu Builder.init(self.app, "How would you like to load the data for '{0}'?".format(season.name())) # Add Menus Builder.add_menu("main", "Empty Round Data", "empty_data") Builder.add_info("empty_data", "This will clear round data in 'seasons.json'.") Builder.add_menu("main", "Generate New Data", "gen_data") Builder.add_info("gen_data", "Generate new round data upto a specific round, this data is stored if the tournament saving flag is True") Builder.add_menu("main", "Load Previous Data", "load_data") Builder.add_info("load_data", "Loads previously saved round data from 'seasons.json'") # Add Functionality ## ROUNDS exit_while = False r = 0 while(not exit_while): # Increment our Round Number r += 1 round_still_exists = False # Check round exists built_arr = [] built_str = "" for gdr in season.players(): if(r <= season.settings()["{}_round_count".format(gdr)]): built_arr.append("{0} Round {1}".format(gdr.title(), r)) round_still_exists = True else: built_arr.append("{0} Round {1}".format(gdr.title(), season.settings()["{}_round_count".format(gdr)])) # Style our built string built_str = ", ".join(built_arr) # Do we have any more rounds? if(not round_still_exists): exit_while = True break # Build to our menu Builder.add_menu("gen_data", "Generate to {0}".format(built_str), "gen_data_{0}".format(r)) Builder.add_func("gen_data", "gen_data_{0}".format(r), partial(self.set_round_mode, season=seasonId, type="generate", rnd=r)) ## PREV DATA Builder.add_func("main", "empty_data", partial(self.set_round_mode, season=seasonId, type="empty")) Builder.add_func("main", "load_data", partial(self.set_round_mode, season=seasonId, type="load")) # Show Menu Builder.show_current_menu()
def build(platforms=None): os.call('npm install -g cordova ionic') os.call('ionic start myApp tabs') os.call('cd myApp') for platfrom in platforms or ['ios', 'android']: os.call('ionic platform add ' + platfrom) os.call('ionic platform build ' + platfrom) os.call('ionic platform emulate ' + platfrom)
def export(): os.call('ionic login') os.call('ionic upload')
def serve(): os.call('ionic serve')