示例#1
0
文件: controller.py 项目: Nastia28/BD
    def show_start_menu(self, subtitle='', **kwargs):
        menu_options = self.tables + ['Знайти майстрів за типом процедур',
                                      'Знайти процедури за типом клієнтів',
                                      'Повнотекстовий пошук (слово не входить)',
                                      'Повнотекстовий пошук (ціла фраза)',
                                      'Створити 100 рандомних майстрів']
        next_steps = [self.show_table_menu] * len(self.tables) + [
            self.get_masters_by_procedures,
            self.get_procedure_by_client_type,
            self.fts_without_word,
            self.fts_phrase,
            self.create_random_masters
        ]
        menu = SelectionMenu(menu_options, subtitle=subtitle,
                             title="Оберіть таблицю або дію:")
        menu.show()

        index = menu.selected_option
        if index < len(menu_options):
            table_name = self.get_table_name(index)
            next_step = next_steps[index]
            try:
                next_step(table_name=table_name)
            except Exception as err:
                self.show_start_menu(subtitle=str(err))
        else:
            print('Пока!!!!')
示例#2
0
    def show_init_menu(self, msg=''):
        selectionMenu = SelectionMenu(
            TABLES_NAMES + [
                'Fill table "product" by random data (10 items)',
                'Find buyers by criteria', 'Find orders by criteria',
                'Find products by criteria'
            ],
            title='Select the table to work with | command:',
            subtitle=msg)
        selectionMenu.show()

        index = selectionMenu.selected_option
        if index < len(TABLES_NAMES):
            tableName = TABLES_NAMES[index]
            self.show_entity_menu(tableName)
        elif index == 4:
            self.fillByRandom()
        elif index == 5:
            self.searchByersByCriteria()
        elif index == 6:
            self.searchOrdersByCriteria()
        elif index == 7:
            self.searchProductsByCriteria()
        else:
            print('Exiting...')
示例#3
0
def display_main_menu(err='', table=None):
    tables = list(model.TABLES.keys())

    menu = SelectionMenu(tables + ['Search users by question.question_datetime',
                                   'Search questions by answer.answer_is_valid',
                                   'Create 10_000 random questions',
                                   'Full Text Search without word',
                                   'Full Text Search by phrase'], subtitle=err,
                         title="Select a table to work with:")
    menu.show()

    index = menu.selected_option
    if index < len(tables):
        table = tables[index]
        display_secondary_menu(table)
    elif index == len(tables):
        search_users_by_question_date()
    elif index == len(tables) + 1:
        search_questions_by_answer_is_valid()
    elif index == len(tables) + 2:
        create_random_questions()
    elif index == len(tables) + 3:
        full_text_search_without_word()
    elif index == len(tables) + 4:
        full_text_search_by_phrase()
    else:
        print('Bye! Have a nice day!')
示例#4
0
文件: controller.py 项目: Nastia28/BD
    def show_table_menu(self, table_name, subtitle=''):
        next_steps = [self.get, self.insert, self.update, self.delete, self.show_start_menu]
        menu = SelectionMenu(
            ['GET', 'INSERT', 'UPDATE', 'DELETE'], subtitle=subtitle,
            title=f'Обрано таблицю `{table_name}`', exit_option_text='Назад', )
        menu.show()

        next_step = next_steps[menu.selected_option]
        next_step(table_name=table_name)
示例#5
0
def display_secondary_menu(table, subtitle=''):
    opts = ['Select', 'Insert', 'Update', 'Delete']
    steps = [select, insert, update, delete, display_main_menu]

    menu = SelectionMenu(
        opts, subtitle=subtitle,
        title=f'Selected table "{table}"', exit_option_text='Go back',)
    menu.show()
    index = menu.selected_option
    steps[index](table=table)
示例#6
0
    def show_entity_menu(self, tableName, msg=''):
        options = ['Get',  'Delete', 'Update', 'Insert']
        functions = [self.get, self.delete, self.update, self.insert]

        selectionMenu = SelectionMenu(options, f'{tableName}',
                                      exit_option_text='Back', subtitle=msg)
        selectionMenu.show()
        try:
            function = functions[selectionMenu.selected_option]
            function(tableName)
        except IndexError:
            self.show_init_menu()
