def test_burgers_ei_results(): from pymordemos import burgers_ei app = Typer() app.command()(burgers_ei.main) args = list(map(str, [1, 2, 10, 100, 10, 30])) _test_demo(lambda: runner.invoke(app, args, catch_exceptions=False)) ei_results, greedy_results = burgers_ei.test_results ei_results['greedy_max_errs'] = greedy_results['max_errs'] check_results('test_burgers_ei_results', args, ei_results, (1e-13, 1e-7), 'errors', 'triangularity_errors', 'greedy_max_errs')
def setUp(self) -> None: self.app = Typer() self.app.command()(generate_token) self.runner = CliRunner() config = self.mock_config.return_value config.Services.restapi.secret_key = ( "752e003f636f402cc23728e185ce8c9eef27b7e02cf509b3015f7757e625b8e4" ) config.Services.restapi.algorithm = "HS256"
def test_demos(demo_args): module, args = demo_args module = import_module(module) if hasattr(module, 'app'): app = module.app else: app = Typer() app.command()(module.main) args = [str(arg) for arg in args] result = _test_demo( lambda: runner.invoke(app, args, catch_exceptions=False)) assert result.exit_code == 0
def test_config_parsing(self): config = self.make_config(MockedJsonConfig, 'argparse') runner = CliRunner() app = Typer() app.add_typer(typer_config, name='config', context_settings=make_ctx_settings(config)) result = runner.invoke(app, ['config', '--global', 'key', 'value']) print(result.stdout) self.assertEqual(result.exit_code, 0) self.assertDictEqual(config, {'key': 'value'})
def assign(sele,preserve=0): from molobj import MolObj from typer import Typer,Rules import rules global state global model result = 1 state = State() model = cmd.get_model(sele) # now assign atom types ruleSet = Rules() # ruleSet.fromList(rules.amber_types) ruleSet.fromList(rules.simple_types) mobj = MolObj() mobj.fromChemPyModel(model) typed = Typer(molObj = mobj) print(" realtime: assigning atom types") typed.applyRules(ruleSet) c = 0 for a in typed.getNamedTypes(): at = model.atom[c] if (at.text_type == '??') or (not preserve): if a=='': print(" warning: unable to assign atom type to atom %d"%c) result = 0 else: cmd.alter("((%s) and (index %s))" % (sele,at.index), "text_type ='%s'" % a) if feedback['tinker']: print(" "+str(__name__)+': %s is a %s' % (at.name,a)) at.text_type = a c = c + 1 sm = 0 for a in model.atom: a.resi = str(a.resi_number) sm = sm + a.partial_charge print(" lig: net charge on ligand is %8.4f\n" % sm) return result
def assign(sele, preserve=0): from molobj import MolObj from typer import Typer, Rules import rules global state global model result = 1 state = State() model = cmd.get_model(sele) # now assign atom types ruleSet = Rules() # ruleSet.fromList(rules.amber_types) ruleSet.fromList(rules.simple_types) mobj = MolObj() mobj.fromChemPyModel(model) typed = Typer(molObj=mobj) print(" realtime: assigning atom types") typed.applyRules(ruleSet) c = 0 for a in typed.getNamedTypes(): at = model.atom[c] if (at.text_type == '??') or (not preserve): if a == '': print(" warning: unable to assign atom type to atom %d" % c) result = 0 else: cmd.alter("((%s) and (index %s))" % (sele, at.index), "text_type ='%s'" % a) if feedback['tinker']: print(" " + str(__name__) + ': %s is a %s' % (at.name, a)) at.text_type = a c = c + 1 sm = 0 for a in model.atom: a.resi = str(a.resi_number) sm = sm + a.partial_charge print(" lig: net charge on ligand is %8.4f\n" % sm) return result
def assign(sele,preserve=0): from molobj import MolObj from typer import Typer,Rules import rules result = 1 state = State() model = cmd.get_model(sele) # now assign atom types ruleSet = Rules() ruleSet.fromList(rules.mmff_types) ruleSet.mappingFromList(rules.mmff_mapping) mobj = MolObj() mobj.fromChemPyModel(model) typed = Typer(molObj = mobj) print " realtime: assigning atom types" typed.applyRules(ruleSet) c = 0 for a in typed.getTypes(): at = model.atom[c] if (at.text_type == '??') or (not preserve): if a==-99: print " warning: unable to assign atom type to atom %d"%c result = 0 else: cmd.alter("((%s) and (index %s))" % (sele,at.index), "numeric_type ='%s'" % a) if feedback['tinker']: print " "+str(__name__)+': %s is a %s' % (at.name,a) at.numeric_type = a c = c + 1 sm = 0 for a in model.atom: a.resi = str(a.resi_number) sm = sm + a.partial_charge return result
class TestHashCredentials(TestCase): def setUp(self) -> None: self.app = Typer() self.app.command()(hash_credentials) self.runner = CliRunner() def test_hash_credentials(self): result = self.runner.invoke(self.app) self.assertNotEqual(result.exit_code, 0) self.assertTrue("Error: Missing argument 'PASSWORD'." in result.stdout) result = self.runner.invoke(self.app, "test_password") self.assertEqual(result.exit_code, 0) # Hash is salted, therefore exact comparison is not possible self.assertTrue("$2b$12$" in result.stdout) self.assertEqual(60, len(result.stdout.strip()))
def test_thermalblock_results(thermalblock_args): from pymordemos import thermalblock app = Typer() app.command()(thermalblock.main) args = [str(arg) for arg in thermalblock_args[1]] _test_demo(lambda: runner.invoke(app, args, catch_exceptions=False)) results = thermalblock.test_results # due to the symmetry of the problem and the random test parameters, the estimated # error may change a lot # fenics varies more than others between MPI/serial first_tolerance = ( 1e-13, 3.5e-6) if '--fenics' in thermalblock_args[1] else (1e-13, 1e-7) check_results('test_thermalblock_results', thermalblock_args[1], results, first_tolerance, 'basis_sizes', 'norms', 'max_norms', (1e-13, 4.), 'errors', 'max_errors', 'rel_errors', 'max_rel_errors', 'error_estimates', 'max_error_estimates', 'effectivities', 'min_effectivities', 'max_effectivities', 'errors')
def create_cli(*args, **kwargs): cli_config = read_config() app = Typer() app.add_typer( ConfigureApp(cli_config).create_app(help="Manage CLI configuration."), name="configure") app.add_typer(ProfileApp(cli_config).create_app(help="Manage profiles."), name="profile") return app
def generate_app() -> Typer: app = Typer() app.add_typer(sparql.app) app.add_typer(context.app) config = load_config() typer_instances = [ plugin.typer() for plugin in config['plugins'].values() if hasattr(plugin, 'typer') ] typer_instances = filter(bool, typer_instances) consume(map( app.add_typer, typer_instances, ), ) return app
from itertools import product from os.path import join from pathlib import Path from typing import Container, Dict, List, Optional # pyright: reportMissingImports=false # pylint: disable=import-error from typer import Exit, Typer from . import SpleeterError from .options import * from .utils.logging import configure_logger, logger # pylint: enable=import-error spleeter: Typer = Typer(add_completion=False) """ CLI application. """ @spleeter.callback() def default(version: bool = VersionOption, ) -> None: pass @spleeter.command() def train( adapter: str = AudioAdapterOption, data: Path = TrainingDataDirectoryOption, params_filename: str = ModelParametersOption, verbose: bool = VerboseOption, ) -> None:
BUILD_ROOT = "WHEELWRIGHT_ROOT" WHEELS_DIR = "WHEELWRIGHT_WHEELS_DIR" REPO_NAME = "WHEELWRIGHT_REPO" GH_SECRET = "GITHUB_SECRET_TOKEN" ROOT = Path(os.environ.get(ENV.BUILD_ROOT, Path(__file__).parent)) WHEELS_DIR = Path(os.environ.get(ENV.WHEELS_DIR, ROOT / "wheels")) SECRET_FILE = "github-secret-token.txt" # We substitute the project name into this string to get the URL to clone: DEFAULT_CLONE_TEMPLATE = "https://github.com/{}.git" # Uncomment this for more GitHub integration debugging info # github.enable_console_debug_logging() cli = Typer(help="Build release wheels for Python projects") @cli.command(name="build") def build( # fmt: off repo: str, commit: str, package_name: str = Option(None, help="Package name (if different from repo)"), py35: bool = Option(False, "--py35", help="Build wheels for Python 3.5"), llvm: bool = Option(False, "--llvm", help="Requires LLVM to be installed"), rust: bool = Option(False, "--rust", help="Requires Rust to be installed"), universal: bool = Option( False, "--universal",
from requests import Session from requests.adapters import HTTPAdapter from requests.compat import urljoin session = Session() session.mount('http', HTTPAdapter(max_retries=3)) session.headers.update({ 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 \ (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' }) operator = utils.Utils(session) console = Console() app = Typer(invoke_without_command=True, no_args_is_help=True, help=config.__description__) @app.callback() def version_callback(version: Optional[bool] = Option(None, '--version', '-v', is_eager=True, help="Show version")): global console if version: console.print( Panel( config.__banner__, title=
def create_app(self, *args, **kwargs) -> Typer: app = Typer(*args, **kwargs) self.on_create_app(app, *args, **kwargs) return app
get_tags, get_commits_between, render_template, get_reverted_commit, ) from ghtc.models import ( ChangelogLine, ChangelogEntryForATag, ConventionalCommitMessage, ConventionalCommitType, UNRELEASED_TAG_TIMESTAMP, ) from ghtc.parser import parse from ghtc.overrides import Overrides app = Typer(add_completion=False) ALL_TYPES = ", ".join([x.name.lower() for x in ConventionalCommitType]) @app.command() def cli( repo_root: str = Argument(..., help="the fullpath to the git repository"), tags_regex: str = Option( "^v[0-9]", help="regex to select tags to show on changelog" ), starting_rev: str = Option( None, help="starting revision (if not set latest tag starting with " "ghtc_changelog_start if exists, else first git commit)", ), remove_duplicates_entries: bool = Option(
from enum import Enum from typing import Optional from typer import Typer, Context, Option, echo, Exit from pms import logger, __doc__, __version__ from pms.sensor import SensorReader from pms.sensor.cli import serial, csv from pms.service.cli import influxdb, mqtt, bridge main = Typer(help=__doc__) main.command()(serial) main.command()(csv) main.command()(influxdb) main.command()(mqtt) main.command()(bridge) class Supported(str, Enum): PMSx003 = "PMSx003" PMS3003 = "PMS3003" PMS5003S = "PMS5003S" PMS5003ST = "PMS5003ST" PMS5003T = "PMS5003T" SDS01x = "SDS01x" SDS198 = "SDS198" HPMA115S0 = "HPMA115S0" HPMA115C0 = "HPMA115C0" SPS30 = "SPS30" MCU680 = "MCU680"
"""Command line interface for {{ cookiecutter.project_name }}. See https://docs.python.org/3/using/cmdline.html#cmdoption-m for why module is named __main__.py. """ from typer import Typer app = Typer(help="{{ cookiecutter.project_description }}") if __name__ == "__main__": app()
from pprint import pprint from benchmark_lsh import get_response, benchmark from typer import Argument, Option, Typer cli = Typer(help=__doc__, no_args_is_help=True) @cli.command() def benchmark( n_classifiers: int = Option( ..., help= "The number of classifiers, ie the number of chunks the feature vectors has been split into, or the number of tokens in each LSH hash" ), n_clusters: int = Option( ..., help="The number of clusters found by each classifier"), sample_size: int = Option( default=250, help= "The number of times the API will be hit to determine an average response time" )): print("Example response:") pprint(get_response(n_classifiers, n_clusters)) print() benchmark(n_classifiers, n_clusters, sample_size) if __name__ == "__main__": cli()
def setUp(self) -> None: self.app = Typer() self.app.command()(hash_credentials) self.runner = CliRunner()
def add_legacy_compatible_commands(app: typer.Typer): """ Add commands from the restructured CLI under the previous names for the commands to the root ``typer`` app. """ # Applications app.command( name="list-applications", help="LIST the available applications", )(list_applications) app.command( name="get-application", help="GET an Application.", )(get_application) app.command( name="create-application", help="CREATE an Application.", )(create_application) app.command( name="delete-application", help="DELETE an Application.", )(delete_application) app.command( name="update-application", help="UPDATE an Application.", )(update_application) # Job Scripts app.command( name="list-job-scripts", help="LIST job scripts", )(list_job_scripts) app.command( name="get-job-script", help="GET a job script", )(get_job_script) app.command( name="create-job-script", help="CREATE a job script", )(create_job_script) app.command( name="update-job-script", help="UPDATE a job script", )(update_job_script) app.command( name="delete-job-script", help="DELETE a job script", )(delete_job_script) # Job Submissions app.command( name="list-job-submissions", help="LIST job submissions", )(list_job_submissions) app.command( name="get-job-submission", help="GET a job submission", )(get_job_submission) app.command( name="create-job-submission", help="CREATE a job submission", )(create_job_submission) app.command( name="delete-job-submission", help="DELETE a job submission", )(delete_job_submission)
"""Generate the Quetz builder package from @jupyterlab/builder""" from copy import copy import sys from pathlib import Path from shutil import which, copytree, rmtree from tempfile import TemporaryDirectory from subprocess import check_call from typer import Typer, Argument, echo app = Typer() HERE = Path(__file__).parent.resolve() JUPYTERLAB_BUILDER_PATH = "builder" QUETZ_BUILDER_PATH = HERE.parent / "builder" QUETZ_BUILDER_PATCHES = HERE / "builder-patches" @app.command() def generate_builder( git_ref: str = Argument( ..., help="JupyterLab Git reference to use to generate Quetz builder."), git_repository: str = Argument( "https://github.com/jupyterlab/jupyterlab.git", help="JupyterLab Git repository path.", ), ) -> None: """Generate the Quetz builder from the JupyterLab one and apply patches.""" git_exec = which("git")
from typer import Typer from kolombo.configuration_files import generate_senders_compose_config from kolombo.console import step from kolombo.util import ( async_command, execute_as_root, needs_database, run, stop_all_kolombo_services, stop_kolombo_service, ) stop_cli = Typer(invoke_without_command=True) @stop_cli.command("all") @execute_as_root @async_command @needs_database async def stop_all() -> None: from kolombo.models import Domain step("Stopping all Kolombo services") stop_all_kolombo_services() domains = [domain.actual for domain in await Domain.all_active()] # Remove duplicates preserving order domains = list(dict.fromkeys(domains)) senders_compose_config = generate_senders_compose_config(domains) project_name = "kolombo_senders"
import sys import jwt from rich.columns import Columns from rich.console import Console from rich.table import Table from rich.traceback import install from typer import Typer, Option cli = Typer() install() console = Console() STDOUT_TTY = sys.stdout.isatty() STDIN_TTY = sys.stdin.isatty() # TODO: add a way to verify the jwt (separate command, just flags, or both?) # TODO: add a way to fetch a jwt (a separate command) @cli.command('decode') def print_jwt(encoded_jwt: str, use_table: bool = Option(False, '--table', '-t'), verbose: int = Option(0, '--verbose', '-v', count=True)): if verbose >= 1: console.print( f'[bold red]STDOUT[/] [blink yellow]is {"not" if not STDOUT_TTY else ""}[/]a tty' ) console.print( f'[bold red]STDIN[/] [blink yellow]is {"not" if not STDIN_TTY else ""}[/]a tty' )
from pathlib import Path from typer import Typer app = Typer(name='context') @app.callback(invoke_without_command=True) def context(path: Path): """Print context for a path.""" raise NotImplementedError('Not implemented yet.')
from pathlib import Path from typer import Typer, Argument, Option from igipy.tmm.parsers import TMMParser from igipy.tmm.exporters import TMM2PNG app = Typer(name='tmm', add_completion=False, help='I.G.I 2: Covert Strike - Terrain Material Map file utils.') @app.command(name='to_png', help='Export all TMM files from directory as PNG.') def command_to_png( source_dir: Path = Argument(..., case_sensitive=False, help="Source directory path."), target_dir: Path = Argument(..., case_sensitive=False, help="Target directory path."), flip_left_right: bool = Option(default=True, help="Flip image left right."), flip_top_bottom: bool = Option(default=False, help="Flip image top bottom.") ): parser = TMMParser() exporter = TMM2PNG(flip_left_right=flip_left_right, flip_top_bottom=flip_top_bottom) for source in source_dir.glob('**/*.tmm'): target = Path(str(source).replace(str(source_dir), str(target_dir), 1)) target.parent.mkdir(parents=True, exist_ok=True) exporter.export(parser.load(source), target) if __name__ == "__main__": app()
from pathlib import Path from typer import Typer, Argument, Option from igipy.thm.parsers import THMParser from igipy.thm.exporters import THM2PNG, THM2TIF, THM2NPY app = Typer(name='thm', add_completion=False, help='I.G.I 2: Covert Strike - Terrain Height Map file utils.') @app.command(name='to_png', help='Export all THM files from directory as PNG.') def command_to_png( source_dir: Path = Argument(..., case_sensitive=False, help="Source directory path."), target_dir: Path = Argument(..., case_sensitive=False, help="Target directory path."), flip_left_right: bool = Option(default=True, help="Flip image left right."), flip_top_bottom: bool = Option(default=False, help="Flip image top bottom."), normalize: bool = Option( default=True, help="Scale down original float32 pixel to uint8.")): parser = THMParser() exporter = THM2PNG(flip_left_right=flip_left_right, flip_top_bottom=flip_top_bottom, normalize=normalize)
from pathlib import Path from typer import Typer, Argument from igipy.tex.parsers import TEXParser app = Typer(add_completion=False, help='Not implemented.') @app.command(name='to_png', help='Not implemented.') def command_to_png(source_dir: Path = Argument(..., case_sensitive=False, help='Source file path.')): parser = TEXParser() for source in source_dir.glob('**/*.tex'): data = parser.load(source) print(source.name, data) if __name__ == "__main__": app()
from docker import from_env # type: ignore[import] from typer import Typer from kolombo.configuration_files import generate_senders_compose_config from kolombo.console import error, step from kolombo.util import ( async_command, build_kolombo_image, execute_as_root, needs_database, run, up_all_kolombo_services, up_kolombo_service, ) run_cli = Typer() @run_cli.command("all") @execute_as_root @async_command @needs_database async def run_all() -> None: from kolombo.models import Domain client = from_env() build_kolombo_image(client, "receiver") build_kolombo_image(client, "auth") build_kolombo_image(client, "nginx") build_kolombo_image(client, "sender")
"""Build OCI images using docker buildx""" from pathlib import Path from sys import exit from typing import List, Optional, Union from kapla.cli.console import console, style_str from kapla.cli.utils import map_string_to_dict from kapla.docker.datatypes import BuildContext, Catalog, Image from loguru import logger from pydantic.error_wrappers import ValidationError from python_on_whales import docker from typer import Argument, Context, Option, Typer app = Typer( name="builder", add_completion=False, no_args_is_help=True, invoke_without_command=False, ) @app.command( "build", context_settings={"allow_extra_args": True, "ignore_unknown_options": True} ) def build( ctx: Context, name: Optional[str] = Argument(None, help="Name of images to build"), builder_file: Optional[str] = Option( None, "--builder-file", "-b", help="builder.yml file to use. By default files are searched accross repo",
def _helper(command_name: str, command_function: Callable): main_app = Typer() main_app.callback()(_main_callback) main_app.command(name=command_name)(command_function) return main_app