Esempio n. 1
0
def turn_page(Statement):
    Statement = Statement.split()
    ops = PageOps(Statement)
    options = [
        ("n", "Next Verse", ops.do_next_page),
        ("p", "Previous Verse", ops.do_last_page),
        ("q", "Quit Classic Verse", say_done),
    ]
    do_menu("Verse Ref", "Option = ", options, "%")
def main():
    # Get a list of plotter.plot()'s exported functions (values from the dict)
    plot_functions = list(plotter.plot().values())
    # Get the plot() function's signature (arguments list)
    plot_signature = str(inspect.signature(plotter.plot))
    # Get the functions's names, signatures, and their docstring comments
    plot_function_names = []
    plot_function_signatures = []
    plot_function_docs = []
    for plot_function in plot_functions:
        # I'm formatting the function identifiers to look like dict keys:
        plot_function_names.append('[\'' + plot_function.__name__ + '\']')
        plot_function_signatures.append(str(inspect.signature(plot_function)))
        plot_function_docs.append(plot_function.__doc__)
    # Kill the tkinter window that plotter.plot() created.
    # (The 5th function in the dict, plot_functions[4], is an alias for
    # destroy().)
    plot_functions[4]()

    while True:
        choice = menu.do_menu('Choose one to see its description:', [
            'Module plotter (plotter.py)', 'Function plotter.plot',
            'Functions returned by plotter.plot'
        ])
        if choice is None:  # Exit choice
            break  # out of program loop
        if choice == 1:
            print('\nModule plotter:')
            print(plotter.__doc__)
        elif choice == 2:
            print()
            plot_header = 'Function plot' + plot_signature
            print(
                textwrap.fill(plot_header,
                              initial_indent='',
                              subsequent_indent='    '))
            print('\n' + my_dedent(plotter.plot.__doc__))
        elif choice == 3:  # Present submenu of functions returned by plot()
            while True:
                choice = menu.do_menu(('Choose a function returned by '\
                                       'plotter.plot() to see its description:'),
                                      plot_function_names)

                if choice is None:  # Exit choice
                    break  # out of inner loop

                print()
                plot_function_header = 'Function ' + \
                                       plot_function_names[choice-1] + \
                                       plot_function_signatures[choice-1]
                print(
                    textwrap.fill(plot_function_header,
                                  initial_indent='',
                                  subsequent_indent='    '))
                print()
                print(my_dedent(plot_function_docs[choice - 1], trim_limit=8))
Esempio n. 3
0
def do_lookups():
    """ Ways to lookup books & verses """
    options = [
        ("l", "List Books", do_list),
        ("c", "Classic book:chapter:verse", do_book_cv),
        ("s", "Sierra #", do_book_vnum),
        ("r", "Read From", do_read_from),
        ("b", "Manage Bookmarks", do_read_bkmrk),
        ("q", "Quit", say_done),
    ]
    do_menu("Find Verse", "Option = ", options, "?")
Esempio n. 4
0
 def display_options(self):
     options = [
         ("a", "lnup", self.do_lineadv),
         ("z", "pgup", self.do_pageadv),
         ("s", "lndn", self.do_linedec),
         ("x", "pgdn", self.do_pagedec),
         ("g", "goto", self.do_goto),
         ("q", "Quit Program", quit),
     ]
     self.do_display()
     do_menu("Main Menu", "Option = ", options, "#")
     self.EndOfPage()
Esempio n. 5
0
 def begin(self):
     val = do_menu("What would you like to do (-1 for quitting) ",  self.__initial_options)
     if(val == 0):
         self.create_survey()
         self.add_questions_to_survey()
     else:
         self.goodbye()
Esempio n. 6
0
def hack(screen):
    if do_menu(screen) == 1:
        world = read("world")
    else:
        world = make_world()
    write(world, "world")
    main(screen, world)
Esempio n. 7
0
 def add_questions_to_survey(self):
     val = -1
     while val != -2:
         questions = get_questions()
         val = do_menu("Choose a question to add (-1 for new questions -2 to finish) ", questions, -2)
         if(val == -1):
             self.create_question_version()
         elif(val >= 0):
             self.add_question(questions[val])
