Beispiel #1
0
def main():
    # initialize the rich environment for command line formatting
    console = Console()

    # get user inputs
    ingredients = console.input("Enter the ingredients you have (each separated by a comma and a space): ")
    amount_recipes = int(console.input("How many recipes do you want to see? "))
    while amount_recipes < 1:
        amount_recipes = int(console.input("Please enter 1 or higher: "))

    # call method to get results
    recipes, missing, links = get_missing_ingredients(ingredients, amount_recipes)

    # format output
    # unpack results and format into table
    from rich.table import Table

    # initialize table
    table = Table(title='Recipes you can make with ' + ingredients)
    table.add_column("Recipe Name", style="cyan")
    table.add_column("Missing Ingredients", style="magenta")
    table.add_column("Recipe Link", style="green")

    # load data
    for recipe, missing_ingredients, link in zip(recipes, missing, links):
        table.add_row(recipe, missing_ingredients, link)
    # FIXME: make full links and ingredient list show up in smaller windows

    console.print(table)
Beispiel #2
0
def choice_dialog(console: Console, message: str, default: bool = None):
    """
    A simple yes/no console dialog option
    :param console: rich.Console Instance
    :param message: Message should be asked
    :param default: Default value when enter is pressed without an input (None, True, False)
    :return: Answer (True, False)
    """
    yes = "y" if default is not True else "[green]Y[/green]"
    no = "n" if default is not False else "[red]N[/red]"

    result = None
    while result is None:
        choice = console.input(
            f"[[green]?[/green]] {message} ({yes}/{no}) ").lower()
        if choice in ["yes", "y"]:
            result = True
        elif choice in ["no", "n"]:
            result = False
        elif choice == "":
            if default is not None:
                result = default

        if result is None:
            console.print("[red]Invalid input, please try again[/red]")

    return result
Beispiel #3
0
class Active(Base):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.console = Console(record=True, stderr=True)
        # load .classes_ at init, and load when load_model

        print(f"Active meta learner instanciated with {args}, {kwargs}")

    def loop(self, name, batch_size=10, n_iter: int = 2, *args):
        if name not in (
                "uncertainty", ):  # TODO : allow functions from modAL ?
            raise ValueError("only uncertainty sampling is supported for now")

        if not hasattr(self.model, "partial_fit") and batch_size < 20:
            batch_size = ask_increase_batch_size(self.console, batch_size)

        for i in range(n_iter):
            cands = uncertainty(self.model, self.data)
            batch_indices = cands.argsort()[-batch_size:]
            batch = self.data.iloc[batch_indices].copy(
            )  # beware, no `.iloc` in dask

            y = list()
            for x in batch.to_dict(orient="records"):
                y_single = self.console.input(
                    f"""Please provide a label for {x}\n""")
                if not y_single:
                    raise ValueError("you must answer the question")
                y.append(y_single)
            self.fit(batch, y)

            batch.loc[:, "_target"] = y
            print(f"fitted model on data: \n{batch}\n")
Beispiel #4
0
def main():
    signal.signal(signal.SIGINT, signal_handler)
    console = Console()

    global gruvbox_factory
    gruvbox_factory = GoNord()
    gruvbox_factory.reset_palette()
    add_gruvbox_palette()

    console.print(
        Panel('🏭 [bold green] Gruvbox Factory [/] 🏭',
              expand=False,
              border_style='yellow'))
    console.print(
        '⚠️ WARNING ⚠️\n[italic]make sure you\'re in the same directory of the image you want to convert [/]\n'
    )
    image_file = console.input(
        '🖼️ [bold yellow]Which image do you want to manufacture?[/] ')

    try:
        image = gruvbox_factory.open_image(image_file)
    except:
        console.print(
            '❌ [red]We had a problem in the pipeline! Make sure you\'re in the same path of the image you want to convert! [/]'
        )
        sys.exit(0)
    console.print('🔨 [yellow]manufacturing your gruvbox wallpaper...[/]')
    gruvbox_factory.convert_image(image, save_path=('gruvbox_' + image_file))

    console.print('✅ [bold green]Done![/] [green](saved as gruvbox_' +
                  image_file + ')[/]')
Beispiel #5
0
def ipi():  # Defines ip info command
    console = Console()
    keys_file = open("keys.txt")
    read = keys_file.readlines()
    access_token = read[0].rstrip()
    handler = ipinfo.getHandler(access_token)
    ip_address = console.input("[bold blue]Enter an IP: [/bold blue]")
    details = handler.getDetails(ip_address)
    ip = details.ip
    city = details.city
    region = details.region
    country = details.country_name
    ping = subprocess.check_output("ping -c 4 " + ip_address, shell=True)
    ping_out = ping.decode()
    try:
        hn = details.hostname
        org = details.org
    except AttributeError:
        hn = "No Hostname found for requested IP "
        org = "No Organization found for requested IP"

    @render_group()
    def get_panels():
        yield Panel(
            city + "," + region + " " + country,
            style="black on spring_green2",
            title="Location",
        )
        yield Panel(org, style="black on spring_green1", title="Organization")
        yield Panel(hn,
                    style="black on medium_spring_green",
                    title="Hostnmame")
        yield Panel(ping_out, style="black on cyan2", title="Ping")

    rich.print(Panel(get_panels(), title="INFO FOR " + ip))