示例#7
0
def show_start_menu():
    main_menu = [
        'Regression analysis for AQI with Wind Speed',
        'Regression analysis for AQI with Air Pressure',
        'Regression analysis for AQI with Humidity',
        'Regression analysis for Humidity with Temperature',
        'Regression analysis for Humidity with Air Pressure',
        'Top 10 countries with worst mean AQI',
        'Top 10 countries with best mean AQI'
    ]

    regression_types = {
        0: ['linear', 'Linear regression'],
        1: ['polynomial', 'Polynomial regression']
    }
    regression_menu = []
    for key in regression_types:
        regression_menu.append(regression_types[key][1])

    menu = SelectionMenu(main_menu,
                         title="Select one of these amazing options :)")
    menu.show()

    if menu.is_selected_item_exit():
        print("bye")
        return

    item = menu.selected_option

    if item in range(0, 5):
        menu = SelectionMenu(regression_menu,
                             title='Select regression type',
                             show_exit_option=False)
        menu.show()
        regression_selected = menu.selected_option
        regression_type = regression_types[regression_selected][0]
        if item == 0:
            datamanipulation.show_and_save_plot_aqi_windspeed(
                df, regression_type)
        elif item == 1:
            datamanipulation.show_and_save_plot_aqi_pressure(
                df, regression_type)
        elif item == 2:
            datamanipulation.show_and_save_plot_aqi_humidity(
                df, regression_type)
        elif item == 3:
            datamanipulation.show_and_save_plot_temp_humidity(
                df, regression_type)
        elif item == 4:
            datamanipulation.show_and_save_plot_humidity_pressure(
                df, regression_type)

    if item == 5:
        datamanipulation.show_and_save_plot_top10_worst_mean_aqi_by_country(df)
    elif item == 6:
        datamanipulation.show_and_save_plot_top10_best_mean_aqi_by_country(df)

    show_start_menu()
示例#8
0
文件: controller.py 项目: Sedatif/db
    def show_entity_menu(self, table_name, input=''):
        options = ['INSERT', 'DELETE', 'UPDATE']
        methods = [self.insert, self.delete, self.update]

        selection_menu = SelectionMenu(options,
                                       f'Table: {table_name}',
                                       exit_option_text='Back',
                                       subtitle=input)
        selection_menu.show()
        try:
            method = methods[selection_menu.selected_option]
            method(table_name)
        except IndexError:
            self.show_start_menu()
示例#9
0
    def __init__(self):
        self.system = Antenna()
        ant_list = self.system.get_list()
        self.target = Target()
        target_list = self.target.get_list()

        title = "INP Generator for Orbit ACUs"
        subtitle = "Choose your Antenna"
        # A menu to select our antenna
        selection = SelectionMenu.get_selection(ant_list,
                                                title=title,
                                                subtitle=subtitle)
        if selection == len(ant_list):
            sys.exit()

        sys_name = ant_list[selection]

        subtitle = "Using " + sys_name + ", Choose the target"
        # A menu to select our target
        selection = SelectionMenu.get_selection(target_list,
                                                title=title,
                                                subtitle=subtitle)
        if selection == len(target_list):
            sys.exit()

        target_name = target_list[selection]

        self.system.ready(sys_name)
        self.target.ready(target_name)
        self.target.ready_antenna(self.system.lat, self.system.lon,
                                  self.system.alt)
        self.target.generate_report()

        if self.target.rise_time is None:
            output = "\n\n  " + target_name + " doesn't rise in the next 12 hours...\n\n"
            print(output)
            sys.exit()
        else:
            output = "\n\n " + target_name + " will be up at " + self.target.rise_time + "\n"
            print(output)
            output = " The report ends or " + target_name + " fades at " + self.target.fade_time + "\n\n"
            print(output)
            filename = "/home/scheduler/Desktop/" + sys_name + "_" + target_name + ".orb"
            output = " Saving INP file to " + filename + "\n\n"
            print(output)
            with open(filename, 'w') as f:
                for line in self.target.report:
                    f.write(line)
            sys.exit()