Esempio n. 8
0
 def create_question(self, question_version_id):
     response_id = -1
     while response_id == -1:
         question = input("What is the prompt for your question? (-1 for same)")
         if question == "-1":
             question = self.__current_question_version_name
         question_type = self.__question_type[do_menu("What type of question ", self.__question_type, 0)]
         health_data = True if do_menu("Is there sleep data? ", ["No", "Yes"], False) == 1 else  False
         answer = []
         key = 0
         if input("Would you like your answers to just be Yes / No? (y is you want this)") == 'y':
             answer = ['Yes', 'No']
         else:
             while key != "-1":
                 key = input("Provide a value ")
                 answer.append(key)
         if input(f"You are going to insert a questions {question} with answer {answer} with type {question_type} and health data {health_data} are you sure (-1 for no)") == "-1":
             continue
         response_id = insert_question(question, str(answer), question_type, question_version_id, health_data)    
Esempio n. 9
0
 def add_question(self, val):
     survey_id = self.__survey_id
     question_id = val[0]
     last_question = self.__last_question_id
     category = ""
     category_num = do_menu("Pick a category (-1 to make new category) ", self.__categories)
     if(category_num == -1):
         self.__categories.append(input("Make a new category "))
         category = self.__categories[-1]
     else:
         category = self.__categories[category_num]
     if input(f"Are you sure you want to add question to survey {survey_id}, {question_id}, {last_question}, {category}? (-1 to not)") == "-1":
         return
     self.__last_question_id = insert_survey_question(survey_id, question_id, last_question, category)
Esempio n. 10
0
    def create_question_version(self):
        question_versions = get_question_versions()
        question_version_names = get_items_of_index(question_versions, 1)
        val = do_menu("Choose a question version (-1 to make a new one) ", question_version_names)
        question_version_id = -1
        if(val == -1):
            while question_version_id == -1:
                version_name = input("What do you want to name your question? ")
                self.__current_question_version_name = version_name
                question_version_id = insert_question_version(version_name)
        else:
            question_version_id = question_versions[val][0]
            self.__current_question_version_name = question_versions[val][1]

        self.create_question(question_version_id)
Esempio n. 11
0
    def create_survey(self, dont_use = ""):
        survey_items_total = get_survey_versions()
        survey_items = get_items_of_index(survey_items_total, 1)
        val = do_menu("What survey version would you like to base this off of (-1 for making new survey version) ", survey_items)
        if val == -1:
            self.__survey_version_id = self.create_survey_version()
        else:
            self.__survey_version_id = survey_items_total[val][0]
            self.__current_survey_version_name = survey_items_total[val][1]
            self.__current_question_version_description = survey_items_total[val][2]

        ret_val= -1
        while(ret_val == -1):
            print("Now to make the actual survey; (-1 to use same) ")
            survey_name = input("Give a survey name ")
            if survey_name == "-1":
                survey_name = self.__current_survey_version_name
                description = self.__current_survey_version_description
                ret_val = insert_survey(survey_name, description, self.__survey_version_id)
            else:  
                description = input("Give a survey description ")
                ret_val = insert_survey(survey_name, description, self.__survey_version_id)
        self.__survey_id = ret_val
        return ret_val
Esempio n. 12
0
def main():
    """Program execution starts here."""
    url = "http://sites.cs.queensu.ca/courses/cisc121/a2/logons.txt"
    data = web_scraper.scrape(url)
    n = len(data)
    data = parse_logons.logons_to_list_of_dicts(data)
    # The data list (and the file it came from) are in chronological
    # order. That means data is currently sorted by timestamp.
    sort_on_key = "timestamp"

    main_menu_title = "Select an operation:"
    main_menu_choices = [
        "Sort logons data", "Show a selection of the data",
        f"Search for a particular {sort_on_key}"
    ]

    sort_on_menu_title = "Select a key to sort on:"
    sort_on_menu_choices = list(data[0].keys())

    sort_menu_title = "Select a sort algorithm:"
    sort_menu_choices = [
        "Insertion sort", "Bubble sort", "Bubble sort (optimized)",
        "Selection sort"
    ]

    while True:
        choice = menu.do_menu(main_menu_title, main_menu_choices)
        if choice is None:
            return  # Exit main() (and program).
        if choice == 1:  # Sort logons data.
            while True:
                sort_on_choice = menu.do_menu(sort_on_menu_title,
                                              sort_on_menu_choices)

                if sort_on_choice is None:
                    break  # Return to main menu.
                sort_on_key = sort_on_menu_choices[sort_on_choice - 1]
                # Change last choice in main menu to reflect the new
                # sort_on_choice.
                main_menu_choices[
                    -1] = f"Search for a particular {sort_on_key}"

                sort_choice = menu.do_menu(sort_menu_title, sort_menu_choices)
                if sort_choice is None:
                    break  # Return to main menu.

                # If we're here, we can proceed with a sort.
                print()
                if sort_choice == 1:  # Insertion sort
                    sort_function = dict_quad_sorts.insertion_sort
                elif sort_choice == 2:  # Bubble sort
                    sort_function = dict_quad_sorts.bubble_sort
                elif sort_choice == 3:  # Bubble sort (opt)
                    sort_function = dict_quad_sorts.bubble_sort_opt
                else:  # Selection sort
                    sort_function = dict_quad_sorts.selection_sort

                # Do the sort.
                print(f"Sorting on key '{sort_on_key}'...")
                sort_function(data, sort_on_key)
                print("Done.")

                # Show it worked.
                long_list_printer.print_list(data, 5)

        elif choice == 2:  # Show a selection of the data.
            long_list_printer.print_list(data, 10)

        elif choice == 3:  # Search for a specific value.
            search_val = input(f"\nSearch for what {sort_on_key}? ")
            found_at = dict_bin_search.search(data, sort_on_key, search_val)
            if found_at is None:
                print(f"{sort_on_key} {search_val} not found.")
            else:
                print(f"{sort_on_key} {search_val} found at position "\
                      f"{found_at}.")
