示例#1
0
    def view_completed_tasks(self):
        """ Prints out the list of tasks completed by the robot. """

        clear_console()
        print('Tasks completed by {0}'.format(self))

        for i in self.tasks_completed:
            print('- ' + i)

        press_enter_to_continue()
        clear_console()
示例#2
0
    def __enter__(self):
        """ Load previous bots and run intro text when starting. """

        self._load()

        print("Welcome to the robot factory! You can create a robot to perform various tasks! And if one robot is not enough, you can create more!")
        print("Once created, robots are automatically assigned 5 random tasks which they will complete right away.")
        print("After they have finished their tasks you can decide to either create a new robot, destroy a robot (or all of them), or assign new tasks to existing robots.")
        press_enter_to_continue()
        clear_console()
        return self
示例#3
0
def main():
    options = parse_args()

    finder = Finder(options["inputfile"], options)
    try:
        clear_console()
        finder.find()
    except KeyboardInterrupt:
        print("Exiting...")
    finally:
        os.system("stty sane")
        if (finder.options["outputsummary"]):
            finder.output_summary()
示例#4
0
    def create_robot(self):
        """ Create a new robot based on user input for name and robot type. """

        clear_console()
        print('*** Entering robot creation room ***\n')
        robot_name = input("What is you robot's name?\n")

        # Some name validation, we want unique names so other robots are not lost/overwritten by new bots with the same name
        while not robot_name or robot_name in self.robots:
            clear_console()
            print("*** Sorry that name is not valid or is already taken, please try another. ***\n")
            robot_name = input("What is you robot's name?\n")

        clear_console()

        _, robot_class = get_user_choice(ROBOT_TYPE_CHOICES, 'What type of robot is {0}'.format(robot_name))

        try:
            robot = ROBOT_TYPES[robot_class](robot_name) # <- instantiate on the fly
        except KeyError:
            print('\n*** Leaving Robot Creation room ***\n')
        else:
            # Store new robots in class-level dict
            self.robots[robot_name] = robot
        finally:
            press_enter_to_continue()
            clear_console()
示例#5
0
    def destroy_a_robot(self):
        """ Destroys a robot based on it's name. """

        clear_console()
        print('*** Entering robot destruction room ***\n')

        # Nothing to do if no robots have been created yet
        if not self.robots:
            print("No robots to destroy, please create one first!")
            press_enter_to_continue()
            clear_console()
            return

        # Get user's robot-to-destroy choice
        _, robot_name = get_user_choice(self.robot_name_choices, 'Choose a robot to destroy.')

        try:
            robot = self.robots[robot_name]
        except KeyError:
            # Only occurs when 0: exit is selected or no robots exist yet
            print("\n*** Leaving robot destruction room ***\n")
        else:
            # Confirrm that the user actually wants to destroy the bot
            clear_console()
            if input('Type DESTROY if you are sre you want to destroy {0} (not case sensitive)\n'.format(robot)).upper() == 'DESTROY':
                del self.robots[robot_name]
                print('\n*** {0} has been destroyed! ***\n'.format(robot_name))
            else:
                print('\n*** {0} was NOT destroyed! ***\n'.format(robot_name))
        finally:
            press_enter_to_continue()
            clear_console()
示例#6
0
def report():

    while True:

        s = '\n'
        for E, i in indices.items():

            status = 'alive' if processes[i].is_alive() else 'dead '
            action = 'shutdown' if processes[i].is_alive() else 'start   '

            s += f'Server {i}: Port: {ports[i]} Status: {status}, To {action} Server {i} Enter: {E} \n'

        utils.clear_console()
        print(s, end='\n\n>>')
        time.sleep(interval)
示例#7
0
    def interact_with(self):
        """ Allows the user to interact with the robot by listing out interaction options. """

        while True:  # Break when users chooses to '0: Leave'
            clear_console()
            print("*** Interacting with {0} ***\n".format(self))

            # Get the user's interaction choice
            _, action_choice = get_user_choice(
                self.interaction_choices,
                'What would you like to do with {0}'.format(self))

            try:
                self.interactions[action_choice]()
            except KeyError:
                pass  # Could break here instead as only hits when '0: Leave' is chosen

            if action_choice == 'Leave':
                break