示例#10
0
    def show_init_menu(self, msg=''):
        selection_menu = SelectionMenu(
            TABLES_NAMES + ['Fill table "book" by random data (10 items)'],
            title='Select the table to work with | command:', subtitle=msg)

        selection_menu.show()

        index = selection_menu.selected_option
        if index < len(TABLES_NAMES):
            table_name = TABLES_NAMES[index]
            self.show_entity_menu(table_name)
        elif index == 5:
            self.fill_by_random()
        else:
            print('Bye, have a beautiful day!')
示例#11
0
def display_main_menu(err='', table=None):
    tables = list(model.TABLES.keys())

    menu = SelectionMenu(tables + ['Make commit'], subtitle=err,
                         title="Select a table to work with:")
    menu.show()


    index = menu.selected_option
    if index < len(tables):
        table = tables[index]
        display_secondary_menu(table)
    elif index == len(tables):
        model.commit()
        display_main_menu('Commit was made successful')
示例#12
0
    def show_init_menu(self, msg=''):
        selectionMenu = SelectionMenu(
            TABLES_NAMES + ['Fill table "faculty" by random data'],
            title='Select the table to work with | command:',
            subtitle=msg)
        selectionMenu.show()

        index = selectionMenu.selected_option
        if index < len(TABLES_NAMES):
            tableName = TABLES_NAMES[index]
            self.show_entity_menu(tableName)
        elif index == 5:
            self.fillByRandom()
        else:
            print('Bye!')
示例#13
0
文件: ui.py 项目: traumgedanken/obd
def show_start_menu():
    """Entrance point in menu"""
    menu = SelectionMenu([
        'Crawl bigmir.net',
        'Find page from bigmir.net with the smallest number of images',
        'Crawl sokol.ua', 'Create XHTML table with fridges from sokol.ua'
    ],
                         title="Select a task to do")
    menu.show()

    if menu.is_selected_item_exit():
        print('Bye!')
    else:
        index = menu.selected_option
        (crawl_bigmir, analize_bigmir, crawl_sokol,
         create_xhtml_table)[index]()
示例#14
0
def show_start_menu(tname='', err=''):
    tables = list(model.TABLES.keys())

    menu = SelectionMenu(tables + ['Custom SQL query'],
                         subtitle=err,
                         title="Select a table to work with:")
    menu.show()

    index = menu.selected_option
    if index < len(tables):
        tname = tables[index]
        show_table_menu(tname)
    elif index == len(tables):
        custom_query()
    else:
        print('Bye! Have a nice day!')
示例#15
0
def autodetect_codec(path):
    if re.search("h.264", path, re.IGNORECASE) != None and (
            re.search("blu", path, re.IGNORECASE) != None
            or re.search("web", path, re.IGNORECASE) == None):
        return 'h.264 Remux'
    elif re.search("h.265", path, re.IGNORECASE) != None and (
            re.search("blu", path, re.IGNORECASE) != None
            or re.search("web", path, re.IGNORECASE) == None):
        return 'x264'
    elif re.search("x265", path, re.IGNORECASE) != None:
        return 'x265'
    elif re.search("x264", path, re.IGNORECASE) != None:
        return 'x264'
    elif re.search("VC-1 Remux", path, re.IGNORECASE) != None:
        return 'VC-1 Remux'
    elif re.search("MPEG2 Remux", path, re.IGNORECASE) != None:
        return 'MPEG2 Remux'

    upstring = f"{os.path.basename(path)}\nWhat is the codec of the Upload?"
    print(upstring)

    options = [
        "x264", "h.264 Remux", "x265", "h.265 Remux", "VC-1 Remux"
        "MPEG2 Remux"
    ]

    if sys.platform != "win32":
        menu = TerminalMenu(options)
        menu_entry_index = menu.show()
    else:
        menu_entry_index = SelectionMenu.get_selection(options)
    value = options[menu_entry_index]
    return value