def main():
    # Set up main menu and sub-menus.
    main_menu_choices = ["Temperatures", "Distances", "Weights"]
    temperatures_menu_choices = [
        "Celsius to Fahrenheit", "Fahrenheit to Celsius", "Celsius to Kelvin",
        "Kelvin to Celsius", "Fahrenheit to Kelvin", "Kelvin to Fahrenheit"
    ]
    distances_menu_choices = [
        "Miles to Kilometres", "Kilometres to Miles", "Feet to Metres",
        "Metres to Feet", "Inches to Centimetres", "Centimetres to Inches"
    ]
    weights_menu_choices = [
        "Tons to Tonnes", "Tonnes to Tons", "Pounds to Kilograms",
        "Kilograms to Pounds", "Ounces to Grams", "Grams to Ounces"
    ]

    # Loop until user wants to quit.
    while True:
        # Declare main menu
        choice = menu.do_menu("Choose a conversion type:", main_menu_choices)
        if choice is None:  # Did the user choose "Exit?"
            break  # Yes, then exit.
        if choice == 1:  # User chose temperature conversions.
            while True:  # Loop until user wants to return to the main menu.
                choice = menu.do_menu("Choose a temperature conversion",
                                      temperatures_menu_choices)
                if choice is None:
                    break
                if choice is 1:  # Celsius to Fahrenheit chosen.
                    cels = get_int.input_int("\nDegrees Celsius: ")
                    print((f"\n{cels} degrees Celsius is "
                           f"{cels_to_fahr(cels):.1f} "
                           "degrees Fahrenheit."))
                if choice is 2:  # Fahrenheit to Celsius chosen.
                    fahr = get_int.input_int("\nDegrees Fahrenheit: ")
                    print((f"\n{fahr} degrees Fahrenheit is "
                           f"{fahr_to_cels(fahr):.1f} "
                           "degrees Celsius."))
                if choice is 3:  # Celsius to Kelvin chosen.
                    cels = get_int.input_int("\nDegrees Celsius: ")
                    print((f"\n{cels} degrees Celsius is "
                           f"{cels_to_kelv(cels):.1f} "
                           "Kelvin."))
                if choice is 4:  # Kelvin to Celsius chosen.
                    kelv = get_int.input_int("\nKelvin: ")
                    print((f"\n{kelv} Kelvin is "
                           f"{kelv_to_cels(kelv):.1f} "
                           "degrees Celsius"))
                if choice is 5:  # Fahrenheit to Kelvin chosen.
                    fahr = get_int.input_int("\nDegrees Fahrenheit: ")
                    print((f"\n{fahr} degrees Fahrenheit is "
                           f"{fahr_to_kelv(fahr):.1f} "
                           "Kelvin."))
                else:  # Kelvin to Fahrenheit chosen.
                    kelv = get_int.input_int("\nKelvin: ")
                    print((f"\n{kelv} Kelvin is "
                           f"{kelv_to_fahr(kelv):.1f} "
                           "degrees Fahrenheit."))

        if choice == 2:  # User chose distance conversions.
            while True:  # Loop until user wants to return to the main menu.
                choice = menu.do_menu("Choose a distance conversion",
                                      distances_menu_choices)
                if choice is None:
                    break
                if choice is 1:  # Miles to Kilometres chosen.
                    miles = get_int.input_int("\nMiles: ")
                    print((f"\n{miles} miles is "
                           f"{miles_to_kiloms(miles):.1f} "
                           "kilometres."))
                if choice is 2:  # Kilometres to Miles chosen.
                    kiloms = get_int.input_int("\nKilometres: ")
                    print((f"\n{kiloms} kilometres is "
                           f"{kiloms_to_miles(kiloms):.1f} "
                           "miles."))
                if choice is 3:  # Feet to Metres chosen.
                    feet = get_int.input_int("\nFeet: ")
                    print((f"\n{feet} feet is "
                           f"{feet_to_metres(feet):.1f} "
                           "metres."))
                if choice is 4:  # Metres to Feet chosen.
                    metres = get_int.input_int("\nMetres: ")
                    print((f"\n{metres} metres is "
                           f"{metres_to_feet(metres):.1f} "
                           "feet."))
                if choice is 5:  # Inches to Centimetres chosen.
                    ins = get_int.input_int("\nInches: ")
                    print((f"\n{ins} inches is "
                           f"{inches_to_centims(ins):.1f} "
                           "centimetres."))
                else:  # Centimetres to Inches chosen.
                    cms = get_int.input_int("\nCentimetres: ")
                    print((f"\n{cms} Kelvin is "
                           f"{centims_to_inches(cms):.1f} "
                           "inches."))

        if choice == 3:  # User chose weight conversions.
            while True:  # Loop until user wants to return to the main menu.
                choice = menu.do_menu("Choose a weight conversion",
                                      weights_menu_choices)
                if choice is None:
                    break
                if choice is 1:  # Tons to Tonnes chosen.
                    tons = get_int.input_int("\nTons: ")
                    print((f"\n{tons} tons is "
                           f"{tons_to_tonnes(tons):.1f} "
                           "tonnes."))
                if choice is 2:  # Tonnes to Tons chosen.
                    tonnes = get_int.input_int("\nTonnes: ")
                    print((f"\n{tonnes} tonnes is "
                           f"{tonnes_to_tons(tonnes):.1f} "
                           "tons."))
                if choice is 3:  # Pounds to Kilograms chosen.
                    lbs = get_int.input_int("\nPounds: ")
                    print((f"\n{lbs} pounds is "
                           f"{pounds_to_kgrams(lbs):.1f} "
                           "kilograms."))
                if choice is 4:  # Kilograms to Pounds chosen.
                    kgs = get_int.input_int("\nKilograms: ")
                    print((f"\n{kgs} kilograms is "
                           f"{kgrams_to_pounds(kgs):.1f} "
                           "pounds."))
                if choice is 5:  # Ounces to Grams chosen.
                    oz = get_int.input_int("\nOunces: ")
                    print((f"\n{oz} ounces is "
                           f"{ounces_to_grams(oz):.1f} "
                           "grams."))
                else:  # Grams to Ounces chosen.
                    grams = get_int.input_int("\nGrams: ")
                    print((f"\n{grams} grams is "
                           f"{grams_to_ounces(grams):.1f} "
                           "ounces."))