示例#8
0
    def get_task_to_perform(self):
        """ Allows the user to choose a task to perform"""

        clear_console()
        # Get the user's task choice
        _, task_choice = get_user_choice(
            self.all_task_choices,
            'Which task would you like {0} to perform?'.format(self))

        # Rest self.msg as it is very likely it was previously changed
        self.msg = ''

        # Actually perform the chosen task
        self.perform_task(task_choice)

        print("\n*** Task finished! ***\n")

        press_enter_to_continue()
        clear_console()
示例#9
0
def report():

    while True:
        to_print = '\n'
        for i, socket in enumerate(down):

            d = down[socket]
            t = total[socket]
            s = speed[socket]

            to_print += f'Server {i}: {d:8d} / {t:8d},\t downloaad speed: {s:.2f} kb/s\n'

        s = sum(speed.values())
        d = sum(down.values())
        t = sum(total.values())

        to_print += f'\nTotal: {d} / {t}, Download speed: {s:.2f} kb/s'

        utils.clear_console()
        print(to_print)
        time.sleep(interval)
示例#10
0
    def view_robot_leaderboard(self):
        """ Sorts all robots by number of tasks completed and prints out the results. """

        clear_console()

        # Nothing to do if no robots have been created yet
        if not self.robots:
            print("There are no robots! Please create one first")
            press_enter_to_continue()
            clear_console()
            return

        # Create a list tuples consisting of robots and the number of tasks completed by each
        leaderboard_list = [(bot, len(bot.tasks_completed)) for bot in list(self.robots.values())]

        # Sort by most tasks completed
        leaderboard_list = sorted(leaderboard_list, key=lambda x: -x[1])

        # Printed out in a table-like view
        print("*** Leaderboard for tasks completed by each robot ***\n")
        print("Tasks | Robot")
        print("------|----------")
        for robot, num_tasks_completed in leaderboard_list:
            spaces = 4 - len(str(num_tasks_completed))
            print("{0}{1}  | {2}".format(' ' * spaces, num_tasks_completed, robot))

        press_enter_to_continue()
        clear_console()
示例#11
0
    def interact_with_robot(self):
        """ Allows for interaction with a robot."""

        clear_console()
        print('*** Entering robot interaction room ***\n')

        # Nothing to do if no robots have been created yet
        if not self.robots:
            print("No robots to interact with, please create one first!")
            press_enter_to_continue()
            clear_console()
            return

        # Get user's robot-to-interact-with choice
        _, robot_name = get_user_choice(self.robot_name_choices, 'Choose a robot to interact with.')

        try:
            bot = self.robots[robot_name]
        except KeyError:
             # Only occurs when 0: exit is selected or no robots exist yet
            print('\n*** Leaving Robot Interaction room ***\n')
        else:
            bot.interact_with()
        finally:
            press_enter_to_continue()
            clear_console()
示例#12
0
    def perform_task(self, task):
        """ Performs a single given task, could leverage the self._current task here if we do not want to pass in the task as a param. """

        try:  # Attempt to get the task, then perform the task by sleeping for the listed eta duration
            # Get the task eta/duration and convert to seconds for sleep()
            eta = int(self.all_tasks[task] / 1000)
        except KeyError:
            pass  # Will only occur when '0: Leave' is chosen
        else:
            self.msg += '\nPerforming task: {0}, it will take approximately {1} seconds'.format(
                task, eta)
            self._current_task = task

            # Clear the console and update the message each iteration to give the impression of ... loading
            for _ in range(eta):
                clear_console()
                self.msg += '.'
                print(self.msg)
                sleep(1)

            # Save the task to completed_tasks list
            self.save_finished_task(task)
