Esempio n. 1
0
def get_day():
    """
    Asks user to specify a day using colorful keyboard input selections and a star 

    Returns:
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """

    cli = Bullet(prompt="\n Choose a day of interest Please ?: ",
                 choices=[
                     'all', 'monday', 'tuesday', 'wednesday', 'thursday',
                     'friday', 'saturday', 'sunday'
                 ],
                 indent=0,
                 align=5,
                 margin=2,
                 bullet="★",
                 bullet_color=colors.bright(colors.foreground["cyan"]),
                 word_color=colors.bright(colors.foreground["yellow"]),
                 word_on_switch=colors.bright(colors.foreground["yellow"]),
                 background_color=colors.background["black"],
                 background_on_switch=colors.background["black"],
                 pad_right=5)

    day = cli.launch()
    print()
    print("Looks like you would like to get information for : \n", day.title())
    print('-' * 60)
    return day
Esempio n. 2
0
def get_month():
    """
    Asks user to specify a month using colorful keyboard input selections and a star 

    Returns:
        (str) month - name of the month to filter by, or "all" to apply no month filter
    """

    cli = Bullet(prompt="\n Choose a month of interest Please ?: ",
                 choices=[
                     'all', 'january', 'february', 'march', 'april', 'may',
                     'june'
                 ],
                 indent=0,
                 align=5,
                 margin=2,
                 bullet="★",
                 bullet_color=colors.bright(colors.foreground["cyan"]),
                 word_color=colors.bright(colors.foreground["yellow"]),
                 word_on_switch=colors.bright(colors.foreground["yellow"]),
                 background_color=colors.background["black"],
                 background_on_switch=colors.background["black"],
                 pad_right=5)

    month = cli.launch()
    print()
    print("Looks like you would like to get information for the month of: \n",
          month.title())
    print('-' * 50)
    return month
Esempio n. 3
0
def get_city():
    """
    Asks user to specify a city using colorful keyboard input selection 

    Returns:
        (str) city - name of the city to analyze
    """
    print('Hello! Let\'s explore some US bikeshare data!')
    print()

    cli = Bullet(prompt="\nPlease choose a City Please ?: ",
                 choices=["chicago", "new york city", "washington"],
                 indent=0,
                 align=5,
                 margin=2,
                 bullet="★",
                 bullet_color=colors.bright(colors.foreground["cyan"]),
                 word_color=colors.bright(colors.foreground["yellow"]),
                 word_on_switch=colors.bright(colors.foreground["yellow"]),
                 background_color=colors.background["black"],
                 background_on_switch=colors.background["black"],
                 pad_right=5)

    city = cli.launch()
    print()
    print("Looks like you would like to know more about: \n", city.title())
    print('-' * 50)
    return city
Esempio n. 4
0
def multi_season_prompt(db_session, prompt=None, heading=None):
    if not prompt:
        prompt = "Select one or multiple seasons from the list below:"
    all_seasons = db.Season.get_all_regular_seasons(db_session)
    choices = {f"{season.year}": season.year for season in all_seasons}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    seasons_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    selected_years = []
    while not selected_years:
        subprocess.run(["clear"])
        if heading:
            print_heading(heading, fg="bright_yellow")
        print_message(prompt, wrap=True)
        result = seasons_prompt.launch()
        if not result:
            print_error("\nYou must select at least one season!")
            pause(message="Press any key to continue...")
            continue
        selected_years = [choices[sel] for sel in result]
    return selected_years