Esempio n. 14
0
def main():
    while True:  # main menu while loop
        # Do menu choices
        user_choice = menu.do_menu("Main Menu", ["Generate sort time files", "Plot average sort times"])
        if user_choice is None:
            break  # exit choice

        print('\nValid choice:', user_choice)

        if user_choice == 1:  # first menu choice - generate tests
            while True:  # Sub menu
                user_choice = menu.do_menu("Select a sort",
                                           ["Bubble sort",
                                            "Insertion Sort",
                                            "Optimized bubble sort",
                                            "Selection sort"])
                if user_choice is None:
                    break  # exit choice
                print('\nValid choice:', user_choice)

                if user_choice == 1:  # Generating test files  for bubble sort
                    # Calling the data test function to generate the csv file
                    print("\nGenerating test files.. for " + counting_quad_sorts.bubble_sort.__name__)
                    collect_function_performance_data.test_function(counting_quad_sorts.bubble_sort, MAX_N, NUM_TESTS)
                    print("\n" + counting_quad_sorts.bubble_sort.__name__ + ".csv generated")


                elif user_choice == 2:  # Generating test files  for insertion sort
                    # Calling the data test function to generate the csv file
                    print("\nGenerating test files.. for " + counting_quad_sorts.insertion_sort.__name__)
                    collect_function_performance_data.test_function(counting_quad_sorts.insertion_sort, MAX_N,
                                                                    NUM_TESTS)
                    print("\n" + counting_quad_sorts.insertion_sort.__name__ + ".csv generated")

                elif user_choice == 3:  # Generating test files for optimized bubble sort
                    # Calling the data test function to generate the csv file
                    print("\nGenerating test files.. for " + counting_quad_sorts.opt_bubble_sort.__name__)
                    collect_function_performance_data.test_function(counting_quad_sorts.opt_bubble_sort, MAX_N,
                                                                    NUM_TESTS)
                    print("\n" + counting_quad_sorts.opt_bubble_sort.__name__ + ".csv generated")


                elif user_choice == 4:  # Generating test files for selection sort
                    # Calling the data test function to generate the csv file
                    print("\nGenerating test files.. for " + counting_quad_sorts.selection_sort.__name__)
                    collect_function_performance_data.test_function(counting_quad_sorts.selection_sort, MAX_N,
                                                                    NUM_TESTS)
                    print("\n" + counting_quad_sorts.selection_sort.__name__ + ".csv generated")



        elif user_choice == 2:  # 2nd menu choice plot average sort times
            # n num of choices
            while True:  # Sub menu
                file_path = file_chooser.get_file_path_and_name(pattern='*.csv')  # file_path is a list of the csv files
                if file_path is None:
                    break  # exit choice

                if file_path != None:  # if there exists a file(s) in file_path
                    print('Path:', file_path[0])  # display its path
                    print('File:', file_path[1])
                    print('Both:', file_path[0] + "\\" + file_path[1])
                    print("\nCalculating Averages for " + file_path[1])

                    # Calculates the column averages for that particular csv file
                    col_avg = file_column_averages.get_file_column_averages(file_path[1])

                    print("\n Plotting Graph: " + file_path[1][:len(file_path[1]) - 4])

                    # Plotting the graph of the averages

                    # Setting up graph
                    plot_graph = plotter.plot(title=file_path[1][:len(file_path[1]) - 4],
                                              origin_x=15,
                                              origin_y=15,
                                              scale_x=6,
                                              scale_y=0.11,
                                              bg='darkseagreen1')

                    plot_graph['draw_axes'](tick_length=4, tick_interval_y=100)  # set up axes

                    # Plot each point by for loop
                    for x in range(len(col_avg)):
                        plot_graph['plot_point'](x, col_avg[x], 6
                                                 , colour='red')  # color red

                    # the n^2/2 function, commented out
                    # plot_graph['plot_function'](lambda x: (x ** 2) / 2 if x >= 0 else None)
                    # plot_graph['put_text']('T(n) = n^2/2', x=70, y=150, size=12, colour='black')

                    # Labels T (100s), n, legend, t(n) = filename
                    plot_graph['put_text']('T\n(100s)', 2, 5500, size=9, colour='Black')
                    plot_graph['put_text']('n', 100, 100, size=9, colour='Black')
                    plot_graph['put_text']('Legend:', x=70, y=450, size=12, colour='blue')
                    plot_graph['put_text']('T(n) = ' + file_path[1][:len(file_path[1]) - 4], x=70, y=300, size=12,
                                           colour='red')

                    plot_graph['block']()  # Module exits when user closes the canvas window.
