Example #1
0
def get_selected_app(apps: Dict[str, list[str]]) -> str:
    apps_range = len(apps["available"])
    console.print(Rule("Select which IDE to work on by typing its id"))

    while not (0 < (select := IntPrompt.ask(
            f"Enter and id between [b]1[/b] and [b]{apps_range}[/b]")) <
               apps_range + 1):
        console.print("[red]You must enter a valid id[red]")
Example #2
0
def getStudentVueData():
    username = IntPrompt.ask('Enter your user id')
    pwd = Prompt.ask('Enter your password')
    domain = 'https://md-mcps-psv.edupoint.com'
    remember = Confirm.ask('Do you want to be remembered?')
    studentvue_client = StudentVue(str(username), pwd, domain)
    while 'RT_ERROR' in studentvue_client.get_gradebook().keys():
        text = Text('Username or password is incorrect. Try again')
        text.stylize(style="red")
        console.print(text)
        username = IntPrompt.ask('Enter your user id')
        pwd = Prompt.ask('Enter your password')
        studentvue_client = StudentVue(str(username), pwd, domain)
    return studentvue_client.get_gradebook()
Example #3
0
    def done(self, group=None):
        """
        Mark tasks as done
        """
        data = self.output_tasks(group=group)
        datadone, datanotdone = self.get_done_tasks(data)

        if len(datanotdone) == 0:
            print("nothing to mark as done!")
            return

        #now ask for option
        dno = IntPrompt.ask("Which task should be marked as done? (1-%d)" %
                            len(datanotdone))
        if not (0 < dno <= len(datanotdone)):
            print("choose a valid option")
            return

        dkey = datanotdone[dno - 1]["id"]
        Group = Query()
        self.db.update(
            {
                'status': True,
                'finished': datetime.datetime.now().__str__()
            }, Group.id == dkey)
        print('updated')
Example #4
0
    def delete(self, group=None):
        """
        Delete tasks
        """
        if group == "all":
            self.reset()
        else:
            data = self.output_tasks(group=group)
            datadone, datanotdone = self.get_done_tasks(data)

            if len(datanotdone) == 0:
                print("nothing to delete!")
                return

            #now ask for option
            dno = IntPrompt.ask("Which task should be deleted? (1-%d)" %
                                len(datanotdone))
            if not (0 < dno <= len(datanotdone)):
                print("choose a valid option")
                return

            dkey = datanotdone[dno]["id"]
            Group = Query()
            self.db.remove(Group.id == dkey)
            print('deleted')
Example #5
0
def cli():
    console.clear()
    welcome()
    bath()

    console.print(
        Panel(
            '[bold]Welcome to [default on red]onsen[/]![/] ([italic]tattoo-friendly)[/]',
            expand=True))
    console.print(
        '[italic]May I help you? (いらっしゃいませ)[/] type [default on red]help[/]')
    while True:
        command = console.input(":hotsprings:  [bold red]>[/] ")

        if command == 'bath':
            console.print('[blue]Relax...')
            bath()
        if command == 'volume':
            value = IntPrompt.ask(
                ':cloud_with_rain:  [bold blue]How much water do you want? (1 to 100)[/]'
            )
            set_volume(value)
        if command == 'help':
            console.print(help_commands)
        if command == 'stop':
            stop()
        if command == 'quit':
            console.print('[italic]Come back soon![/] (ありがとうございました)')
            break
    return
Example #6
0
def start_commands(gradebook):
    command = ''
    print('Welcome!')
    print('Enter "course" to select a course to view')
    command = Prompt.ask("Enter a command")
    while command.lower() != 'end':
        if command == 'course':
            grid = Table()
            grid.add_column('ID')
            grid.add_column('Course')
            count = 1
            for course in gradebook.courses:
                grid.add_row(str(count), course.title)
                count += 1
            console.print(Columns(
                (grid, ),
                align="center",
                expand=True,
            ), )
            course_id = IntPrompt.ask(
                "Enter the ID of the course you want to view")
            console.clear()
            gradebook.courses[course_id - 1].print_grade_table()
            course_commands(gradebook.courses[course_id - 1])
            console.clear()
            print_grade_table(gradebook)
        elif command == 'help':
            print('[green bold] course: Pick a course to view')
            print('[red bold] end: Exit Scholaris')
        else:
            console.clear()
            print_grade_table(gradebook)
            print(
                "[red]Invalid command! Enter 'help' to see possible commands")
        command = Prompt.ask("Enter a command")