示例#16
0
def update(name, col_search=None, val_search=None):
    try:
        cols = []
        vals = []
        val = 0
        if col_search == None:
            col_search = columns[name][SelectionMenu.get_selection(
                [i for i in columns[name]],
                show_exit_option=False,
                title="Choose column to search",
            )]
        if val_search == None:
            val_search = Screen().input("Enter value to update: ")
        Screen().println(
            'Enter columns, text values must be surrounded by "\'"')
        Screen().println("Empty lines will be ignored")
        for i in range(1, len(columns[name])):
            col = columns[name][i]
            val = Screen().input(f"{(col)}: ")
            if bool(val and not val.isspace()):
                cols.append(col)
                vals.append(val)
        ens = db.update(name, cols, vals, col_search, val_search)
        if isinstance(ens, Exception):
            Screen().input(f"Derror: {ens}")
            return
        else:
            Screen().input(f"Updated { ens } items")
    except Exception as e:
        Screen().input("\n".join(
            [f"CError: {e}", "Press any key to continue..."]))
示例#17
0
def process_data(name, data, page, nested=None):
    if isinstance(data, Exception):
        Screen().input(f"DError: {data}")
        return
    subtitle = "".join(f"{i} " for i in columns[name])
    arr = [f" Page {page - 1}", f" Page {page + 1}"]
    for en in data:
        arr.append(" ".join(map(str, en)))
    sel = SelectionMenu.get_selection(arr, subtitle)
    if sel in range(2, len(arr)):
        subtitle = ""
        for i in range(len(columns[name])):
            subtitle += f"{columns[name][i]}: {data[sel - 2][i]}; "
        menu = ConsoleMenu("Item actions", subtitle)
        if name == "Seller" and nested == None:
            menu.append_item(
                FunctionItem("Find products", find_products,
                             [data[sel - 2][0], 1]))
        elif name == "Product" and nested == None:
            menu.append_item(
                FunctionItem("Find sellers", find_sellers,
                             [data[sel - 2][0], 1]))
        menu.append_item(
            FunctionItem("Edit", update,
                         [name, columns[name][0], data[sel - 2][0]]))
        menu.append_item(
            FunctionItem("Delete", delete,
                         [name, columns[name][0], data[sel - 2][0]]))
        menu.show()
    elif sel < 2:
        return sel + 1
示例#18
0
文件: ui.py 项目: goroanya/DB_labs
def show_start_menu():
    """Entrance point in menu"""
    menu = SelectionMenu([
        'Crawl isport.ua', 'Print all links crawled from isport.ua',
        'Crawl portativ.ua',
        'Create XHTML table with headphones from portativ.ua'
    ],
                         title="Select a task to do")
    menu.show()

    if menu.is_selected_item_exit():
        print('Bye!')
    else:
        index = menu.selected_option
        (crawl_isport, print_all_links_from_isport, crawl_portativ,
         create_xhtml_table)[index]()
示例#19
0
def select_emulator_resolution():
    while True:
        selection = SelectionMenu.get_selection(
            [
                'Default - {} x {}: {}dpi'.format(
                    *DEFAULT_RESOLUTION.values()), 'Customize...'
            ],
            title="Select the emulator screen resolution:")
        if selection == 0:
            return DEFAULT_RESOLUTION
        elif selection == 1:
            width = click.prompt('Please enter emulator screen width',
                                 type=int)
            height = click.prompt('Please enter emulator screen height',
                                  type=int)
            density = click.prompt('Please enter emulator screen density',
                                   type=int)
            customized_resolution = {
                'width': width,
                'height': height,
                'density': density
            }
            if click.confirm(
                    "Please confirm your emulator screen resolution - {} x {}: {}dpi."
                    .format(*customized_resolution.values())):
                return customized_resolution
        elif selection == 2:
            sys.exit(1)