Esempio n. 15
0
def main():
	"""Program execution starts here."""
	intersections = read_intersections("intersections.data")
	intersection_list = []
	
	for i in range(len(intersections)):
		intersection_list.append(intersections[i]['name'].strip(' '))
		
	#sel_intersection = intersections[0]['name']
	sel_intersection = "4589"

	df = get_dataset(sel_intersection, intersections)
	x_train, x_test, y_train, y_test = preprocessing(df)

	model_file = search(intersections, 'name', sel_intersection)

	main_menu = [
		"CAPSTONE TRAFFIC PREDICTION",

		"Select Intersection",
		"List of Intersections",
		"Train Intersection",
		"Test Intersection (Accuracy)",
		"Route Check"
	]
	train_menu = [
		"Train Mode:",

		"Train from scratch w/ events",
		"Train from file w/ events",
		"Train from scratch",
		"Train from file",
	]
	route_check_menu = [
		"Train Mode:",

		"Train from scratch w/ events",
		"Train from file w/ events",
		"Train from scratch",
		"Train from file",
	]

	while True:
		print("Currently Selected Intersection:", sel_intersection)
		choice = menu.do_menu(main_menu)
		model = LSTMModel(x_train.shape[1], y_train.shape[1])
		if choice is None:
			return  # Exit main() (and program).
		if choice == 1:
			# Select Intersection
			temp_menu = ["Please Select a New Intersection"]

			for line in intersections:
				option = line["name"] + ": " + line["street"]
				temp_menu.append(option)

			choice = menu.do_menu(temp_menu)
			if choice is not None:
				sel_intersection = intersections[choice - 1]['name']
				print(sel_intersection, "set as current intersection.")

				df = get_dataset(sel_intersection, intersections)
				x_train, x_test, y_train, y_test = preprocessing(df)

				model_file = search(intersections, 'name', sel_intersection)
				if model_file is not None:
					model_file = intersections[model_file]['model']
					#try:
					model.load_network('./model/'+str(sel_intersection)+'.hdf')
					#except:
					#	print("File for loading model is not found! Creating a new model from scratch")
					#	model.init_network(hidden_size=50)

		elif choice == 2:
			# List Intersections
			print_intersections(intersections)
		elif choice == 3:
			model = LSTMModel(x_train.shape[1], y_train.shape[1])
			# Train Intersections
			# TODO test each option
			choice = menu.do_menu(train_menu)
			if choice == 1:
				x_train, x_test, y_train, y_test = preprocessing(df, events=True)
				model = LSTMModel(x_train.shape[1], y_train.shape[1])

				intersection_idx = search(intersections, 'name', sel_intersection)
				model_file = "model/" + sel_intersection + ".hdf"
				#if os.path.exists(model_file):
					#os.remove(model_file)
				model.init_network(hidden_size=50)
			elif choice == 2:
				x_train, x_test, y_train, y_test = preprocessing(df, events=True)
				model = LSTMModel(x_train.shape[1], y_train.shape[1])

				intersection_idx = search(intersections, 'name', sel_intersection)
				model_file = "model/" + sel_intersection + ".hdf"
				if os.path.exists(model_file):
					model.load_network(model_file)
				else:
					print("Model does not exist, starting from scratch")
					model.init_network(hidden_size=50)
			elif choice == 3:
				x_train, x_test, y_train, y_test = preprocessing(df, events=False)
				model = LSTMModel(x_train.shape[1], y_train.shape[1])

				intersection_idx = search(intersections, 'name', sel_intersection)
				model_file = "model/" + sel_intersection + ".hdf"
				if os.path.exists(model_file):
					os.remove(model_file)
				model.init_network(hidden_size=50)
			elif choice == 4:
				x_train, x_test, y_train, y_test = preprocessing(df, events=False)
				model = LSTMModel(x_train.shape[1], y_train.shape[1])

				intersection_idx = search(intersections, 'name', sel_intersection)
				model_file = "model/" + sel_intersection + ".hdf"
				if os.path.exists(model_file):
					model.load_network(model_file)
				else:
					print("Model does not exist, starting from scratch")
					model.init_network(hidden_size=50)
			try:
				e = int(input("Enter Epochs to train for (Default=50): "))
				model.epochs = e
			except ValueError:
				print("Invalid number entered, using default value")
			model.train(x_train, y_train, './'+ model_file)

			intersections[intersection_idx]['model'] = model_file
			save_intersections(intersections, "intersections.data")

		elif choice == 4:
			# Test Intersections
			model_file = "model/" + sel_intersection + ".hdf"
			model = LSTMModel(x_train.shape[1], y_train.shape[1])
			if os.path.exists(model_file):
				model.load_network(model_file)
				test_output = model.get_accuracy(x_test, y_test)
				N, S, E, W = confusion_matrix(test_output, y_test, True)
			else:
				print("Please train intersection first")

		elif choice == 5:
			model = LSTMModel(x_train.shape[1], y_train.shape[1], intersection_list)
			# Route Check
			x_data = []
			day_week = [1,2,3,4,5,6,7]
			season=[1,2,3,4]
			time_str = ''
			flag = 0
			x_data = []
			peak = 0

			while flag == 0:
				num_inter = input("Please enter intersection number: ")
				if num_inter in intersection_list:
					flag = 1
					num_inter = int(num_inter)
					#x_data.append(int(num_inter))
				else:
					print("Intersection not found!")
					
			flag = 0
			while flag == 0:
				week = [0,0,0,0,0,0,0]
				num_day = input("Please enter the day of the week:\nOptions:\n1:Sunday\n2:Monday\n3:Tuesday\n4:Wednesday\n5:Thursday\n6:Friay\n7:Saturday\n")
				num_day = int(num_day)
				if num_day in day_week:
					flag = 1
					week[num_day-1] = 1
					x_data = x_data + week
				else:
					print("Day of the week not found!")
			
			flag = 0
			while flag == 0:
				time_day = input("Please enter the time of the day (ex. 17:30): ")
				temp = time_day.split(':')
				if len(temp) == 2:
					hour = int(temp[0]) * 60
					if hour > 9 and hour < 17:
						peak = 1
					time = hour + int(temp[1])
					time_d = float(time) / float(1440)
					if time_d > 1.0:
						print("Please enter time in the proper format!")
					else:
						x_data.append(time_d)
						flag = 1
				else:
					print("Please enter time in the proper format!")
			
			flag = 0
			while flag == 0:
				seasons = [0,0,0,0]
				season_input = input("Please enter the season:\n1:Summer\n2:Fall\n3:Winter\n4:Spring\n")
				season_input = int(season_input)
				
				if season_input in season:
					flag = 1
					seasons[season_input-1] = 1
					x_data = x_data + seasons
				else:
					print("Season not found!")
			
			# add [0,0] for events
			x_data.append(peak)
			x_data = x_data + [0,0]
			x_test = np.array([x_data])
			x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
			res = model.predict(x_test, num_inter)
			print("Prediction: " + str(res))