Example #7
0
    def render_menu(self, menu: Menu) -> int:
        """
        Render Menu

        :param menu: Menu (See Types/Menu.py)
        :return: User's selection from menu
        :rtype: int
        """
        self._console.print(f"{'='*40}")
        self._console.print(f"{menu.__menuname__}")

        # Print out all of the options in the menu
        options: List[str] = []
        for index, option in enumerate(menu.options.keys()):
            # We don't want to zero-index our menus
            index += 1

            # Add option index
            options.append(str(index))

            # Prettify name
            self._console.print(f"    ({index})> {option}")

        # Print out a 40 char bar just as a visual index
        self._console.print(f"\n{'-'*40}")

        # Prompt for input
        selection: int = IntPrompt.ask("Selection", choices=options)

        return selection
Example #8
0
    def new_habit_freq_start_date(self, date_today: arrow.Arrow) -> None:
        """Get new frequency and start date.

        :param date_today:
        :return:
        """
        console.print(
            f"[bold]{escape('[perry-bot]:')}[/bold] "
            f"How frequent is this habit?",
            style="default",
        )
        console.print(
            "[b]1.[/b] Daily\n[b]2.[/b] Weekly\n[b]3.[/b] "
            "Every other week\n[b]4.[/b] Monthly\n"
            "[b]5.[/b] Every other month\n[b]6.[/b] Yearly",
            style="default",
        )
        frequency = IntPrompt.ask(
            choices=["1", "2", "3", "4", "5", "6"],
            default=1,
            show_default=True,
        )
        freq_str = self.new_habit_freq_to_string(frequency=frequency)
        self.frequency.append(freq_str)
        console.print(
            f"[bold]{escape('[perry-bot]:')}[/bold] "
            f"What's the start date (YYYY-MM-DD) of this habit?",
            style="default",
        )
        start_date_input = Prompt.ask(default=date_today.format("YYYY-MM-DD"),
                                      show_default=True)
        start_date = self.check_date_format(start_date_input=start_date_input,
                                            date_today=date_today)
        self.start_date.append(start_date)
Example #9
0
 def reset(self):
     """
     Hard reset all tasks
     """
     dno = IntPrompt.ask(
         "This will really delete all tasks, press 1 to continue.")
     if dno == 1:
         self.db.truncate()
Example #10
0
def pick(choices: list, end_msg: str = None):
    msg = ""
    for i, v in enumerate(choices):
        msg += f'{i + 1}) {v}\n'
    if end_msg: msg += f'{end_msg}\n'
    int_choices = [str(x) for x in range(1, len(choices) + 1)]
    picked = IntPrompt.ask(msg, choices=int_choices, show_choices=False)
    return choices[picked - 1]
Example #11
0
 def reset(self) -> None:
     self.player = self._players.copy()
     board_size = IntPrompt.ask(
         "Leave blank for previous board size or enter a new one",
         default=self.board_size,
     )
     self.board_size = board_size
     self._max_pos = board_size - 1
     self.board = Board(size=board_size)
Example #12
0
def beer_creation():
    """
    Create beer.

    Returns
    -------
    list
        A list with all beers.
    """
    quantity = IntPrompt.ask("How many products do you want to create?")
    make_progress_display(quantity)
Example #13
0
def test_prompt_int():
    INPUT = "foo\n100"
    console = Console(file=io.StringIO())
    number = IntPrompt.ask(
        "Enter a number",
        console=console,
        stream=io.StringIO(INPUT),
    )
    assert number == 100
    expected = "Enter a number: Please enter a valid integer number\nEnter a number: "
    output = console.file.getvalue()
    print(repr(output))
    assert output == expected
