paint_deployer_contract_inspection, paint_receipt_summary, paint_multisig_contract_info, paint_multisig_proposed_transaction ) from nucypher.cli.types import EIP55_CHECKSUM_ADDRESS, EXISTING_READABLE_FILE, GAS_STRATEGY_CHOICES from nucypher.cli.types import WEI from nucypher.config.constants import DEFAULT_CONFIG_ROOT option_deployer_address = click.option('--deployer-address', help="Deployer's checksum address", type=EIP55_CHECKSUM_ADDRESS) option_registry_infile = click.option('--registry-infile', help="Input path for contract registry file", type=EXISTING_READABLE_FILE) option_registry_outfile = click.option('--registry-outfile', help="Output path for contract registry file", type=click.Path(file_okay=True)) option_target_address = click.option('--target-address', help="Address of the target contract", type=EIP55_CHECKSUM_ADDRESS) option_gas = click.option('--gas', help="Operate with a specified gas per-transaction limit", type=click.IntRange(min=1)) option_gas_strategy = click.option('--gas-strategy', help="Operate with a specified gas price strategy", type=click.STRING) # TODO: GAS_STRATEGY_CHOICES option_network = click.option('--network', help="Name of NuCypher network", type=click.Choice(NetworksInventory.networks)) option_ignore_deployed = click.option('--ignore-deployed', help="Ignore already deployed contracts if exist.", is_flag=True) option_ignore_solidity_version = click.option('--ignore-solidity-check', help="Ignore solidity version compatibility check", is_flag=True) def _pre_launch_warnings(emitter, etherscan, hw_wallet): if not hw_wallet: emitter.echo("WARNING: --no-hw-wallet is enabled.", color='yellow') if etherscan: emitter.echo("WARNING: --etherscan is enabled. " "A browser tab will be opened with deployed contracts and TXs as provided by Etherscan.", color='yellow') else: emitter.echo("WARNING: --etherscan is disabled. " "If you want to see deployed contracts and TXs in your browser, activate --etherscan.", color='yellow')
next = __next__ @click.command() @click.argument('image-file', type=click.Path(readable=True, dir_okay=False, exists=True)) @click.option('--chunk-size', '-C', type=ByteSize, default=None, help='Read-buffer size (default: auto-adjust)') @click.option('-d', '--decompress', default='auto', type=click.Choice(['auto', 'none', 'xz']), help='On-the-fly decompression (default: auto-detect)') @click.option('-e/-E', '--eject/--no-eject', default=True, help='Eject medium after writing (default: True).') @click.option('--limit', '-l', type=ByteSize, help='Write no more than this many bytes to device.') @click.option('--max-size', default=None, help='Maximum size in bytes before rejecting to write to device.' ) @click.option('--target', '-t',
Mean teachers are better role models: Weight-averaged consistency targets improve semi-supervised deep learning results Antti Tarvainen, Harri Valpola https://arxiv.org/abs/1703.01780 """ import click @click.command() @click.option('--exp', type=click.Choice([ 'svhn_mnist', 'mnist_svhn', 'svhn_mnist_rgb', 'mnist_svhn_rgb', 'cifar_stl', 'stl_cifar', 'mnist_usps', 'usps_mnist', 'syndigits_svhn', 'synsigns_gtsrb', ]), default='mnist_svhn', help='experiment to run') @click.option('--arch', type=click.Choice([ '', 'mnist-bn-32-64-256', 'grey-32-64-128-gp', 'grey-32-64-128-gp-wn', 'grey-32-64-128-gp-nonorm', 'rgb-128-256-down-gp',
def version(): """ Display the current version """ distribution = pkg_resources.get_distribution(u'devbox') click.echo(u'{} {} from {}'.format(distribution.project_name, distribution.version, distribution.location)) @cli.command() @click.option('--path', default='devbox.yaml', help='Path to manifest file') @click.option('--deploy', default='docker', help='Deployment to use', type=click.Choice(get_deployment_engine_names())) @click.option('--provision', default='ansible', help='Provisioning to use', type=click.Choice(get_provisioning_engine_names())) def push(path, deploy, provision): """ Deploy the app """ PushCommandExecutor().push(path, deploy, provision) @cli.command() @click.option('--path', default='devbox.yaml', help='Path to manifest file') @click.option('--deploy', default='docker',
def validate_output(ctx, param, value): o = value.lower() if o == 'csv': return 'text/csv; charset=utf8' if o == 'json': return 'application/json; charset=utf8' else: raise click.BadParameter('Output type must be CSV or JSON.') CONTEXT_SETTINGS = dict(token_normalize_func=lambda x: x.lower()) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--country', '-c', default ='US', help='iso-alpha2 country code' , type=click.Choice(['US', 'DE'])) @click.option('--location', '-l', default ='', help='city') @click.option('--jobtitle', '-j', default ='', help='job title') @click.option('--skills', '-s', default ='', help='search terms') @click.option('--firm', '-f', default ='', help='company name') @click.option('--page', '-p', default = 1, help='search result page') @click.option('--output', '-o', default ='csv', help='output format' , type=click.Choice(['CSV', 'JSON']) , callback=validate_output) @click.version_option('0.1b2', '--version', '-v') def cli(jobtitle, country, location, output, firm, skills, page): """JobCLI: Your Command Line Job Board""" url = 'http://api.jobcli.com/rpc/ads' headers = {'Accept': output} payload = {
import click from getproxies import get_proxies @click.command() @click.option('-p', '--protocol', help='restrict to specific protocol', type=click.Choice(['https', 'http', 'socks4', 'socks5'])) @click.option('-c', '--country', help='only proxies from specified country (ISO double char code, e.g. US)') @click.option('-l', '--limit', help='limit proxy retrieval - increases performance', type=click.INT) @click.option('-f', '--format', help='proxy output format, available variables: host,port,protocol,code,country,anonymous,source', default='{protocol}://{host}:{port}', show_default=True) def main(protocol, country, limit, format): """scrape free proxies from all sources and put it to STDOUT""" proxies = get_proxies(limit=limit, protocol=protocol, country=country) for proxy in proxies: click.echo(format.format(**proxy.__dict__)) if __name__ == '__main__': main()
is_flag=True, default=True, help="Generate full predicates", ) # noqa def export_rdf(infile, outfile, qualified=True): exporter = RDFExporter(outfile, qualified=qualified) export_stream(exporter, infile) @cli.command("export-gexf", help="Export to GEXF (Gephi) format") @click.option("-i", "--infile", type=click.File("r"), default="-") # noqa @click.option("-o", "--outfile", type=click.File("w"), default="-") # noqa @click.option( "-e", "--edge-types", type=click.Choice(edge_types()), multiple=True, default=DEFAULT_EDGE_TYPES, help="Property types to be reified into graph edges.", ) def export_gexf(infile, outfile, edge_types): exporter = NXGraphExporter(outfile, edge_types=edge_types) export_stream(exporter, infile) @cli.command("export-cypher", help="Export to Cypher script") @click.option("-i", "--infile", type=click.File("r"), default="-") # noqa @click.option("-o", "--outfile", type=click.File("w"), default="-") # noqa @click.option( "-e", "--edge-types",
""" pass @transiter_clt.command() @click.option( "-f", "--force", is_flag=True, help="Force start by killing any process listening on the target port.", ) @click.option( "-l", "--log-level", default="warning", type=click.Choice(["debug", "info", "warning", "error", "fatal"]), help="The log level.", ) @click.argument("server", type=click.Choice(["webservice", "scheduler", "executor"])) def launch(force, log_level, server): """ Launch a Transiter service in debug mode. """ if server == "webservice": # NOTE: the flask app is imported here because otherwise the task server will # use the app's logging configuration. from transiter.http import flaskapp flaskapp.launch(force) if server == "scheduler":
@click.group() def user_cmd(): # pragma: no cover pass @user_cmd.command(help='Configure a user.') @click.option('--environment', type=click.STRING, envvar='FLOTILLA_ENV', default=DEFAULT_ENVIRONMENT, help='Environment name.') @click.option('--region', '-r', multiple=True, type=click.Choice(REGIONS), envvar='FLOTILLA_REGION', default=DEFAULT_REGIONS, help='Regions (multiple allowed).') @click.option('--name', type=click.STRING, help='User name.') @click.option('--ssh-key', type=click.STRING, multiple=True, help='User SSH key(s).') @click.option('--active/--inactive', default=None, help='Disable automatic provisioning.') def user(environment, region, name, ssh_key, active): # pragma: no cover configure_user(environment, region, name, ssh_key, active)
super().__init__(from_date=monday_str, to_date=to_date, config=config) self.report_title = '{}至{}禅道周报'.format(monday_str, to_date) class MonthlyReporter(Reporter): """月报""" def __init__(self, to_date, config=default_config): month = to_date[:7] first_day = month + '-01' super().__init__(from_date=first_day, to_date=to_date, config=config) self.report_title = '{}禅道月报'.format(month) @click.command() @click.option('--report-type', type=click.Choice(['daily', 'weekly', 'monthly'], case_sensitive=False), help='报告类型, 不选择则生成普通报告') @click.option('--from-date', type=click.DateTime(formats=('%Y-%m-%d', )), help='报告开始日期,如 --to-date 2020-02-03') @click.option('--to-date', type=click.DateTime(formats=('%Y-%m-%d', )), help='报告结束日期,如 --to-date 2020-02-14') @click.option('--today', is_flag=True, help='以今日为报告结束日期,等同 --to-date 今日') def build_zentao_report(report_type, from_date, to_date, today): """生成禅道报告""" if today and to_date: raise click.BadParameter('参数 --to-date 和 --today 冲突, 只能给其中一个参数赋值') elif today and not to_date: to_date_str = datetime.now().strftime('%Y-%m-%d') elif not today and to_date:
"-d", "--directory", type=click.Path(exists=True, file_okay=False), help="Use the specified project directory.", ) @click.option( "-c", "--config", type=click.Path(exists=True, dir_okay=False), help="Use the specified config file.", ) @click.option( "-l", "--log", metavar="LEVEL", type=click.Choice(["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"], case_sensitive=False), default="WARNING", help="Configure output verbosity.", ) @click.version_option( __version__, "-v", "--version", message=click.style("%(prog)s", fg="red") + click.style(" v%(version)s", fg="green"), ) def beet( ctx: click.Context, directory: Optional[str], log: str, config: Optional[str],
help="Disable the welcome forum.") @click.option("--force", "-f", default=False, is_flag=True, help="Doesn't ask for confirmation.") @click.option("--username", "-u", help="The username of the user.") @click.option("--email", "-e", type=EmailType(), help="The email address of the user.") @click.option("--password", "-p", help="The password of the user.") @click.option("--group", "-g", help="The group of the user.", type=click.Choice(["admin", "super_mod", "mod", "member"])) def install(welcome, force, username, email, password, group): """Installs flaskbb. If no arguments are used, an interactive setup will be run. """ click.secho("[+] Installing FlaskBB...", fg="cyan") if database_exists(db.engine.url): if force or click.confirm( click.style( "Existing database found. Do you want to delete the old one and " "create a new one?", fg="magenta")): drop_database(db.engine.url) else: sys.exit(0) create_database(db.engine.url)
config_file = os.environ.get("SWH_CONFIG_FILENAME") conf = config.read(config_file) ctx.obj["config"] = conf @lister.command( name="run", context_settings=CONTEXT_SETTINGS, help="Trigger a full listing run for a particular forge " "instance. The output of this listing results in " '"oneshot" tasks in the scheduler db with a priority ' "defined by the user", ) @click.option( "--lister", "-l", help="Lister to run", type=click.Choice(SUPPORTED_LISTERS) ) @click.argument("options", nargs=-1) @click.pass_context def run(ctx, lister, options): from swh.scheduler.cli.utils import parse_options config = deepcopy(ctx.obj["config"]) if options: config.update(parse_options(options)[1]) get_lister(lister, **config).run() if __name__ == "__main__":
@click.command(short_help='retrieve actions') @common.add_options(common.actionids) @common.add_options(common.groupids) @common.add_options(common.hostids) @common.add_options(common.triggerids) @common.add_options(common.mediatypeids) @common.add_options(common.usrgrpids) @common.add_options(common.userids) @common.add_options(common.scriptids) # todo: for future use once we sort out passing queries # @common.add_options(common.selectFilters) # @common.add_options(common.selectOperations) # @common.add_options(common.selectRecoveryOperations) # todo: work out how to pass choices to DRY this @click.option('--sortfield', type=click.Choice(['actionid', 'name', 'status'])) @common.add_options(common.countOutput) @common.add_options(common.editable) @common.add_options(common.excludeSearch) @common.add_options(common.filter) @common.add_options(common.limit) @common.add_options(common.output) @common.add_options(common.preservekeys) @common.add_options(common.search) @common.add_options(common.searchByAny) @common.add_options(common.searchWildcardsEnabled) @common.add_options(common.sortorder) @common.add_options(common.startSearch) @common.add_options(common.outputformat) @click.pass_obj def action(zart, sortfield, **kwargs):
@cli.command() @click.argument('p', type=click.Path(exists=True)) def validate(p): core.validate(p) @cli.command() @click.argument('p', type=click.Path(exists=True)) @click.option("--branch-override") def generate_via_luigi(p, branch_override=None): core.generate_via_luigi(p, branch_override) @cli.command() @click.argument('p', type=click.Path(exists=True)) @click.option('--format', '-f', type=click.Choice(['table', 'json']), default='table') def show_pipelines(p, format): core.show_pipelines(p, format) @cli.command() @click.argument('p', type=click.Path(exists=True)) def deploy(p): core.deploy(p) @cli.command() @click.argument('portfolio-name') @click.argument('product') @click.argument('version') def nuke_product_version(portfolio_name, product, version):
return dest, folder_write_bytes, lambda: None # ---------------------------------------------------------------------------- @click.command() @click.pass_context @click.option("--source", help="Directory or archive name for input dataset", required=True, metavar="PATH") @click.option("--dest", help="Output directory or archive name for output dataset", required=True, metavar="PATH") @click.option("--max-images", help="Output only up to `max-images` images", type=int, default=None) @click.option( "--resize-filter", help="Filter to use when resizing images for output resolution", type=click.Choice(["box", "lanczos"]), default="lanczos", show_default=True, ) @click.option("--transform", help="Input crop/resize mode", type=click.Choice(["center-crop", "center-crop-wide"])) @click.option("--width", help="Output width", type=int) @click.option("--height", help="Output height", type=int) def convert_dataset( ctx: click.Context, source: str, dest: str, max_images: Optional[int], transform: Optional[str], resize_filter: str, width: Optional[int], height: Optional[int],
conf=conf, ) check = checks.Freshness( metrics=statsd, conf=conf, source=source, ) return check @click.command() @click.option('--conn-string', help='connection string for the db') @click.option('--db', type=click.Choice(['s3', 'postgres']), default='postgres', help='which db backend') @click.option('--conf', type=click.File('rb'), help='configuration file to use for monitoring') @click.option('--type', type=click.Choice(['storage', 'freshness']), help='check type, need to figure out clean subcommands') def main(**kwargs): init_logging() check = init_check(kwargs) return check.execute() if __name__ == '__main__':
def init(): """Return top level command handler.""" ctx = {} @click.group() @click.option('--cell', required=True, envvar='TREADMILL_CELL', callback=cli.handle_context_opt, expose_value=False) @click.option('--api', required=False, help='API url to use.', envvar='TREADMILL_ADMINAPI') @click.option('--outfmt', type=click.Choice(['json', 'yaml']), default='json') def top(api, outfmt): """Invoke Treadmill HTTP REST API.""" cli.OUTPUT_FORMAT = outfmt ctx['api'] = [api] @top.command() @click.argument('path') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def get(path): """REST GET request.""" response = restclient.get(ctx['api'], path) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) @top.command() @click.argument('path') @click.argument('payload', type=click.Path(exists=True, readable=True)) @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def post(path, payload): """REST POST request.""" with io.open(payload, 'rb') as fd: request = yaml.load(stream=fd) response = restclient.post(ctx['api'], path, payload=request) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) @top.command() @click.argument('path') @click.argument('payload', type=click.Path(exists=True, readable=True)) @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def put(path, payload): """REST PUT request.""" with io.open(payload, 'rb') as fd: request = yaml.load(stream=fd) response = restclient.put(ctx['api'], path, payload=request) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) @top.command() @click.argument('path') @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS) def delete(path): """REST DELETE request.""" response = restclient.delete(ctx['api'], path) formatter = cli.make_formatter(None) cli.out(formatter(response.json())) del get del post del put del delete return top
if v4 and not host: host = "0.0.0.0" run_server(basedir, configfile, host, port, v6, debug, allow_root, logging, verbosity, safe_mode, ignore_blacklist) if sys.platform != "win32" and sys.platform != "darwin": # we do not support daemon mode under windows or macosx @server_commands.command(name="daemon") @standard_options() @server_options @daemon_options @click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]), metavar="start|stop|restart|status") @click.pass_context def daemon_command(ctx, command, **kwargs): """ Starts, stops or restarts in daemon mode. Please note that daemon mode is not supported under Windows and MacOSX right now. """ def get_value(key): return get_ctx_obj_option(ctx, key, kwargs.get(key)) host = get_value("host") port = get_value("port") v4 = get_value("v4")
) @click.option("--name", "-n", required=True, type=str, help="name of the tileset") @click.option("--description", "-d", required=False, type=str, help="description of the tileset") @click.option( "--privacy", "-p", required=False, type=click.Choice(["public", "private"]), help="set the tileset privacy options", ) @click.option( "--attribution", required=False, type=str, help= "attribution for the tileset in the form of a JSON string - Array<Object<text,link>>", ) @click.option("--token", "-t", required=False, type=str, help="Mapbox access token") @click.option("--indent",
default=None, required=False, ) @click.option( '--connect', '-c', default='tcp:host=127.0.0.1:port=9051', help=('Where to connect to Tor. This accepts any Twisted client endpoint ' 'string, or an ip:port pair. Examples: "tcp:localhost:9151" or ' '"unix:/var/run/tor/control".'), metavar='ENDPOINT', ) @click.option( '--color', '-C', type=click.Choice(['auto', 'no', 'always']), default='auto', help='Colourize output using ANSI commands.', ) @click.pass_context def carml(ctx, timestamps, no_color, info, quiet, debug, password, connect, color): if (color == 'always' and no_color) or \ (color == 'no' and no_color is True): raise click.UsageError("--no-color={} but --color={}".format( no_color, color)) cfg = Config() ctx.obj = cfg cfg.timestamps = timestamps
import click import os import pandas as pd from datetime import datetime import logging def _s(s): return s.split(" ") @click.command() @click.option("-l", "--language", type=click.Choice(_s("jpn eng chi_sim chi_tra deu")), default="jpn") @click.option("-i", "--index", type=int, default=-1) @click.option("--debug/--no-debug", default=True) @click.option("--pbcopy/--no-pbcopy", default=False) def tesseract(language, index, debug, pbcopy): if debug: logging.basicConfig(level=logging.INFO) files_ = [] for root, dirs, files in os.walk("/Users/nailbiter/Desktop", topdown=False): for name in files: if name.endswith(".png"): fn = os.path.join(root, name) files_.append({ "last_modification":
from bentoml.saved_bundle import ( load, load_bento_service_api, load_bento_service_metadata, ) try: import click_completion click_completion.init() shell_types = click_completion.DocumentedChoice( click_completion.core.shells) except ImportError: # click_completion package is optional to use BentoML cli, click_completion = None shell_types = click.Choice(['bash', 'zsh', 'fish', 'powershell']) yatai_proto = LazyLoader('yatai_proto', globals(), 'bentoml.yatai.proto') def escape_shell_params(param): k, v = param.split('=') v = re.sub(r'([^a-zA-Z0-9])', r'\\\1', v) return '{}={}'.format(k, v) def to_valid_docker_image_name(name): # https://docs.docker.com/engine/reference/commandline/tag/#extended-description return name.lower().strip("._-")
help= 'Topic for committed offsets to be written to, triggering post-processing task(s)' ) @click.option('--control-topic', default=None, help='Topic used to control the snapshot') @click.option('--consumer-group', default='snuba-consumers', help='Consumer group use for consuming the raw events topic.') @click.option('--bootstrap-server', default=None, multiple=True, help='Kafka bootstrap server to use.') @click.option('--dataset', default='events', type=click.Choice(DATASET_NAMES), help='The dataset to target') @click.option( '--max-batch-size', default=settings.DEFAULT_MAX_BATCH_SIZE, help='Max number of messages to batch in memory before writing to Kafka.') @click.option( '--max-batch-time-ms', default=settings.DEFAULT_MAX_BATCH_TIME_MS, help= 'Max length of time to buffer messages in memory before writing to Kafka.') @click.option('--auto-offset-reset', default='error', type=click.Choice(['error', 'earliest', 'latest']), help='Kafka consumer auto offset reset.') @click.option(
''' Fast Fourier Spin Stress test GPUs for FFT and other things. ''' import os import time import click import numpy @click.group() @click.option("-m", "--module", default="numpy", type=click.Choice(["cupy", "numpy"]), help="Set GPU interface module") @click.pass_context def cli(ctx, module): from importlib import import_module ctx.obj = import_module(f'ffs.api_{module}') @cli.command() @click.option("--copy/--no-copy", default=True, help="Whether to round-trip between CPU and GPU") @click.option("-s", "--shape", default="1000,1000", help="Array shape") @click.option("-c", "--count", type=int, default=100, help="Number of cycles") @click.option("-d", "--dtype", default="float32", help="The array dtype") @click.pass_context
NAGIOS_TEMPLATE = ''''%s' => { parents => 'fw1.private.releng.scl3.mozilla.net', check_command => 'check_tcp2!443!2!4', ping_check_command => 'check_tcp2!443!2!4', contact_groups => '%s', hostgroups => [ 'releng-apps' ] },''' @click.command() @click.option( '--channel', type=click.Choice(please_cli.config.CHANNELS), default=None, ) def cmd(channel): if channel is None: channels = please_cli.config.CHANNELS else: channels = [channel] for project_id in sorted(please_cli.config.PROJECTS_CONFIG.keys()): project = please_cli.config.PROJECTS_CONFIG[project_id].get('deploy_options') if project: for channel in sorted(channels):
def wrimg(image_file, target, verbose, i_know_what_im_doing, limit, chunk_size, decompress, max_size, eject, pause): if pause: atexit.register(lambda: input('Press enter to close')) if verbose: info = click.echo else: info = lambda *args, **kwargs: None error = partial(click.echo, err=True) if not target: candidates = [] for dev in sorted(Device.iter_block_devices(), key=lambda d: d.path): ok, msg = candidate_for_writing(dev, max_size) if not ok: info('skipping {}: {}'.format(dev.path, msg)) continue candidates.append(dev) if not candidates: error('No device given on command-line and no suitable candidate ' 'found') sys.exit(1) elif len(candidates) == 1: target = candidates[0] else: # display menu for i, c in enumerate(candidates): click.echo('[{}] {}'.format(i, dev_info(c))) idx = int( click.prompt('Select a device', type=click.Choice(map(str, range(len(candidates)))))) target = candidates[idx] else: target = Device(target) # sanity-check target-device ok, msg = candidate_for_writing(target, max_size) if not ok: if not i_know_what_im_doing: error('{.path}: {}.\nAdd --i-know-what-im-doing to disable this ' 'check.'.format(target, msg)) sys.exit(0) error('WARNING: {}: {}'.format(dev_info(target), msg)) # determine compression type verb = 'Write' if decompress == 'auto': if image_file.endswith('.xz'): decompress = 'xz' elif image_file.endswith('.iso') or image_file.endswith('.img'): decompress = None else: error('Could not determine compression type from file-ending') sys.exit(1) elif decompress == 'none': decompress = None if decompress: info('Decompression enabled, using {}'.format(decompress)) verb = 'Decompress ({}) and write'.format(decompress) # confirm start, featuring the defensive assert! assert click.confirm('{} to {}?'.format(verb, dev_info(target)), err=True, abort=True) # determine number of bytes to write img_st = os.stat(image_file) # start with the target device size total = target.size if not decompress and img_st.st_mode & S_IFREG: # regular file, limit by its size total = min(total, img_st.st_size) # apply limit if limit is not None: total = min(total, limit) info('Copying {:.0f} bytes from {} to {.path}'.format( total, image_file, target)) with open(image_file, 'rb') as src, target.open('wb') as dst: # compression hooks in here if decompress: if decompress == 'xz': decompress = subprocess.Popen( ['xz', '--decompress', '--stdout'], stdout=subprocess.PIPE, stdin=src, ) else: raise NotImplementedError( 'Unknown compressoin type {}'.format(decompress)) src = decompress.stdout reader = Reader(src, chunk_size, limit) if not decompress: pbar = click.progressbar(length=total, label='writing', info_sep='| ') else: def show_bytes_written(item): return 'total: {:.1f H}'.format(ByteSize(reader.bytes_read)) pbar = click.progressbar(reader, label='writing', info_sep='| ', item_show_func=show_bytes_written) with pbar as bar: chunk_source = pbar if decompress else reader for chunk in chunk_source: # measure time start = time.time() dst.write(chunk) dst.flush() os.fsync(dst.fileno()) end = time.time() speed = ByteSize(len(chunk) / (end - start)) # adjust chunk size if needed if chunk_size is None: if end - start > 2: # took longer then two seconds, halve bufsize reader.decrease_buffer() elif end - start < 0.5: reader.increase_buffer() bar.label = '{:.1f H}/s'.format(speed) if not decompress: bar.update(len(chunk)) # we're done writing, call eject info('Ejecting {}'.format(target.path)) subprocess.check_call(['eject', target.path]) click.echo('Safe to remove {}'.format(target.path))
TAURUS_MENU_ENABLED = False TOOLS_MENU_ENABLED = False PANELS_MENU_ENABLED = False HELP_MENU_ENABLED = False FULLSCREEN_TOOLBAR_ENABLED = False APPLETS_TOOLBAR_ENABLED = False QUICK_ACCESS_TOOLBAR_ENABLED = False USER_PERSPECTIVES_ENABLED = False LOGGER_WIDGET_ENABLED = False SPLASH_LOGO_NAME = None @click.command() @click.option('--group', default='x-axis', type=click.Choice(['single', 'x-axis']), help='group curves') @click.option('--taurus-log-level', type=click.Choice( ['critical', 'error', 'warning', 'info', 'debug', 'trace']), default='error', show_default=True, help='Show only logs with priority LEVEL or above') @click.argument('door') def main(group, taurus_log_level, door): import taurus taurus.setLogLevel(getattr(taurus, taurus_log_level.capitalize())) from taurus.qt.qtgui.application import TaurusApplication app = TaurusApplication(app_name='Showscan Online',
from easydict import EasyDict from zmon_cli import __version__ from zmon_cli.config import DEFAULT_CONFIG_FILE, DEFAULT_TIMEOUT from zmon_cli.config import get_config_data, configure_logging, set_config_file from zmon_cli.output import Output, render_status from zmon_cli.client import Zmon CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) output_option = click.option('-o', '--output', type=click.Choice(['text', 'json', 'yaml']), default='text', help='Use alternative output format') yaml_output_option = click.option( '-o', '--output', type=click.Choice(['text', 'json', 'yaml']), default='yaml', help='Use alternative output format. Default is YAML.') pretty_json = click.option( '--pretty', is_flag=True, help='Pretty print JSON output. Ignored if output format is not JSON')
callback=validate_key, envvar='POLYSWARM_API_KEY') @click.option('-u', '--api-uri', default='https://api.polyswarm.network/v1', envvar='POLYSWARM_API_URI', help='The API endpoint (ADVANCED)') @click.option('-o', '--output-file', default=sys.stdout, type=click.File('w'), help='Path to output file.') @click.option('--fmt', '--output-format', default='text', type=click.Choice(['text', 'json']), help='Output format. Human-readable text or JSON.') @click.option('--color/--no-color', default=True, help='Use colored output in text mode.') @click.option('-v', '--verbose', default=0, count=True) @click.option('-c', '--community', default='lima', envvar='POLYSWARM_COMMUNITY', help='Community to use.') @click.option( '--advanced-disable-version-check/--advanced-enable-version-check', default=False, help='Enable/disable GitHub release version check.') @click.pass_context