示例#20
0
    def show_init_menu(self, message=''):
        selection_menu = SelectionMenu(
            TABLES_NAMES + ['Fill table "level" by random data', 'Commit'], title='Menu:', subtitle=message)
        selection_menu.show()

        index = selection_menu.selected_option
        if index < len(TABLES_NAMES):
            tableName = TABLES_NAMES[index]
            self.show_entity_menu(tableName)
        elif index == len(TABLES_NAMES):
            self.fill_level_by_random_data()
        elif index == len(TABLES_NAMES) + 1:
            self.model.commit()
            self.show_init_menu(message='Commit success')
        else:
            print('Closing...')
def select_scan():

    global lightsheetPackages, lightsheetScanPaths, displayNames

    scanIndex = SelectionMenu.get_selection(displayNames)

    if scanIndex >= len(displayNames):
        return None

    scanName = displayNames[scanIndex]
    scan = lightsheetPackages[scanIndex]
    attribs = scan.get_filled_attr_dict()

    # TODO: Open the scan and spawn the GUI showing the metadata and thumbnail

    analysisList = ['3D Density Map', 'Stroke Volume', 'Vessel Diameter']

    scanMenu = ConsoleMenu(scanName, exit_option_text="Close Scan")
    viewAttribsItem = FunctionItem("View Metadata", show_scan_metadata,
                                   [attribs])
    viewMaxProjItem = FunctionItem("View Max-Proj", show_scan_maxproj,
                                   [attribs['maxProjPath'], attribs['name']])
    #selectAnalysisPackageItem = FunctionItem("View Analysis", select_existing_analysis, [analysisList])
    #createNewAnalysisPackageItem = FunctionItem("Import Analysis", perform_new_analysis, [analysisList])
    downloadScanItem = FunctionItem("Download Copy", download_scan,
                                    [scan.get_uniqueID()])
    scanMenu.append_item(viewAttribsItem)
    scanMenu.append_item(viewMaxProjItem)
    #scanMenu.append_item(selectAnalysisPackageItem)
    #scanMenu.append_item(createNewAnalysisPackageItem)
    scanMenu.append_item(downloadScanItem)
    scanMenu.show()
示例#22
0
def show_first_menu():
    # Record which models are in the models folder
    models_list = [
        f for f in listdir(models_path)
        if isfile(join(models_path, f)) and f[-4:] == ".dat"
    ]

    first_menu = ConsoleMenu("Main menu")

    submenu = SelectionMenu(models_list, "Load Model")
    submenu_item = SubmenuItem("Load a model",
                               submenu,
                               menu=first_menu,
                               should_exit=True)

    first_menu.append_item(submenu_item)

    first_menu.start()
    first_menu.join()

    if submenu.selected_option >= len(models_list):
        show_first_menu()
        return
    elif submenu.selected_option == -1:
        return

    selected_model = models_list[submenu.selected_option]

    net, jtree = util.load_model(models_path + selected_model)
    if net is not None and jtree is not None:
        jtree.initialize_tables(net)
        print("Model loaded succesfully")
        show_loaded_model_menu(selected_model, net, jtree)
    else:
        show_first_menu()
示例#23
0
    def action_write(args):
        i = 0
        data = []

        encoded_file = os.path.expanduser(args.write)

        while True:
            env_list = []
            if data:
                for osenv in data:
                    env = next(iter(osenv)).split("_")[0]
                    env_list.append("Delete {0} environment.".format(env))

            selection_list = ["Add a new OpenStack Environment"]
            selection_list.extend(env_list)
            selection_list.append(
                "Encode and write file {file}.".format(file=encoded_file))
            selection = SelectionMenu.get_selection(selection_list)

            i = len(env_list)

            if selection == 0:
                osenv = input(
                    "Input environment name for configuration and press [ENTER]: "
                )
                data.append(json.loads(OSEnvController.add_tenant(name=osenv)))
                #i += 1
            elif selection > 0 and selection <= i:
                if not input(
                        "Are you sure? (y/n): ").lower().strip()[:1] == "y":
                    break
                data.pop(selection - 1)
            elif selection == len(env_list) + 1:
                print("Encrypt and write file...")
                crypto = FileEncryption()
                crypto.encrypt_configfile(data=json.dumps(data),
                                          output_file=encoded_file)
                #crypto.encrypt_configfile(data=json.dumps(data), output_file=args.edit, key=userkey)

                if not os.path.isfile(encoded_file):
                    print("{0} file not found.".format(encoded_file))
                    break

                try:
                    os.chmod(encoded_file, 0o600)
                except OSError as e:
                    print(
                        "Couldn't change file permissions to 0600. Please change it, otherwise you are not able to read this file. [{0}]"
                        .format(e))

                print("File {file} written ...".format(file=encoded_file))
                print("Finish")
                return True

            elif selection == len(env_list) + 2:
                print("Program termination ...")
                # break
                # print(json.dumps(data))
                sys.exit()