Example #14
0
    def _ask_cell(self) -> tuple[int, int]:
        maximum = self._max_pos

        while True:
            row = IntPrompt.ask("Enter the row of the cell you want to mark")

            if not 0 <= row <= maximum:
                console.print(self.error_msg.format("row", maximum))
                continue

            break

        while True:
            col = IntPrompt.ask("Enter the column")

            if not 0 <= col <= maximum:
                console.print(self.error_msg.format("column", maximum))
                continue

            break

        return row, col
 def generate_password(self):
     """Generate a new password based on user requirements"""
     has_symbols = Confirm.ask("Do you want it to have symbols?")
     has_letters = True  # Always have letters
     has_numbers = Confirm.ask("Do you want it to have numbers?")
     while True:
         length = IntPrompt.ask(
             "Enter a number between [b]8[/b] and [b]128[/b]", default=32)
         if 8 <= length <= 128:
             break
     password = self.pass_obj.generate_password(has_symbols, has_letters,
                                                has_numbers, length)
     self.print(password, style="yellow on black")
     self.print('Password was generated and copied to clipboard!',
                style="green on white")
Example #16
0
    def get_new_value(self):
        """Get the new value.

        :return:
        """
        console.print(
            f"[bold]{escape('[perry-bot]:')}[/bold] Enter the new value",
            style="default",
        )
        if (len(self.column_choices) == 2
                and self.column_to_edit in self.column_choices[1]):
            self.new_value = Prompt.ask()
        elif (len(self.column_choices) == 2
              and self.column_to_edit in self.column_choices[0]
              or len(self.column_choices) == 1):
            self.new_value = IntPrompt.ask()
Example #17
0
    def get_num_to_edit(self):
        """Get the number user wants to edit.

        :return:
        """
        console.print(
            f"[bold]{escape('[perry-bot]:')}[/bold] Enter the number of "
            f"the entry you want to edit.",
            style="default",
        )
        num = IntPrompt.ask()
        while num not in self.id:
            wrong_id = self.wrong_num_loop(num=num)
            if self.number_to_edit in self.id:
                break
            if not wrong_id:
                return False
        self.number_to_edit = num
        return True
Example #18
0
def getChoice(SONG_INFO, type):
    """If more than 1 result from getData then ask for a choice."""
    # Print 5 of the search results
    # In case less, print all

    prepend.PREPEND(1)
    print('Choose One {}'.format(
                        '(One with [M] is verified music)'
                        if type == 'mp3' else ''))

    results = len(SONG_INFO)

    if results > 5:
        results = 5

    PRINT_WHOLE = True

    default_choice = get_default(SONG_INFO, type)

    beg = 0
    while True:
        # Print the results first
        if PRINT_WHOLE:
            print_choice(beg, results, SONG_INFO, type)
        prepend.PREPEND(1)
        choice = IntPrompt.ask('Enter Choice', default=default_choice)

        choice = int(choice)

        # If the choice is 6 then try to print more results
        if choice <= results and choice > 0:
            break
        elif choice == 0 and results < len(SONG_INFO):
            PRINT_WHOLE = True
            beg = results
            results = beg + 5
        else:
            PRINT_WHOLE = False

    choice = int(choice)
    choice -= 1
    return choice
Example #19
0
def getChoice(SONG_INFO, type):
    """If more than 1 result from getData then ask for a choice."""
    # Print 5 of the search results
    # In case less, print all

    logger.info('Choose One {}'.format(
        '(One with [M] is verified music)' if type == 'mp3' else ''))

    results = len(SONG_INFO)

    if results > 5:
        results = 5

    PRINT_WHOLE = True

    default_choice = get_default(SONG_INFO, type)

    beg = 0
    while True:
        # Print the results first
        if PRINT_WHOLE:
            print_choice(beg, results, SONG_INFO, type)
        prepend.PREPEND(1)
        choice = IntPrompt.ask('Enter Choice', default=default_choice)

        logger.debug(choice)
        choice = int(choice)

        # If the choice is 0 then try to print more results
        # The choice is valid if it is in the range and it is greater than 0
        # We also need to break when the user enters -1 which means the exec
        # will skip the current song
        if (choice <= len(SONG_INFO) and choice > 0) or choice == -1:
            break
        elif choice == 0 and results < len(SONG_INFO):
            PRINT_WHOLE = True
            beg = results
            results = beg + 5
        else:
            PRINT_WHOLE = False

    return choice - 1