示例#13
0
def run_session():
    clear_console(
    )  # <- clears the console, makes following prompts and information easier

    # Factory used as a context manager to ensure load and save methods are run
    with RobotFactory() as rf:

        # Choices from ACTION_CHOICES above mapped to actual methods
        actions_map = {
            'Create a new robot': rf.create_robot,
            'Interact with a robot': rf.interact_with_robot,
            'Destroy a robot': rf.destroy_a_robot,
            'Destroy all robots': rf.destroy_all_robots,
            'View robot task leaderboard': rf.view_robot_leaderboard,
            # Exit' is not mapped so that it passes choice validation and still exits
        }

        # Primary user interaction loop runs until a user chooses to exit
        while True:
            # Below function gets user input based on dict of choices
            _, choice = get_user_choice(ACTION_CHOICES,
                                        'What would you like to do?')

            try:
                actions_map[choice]()  # <- Call the method on the fly
            except KeyError:
                clear_console()
                pass  # Only hits KeyError if '0' : Exit is chosen

            if choice == 'Exit':
                # Have user confirm exit with case insensitve typed input
                if input(
                        'Type EXIT to quit if you are sure you want to leave.\n'
                ).upper() == 'EXIT':
                    clear_console()
                    break

        print('\n*** You are now leaving the robot factory! ***\n')
    print('\n*** Your robots have been saved, goodbye! ***\n')
示例#14
0
    def destroy_all_robots(self):
        """ Destroy all currently existing robots in this container. """

        clear_console()
        print('*** Entering super serious robot destruction room ***\n')

        # Nothing to do if no robots have been created yet
        if not self.robots:
            print("No robots to destroy, please create one first!")
            press_enter_to_continue()
            clear_console()
            return

        # Get user confirmation to actually destroy all robots
        if input('Type DESTORY if you are sure you want to destroy ALL robots (not case sensitive)\n').upper() == 'DESTROY':
            self.robots = {}
            print("\n*** All robots have been destroyed! ***\n")
        else:
            print("\n*** Robots were NOT destroyed! ***\n")

        print("\n*** Leaving robot destruction room ***\n")
        press_enter_to_continue()
        clear_console()
示例#15
0
def network_test():
    """
    Test the network connectivity. Focus on the Google services that
    will be used in the program. If the connectivity test fails, will
    warn the user.
    """

    print("Testing network connectivity...")
    test_fund_code = "161725"

    def can_fetch_fund_data():
        print("Testing fund data APIs...")
        response_time = 0
        try:
            for url in [FUND_DATA_URL, STOCK_DATA_URL, NET_VALUE_URL]:
                response = requests.get(url.format(test_fund_code, None))
                if not str(response.status_code).startswith("2"):
                    raise ConnectionError("Failed to connect to {}".format(url.format(test_fund_code, None)))
                response_time += response.elapsed.total_seconds()
            print("Average time delay: {:.3f}s".format(response_time / 3))
            return True
        except Exception as exception:
            print("Failed to fetch fund data, please check network connectivity: {}".format(exception))
        return False

    def can_fetch_news_articles():
        print("Testing connection to news articles...")
        response_time = 0
        try:
            for url in [TEST_URL_1, TEST_URL_2, TEST_URL_3]:
                response = requests.get(url)
                if not str(response.status_code).startswith("2"):
                    raise ConnectionError("Failed to connect to {}".format(url))
                response_time += response.elapsed.total_seconds()
            print("Average time delay: {:.3f}s".format(response_time / 3))
            return True
        except Exception as exception:
            print("Failed to fetch news articles, please check network connectivity: {}".format(exception))
            return False

    def can_connect_to_google_services():
        print("Testing connection to Google services...")
        response_time = 0
        try:
            api_key = os.environ["API_KEY"]
            payload = open(REQUEST_TEST_FILE, "rb")
            headers = {'content-type': 'application/json'}
            response = requests.post(GOOGLE_LANGUAGE_API.format(api_key), data=payload, headers=headers)
            if not str(response.status_code).startswith("2"):
                raise ConnectionError("Failed to connect to Google natural language api")
            response_time += response.elapsed.total_seconds()

            response = requests.get("http://www.google.com/search?q=test")
            if not str(response.status_code).startswith("2"):
                raise ConnectionError("Failed to fetch query results from Google")
            response_time += response.elapsed.total_seconds()
            print("Average time delay: {:.3f}s".format(response_time / 2))
            return True
        except KeyError:
            print("Please add your google API key to the list of environment variables, "
                  "'predict' functionality is disabled...")
        except Exception as exception:
            print("Failed to connect to Google services: {}".format(exception))
        return False

    if not all([can_fetch_fund_data(), can_fetch_news_articles(), can_connect_to_google_services()]):
        print("Network connectivity test failed...")
    else:
        clear_console()
        print("Network connection stable...")