Esempio n. 5
0
def file_types_prompt(prompt, valid_file_types=VigFile.ALL):
    if not prompt:
        prompt = "Select one or multiple file types from the list below:"
    choices = {f"{f}": f for f in VigFile if int(f) & valid_file_types == f}
    instructions = "(use SPACE BAR to select each file type, ENTER to confirm your selections)"
    file_types_prompt = Check(
        prompt=instructions,
        choices=list(choices.keys()),
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
    file_types = []
    while not file_types:
        subprocess.run(["clear"])
        print_message(prompt, fg="bright_yellow", bold=True, underline=True)
        result = file_types_prompt.launch()
        if not result:
            print_error("\nYou must select at least one file type!")
            pause(message="Press any key to continue...")
            continue
        file_types = [choices[sel] for sel in result]
    return file_types
Esempio n. 6
0
 def __init__(
     self,
     pages: List[DisplayPage],
     prompt: str,
     confirm_only: bool = False,
     yes_choice: str = "YES",
     no_choice: str = "NO",
     heading_color: str = None,
     text_color: str = None,
 ) -> None:
     self.choices_dict = self.get_prompt_choices(confirm_only, yes_choice,
                                                 no_choice)
     super(PageViewer, self).__init__(
         prompt=prompt,
         choices=list(self.choices_dict.keys()),
         bullet="",
         bullet_color=colors.foreground["default"],
         word_color=colors.foreground["default"],
         word_on_switch=colors.bright(colors.foreground["cyan"]),
         background_color=colors.background["default"],
         background_on_switch=colors.background["default"],
         shift=0,
         indent=0,
         margin=2,
         pad_right=0,
         align=0,
         return_index=False,
     )
     self.pages = pages
     self.confirm_only = confirm_only
     self.heading_color = heading_color
     self.text_color = text_color
     self.page_count = len(pages)
     self.page_index = 0
     self.needs_update = False
Esempio n. 7
0
File: cli.py Progetto: janik6n/jetzt
def run_install(app_path=None, jetzt_metadata=None, jetzt_metadata_file='jetzt_metadata.json'):
    prompt_pkg_name = 'What package from PyPI would you like to install (single pkg)? '
    prompt_dep_type = 'PROD or DEV dependency? '
    cli = SlidePrompt(
        [
            Input(prompt_pkg_name, word_color=colors.foreground["yellow"]),
            Bullet(prompt_dep_type,
                   choices=["PROD", "DEV"],
                   bullet=" >",
                   margin=2,
                   bullet_color=colors.bright(colors.foreground["cyan"]),
                   background_on_switch=colors.background["black"],
                   word_color=colors.foreground["white"],
                   word_on_switch=colors.foreground["white"]),
        ]
    )

    result = cli.launch()
    cli.summarize()

    pkg_name = ''
    dep_type = 'PROD'

    for result_item in result:
        key, value = result_item
        if key == prompt_pkg_name:
            pkg_name = value
        elif key == prompt_dep_type:
            dep_type = value

    if (len(pkg_name) < 1):
        sys.exit(Fore.RED + 'The PyPI package name to be installed should contain at least one character.')

    subprocess.call(f'source {app_path}/bin/install_pypi_pkg.sh "{pkg_name}" "{dep_type}" "{app_path}"', shell=True)
    sys.exit()
Esempio n. 8
0
File: cli.py Progetto: janik6n/jetzt
def run_reinstall(app_path=None, jetzt_metadata=None, jetzt_metadata_file='jetzt_metadata.json'):
    prompt_are_you_sure = 'Are you sure, you want to reinstall all dependencies? Are you sure, you are in an active virtualenv? '

    cli = SlidePrompt(
        [
            Bullet(prompt_are_you_sure,
                   choices=['No', 'Yes'],
                   bullet=" >",
                   margin=2,
                   bullet_color=colors.bright(colors.foreground["cyan"]),
                   background_on_switch=colors.background["black"],
                   word_color=colors.foreground["white"],
                   word_on_switch=colors.foreground["white"]),
        ]
    )

    result = cli.launch()
    cli.summarize()

    choice = 'No'

    for result_item in result:
        key, value = result_item
        if key == prompt_are_you_sure:
            choice = value

    if choice == 'Yes':
        subprocess.call(f'source {app_path}/bin/reinstall_reqs.sh "{app_path}"', shell=True)
    sys.exit()
Esempio n. 9
0
File: cli.py Progetto: janik6n/jetzt
def run_scaffold(jetzt_home=None, app_path=None, jetzt_metadata=None, jetzt_metadata_file='jetzt_metadata.json'):
    cli = SlidePrompt(
        [
            Input("What is the name of your project? ",
                  word_color=colors.foreground["yellow"]),
            Bullet("What kind of project would you like to scaffold? ",
                   choices=["Python - [Blank]", "Python - Flask", "Python - Jupyter"],
                   bullet=" >",
                   margin=2,
                   bullet_color=colors.bright(colors.foreground["cyan"]),
                   # background_color=colors.background["black"],
                   background_on_switch=colors.background["black"],
                   word_color=colors.foreground["white"],
                   word_on_switch=colors.foreground["white"]),
        ]
    )

    result = cli.launch()
    cli.summarize()

    project_name = ''
    project_type = ''

    for result_item in result:
        key, value = result_item
        if key == 'What is the name of your project? ':
            project_name = value
        elif key == 'What kind of project would you like to scaffold? ':
            project_type = value

    # Make project_name safe
    project_name = "".join([c for c in project_name if c.isalpha() or c.isdigit() or c == '_' or c == '-']).rstrip()

    ''' There should be at least one character in the project (directory) name. '''
    if (len(project_name) < 1):
        sys.exit(Fore.RED + 'The project_name should contain at least one character.')

    ''' Let's validate paths. '''
    if os.path.exists(jetzt_home) and os.path.isdir(jetzt_home):
        os.chdir(jetzt_home)
        ''' Again, let's make sure we do not try to create a project dir, which already exists. '''
        if os.path.exists(project_name):
            sys.exit(Fore.RED + 'The project directory already exists.')

        # Create project root
        os.mkdir(project_name)

    jetzt_metadata['project_name'] = project_name
    jetzt_metadata['project_type'] = project_type
    dump_jetzt_metadata(jetzt_metadata, f"{project_name}/{jetzt_metadata_file}")

    ''' Call a shell script to install packages etc. '''
    subprocess.call(f'source {app_path}/bin/jetzt_scaffold.sh {jetzt_home} {project_name} "{project_type}" "{app_path}"', shell=True)

    print(Fore.GREEN + 'Scaffold complete.')
    print('To jump in the new environment, run:')
    print(Fore.GREEN + f'cd {jetzt_home}/{project_name} && source venv/bin/activate')
    sys.exit()
Esempio n. 10
0
def main():
  configdir = "configs"
  cli = Bullet(
    prompt = "\nChoose your config (wisely):",
    choices = list(list_files(configdir)),
    indent = 0,
    align = 5,
    margin = 2,
    bullet = ">",
    bullet_color=colors.bright(colors.foreground["yellow"]),
    # word_color=colors.bright(colors.foreground["yellow"]),
	  word_on_switch=colors.bright(colors.foreground["yellow"]),
    # background_color=colors.background["black"],
    # 
    background_on_switch=colors.background["black"],
	  pad_right = 2
  )
  choice = cli.launch()
  os.system("dotbot -d . -c " + os.path.join(configdir, choice))
Esempio n. 11
0
def _render_menu(hosts):
    cli = Bullet(
        choices=list(hosts + ["exit"]),
        indent=0,
        align=4,
        margin=2,
        bullet=">",
        bullet_color=colors.bright(colors.foreground["cyan"]),
        background_on_switch=colors.background["black"],
        word_color=colors.bright(colors.foreground["red"]),
        word_on_switch=colors.bright(colors.foreground["red"]),
        pad_right=5,
    )

    _clear()

    print("\n    Choose ssh profile:")

    return cli.launch()
Esempio n. 12
0
File: cli.py Progetto: janik6n/jetzt
def run_update(app_path=None, jetzt_metadata=None, jetzt_metadata_file='jetzt_metadata.json'):
    prompt_pkg_name = 'Which of these would you like to update? '

    pkg_list = []

    ''' Read existing metadata if available. '''
    if os.path.exists(jetzt_metadata_file):
        with open(jetzt_metadata_file) as metadata_file:
            metadata = json.load(metadata_file)

    if 'pending_dependency_updates' in metadata:
        if 'dependencies' in metadata['pending_dependency_updates']:
            for key, value in metadata['pending_dependency_updates']['dependencies'].items():
                pkg_list.append(f"[PROD] {value['package']}: {value['installed_version']} > {value['latest_version']}")
        if 'dev_dependencies' in metadata['pending_dependency_updates']:
            for key, value in metadata['pending_dependency_updates']['dev_dependencies'].items():
                pkg_list.append(f"[DEV] {value['package']}: {value['installed_version']} > {value['latest_version']}")

    cli = SlidePrompt(
        [
            Bullet(prompt_pkg_name,
                   choices=pkg_list,
                   bullet=" >",
                   margin=2,
                   bullet_color=colors.bright(colors.foreground["cyan"]),
                   background_on_switch=colors.background["black"],
                   word_color=colors.foreground["white"],
                   word_on_switch=colors.foreground["white"]),
        ]
    )

    result = cli.launch()
    cli.summarize()

    pkg_name = ''
    pkg_to_update = ''
    dep_type = ''

    for result_item in result:
        key, value = result_item
        if key == prompt_pkg_name:
            pkg_name = value

    match_object = re.match(r'^\[(?P<dep_type>\w+)\]\s+(?P<pkg_to_update>[\w\-]+):.*$', pkg_name)
    if match_object:
        dep_type = match_object.group('dep_type')
        pkg_to_update = match_object.group('pkg_to_update')

    subprocess.call(f'source {app_path}/bin/update_pypi_pkg.sh "{pkg_to_update}" "{dep_type}" "{app_path}" ', shell=True)
    sys.exit()
Esempio n. 13
0
def data_sets_prompt(
    heading: str = None,
    prompt: str = None,
    valid_data_sets: Optional[List[DataSet]] = None,
    checked_data_sets: Optional[List[DataSet]] = None,
):
    if not prompt:
        prompt = "Select one or multiple data sets from the list below:"
    if not valid_data_sets:
        valid_data_sets = [DataSet.ALL]
    instructions = "(use SPACE BAR to select each data set, ENTER to confirm your selections)"
    valid_data_sets_int = sum(int(ds) for ds in valid_data_sets)
    choices = {
        f"{DATA_SET_TO_NAME_MAP[ds]}": ds
        for ds in DataSet if valid_data_sets_int & ds == ds
    }
    if checked_data_sets:
        checked_int = sum(int(ds) for ds in checked_data_sets)
        checked_data_sets = [
            f"{DATA_SET_TO_NAME_MAP[ds]}" for ds in DataSet
            if checked_int & ds == ds
        ]
    ds_prompt = DataSetCheck(
        prompt=instructions,
        choices=list(choices.keys()),
        checked_data_sets=checked_data_sets,
        check=EMOJIS.get("CHECK", ""),
        shift=1,
        indent=0,
        margin=2,
        check_color=colors.foreground["default"],
        check_on_switch=colors.foreground["default"],
        background_color=colors.foreground["default"],
        background_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
    )
    data_sets = []
    while not data_sets:
        subprocess.run(["clear"])
        if heading:
            print_heading(heading, fg="bright_yellow")
        print_message(prompt, wrap=True)
        result = ds_prompt.launch()
        if not result:
            print_error("\nYou must select at least one data set!")
            pause(message="Press any key to continue...")
            continue
        data_sets = [DATA_SET_FROM_NAME_MAP[sel] for sel in result]
    return data_sets
Esempio n. 14
0
def create_bullet_prompt(prompt, choices, wrap=True, max_line_len=70):
    if wrap:
        prompt = wrap_text(prompt, max_line_len)
    return Bullet(
        prompt,
        choices,
        bullet="",
        shift=1,
        indent=0,
        margin=2,
        bullet_color=colors.foreground["default"],
        background_color=colors.foreground["default"],
        background_on_switch=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
    )
Esempio n. 15
0
def create_scrolling_prompt(prompt, choices, wrap=True, max_line_len=70):
    if wrap:
        prompt = wrap_text(prompt, max_line_len)
    return ScrollBar(
        prompt,
        choices,
        height=8,
        pointer="",
        shift=1,
        indent=0,
        margin=2,
        pointer_color=colors.foreground["default"],
        word_color=colors.foreground["default"],
        word_on_switch=colors.bright(colors.foreground["cyan"]),
        background_color=colors.background["default"],
        background_on_switch=colors.background["default"],
    )
def lookup_bullet_color(ini_color_value):
    ini_color_value = ini_color_value.lower()
    color = ini_color_value.split('.')[-1]

    lookup_color = colors.foreground[BulletStrings.Colors.DEFAULT]
    if BulletStrings.Colors.FOREGROUND in ini_color_value:
        lookup_color = colors.foreground[color]
    elif BulletStrings.Colors.BACKGROUND in ini_color_value:
        lookup_color = colors.background[color]
    elif BulletStrings.Colors.REVERSE in ini_color_value:
        lookup_color = colors.REVERSE
    elif BulletStrings.Colors.RESET_REVERSE in ini_color_value:
        lookup_color = colors.RESET_REVERSE
    elif BulletStrings.Colors.RESET in ini_color_value:
        lookup_color = colors.RESET

    for _ in range(ini_color_value.count(BulletStrings.Colors.BRIGHT)):
        lookup_color = colors.bright(lookup_color)

    return lookup_color
Esempio n. 17
0
def menu_start():
    #UI Colour assignment
    bright_cyan = colors.bright(colors.foreground["cyan"])

    choices = is_users()
    menu = SlidePrompt([
        Bullet("\nOparu v0.0.1",
               choices=choices,
               bullet="",
               indent=0,
               pad_right=8,
               shift=1,
               align=1,
               margin=2)
    ])

    result = menu.launch()
    if result[0][1] == "Continue":
        continue_user()
    else:
        new_user()
Esempio n. 18
0
class MenuItem(ABC):
    # TODO: Update all menu items to use the menu_heading value

    _menu_item_text = ""
    menu_item_emoji = ""
    menu_heading = "Menu"
    background_color = colors.background["default"]
    background_on_switch = colors.background["default"]
    word_color = colors.foreground["default"]
    word_on_switch = colors.bright(colors.foreground["cyan"])
    exit_menu = False

    def __init__(self, app):
        self.app = app
        self.dotenv = app.dotenv
        self.config = app.config
        self.db_engine = app.db_engine
        self.db_session = app.db_session
        self.scraped_data = app.scraped_data

    @property
    def menu_item_text(self):
        return f"{self.menu_item_emoji} {self._menu_item_text}"

    @menu_item_text.setter
    def menu_item_text(self, menu_item_text):
        self._menu_item_text = menu_item_text

    def get_menu_heading(self, status):
        return f"{self.menu_heading}: {status}"

    def update_menu_heading(self, status, heading_color="bright_yellow"):
        subprocess.run(["clear"])
        print_heading(self.get_menu_heading(status), fg=heading_color)

    @abstractmethod
    def launch(self):
        pass
Esempio n. 19
0
 def rlaunch(self, key, depth):
   results = {}
   section_config = self.configuration[key]
   if section_config["prompt_type"] == "Check":
     ui = Check(section_config["prompt"],
                choices=section_config["choices"],
                check=" √",
                margin=2,
                check_color=colors.bright(colors.foreground["red"]),
                check_on_switch=colors.bright(colors.foreground["red"]),
                background_color=colors.background["black"],
                background_on_switch=colors.background["white"],
                word_color=colors.foreground["white"],
                word_on_switch=colors.foreground["black"],
                indent=depth * 2)
     choices = ui.launch()
     branching = section_config.get("branching")
     if branching is not None:
       for sub_key in choices:
         branching_key = branching.get(sub_key)
         if branching_key is not None:
           if branching_key.startswith("."):
             results[sub_key] = self.rlaunch("{}{}".format(key, branching_key), depth)
           else:
             results[sub_key] = self.rlaunch(branching_key, depth)
         else:
           raise ValueError("the key {} is not in branching {}".format(sub_key, branching.keys()))
       return results
     else:
       return results
   if section_config["prompt_type"] == "ListInput":
     ui = ListInput(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "Input":
     ui = Input(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "YesNo":
     ui = YesNo(section_config["prompt"],
       word_color=colors.foreground["yellow"],
       default=section_config["default"] if "default" in section_config else 'y',
       indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "Bullet":
     ui = Bullet(section_config["prompt"],
           choices=section_config["choices"],
           bullet=" >",
           margin=2,
           bullet_color=colors.bright(colors.foreground["cyan"]),
           background_color=colors.background["black"],
           background_on_switch=colors.background["black"],
           word_color=colors.foreground["white"],
           word_on_switch=colors.foreground["white"],
           indent=depth * 2)
     results = ui.launch()
     return results
   if section_config["prompt_type"] == "GoTo":
     for sub_key in section_config["goto"]:
       if sub_key.startswith("."):
         sub_value = self.rlaunch("{}{}".format(key, sub_key), depth)
         sub_key = sub_key[1:]
       else:
         sub_value = self.rlaunch(sub_key, depth)
       if isinstance(sub_value, bool) or sub_value:
         # If True/False or other non-empty data (! "", [], {})
         results[sub_key] = sub_value
     return results
Esempio n. 20
0
 YesNo("Are you a good student? ",
     default = 'y',
     word_color = colors.foreground["yellow"]),
 Input("Who are you? ",
     default = "Batman",
     word_color = colors.foreground["yellow"]),
 Input("Really? ",
     word_color = colors.foreground["yellow"]),
 Numbers("How old are you? ", 
     word_color = colors.foreground["yellow"], 
     type = int),
 Bullet("What is your favorite programming language? ",
     choices = ["C++", "Python", "Javascript", "Not here!"],
     bullet = " >",
     margin = 2,
     bullet_color = colors.bright(colors.foreground["cyan"]),
     background_color = colors.background["black"],
     background_on_switch = colors.background["black"],
     word_color = colors.foreground["white"],
     word_on_switch = colors.foreground["white"]
 ),
 Check("What food do you like? ",
     choices = ["🍣   Sushi", 
                "🍜   Ramen",
                "🌭   Hotdogs", 
                "🍔   Hamburgers", 
                "🍕   Pizza",
                "🍝   Spaghetti",
                "🍰   Cakes",
                "🍩   Donuts"],
     check = " √",
Esempio n. 21
0
###################
## Main Function ##
###################

# +
if __name__ == "__main__":
    print("Program 5a: Plot Bid or Ask Prices by Venue")

    TYPE = Bullet(prompt="\nPlease choose a filetype: ",
                  choices=["A", "B", "C", "D"],
                  indent=0,
                  align=5,
                  margin=2,
                  bullet=">",
                  bullet_color=colors.bright(colors.foreground["green"]),
                  word_color=colors.bright(colors.foreground["yellow"]),
                  word_on_switch=colors.bright(colors.foreground["green"]),
                  background_color=colors.background["black"],
                  background_on_switch=colors.background["black"],
                  pad_right=5)

    filetype = TYPE.launch()

    print("You chose:", filetype)

    filetype = pf.get_validInput(filetype, 4)

    DATE = Bullet(prompt="\nPlease choose a filetype: ",
                  choices=projLists.file_list,
                  indent=0,
Esempio n. 22
0
def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.
    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """

    print(
        'Hello! My Name is Jason. Let\'s explore some US bikeshare data today!'
    )
    cli = Bullet(
        prompt="\nPlease select a city [move 👉 cursor with arrow keys]",
        choices=["chicago", "new york city", "washington"],
        indent=0,
        align=5,
        margin=2,
        bullet="👉",
        bullet_color=colors.bright(colors.foreground["cyan"]),
        word_color=colors.bright(colors.foreground["red"]),
        word_on_switch=colors.bright(colors.foreground["blue"]),
        background_color=colors.background["gray"],
        background_on_switch=colors.background["black"],
        pad_right=5)
    result = cli.launch()
    city = result
    print("You chose:", result)
    cli = Bullet(
        prompt=
        "\nPlease select month name(Only January to June or all [move 👉 cursor with arrow keys]",
        choices=[
            "all", "january", "february", "march", "april", "may", "june"
        ],
        indent=0,
        align=5,
        margin=2,
        bullet="👉",
        bullet_color=colors.bright(colors.foreground["cyan"]),
        word_color=colors.bright(colors.foreground["red"]),
        word_on_switch=colors.bright(colors.foreground["blue"]),
        background_color=colors.background["gray"],
        background_on_switch=colors.background["black"],
        pad_right=5)
    result = cli.launch()
    month = result
    print("You chose:", result)
    cli = Bullet(
        prompt=
        "\nPlease select day of week or all [move 👉 cursor with arrow keys]",
        choices=[
            "all", "monday", "tuesday", "wednesday", "thursday", "friday",
            "saturday", "sunday"
        ],
        indent=0,
        align=5,
        margin=2,
        bullet="👉",
        bullet_color=colors.bright(colors.foreground["cyan"]),
        word_color=colors.bright(colors.foreground["red"]),
        word_on_switch=colors.bright(colors.foreground["blue"]),
        background_color=colors.background["gray"],
        background_on_switch=colors.background["black"],
        pad_right=5)
    result = cli.launch()
    day = result
    print("You chose:", result)
    return (city, month, day)
Esempio n. 23
0
from bullet import ScrollBar
from bullet import colors
import random
''' Pumping bars. '''

n = [random.randint(0, 15) for _ in range(1000)]
choices = []
# Do some interpolation
for i in range(0, len(n) - 1):
    choices.append(n[i])
    choices.append(int((n[i] + n[i + 1]) / 2))
choices = list(map(lambda i: "▉" * i, choices))

cli = ScrollBar(prompt="",
                choices=choices,
                height=1,
                pointer="",
                word_color=colors.bright(colors.foreground["cyan"]),
                word_on_switch=colors.bright(colors.foreground["cyan"]),
                background_color=colors.background["black"],
                background_on_switch=colors.background["black"])
print('\n')
cli.launch()
Esempio n. 24
0
class Menu(MenuItem, ABC):
    menu_text = ""
    selected_menu_item_text = ""
    pointer = ""
    menu_items = []
    bullet_color = colors.bright(colors.foreground["default"])
    check_color = colors.bright(colors.foreground["default"])
    check_on_switch = colors.bright(colors.foreground["default"])
    pointer_color = colors.bright(colors.foreground["default"])

    def __init__(self, app):
        super().__init__(app)

    @property
    def menu_item_text_list(self):
        return list(self.menu_item_dict.keys())

    @property
    def menu_item_dict(self):
        return {
            ellipsize(item.menu_item_text, 70): item
            for item in self.menu_items
        }

    @property
    def menu_item_count(self):
        return len(self.menu_items)

    @property
    def selected_menu_item_pos(self):
        if not self.selected_menu_item_text:
            return 0
        menu_item_pos_dict = {
            ellipsize(item.menu_item_text, 70): i
            for i, item in enumerate(self.menu_items)
        }
        return menu_item_pos_dict.get(self.selected_menu_item_text, 0)

    @property
    def selected_menu_item(self):
        return self.menu_item_dict.get(self.selected_menu_item_text)

    def launch(self):
        exit_menu = False
        while not exit_menu:
            subprocess.run(["clear"])
            self.populate_menu_items()
            result = self.prompt_user_for_menu_selection()
            if result.failure:
                return result
            exit_menu = result.value
        return Result.Ok(exit_menu)

    def prompt_user_for_menu_selection(self):
        if self.menu_item_count <= 8:
            menu = self._get_bullet_menu()
            menu.pos = self.selected_menu_item_pos
        else:
            menu = self._get_scroll_menu()
        self.selected_menu_item_text = menu.launch()
        result = self.selected_menu_item.launch()
        exit_menu = self.selected_menu_item.exit_menu
        return Result.Ok(exit_menu) if result.success else result

    @abstractmethod
    def populate_menu_items(self):
        pass

    def _get_bullet_menu(self):
        return Bullet(
            self.menu_text,
            choices=self.menu_item_text_list,
            bullet=self.pointer,
            shift=1,
            indent=2,
            margin=2,
            bullet_color=self.bullet_color,
            background_color=self.background_color,
            background_on_switch=self.background_on_switch,
            word_color=self.word_color,
            word_on_switch=self.word_on_switch,
        )

    def _get_scroll_menu(self):
        return ScrollBar(
            self.menu_text,
            choices=self.menu_item_text_list,
            height=8,
            pointer=self.pointer,
            shift=1,
            indent=2,
            margin=2,
            pointer_color=self.pointer_color,
            background_color=self.background_color,
            background_on_switch=self.background_on_switch,
            word_color=self.word_color,
            word_on_switch=self.word_on_switch,
        )