Example #20
0
def beer_specification():
    """
    Prompts beer specification.

    Returns
    -------
    dict
        A dict with beer specifications.
    """
    name = Prompt.ask("Enter the beer name")
    quantity = IntPrompt.ask("Quantity")
    price = FloatPrompt.ask("Price (Float format)")
    is_alcoholic = Confirm.ask("Is alcoholic?")

    return {
        "name": name,
        "quantity": quantity,
        "price": price,
        "isAlcoholic": is_alcoholic
    }
Example #21
0
def list_countries():
    """Country list menu."""
    console = Console()
    console.print(MARKDOWN)

    mapper = {
        1: "Brazil",
        2: "Germany",
        3: "Belgium",
        4: "United Kingdom",
        5: "Netherlands",
    }

    option = IntPrompt.ask("Enter your choice",
                           choices=["1", "2", "3", "4", "5"],
                           show_choices=False)

    with console.status(f"Getting {mapper[option]} brands..."):
        sleep(2)

        console.rule(f"{mapper[option]} Brands")
        options(option)
Example #22
0
    def wrong_num_loop(self, num: int) -> bool:
        """Loop while user enters a number that doesn't exist.

        :param num:
        :return:
        """
        check_cancel = self.check_cancel_edit(num=num)
        if not check_cancel:
            return False
        console.print(
            f"[bold]{escape('[perry-bot]:')}[/bold] Please enter "
            f"a valid number from the table",
            style="default",
        )
        num_again = IntPrompt.ask()
        check_cancel_again = self.check_cancel_edit(num=num_again)
        if not check_cancel_again:
            return False
        if num_again in self.id:
            self.number_to_edit = num_again
            return True
        return False
Example #23
0
def finish_setup() -> None:
    """Configs who directly refer to the bot."""
    name = get_name()

    console.print(
        Rule("Now, it's time to finish this setup by giving bot information")
    )
    console.print()

    token = get_token()

    ip = get_ip()

    console.print()
    prefixes = get_multiple(
        "Choice a (or multiple) prefix for the bot",
        "Add another prefix ?",
        str,
    )

    console.print()
    mentionable = (
        Prompt.ask(
            "Does the bot answer if it's mentioned?",
            choices=["y", "n"],
            default="y",
        )
        == "y"
    )

    console.print()
    owners_id = get_multiple(
        "Give the owner id of this bot", "Add another owner ?", int
    )

    console.print("\n" * 4)
    console.print(Rule("\nAnd to finish, the configuration for PostgreSQL"))
    console.print()

    database = {
        "username": Prompt.ask(
            "Please enter the username for PostgreSQL",
            console=console,
        ),
        "password": Prompt.ask(
            "Please enter the password for PostgreSQL",
            console=console,
        ),
        "domain": Prompt.ask(
            "Please enter the domain for PostgreSQL",
            console=console,
            default="localhost",
        ),
        "port": IntPrompt.ask(
            "Please enter the port for PostgreSQL",
            console=console,
            default="5432",
        ),
        "db_name": Prompt.ask(
            "Please enter the database name for PostgreSQL", console=console
        ),
    }

    _config_file = config.ConfigFile(str(config_file), config.Config)

    _config_file.config.Core.owners_id = owners_id
    _config_file.config.Core.prefixes = prefixes
    _config_file.config.Core.token = token
    _config_file.config.Core.ip = ip
    _config_file.config.Core.mentionable = mentionable
    _config_file.config.Core.locale = "en-US"
    _config_file.config.Core.instance_name = name

    _config_file.config.Core.Database.username = database["username"]
    _config_file.config.Core.Database.password = database["password"]
    _config_file.config.Core.Database.domain = database["domain"]
    _config_file.config.Core.Database.port = database["port"]
    _config_file.config.Core.Database.db_name = database["db_name"]