示例#24
0
    def show_init_menu(self, msg=''):
        selectionMenu = SelectionMenu(
        TABLES_NAMES + ['Fill table "product" by random data (1000 items)',
                        'commit'], title='Select the table to work with | command:', subtitle=msg)
        selectionMenu.show()

        index = selectionMenu.selected_option
        if index < len(TABLES_NAMES):
            tableName = TABLES_NAMES[index]
            self.show_entity_menu(tableName)
        elif index == 4:
            self.fillByRandom()
        elif index == 5:
            self.model.commit()
            self.show_init_menu(msg='Commit success')
        else:
            print('Exiting...')
示例#25
0
    def show_init_menu(self, msg=''):
        selection_menu = SelectionMenu(
            TABLES_NAMES + ['Fill table "department" by random data (10 000 items)', 'Commit'],
            title='Select the table to work with | command:', subtitle=msg)
        selection_menu.show()

        index = selection_menu.selected_option
        if index < len(TABLES_NAMES):
            table_name = TABLES_NAMES[index]
            self.show_entity_menu(table_name)
        elif index == len(TABLES_NAMES):
            self.fill_by_random()
        elif index == len(TABLES_NAMES) + 1:
            self.model.commit()
            self.show_init_menu(msg='Commit success')
        else:
            print('Bye, have a beautiful day!')
示例#26
0
def show_LibrMenu():
    libr_list = [
        "Add item", "Update item", "Archive a item", "Check borrowed items"
    ]
    selection_lib = SelectionMenu.get_selection(
        libr_list, "Digital Library Service - Librarian Functions",
        "Please select function:")
    return selection_lib
示例#27
0
def select_emulator():
    """Displayes an interactive menu to select a released emulator binary.

    Returns a ImuInfo object with the choice or None if the user aborts.    """
    emu_infos = [x for x in get_emus_info() if "linux" in x.urls]
    display = ["EMU {} {}".format(emu_info.channel, emu_info.version) for emu_info in emu_infos]
    selection = SelectionMenu.get_selection(display, title="Select the emulator you wish to use:")
    return emu_infos[selection] if selection < len(emu_infos) else None
示例#28
0
def show_UserMenu():
    user_list = [
        "List all contents", "Serch for contents", "Borrow an item",
        "Return item"
    ]
    selection_usr = SelectionMenu.get_selection(
        user_list, "Digital Library Service - User Functions",
        "Please select function:")
    return selection_usr
示例#29
0
文件: controller.py 项目: Sedatif/db
    def show_start_menu(self, input=''):
        selection_menu = SelectionMenu(
            TABLES_NAMES + ['Find books by name or author`s fullname',
            'Fill the Readers (random)'],
            title = 'Input:',
            subtitle=input)

        selection_menu.show()
        option = selection_menu.selected_option
        if option < len(TABLES_NAMES):
            table_name = TABLES_NAMES[option]
            self.show_entity_menu(table_name)
        elif option == 6:
            self.filter_books()
        elif option == 7:
            self.random_data_for_readers_table()
        else:
            print('')
def select_emulator():
    emu_infos = [x for x in get_emus_info() if 'linux' in x.urls]
    display = [
        "EMU {} {}".format(emu_info.channel, emu_info.version)
        for emu_info in emu_infos
    ]
    selection = SelectionMenu.get_selection(
        display, title='Select the emulator you wish to use:')
    return emu_infos[selection] if selection < len(emu_infos) else None