Beispiel #6
0
class VersionManager:
    def __init__(self):
        self.console = Console()
        self.location = Location()
        self.utils = Utils()

        self.home = str(Path.home())
        self.version_manager_loc = "sh $HOME/.config/zsh-config/groups/Version-Manager/"

    def pyenv(self):
        self.console.print()
        self.console.print("Installing [bold red]pyenv[/]...")
        os.system(self.version_manager_loc + "pyenv.sh")


    def rbenv(self):
        self.console.print()
        self.console.print("Installing [bold red]rbenv[/]...")
        os.system(self.version_manager_loc + "rbenv.sh")

    def sdkman(self):
        self.console.print()
        self.console.print("Installing [bold red]SDK Man[/]...")
        os.system(self.version_manager_loc + "sdkman.sh")

    def gvm(self):
        self.console.print()
        self.console.print("Installing [bold red]gvm[/]...")
        os.system(self.version_manager_loc + "gvm.sh")

    def run(self):
        tasks = {
            0: "All",
            1: "pyenv",
            2: "rbenv",
            3: "sdkman",
            4: "gvm",
        }

        self.console.rule("Install package from?")
        self.utils.tasks_print(tasks)

        choice = self.console.input("What is your [bold red]choice[/]? :smiley: ")
        self.console.print(f'You entered {choice}')
        choice = int(choice)

        if choice == 0:
            self.pyenv()
            self.rbenv()
            self.sdkman()
        elif choice == 1:
            self.pyenv()
        elif choice == 2:
            self.rbenv()
        elif choice == 3:
            self.sdkman()
        elif choice == 4:
            self.gvm()
Beispiel #7
0
def test_input_legacy_windows(monkeypatch, capsys):
    def fake_input(prompt):
        console.file.write(prompt)
        return "bar"

    monkeypatch.setattr("builtins.input", fake_input)
    console = Console(legacy_windows=True)
    user_input = console.input(prompt="foo:")
    assert capsys.readouterr().out == "foo:"
    assert user_input == "bar"
Beispiel #8
0
def main():
    args = parse_args()
    console = Console()
    certificate = args.certificate

    if (certificate is not None) and (not os.path.exists(certificate)):
        console.print(_('[red]The file {} does not exist.').format(certificate))
        sys.exit(1)

    if args.insecure:
        certificate = False
        console.print(_('[bold yellow]WARNING:[/bold yellow][yellow] The program is currently running in '
                        '[bold yellow]INSECURE[/bold yellow] mode. Server authenticity will not be checked.'))

    api = SmershAPI(args.url, certificate=certificate)

    print_hello(console)

    try:
        while not api.authenticated:
            username = console.input(_('Enter your username: '******'Enter your password (will not be echoed): '), password=True)

            try:
                if api.authenticate(username, password):
                    username = User.get(api, api.authenticated_user_id).username
                    console.print(_('[green]:heavy_check_mark: Hello, [bold]{}[/bold]. You are successfully logged in').format(username))
                else:
                    console.print(_('[red]:cross_mark: Unable to log you in. Your credentials seem invalid'))
            except requests.exceptions.ConnectionError:
                console.print(_("[red]Oh no. I can't connect to the specified URL. Please check there is no typo and "
                                "that the host accepts connections then try again."))
            except requests.exceptions.HTTPError as e:
                console.print(_('[red]An HTTP error occurred (code {}): {}').format(e.response.status_code, e))
    except EOFError:
        # The \n is important because we need to not print inside the input caption
        console.print(_('\nBye'))
        sys.exit(0)

    app = App(api)
    sys.exit(app.cmdloop())
Beispiel #9
0
    def write_labels_interactively(self, feature_column_names,
                                   label_column_name):
        labels = []
        console = Console()
        for i, row in self.dataset.iterrows():
            console.print(f"[bold green]--------------------------------")
            for feature_name in feature_column_names:
                feature = row[feature_name]
                console.print(
                    f"[bold yellow] {feature_name} [bold red]{feature}?")

            console.print(f"[bold green]--------------------------------")
            label = console.input(
                f"[bold blue] Food safety issue (1) or not (0)?")
            self.dataset.at[i, label_column_name] = label
def ask_for_saving(console: Console) -> (bool, str):
    """
    Ask the user if he wants to save the passwords to a file.
    :param console: Console object to display the messages.
    :return: True and file name to save passwords to if the user wants to save the passwords to a file,
             False and None otherwise.
    """
    should_save_to_file = None
    while not type(should_save_to_file) == bool:
        value = console.input(
            ':memo: Do you want to save passwords to file? [Y/n] ')
        if not value:
            value = 'y'
        if (lower := value.lower()) in ('y', 'yes'):
            should_save_to_file = True
        elif lower in ('n', 'no'):
            should_save_to_file = False