Example #24
0
def main(url = None):
    console = Console()


    session = requests_html.HTMLSession()

    if url == None: url = Prompt.ask("Enter the google form url")

    url_parse = urllib.parse.urlparse(url)
    if (url_parse.scheme == "" or url_parse.netloc == ""):
        console.log("red bold]ERROR[/red bold] Invalid url.")
        return 


    with console.status("[bold green]Retriving google form...") as status:
        try :
            r = session.get(url) 
            if (r.status_code != 200): raise Exception("Invalid url, error code "+str(r.status_code))
        except Exception as e:
            console.log("[red bold]ERROR[/red bold] Invalid url, can't retrived google form. (error: "+str(e)+")")
            return
        else :
            console.log("Google form retrived.")
        
    with console.status("[bold green]Parsing questions...") as status:
        try:
            items = r.html.find(".freebirdFormviewerViewNumberedItemContainer")
            qr = []

            for item in items:
                t = item.find('.m2', first=True)
                a =  ast.literal_eval(("["+t.attrs.get("data-params")[4:]).replace("null", "0").replace("false", "False").replace("true", "True"))
                e = [a[0][1], a[0][4][0][0], []]
                for el in a[0][4][0][1]:
                    e[2].append(el[0])
                qr.append(e)
        except Exception as e:
            console.log("[red bold]ERROR[/red bold] error while parsing questions : "+str(e))
            return
        else:
            console.log("Questions parsed.")

    console.print("\n")

    rep = {}

    for i, question in enumerate(qr):
        console.print(Panel(Columns([str(j+1) + ". "+question[2][j] for j in range(len(question[2]))]), title="Question "+str(i+1)+" : "+question[0]))
        while True:    
            ans = IntPrompt.ask("Response", default=randint(1, len(question[2])))
            if ans >= 1 and ans <= len(question[2]):
                break
            console.print("[prompt.invalid]Choice bewteen 1 and"+ len(question[2]))
        rep['entry.'+str(question[1])] = urllib.parse.quote_plus(question[2][ans-1])
        console.print("\n")

    n = IntPrompt.ask("Number of response : ", default=1)
    if n > 100: n = 100

    with console.status("[bold green]Sending responses...") as status:
        try:
            for i in range(n):
                r = requests.post(url.replace("viewform", "formResponse"), headers={"content-type":"application/x-www-form-urlencoded"}, data = rep)        
                console.log(str(i+1)+" responses sended.")
        except Exception as e:
            console.log("[bold red]ERROR[/bold red] Something wrong happend during sending : "+str(e))
            return

    console.print("\nbye")
Example #25
0
def main(download: bool) -> None:
    log.info(f"VVVVID Downloader {__version__}")

    ffmpeg_path = which("ffmpeg")

    if download and not ffmpeg_path:
        log.critical("FFmpeg non trovato.")
        exit()

    show_id = IntPrompt.ask("ID Show")

    api = Api()
    api.login()

    info = api.info(show_id)

    if not info.exists:
        log.critical("Questo show non esiste.")
        exit()

    log.info(f"Scarico info su [bold]{info.title}[/]...")

    # Get the seasons of the show (this could also contain dubbed versions)
    seasons = api.seasons(show_id)

    # Ask the user the season to download
    questions = [i.name for i in seasons]
    choice = list_input("Seleziona la versione che vuoi scaricare",
                        choices=questions)

    season_flt = list(filter(lambda i: i.name == choice, seasons))
    season = api.season(show_id, season_flt[0].season_id)

    qualities = {}
    questions = []
    if info.video_format.lower() == "sd":
        questions.append("SD")

        if season[0].embed_info:
            qualities.update({"sd": "embed_info"})
        else:
            qualities.update({"sd": "embed_info_sd"})
    else:
        questions.append("HD")
        questions.append("SD")
        qualities.update({"hd": "embed_info", "sd": "embed_info_sd"})

    quality = list_input(f"Seleziona la qualità", choices=questions)
    quality_code = qualities[quality.lower()]

    if len(season) > 1:
        choice = list_input(
            f"{len(season)} episodi disponibili. Li scarico tutti?",
            default="Si",
            choices=["Si", "No"],
        )

        if choice == "No":
            log.info(
                f"Inserisci gli episodi che vuoi scaricare separati da una virgola (,).\nEsempio: 1,4,5"
            )
            answer = None

            while not answer:
                p = Prompt.ask("Episodi", default=None)

                if not p:
                    continue

                answer = [int(i) for i in p.split(",")]

            season = [
                i for index, i in enumerate(season, 1) if index in answer
            ]

    for i in track(season, "Scarico..."):
        show_title = i.show_title
        episode_number = i.number

        embed_code = getattr(season[0], quality_code, "")
        output_dir = Path().joinpath("vvvvid", show_title)
        output_name = re_sub(r"\s", "_",
                             f"{show_title}_Ep_{episode_number}_{quality}")

        log.info(f"Scarico episodio #{episode_number}...")

        response = i.download(embed_code, output_dir, output_name)

        if response == DownloadResponse.HTTP_FAILED:
            log.critical(
                f"Impossibile scaricare [bold]{show_title} - #{episode_number} (ID: {show_id})[/]."
            )
            continue

        if not download:
            continue

        input_full = output_dir.joinpath(f"{output_name}.m3u8").absolute()
        output_mp4 = output_dir.joinpath(f"{output_name}.mp4").absolute()

        if output_mp4.exists():
            log.warning(f"L'episodio {episode_number} è già stato scaricato.")
            continue

        sp_run(
            [
                ffmpeg_path,  # type: ignore
                "-protocol_whitelist",
                "https,file,tls,tcp",
                "-i",
                input_full,
                "-c",
                "copy",
                "-bsf:a",
                "aac_adtstoasc",
                str(output_mp4),
            ], )

    log.info("Download completato.")