Esempio n. 16
0
        pager.page_dec()
        do_display()

    def do_linedec():
        pager.line_inc()
        do_display()

    def do_pagedec():
        pager.page_inc()
        do_display()

    def do_goto():
        which = input("Go to: ")
        if which.isnumeric():
            pager.set_line(int(which))
            do_display()
        else:
            print("meh...")

    options = [
        ("a", "lnup", do_linedec),
        ("z", "pgup", do_pagedec),
        ("s", "lndn", do_lineadv),
        ("x", "pgdn", do_pageadv),
        ("g", "goto", do_goto),
        ("q", "Quit Program", quit),
    ]
    do_display()
    do_menu("Main Menu", "Option = ", options, "#")
    print('.')
Esempio n. 17
0
def main():
    """Program execution starts here."""

    # Set up main menu and sub-menus.
    main_menu_choices = ["Temperatures", "Distances", "Weights"]

    temperatures_menu_choices = [
        "Celsius to Fahrenheit",  # 1
        "Fahrenheit to Celsius",  # 2
        "Farenheit to Kelvin",  # 3
        "Celsius to Kelvin",  # 4
        "Kelvin to Farenheit",  # 5
        "Kelvin to Celsius",  # 6
    ]

    distances_menu_choices = [
        "Miles to Kilometers",  # 1
        "Kilometres to Miles",  # 2
        "Feet to Metres",  # 3
        "Metres to Feet",  # 4
        "Inches to Centimetres",  # 5
        "Centimetres to Inches",  # 6
    ]

    weights_menu_choices = [
        "Tons to Tonnes",  # 1
        "Tonnes to Tons",  # 2
        "Pounds to Kilograms",  # 3
        "Kilograms to Pounds",  # 4
        "Ounces to Grams",  # 5
        "Grams to Ounces",  # 6
    ]

    # Loop until user wants to quit.
    while True:
        choice = menu.do_menu("Choose a conversion type:", main_menu_choices)
        # Did the user choose "Exit?"
        if choice is None:
            # Yes, then exit.
            break
        if choice == 1:  # User chose temperature conversions.
            # Loop until user wants to return to the main menu.
            while True:
                choice = menu.do_menu("Choose a temperature conversion",
                                      temperatures_menu_choices)
                if choice is None:
                    break
                if choice is 1:  # Celsius to Fahrenheit chosen.
                    cels = get_int.input_int("\nDegrees Celsius: ")
                    print((f"\n{cels} degrees Celsius is: "
                           f"{temperatures.cels_to_fahr(cels):.1f} "
                           "degrees Fahrenheit."))
                if choice is 2:  # Fahrenheit to Celsius chosen.
                    fahr = get_int.input_int("\nDegrees Fahrenheit: ")
                    print((f"\n{fahr} degrees Fahrenheit is: "
                           f"{temperatures.fahr_to_cels(fahr):.1f} "
                           "degrees Celsius."))
                if choice is 3:  # Farenheit to kelvin chosen
                    fahr = get_int.input_int("\nDegrees Farenheit: ")
                    print((f"\n{fahr} degrees Fahrenheit is: "
                           f"{temperatures.fahr_to_kelv(fahr):.1f}"
                           " degrees Kelvin."))
                if choice is 4:  # Celsius to Kelvin chosen
                    cels = get_int.input_int("\nDegrees Celsius: ")
                    print((f"\n{cels} degrees Celsius is: "
                           f"{temperatures.cels_to_kelv(cels):.1f}"
                           " degrees Kelvin."))
                if choice is 5:  # Kelvin to Farenheit chosen
                    kelv = get_int.input_int("\nDegrees Kelvin: ")
                    print((f"\n{kelv} degrees Kelvin is: "
                           f"{temperatures.kelv_to_fahr(kelv):.1f}"
                           " degrees Farenheit."))
                if choice is 6:  # Kelvin to Celsius chosen
                    kelv = get_int.input_int("\nDegrees Kelvin: ")
                    print((f"\n{kelv} degrees Kelvin is: "
                           f"{temperatures.kelv_to_cels(kelv):.1f}"
                           " degrees Celsius."))
        if choice == 2:  # User chose distance conversions.
            # Loop until user wants to return to the main menu.
            while True:
                choice = menu.do_menu("Choose a distance conversion",
                                      distances_menu_choices)
                if choice is None:
                    break
                if choice is 1:  # Miles to Kilometeres chosen.
                    miles = get_int.input_int("\nMiles: ")
                    print((f"\n{miles} miles is: "
                           f"{distances.miles_to_kiloms(miles):.1f} "
                           " kilometers."))
                if choice is 2:  # Kilometers to Miles chosen.
                    kiloms = get_int.input_int("\nKilometers: ")
                    print((f"\n{kiloms} kilometers is: "
                           f"{distances.kiloms_to_miles(kiloms):.1f} "
                           " miles."))
                if choice is 3:  # Feet to meters chosen
                    feet = get_int.input_int("\nFeet: ")
                    print((f"\n{feet} feet is: "
                           f"{distances.feet_to_metres(feet):.1f}"
                           " meters."))
                if choice is 4:  # Meters to feet chosen
                    metres = get_int.input_int("\nMeters: ")
                    print((f"\n{metres} meters is: "
                           f"{distances.metres_to_feet(metres):.1f}"
                           " feet."))
                if choice is 5:  # Inches to centimeters chosen
                    inches = get_int.input_int("\nInches: ")
                    print((f"\n{inches} inches is: "
                           f"{distances.inches_to_centims(inches):.1f}"
                           " centimeters."))
                if choice is 6:  # Centimeters to inches chosen
                    centims = get_int.input_int("\nCentimeters: ")
                    print((f"\n{centims} centimeters is: "
                           f"{distances.centims_to_inches(centims):.1f}"
                           " Inches"))
        if choice == 3:  # User chose weight conversions.
            # Loop until user wants to return to the main menu.
            while True:
                choice = menu.do_menu("Choose a weight conversion",
                                      weights_menu_choices)
                if choice is None:
                    break
                if choice is 1:  # tons to tonnes.
                    tons = get_int.input_int("\nTons: ")
                    print((f"\n{tons} tons is: "
                           f"{weights.tons_to_tonnes(tons):.1f} "
                           " tonnes."))
                if choice is 2:  # Tonnes to tons chosen
                    tonnes = get_int.input_int("\nTonnes: ")
                    print((f"\n{tonnes} Tonnes is: "
                           f"{weights.tonnes_to_tons(tonnes):.1f} "
                           " tons."))
                if choice is 3:  # Pounds to kilograms chosen
                    pounds = get_int.input_int("\nPounds: ")
                    print((f"\n{pounds} pounds is: "
                           f"{weights.pounds_to_kgrams(pounds):.1f}"
                           " kilograms."))
                if choice is 4:  # Meters to feet chosen
                    kgrams = get_int.input_int("\nKilograms: ")
                    print((f"\n{kgrams} kilograms is: "
                           f"{weights.kgrams_to_pounds(kgrams):.1f}"
                           " pounds."))
                if choice is 5:  # Ounces to grams chosen
                    ounces = get_int.input_int("\nOunces: ")
                    print((f"\n{ounces} ounces is: "
                           f"{weights.ounces_to_grams(ounces):.1f}"
                           " grams."))
                if choice is 6:  # Centimeters to inches chosen
                    grams = get_int.input_int("\nGrams: ")
                    print((f"\n{grams} grams is: "
                           f"{weights.grams_to_ounces(grams):.1f}"
                           " ounces."))
Esempio n. 18
0
def use_wireless():
    # restart tcp port
    os.system("adb tcpip 5555")
    phone_one = IP_PREFIX + input('IP Address of phone 1\n')
    phone_two = IP_PREFIX + input('IP Address of phone 2\n')
    connect(phone_one)
    pull_phone()
    # adb_wireless_disconnect()
    # adb_wireless_connect(phone_two)


def pull_phone():
    reported_command(f"adb pull {REMOTE} {LOCAL}")


def reset_connection():
    reported_command("adb disconnect")
    reported_command("adb kill-server")


if __name__ == '__main__':
    reset_connection()
    print("\n当前WIFI信息:")
    WIFI_INFO = reported_command('netsh WLAN show interfaces')
    choice = do_menu(f"Change IP Prefix? Current One is \"{IP_PREFIX}\"",
                     ["Yes", "No"])
    if choice == 1:
        IP_PREFIX = input("Input a new one.")
    use_wireless()