Beispiel #11
0
def start():
    console = Console()
    console.print("Pythonic Ro interactions parser v1")

    with open('interactions.json') as fp:
        jdata = json.load(fp)

    if len(sys.argv) < 2:
        console.print("Type exit to quit")
        while True:
            input = console.input("Enter drugs: ")
            drugs = list(map(str.lower, input.split()))
            if 'exit' in drugs:
                exit()

            find_interactions(jdata, drugs)
    else:
        find_interactions(jdata, sys.argv)
Beispiel #12
0
class Utils:
    def __init__(self):
        self.console = Console()

    def close(self):
        """Exit the program."""
        try:
            sys.exit(1)
        except SystemExit:
            os._exit(1)

    def lang_prompt(self):
        """Prompt the user for a language."""
        language = self.console.input("[green]Enter your language:[/green] ")
        if language not in compilers_:
            self.console.print("Language is not supported!", style="bold red")
        return language

    def print_msg_box(self, msg, indent=1, width=None, title=None):
        """Print message-box with optional title."""
        lines = msg.split("\n")
        true_lines = []

        for line in lines:
            if len(line) > width:
                for trimmed in range((len(line) // width) + 1):
                    true_lines.append(line[width * trimmed:width +
                                           (trimmed * width)])
            else:
                true_lines.append(line)

        lines = [i for i in true_lines if i]
        space = " " * indent
        if not width:
            width = max(map(len, lines))
        box = f'┏{"━" * (width + indent * 2)}┓\n'
        if title:
            box += f"┃{space}{title:<{width}}{space}┃\n"
            box += f'┃{space}{"-" * len(title):<{width}}{space}┃\n'
        box += "".join(
            [f"┃{space}{line:<{width}}{space}┃\n" for line in lines])
        box += f'┗{"━" * (width + indent * 2)}┛'
        return box
Beispiel #13
0
def create_config(console: Console) -> Config:
    """
    Create a Config object from the user input.
    :param console: Console object to display the messages.
    :return: Config object.
    """
    choice_yes = ('y', 'yes')
    choice_no = ('n', 'no')

    use_user_config = None
    while not type(use_user_config) == bool:
        use_user_config = console.input(
            ':gear: Do you want to use custom config? [Y/n] ')
        if not use_user_config:
            use_user_config = 'y'
        if (lower := use_user_config.lower()) in choice_yes:
            use_user_config = True
        elif lower in choice_no:
            use_user_config = False
Beispiel #14
0
def dinfo():  # Defines the dns command
    console = Console()
    url = console.input(
        "[blue]Enter a Domain[/blue] :warning:[bold red](Do not use WWW)[/bold red]:warning: [blue][/blue]"
    )
    for a in dns.resolver.resolve(url, "a"):
        print(
            "[red]  A Record :arrow_forward:  :arrow_forward:  :arrow_forward:  :arrow_forward: [/red]",
            a,
        )
    for mx in dns.resolver.resolve(url, "mx"):
        print(
            "[red] MX Record :arrow_forward:  :arrow_forward:  :arrow_forward:  :arrow_forward: [/red]",
            mx,
        )
    for ns in dns.resolver.resolve(url, "ns"):
        print(
            "[red] NS Record :arrow_forward:  :arrow_forward:  :arrow_forward:  :arrow_forward: [/red]",
            ns,
        )
Beispiel #15
0
class Patch:
    def __init__(self):
        self.console = Console()
        self.location = Location()
        self.utils = Utils()

        self.prefix_cmd = "sh $HOME/" + self.location.PATCH_LOCATION

    def youcompleteme(self):
        self.console.print()
        self.console.print("Patching [bold red]YouCompleteMe[/]...")
        cmd = self.prefix_cmd + "YouCompleteMe.sh"
        os.system(cmd)

    def nerdfont(self):
        self.console.print()
        self.console.print("Patching [bold red]Nerd Font[/]...")
        cmd = self.prefix_cmd + "nerd-font.sh"
        os.system(cmd)

    def run(self):
        tasks = {
            0: "All",
            1: "YouCompleteMe",
            2: "Nerd Font"
        }

        self.console.rule("Patch package from?")
        self.utils.tasks_print(tasks)

        choice = self.console.input("What is your [bold red]choice[/]? :smiley: ")
        self.console.print(f'You entered {choice}')
        choice = int(choice)

        if choice == 0:
            self.youcompleteme()
            self.nerdfont()
        elif choice == 1:
            self.youcompleteme()
        elif choice == 2:
            self.nerdfont()
Beispiel #16
0
class Interactive(Base):
    def __init__(self, *args, name=None, save_on_quit=True, **kwargs):
        super().__init__(*args, **kwargs)
        self.console = Console(record=True, stderr=True)

        if save_on_quit:

            def signal_handler(sig, frame):
                name = self.name + "pkl"
                print(f"dumping model at {name}")
                joblib.dump(self.model, name)
                sys.exit(0)

            signal.signal(signal.SIGINT, signal_handler)

    def active(self):
        slim = self.model
        D = self.data
        slim._prefit(D)
        stack = set()  # already seen candidates
        while True:
            cands = slim.generate_candidates(stack=stack)
            for cand, tids in cands:
                data_size, model_size, update_d, prune_set = slim.evaluate(
                    cand)
                diff = (slim.model_size_ + slim.data_size_) - (data_size +
                                                               model_size)
                include = self.console.input(f"""
                    Do we include candidate {cand} into our pattern set ?\n
                    estimated MDL diff : {diff}\n
                    Answer by `y`|`yes` or `n`|`no`
                """)
                if include.lower() in ("yes", "y"):
                    slim.codetable_.update(update_d)
                    slim.data_size_ = data_size
                    slim.model_size_ = model_size
Beispiel #17
0
class AddTask:
    """ Class to create new tasks and categories in the database

    This class only has the purpose to create and display the preview of tasks, also create new categories and save 
    tasks in it. The arguments that will be used to create it are the task content and optionally a category

    Attributes
    ----------
    category_id: int
        Category Id where the note will be stored (Default 1)

    category_name: str
        Category name where the note will be stored (Default 'TODO Task')

    creation_date: date
        Date of the creation of the note (Today date)

    task: Union[list[str], str]
        Task or list of task that will be store in database

    console: Console
        (Rich) Console for beatiful printting
    """

    category_id: int = 1
    category_name: str = 'TODO Task'
    creation_date: date
    task: Union[list[str], str]
    console: Console

    def __init__(self, args: Namespace) -> None:
        """ Constructor fro AddTask class 
        
        Parameters
        ----------
        args : NameSpace
            Arguments of argparse
        """
        self.console = Console()
        self.db = SQLiteConnection()
        self.creation_date = datetime.now().date()

        if not add_task_args_empty(args):
            try:
                if args.category:
                    # Will create a new category if not exists
                    self.category_name = format_argument_text(args.category)
                    self.save_category()

                if args.text:
                    self.task = format_task_text(args.text)

                    if args.preview:
                        self._show_preview()
                    else:
                        self.save_task()

            except KeyboardInterrupt:
                self.console.print(
                    '[bold yellow]\nCorrectly Cancelled[/bold yellow]')

        else:
            PrintFormatted.print_help(help_text.ADD_TASK_USAGE_TEXT)

    @classmethod
    def set_args(cls, args: Namespace) -> None:
        """ Set args and initialize class
        
        Parameters
        ----------
        args: NameSpace
            Arguments of argparse
        """
        cls(args)

    def category_exists(self) -> bool:
        """ Checks if the typed category exists

        Returns
        -------
        exists: bool
            Boolean value flag if the category already exists
        """
        sql = f"SELECT {categories.COLUMN_ID} FROM {categories.TABLE_NAME} WHERE {categories.COLUMN_NAME} = '{self.category_name}'"
        query = self.db.exec_sql(sql)
        categories_list: list[tuple] = query.fetchall()

        if categories_list:  # categories_list == []
            self.category_id = categories_list[0][0]
            return True
        return False

    def save_category(self) -> None:
        """ Creates and saves a new category if not exists

        When the task(s) is going to be saved and is created a new category, it will set the id of this new one and 
        store the task(s) in this created category
        """
        if len(self.category_name) <= 30:
            if not self.category_exists():
                sql = f'INSERT INTO {categories.TABLE_NAME} ({categories.COLUMN_NAME}) VALUES (?)'
                cursor = self.db.exec_sql(sql, (self.category_name, ))

                self.category_id = cursor.lastrowid

                self.db.commit()
                PrintFormatted.print_category_creation(self.category_name)
            else:
                custom_theme = Theme({
                    'msg': '#31f55f bold',
                    'name': '#616161 italic'
                })
                PrintFormatted.custom_print(
                    f'[msg]Category selected:[/msg][name]{self.category_name}[/name]',
                    custom_theme)
        else:
            self._ask_category()

    def save_task(self) -> None:
        """ Function in charge to store the tasks in the database"""

        sql = f'INSERT INTO {tasks.TABLE_NAME} ({tasks.COLUMN_CONTENT},{tasks.COLUMN_CREATION}, '\
              f'{tasks.COLUMN_CATEGORY}) VALUES (?,?,?);'

        with self.console.status('[bold yellow]Saving Tasks...') as status:
            if isinstance(self.task, list):
                for task in self.task:
                    values = (task, self.creation_date, self.category_id)
                    self.db.exec_sql(sql, values)

                    PrintFormatted.print_content_storage(
                        task, self.category_name)

            elif isinstance(self.task, str):
                values = (self.task, self.creation_date, self.category_id)
                self.db.exec_sql(sql, values)

                PrintFormatted.print_content_storage(self.task,
                                                     self.category_name)

            if self.task:
                self.console.print('[bold green]✔️Task Saved')
            else:
                self.console.print('[bold red] 💥 No Task Saved')

            status.stop()

        self.db.commit()
        self.db.close()

    def _ask_category(self) -> None:
        """ Function that asks to the user to introduce different category name """

        text = '⚠️[yellow]Category name is too long (Max. 30 characters).[/yellow]Write another name:'
        self.category_name = self.console.input(text).strip()

        while len(self.category_name) == 0 or len(self.category_name) > 30:
            self.category_name = self.console.input(text).strip()
        else:
            self.save_category()

    def _show_preview(self) -> None:
        """ Method that displays a table with the tasks written"""
        formatted_date = self.creation_date.strftime('%Y-%m-%d')

        self.console.rule('Preview', style='purple')

        table = Table(box=box.ROUNDED)
        table.add_column('Task', overflow='fold')
        table.add_column('Creation Date', justify='center', style='yellow')

        if isinstance(self.task, list):
            for task in self.task:
                table.add_row(task, formatted_date)
        elif isinstance(self.task, str):
            table.add_row(self.task, formatted_date)

        self.console.print(table, justify='center')

        if PrintFormatted.ask_confirmation(
                '[yellow]Do you want to save them?(y/n):[/yellow]'):
            self.save_task()
Beispiel #18
0
from github import Github
from rich.console import Console
from rich.table import Table

console = Console()

# Set your Github access token
console.print("Enter a Github access token that has the `delete_repo` permission", style="blue")
console.print ("(https://docs.github.com/en/free-pro-team/github/authenticating-to-github/creating-a-personal-access-token)")
token = console.input("\nAccess token: ")

g = Github(token)

  
def printRepos():
  allRepos = []
  repoTable = Table(title="Repos")
  repoTable.add_column("#")
  repoTable.add_column("Name")
  repoTable.add_column("URL")
  repoTable.add_column("Privacy")
  repoTable.add_column("Forked?")
  i = 0
  g.get_user().update()
  for repo in g.get_user().get_repos():
    allRepos.append(repo)
    i+=1

    repoTable.add_row(str(i), repo.name, repo.html_url, ("Private" if repo.private else "Public"), ("Yes" if repo.fork else "No"))
  console.print(repoTable)
  return allRepos
Beispiel #19
0
                val = ord(key)
                if val > 57 or val < 48:
                    return
                # String to int via conversion
                val = val - 48
                page = wikipedia.page(ls[val])

                # Print the results of the page
                console.print(
                    Panel.fit("[bold yellow]" + page.url +
                              "[/bold yellow]\n[bold magenta]" + page.title +
                              "[/bold magenta]",
                              title="url & title"))
                console.print(Panel.fit(page.content, title="content"))
                break
            except:
                console.print(
                    "[bold red]Try again, this time a number please.[/bold red]\n"
                )


if __name__ == "__main__":
    console = Console()
    while True:
        query = console.input(
            "[bold yellow](type 'quit' to exit) $> [/bold yellow]")
        # Exit if the user says so
        if query == 'quit':
            exit(0)
        process(query, console)
Beispiel #20
0
def test_input(monkeypatch, capsys):
    monkeypatch.setattr("builtins.input", lambda: "bar")
    console = Console()
    user_input = console.input(prompt="foo:")
    assert capsys.readouterr().out == "foo:"
    assert user_input == "bar"
    if isinstance(data, str):
        return ''.join([format(ord(i), "08b") for i in data])
    elif isinstance(data, bytes) or isinstance(data, np.ndarray):
        return [format(i, "08b") for i in data]
    elif isinstance(data, int) or isinstance(data, np.uint8):
        return format(data, "08b")
    else:
        raise TypeError("Type not supported.")


def decode(image):
    console.print(log("Decoding..."))
    image = cv2.imread(image)
    binary_data = ""
    for row in image:
        for pixel in row:
            r, g, b = to_bin(pixel)
            binary_data += r[-1]
            binary_data += g[-1]
            binary_data += b[-1]
    all_bytes = [binary_data[i:i + 8] for i in range(0, len(binary_data), 8)]
    decoded_data = ""
    for byte in all_bytes:
        decoded_data += chr(int(byte, 2))
        if decoded_data[-5:] == "=====":
            break
    return decoded_data[:-5]


text = decode(console.input("[blue]image name ->"))
console.input(f'[blue]ENCODED TEXT:\n[red]{text}\n')
Beispiel #22
0
from rich.panel import Panel
from rich.table import Table
from rich import print as rprint
#system = damit clear funktion ausgeführt werden kann, name = name Betriebssystem
from os import system, name
import random
import json

# Globale variablen
console = Console()
menu_text = "Wilkommen in Python Adventure!\n\n1: Spiel starten\n2: Highscore ansehen"
terminal_breite = console.size.width
terminal_hoehe = console.size.height

# Sollen die Zeichen als Emoji oder normale Text zeichen dargestellt werden
emoji_support = console.input(
    "Willst du mit Emoji Support spielen (j/n?) ").lower() == "j"

# Die unterstützten Emojis können unter folgendem Link gefunden werden: https://github.com/willmcgugan/rich/blob/master/rich/_emoji_codes.py
symbol_boden = ":white_large_square:"
symbol_wand = ":brick:"
symbol_monster = ":dragon:"
symbol_spieler = ":snake:"
symbol_ziel = ":castle:"
symbol_leben = ":sparkling_heart:"

if not emoji_support:
    symbol_boden = "."
    symbol_wand = "#"
    symbol_monster = "m"
    symbol_spieler = "@"
    symbol_ziel = "%"
Beispiel #23
0
class Update:
    def __init__(self):
        self.console = Console()
        self.location = Location()
        self.utils = Utils()

        self.prefix_cmd = "sh $HOME/" + self.location.UPDATE_LOCATION

    def homebrew(self):
        self.console.print()
        self.console.print("Updating [bold red]Homebrew[/]...")
        cmd = self.prefix_cmd + "homebrew.sh"
        os.system(cmd)

    def sdkman(self):
        self.console.print()
        self.console.print("Updating [bold red]SDK Man[/]...")
        cmd = self.prefix_cmd + "sdkman.sh"
        os.system(cmd)

    def yarn(self):
        self.console.print()
        self.console.print("Updating [bold red]Yarn[/] packages...")
        cmd = self.prefix_cmd + "yarn.sh"
        os.system(cmd)

    def neovim(self):
        self.console.print()
        self.console.print("Updating [bold red]NeoVim[/] plugins...")
        cmd = self.prefix_cmd + "neovim.sh"
        os.system(cmd)

    def zinit(self):
        self.console.print()
        self.console.print("Updating [bold red]zinit[/]...")
        cmd = self.prefix_cmd + "zinit.sh"
        os.system(cmd)

    def nvm(self):
        self.console.print()
        self.console.print("Updating [bold red]nvm[/]...")
        cmd = self.prefix_cmd + "nvm.sh"
        os.system(cmd)

    def tmux(self):
        self.console.print()
        self.console.print("Updating [bold red]oh-my-tmux[/]...")
        cmd = self.prefix_cmd + "oh-my-tmux.sh"
        os.system(cmd)

    def krew(self):
        self.console.print()
        self.console.print("Updating [bold red]krew[/]...")
        cmd = self.prefix_cmd + "krew.sh"
        os.system(cmd)

    def prezto(self):
        self.console.print()
        self.console.print("Updating [bold red]prezto[/]...")
        cmd = self.prefix_cmd + "prezto.sh"
        os.system(cmd)

    def flutter(self):
        self.console.print()
        self.console.print("Updating [bold red]Flutter[/]...")
        cmd = self.prefix_cmd + "flutter.sh"
        os.system(cmd)

    def pip(self):
        pip = Pip()

        self.console.print()
        self.console.print("Updating [bold red]pip[/] packages...")
        pip.exec_single(
            self.utils.absolute_location(self.location.PIP +
                                         self.location.PIP_FILE), True)

    def go(self):
        self.console.print()
        self.console.print("Updating [bold red]go[/] packages...")
        cmd = self.prefix_cmd + "go.sh"
        os.system(cmd)

    def run(self):
        tasks = {
            0: "All",
            1: "Homebrew",
            2: "SDK Man",
            3: "Yarn",
            4: "NeoVim",
            5: "zinit",
            6: "krew",
            7: "nvm",
            8: "oh-my-tmux",
            9: "Prezto",
            10: "Flutter",
            11: "pip",
        }

        self.console.rule("Update package from?")
        self.utils.tasks_print(tasks)

        choice = self.console.input(
            "What is your [bold red]choice[/]? :smiley: ")
        self.console.print(f'You entered {choice}')
        choice = int(choice)

        if choice == 0:
            self.homebrew()
            self.sdkman()
            self.yarn()
            self.neovim()
            self.zinit()
            self.krew()
            self.nvm()
            self.tmux()
            self.prezto()
            self.flutter()
            self.pip()
            self.go()
        elif choice == 1:
            self.homebrew()
        elif choice == 2:
            self.sdkman()
        elif choice == 3:
            self.yarn()
        elif choice == 4:
            self.neovim()
        elif choice == 5:
            self.zinit()
        elif choice == 6:
            self.krew()
        elif choice == 7:
            self.nvm()
        elif choice == 8:
            self.tmux()
        elif choice == 9:
            self.prezto()
        elif choice == 10:
            self.flutter()
        elif choice == 11:
            self.pip()
        elif choice == 12:
            self.go()
Beispiel #24
0
    def __str__(self):
        return self.player_cards


# game setup

# variables
name1 = ''
name2 = ''
game_on = True
round_num = 0

# validating name input
while name1 == '' or name2 == '':
    name1 = console.input(
        '[violet]Enter the name of [underline]first player[/][/]: ')
    name2 = console.input(
        '[violet]Enter the name of [underline]second player[/][/]: ')

# creating an instance of two players
player1 = Player(name1)
player2 = Player(name2)

# creating an instance deck
deck = Deck()
deck.shuffle_deck()

# distributing cards equally amongst players
for x in range(26):
    player1.add_cards(deck.deal_one())
    player2.add_cards(deck.deal_one())
Beispiel #25
0
class AddNote:
    """ Class to create new notes and categories in the database

    This class only has the purpose to create and display the preview of notes, also create new categories and save 
    notes in it. The arguments that will be used to create it are title, content and optionally a category

    Attributes
    ----------
    category_id: int
        Category Id where the note will be stored (Default 1)

    category_name: str
        Category name where the note will be stored (Default 'General')

    note_title: str
        Note title that can be assigned by the user or by its content

    note_text: str
        Content title that can be assigned by the user or not

    creation_date: date
        Date of the creation of the note (Today date)

    console: Console
        (Rich) Console for beatiful printting
    """

    category_id: int = 1 # Default Id of 'General' category
    category_name: str = 'General' # Default category name
    note_title: str = None
    note_text: str = None
    creation_date: date # Today's date
    console: Console

    def __init__(self, args: Namespace) -> None:
        """ Constructor of AddTask class 
        
        Parameters
        ----------
        args : NameSpace
            Arguments of argparse
        """
        self.console = Console()
        self.db = SQLiteConnection()
        self.creation_date = datetime.now().date()

        if not add_note_args_empty(args):
            try:
                if args.category:
                    self.category_name = format_argument_text(args.category)
                    self.save_category()

                if args.text or args.title:
                    self._set_note_content(args)

                    if args.preview:
                        self._show_preview()

                    else:
                        self.save_note()
            except KeyboardInterrupt:
                self.console.print('[bold yellow]\nCorrectly Cancelled[/bold yellow]')
        
        else:
            PrintFormatted.print_help(help_text.ADD_NOTE_USAGE_TEXT)


    @classmethod
    def set_args(cls, args: Namespace) -> None:
        """ Set args and initialize class
        
        Parameters
        ----------
        args : NameSpace
            Arguments of argparse
        """
        cls(args)

    def category_exists(self) -> bool:
        """ Checks if the typed category exists

        Returns
        -------
        exists: bool
            Boolean value flag if the category already exists
        """
        sql = f"SELECT {categories.COLUMN_ID} FROM {categories.TABLE_NAME} WHERE {categories.COLUMN_NAME} = '{self.category_name}'"
        query = self.db.exec_sql(sql)
        categories_list: list[tuple] = query.fetchall()

        if categories_list: # categories_list == []
            self.category_id = categories_list[0][0]
            return True
        return False

    def save_category(self) -> None:
        """ Creates and saves a new category if not exists
        
        When the note(s) is going to be saved and is created a new category, it will set the id of this new one and 
        store the note(s) in this created category
        """
        if len(self.category_name) <= 30: # Category name can't be longer than 30 characters

            if not self.category_exists():
                sql = f'INSERT INTO {categories.TABLE_NAME} ({categories.COLUMN_NAME}) VALUES (?)'
                cursor = self.db.exec_sql(sql, (self.category_name,))

                self.category_id = cursor.lastrowid

                self.db.commit()
                PrintFormatted.print_category_creation(self.category_name)
            else:
                custom_theme = Theme({
                    'msg': '#31f55f bold',
                    'name': '#616161 italic'
                })
                PrintFormatted.custom_print(f'[msg]Category selected:[/msg][name]{self.category_name}[/name]',
                                            custom_theme)
        else:
            self._ask_category()

    def save_note(self) -> None:
        """ Saves the note created in the database and setting category to store """
        sql = f'INSERT INTO {notes.TABLE_NAME} ({notes.COLUMN_TITLE}, {notes.COLUMN_CONTENT}, ' \
              f'{notes.COLUMN_CATEGORY}, {notes.COLUMN_CREATION}) VALUES (?,?,?,?);'

        with self.console.status('[bold yellow]Saving Note') as status:
            values = (self.note_title, self.note_text, self.category_id, self.creation_date)
            self.db.exec_sql(sql, values)

            PrintFormatted.print_content_storage(self.note_title, self.category_name)

            self.console.print('[bold green]✔️ Note Correctly Saved')
            status.stop()

        self.db.commit()
        self.db.close()

    def _set_note_content(self, args) -> None:
        """ Set the content (title and text) of the note according to the arguments """
        if args.text:
            self.note_text = format_argument_text(args.text)

            if not args.title:
                self.note_title = self.note_text[:30]
            else:
                self.note_title = format_argument_text(args.title)
                self._check_note_title()
        else:
            if args.title:
                self.note_title = format_argument_text(args.title)
                self._check_note_title()

    def _ask_category(self) -> None:
        """ Function that asks to the user to introduce different category name """

        text = '⚠️[yellow]Category name is too long (Max. 30).[/yellow] Write another name:'
        self.category_name = self.console.input(text).strip()

        while len(self.category_name) == 0 or len(self.category_name) > 30:
            self.category_name = self.console.input(text).strip()
        else:
            self.save_category()

    def _check_note_title(self) -> None:
        """ Check if the note title can be saved
        
        The title that will be assigned to the note can't be longer than 30 characters
        """
        if len(self.note_title) > 30:
            text = '⚠️[yellow]Note title is too long(Max. 30).[/yellow] Write another title:'
            self.note_title = self.console.input(text).strip()

            while len(self.note_title) == 0 or len(self.note_title) > 30:
                self.note_text = self.console.input(text).strip()

    def _show_preview(self) -> None:
        """ Method that displays a panel with the title and text of the note """

        self.console.rule('Preview', style='purple')
        self.console.print(
                Panel(self.note_text if self.note_text else '[red bold]Empty note[/red bold]', title=self.note_title)
            )

        if PrintFormatted.ask_confirmation(
                '[yellow]Do you want to save it?(y/n):[/yellow]'
            ):
            self.save_note()
Beispiel #26
0
        time.sleep(4)
        print("You fall asleep soon after.")
    elif sleep_reply == "3":
        print("You set your alarm, take deep breaths, and lay down")
        time.sleep(4)
        print("You refelct over your day today.")
        time.sleep(4)
        print(
            "You try to focus on how you can make tomorrow even better as you fall asleep with the counting sheep."
        )


intro()

new_day = console.input(
    "\nWhen you are ready to play, click the rectangle on the right and type 'yes': "
)
while new_day[0] != "y":
    new_day = input(
        "Invalid response. Please type 'yes' to proceed to the game!")
while new_day[0] == "y":

    wake_up()
    breakfast()
    first_class()
    second_class()
    lunch()
    test()
    email()
    after_school()
    hangout()
Beispiel #27
0
    """
    ⏬ Download a dataset.

    Pass a name to directly download that dataset.
    Otherwise, this command will show an interactive menu.
    """

    if "all" in datasets:
        datasets = get_datasets_list().keys()

    for dataset in datasets:
        download(dataset)


@data_app.command("gen")
def data_generate():
    """
    🎲 Generate a random dataset.
    """


if __name__ == "__main__":
    try:
        app(prog_name="autogoal")
    except Exception as e:
        console.print(f'⚠️  The command failed with message:\n"{str(e)}".')

        if console.input(
                "❓ Do you want to inspect the traceback? \[y/N] ") == "y":
            logger.exception("Check the traceback below.")
Beispiel #28
0
    display_desktop()

    """抽卡片"""
    draw_card()
    accepted = False
    while(not accepted):
        """"判断当前玩家是否具备 pass 资格"""
        if current_player["pass"] > 0:
            """请当前玩家做出选择"""
            accepted = Confirm.ask(
                "玩家 [yellow]%s[/yellow] 是否接受这张卡片" % current_player["name"])
        else:
            accepted = True
            console.print("玩家 [yellow]%s[/yellow] 自动接受这张卡片" %
                          current_player["name"])
            console.input("[yellow][i]输入任意字符继续……")

        if accepted:
            on_accepted()
        else:
            on_passed()
            display_players()
            display_desktop()

        next_player()

console.clear()
display_readme()
display_cards()
display_players()
Beispiel #29
0
		if selection <= len(choices):
			valid_selection = True
		else:
			system(clear_command)
			print_error_centered("This is not a choice you should make...")
	except ValueError:
		system(clear_command)
		print_error_centered("This is not a choice you should make...")

# At this point the user has made a valid choice, figure out which one

system(clear_command)
# Start the game
if selection == 1:
	start_game()
# View High Score
elif selection == 2:
	view_highscore()
# Random dungeon generator
elif selection == 3:
	number_of_dungeons = int(console.input("How many random dungeons should be generated: "))
	width = int(console.input("How many cells for the width : "))
	height = int(console.input("How many cells for the height : "))
	empty = int(console.input("How many empty cells : "))

	for i in range(number_of_dungeons):
		dungeon = generate_random_dungeon(width, height, empty)
		console.print(Panel(center_text("Dungeon # " + str(i + 1))))
		draw_map(dungeon)
		print_new_lines(1)
Beispiel #30
0
name = 'WORLD'
#  print(f'[i]HELLO [b]{name}![/b][/i]')
#  print(locals())

from rich import inspect
from rich.color import Color
color = Color.parse("red")
#  inspect(color, methods=True)

console.rule('[frame]HELLO![/frame]', align='left')
console.print('[frame]HELLO![/frame]')
console.print("Google", style="link https://google.com")

console.log(f'[i]hello [b]{name}![/b][/i]')
console.input("What is [i]your[/i] [bold red]name[/]? :smiley: ")
#  with console.status("Monkeying around...", spinner="monkey"):
#  while True:
#  pass

from rich.style import Style
danger_style = Style(color="red", blink=True, bold=True)
console.print("Danger, Will Robinson!", style=danger_style)
from rich.theme import Theme
custom_theme = Theme({
    "info": "dim cyan",
    "warning": "magenta",
    "danger": "bold #FF3333"
})
console = Console(theme=custom_theme)
console.print("This is information", style="info")