Example #26
0
def sci_dl_init_config():
    """
    initialize sci-dl configuration
    """
    try:
        console = Console()
        # base_url
        while True:
            base_url = Prompt.ask(_('SciHub base url'),
                                  default=DEFAULT_BASE_URL)
            if validators.url(base_url):
                break
            console.log(_('Invalid base_url %s') % base_url)

        # retries
        while True:
            retries = IntPrompt.ask(_('Number of failure download retries'),
                                    default=5)
            if MIN_RETRIES <= retries <= MAX_RETRIES:
                break
            console.log(
                _('invalid number of failure download retries %s, '
                  'must between %s and %s') %
                (retries, MIN_RETRIES, MAX_RETRIES))

        # use_proxy
        use_proxy = Confirm.ask(_('Do you want to use a proxy?'), default=True)
        proxy_protocol = DEFAULT_PROXY_PROTOCOL
        proxy_user = DEFAULT_PROXY_USER
        proxy_password = DEFAULT_PROXY_PASSWORD
        proxy_host = DEFAULT_PROXY_HOST
        proxy_port = DEFAULT_PROXY_PORT
        if use_proxy:
            # proxy_protocol
            proxy_protocol = Prompt.ask(_('Protocol of your proxy'),
                                        choices=PROXY_PROTOCOLS,
                                        default=DEFAULT_PROXY_PROTOCOL)

            # proxy_user
            proxy_user = Prompt.ask(
                _('User of your proxy, leave blank if not need'),
                default=DEFAULT_PROXY_USER)

            # proxy_password
            proxy_password = Prompt.ask(
                _('Password of your proxy, leave blank if not need'),
                password=True,
                default=DEFAULT_PROXY_PASSWORD,
            )

            # proxy_host
            while True:
                proxy_host = Prompt.ask(_('Host of your proxy'),
                                        default=DEFAULT_PROXY_HOST)
                if validators.domain(proxy_host) or validators.ipv4(
                        proxy_host) or validators.ipv4(proxy_host):
                    break
                console.log(_('Invalid host %s') % proxy_host)

            # proxy port
            while True:
                proxy_port = IntPrompt.ask(_('Port of your proxy'),
                                           default=DEFAULT_PROXY_PORT)
                if 1 <= proxy_port <= 65535:
                    break
                console.log(
                    _('Invalid port %s, should between 1 and 65535') %
                    proxy_port)

        # log file
        while True:
            log_file = Prompt.ask(_('Log file'), default=DEFAULT_LOG_FILE)
            try:
                log_directory = dirname(log_file)
                if not exists(log_directory):
                    makedirs(log_directory)
                break
            except Exception:
                console.log(_('Invalid log file %s') % log_file)

        # 输出目录
        while True:
            outdir = Prompt.ask(_('Where you want to save PDF file'),
                                default=expanduser('~'))
            if exists(outdir):
                break
            console.log(_('Invalid directory %s') % outdir)

        # 是否打开调试模式
        debug_mode = Confirm.ask(_('Enable DEBUG mode?'), default=False)
        config = Config({
            'base_url': base_url,
            'retries': retries,
            'use_proxy': use_proxy,
            'proxy_protocol': proxy_protocol,
            'proxy_user': proxy_user,
            'proxy_password': proxy_password,
            'proxy_host': proxy_host,
            'proxy_port': proxy_port,
            'log_file': log_file,
            'outdir': outdir,
            'debug_mode': debug_mode
        })
        config.write(CONFIG_FILE)
        console.log(
            _('Configurations saved, you can edit "%s" if needed.') %
            CONFIG_FILE)
    except SciDlError as e:
        logger.exception(e)
        raise click.UsageError(e)
    except Exception as e:
        logger.exception(e)
        raise click.UsageError(UNKNOWN_ERROR_MSG)
    return 0
Example #27
0
    footer layout.
    """
    product_range: str = ""
    for count, product in enumerate(settings.CLIENT_PRODUCT_CODES):
        product_range = "".join((product_range, f"{count + 1}-{product}   "))

    layout["footer"].update(
        gui.Status(Text("".join(("Available Products: ", product_range)), style="warning"))
    )


if __name__ == "__main__":
    with console.screen() as screen:
        while True:
            screen.update(layout)
            option = IntPrompt.ask("Select an option: ", choices=[f"{i + 1}" for i in range(5)])

            if option == 1:
                create_cart()

            elif option == 2:
                screen.update(layout)
                cart_selection = IntPrompt.ask(
                    "Select a cart: ", choices=[f"{i + 1}" for i in range(len(cart_ids))]
                )
                select_cart(cart_selection)

            elif option == 3:
                display_products()
                screen.update(layout)
                product_selection = IntPrompt.ask(
Example #28
0
def course_commands(course):
    command = Prompt.ask(f"[green bold]({course.title}) Enter a command")
    while True:
        if command == 'exit':
            console.clear()
            return
        elif command == 'modify':
            grid = Table()
            grid.add_column('ID')
            grid.add_column('Assignment')
            count = 1
            for assignment in course.assignments:
                grid.add_row(str(count), assignment.name)
                count += 1
            console.print(Columns(
                (grid, ),
                align="center",
                expand=True,
            ), )
            assignment_id = IntPrompt.ask(
                f"[green bold]({course.title}) Enter the ID of the assignment you want to modify"
            )
            property = Prompt.ask(
                f"[green bold]({course.title}) What do you want to modify?",
                choices=["Points", "Total Points", "Category"])
            if property == 'Points':
                new_points = IntPrompt.ask(
                    f"[green bold]({course.title}) What should the new amount of points be? It can have {course.assignments[assignment_id - 1].total_points} total"
                )
                course.assignments[assignment_id - 1].set_points(new_points)
            elif property == 'Total Points':
                new_points = IntPrompt.ask(
                    f"[green bold]({course.title}) What should the new amount of total points be?"
                )
                course.assignments[assignment_id -
                                   1].set_total_points(new_points)
            elif property == 'Category':
                grid = Table()
                grid.add_column('ID')
                grid.add_column('Category')
                count = 1
                for category in course.categories:
                    grid.add_row(str(count), category)
                    count += 1
                console.print(Columns(
                    (grid, ),
                    align="center",
                    expand=True,
                ), )
                category_id = IntPrompt.ask(
                    f"[green bold]({course.title}) What should the new category be?"
                )
                course.assignments[assignment_id - 1].set_category(
                    course.categories[category_id - 1])
            console.clear()
            course.calculate_grade()
            course.print_grade_table()
        elif command == 'add':
            name = Prompt.ask(
                f"[green bold]({course.title}) What should the name of the Assignment be?"
            )
            new_points = IntPrompt.ask(
                f"[green bold]({course.title}) What should the new amount of points be?"
            )
            new_t_points = IntPrompt.ask(
                f"[green bold]({course.title}) What should the new amount of total points be?"
            )
            grid = Table()
            grid.add_column('ID')
            grid.add_column('Category')
            count = 1
            for category in course.categories:
                grid.add_row(str(count), category)
                count += 1
            console.print(Columns(
                (grid, ),
                align="center",
                expand=True,
            ), )
            category_id = IntPrompt.ask(
                f"[green bold]({course.title}) What should the new category be?"
            )
            a = Assignment(f'{new_points} / {new_t_points}',
                           course.categories[category_id - 1], name, False)
            course.add_assignment(a)
            console.clear()
            course.calculate_grade()
            course.print_grade_table()
        elif command == 'reset':
            grid = Table()
            grid.add_column('ID')
            grid.add_column('Assignment')
            count = 1
            grid.add_row(str(0), 'All')
            for assignment in course.assignments:
                grid.add_row(str(count), assignment.name)
                count += 1
            console.print(Columns(
                (grid, ),
                align="center",
                expand=True,
            ), )
            assignment_id = IntPrompt.ask(
                f"[green bold]({course.title}) Enter the ID of the assignment you want to modify"
            )
            if assignment_id == 0:
                for assignment in course.assignments:
                    assignment.reset()
                course.assignments = [a for a in course.assignments if a.real]
            else:
                course.assignments[assignment_id - 1].reset()
            console.clear()
            course.calculate_grade()
            course.print_grade_table()
        elif command == 'help':
            print(f"[blue bold] modify: Change an aspect of an assignment")
            print(f"[yellow bold] add: Add a custom assignment")
            print(
                f"[purple bold] reset: Undo your changes for a specific assignment or the entire course"
            )
            print(f"[red bold] exit: Leave the course dialog")
        else:
            print(
                f"[green bold]({course.title}) [red]Invalid command! Enter 'help' to see possible commands."
            )
        command = Prompt.ask(f"[green bold]({course.title}) Enter a command")
        console.clear()
Example #29
0
    if args.interactive in [True, None]:
        name = Prompt.ask("Please enter a name for this service")
        description = Prompt.ask("Please enter a description of this service")
        _type = Prompt.ask(f"What type is this service?",
                           choices=types).lower().strip()
        remain_after_exit = Confirm.ask(
            "Should this service be considered offline when all of its processes are exited?",
            default=True)
        restart_on_death = Confirm.ask(
            "Should this service be automatically restarted on death?",
            default=False)
        max_restarts = 0
        if restart_on_death:
            max_restarts = IntPrompt.ask(
                "If enabled, how many times can this service restart before systemd gives up?"
            )
        exec_path = Prompt.ask(
            "What command should this service run? (e.g. /usr/local/opt/python-3.9.0/bin/python3.9 /root/thing.py)\n"
        )
        requires_network = Confirm.ask(
            "Should the service wait until network connectivity is established?"
        )
        user = None
        while user is None:
            user = Prompt.ask(
                "What user should this service run as? (e.g. root, nobody, etc.)",
                default="default")
            if user.lower() in ["root", "default", "none", " "]:
                user = None
                break
Example #30
0

console = Console()

"""
打印游戏说明
"""
display_readme()

"""
输入玩家数量
player_count: 玩家数量
"""
player_count = 0
while(player_count < 2 or player_count > 8):
    player_count = IntPrompt.ask("请输入玩家数量[violet][2~8]")

"""
输入玩家昵称
players: 玩家集合,每个玩家有三个属性: name,pass,cards
    name: 玩家昵称
    pass: 玩家拥有的 pass 卡片数量
    cards: 玩家拥有的负数卡片集合
"""
players = []
for i in range(player_count):
    name = Prompt.ask("请输入玩家 [yellow]%d[/yellow] 的昵称" % (i+1))
    players.append({"name": name, "pass": 9, "cards": []})

"""
cards: 负数卡片集合, 每张卡片有两个属性: value 和 owner