コード例 #1
0
ファイル: test_basic.py プロジェクト: kx-chen/click
def test_float_range_option(runner):
    @click.command()
    @click.option("--x", type=click.FloatRange(0, 5))
    def cli(x):
        click.echo(x)

    result = runner.invoke(cli, ["--x=5.0"])
    assert not result.exception
    assert result.output == "5.0\n"

    result = runner.invoke(cli, ["--x=6.0"])
    assert result.exit_code == 2
    assert (
        "Invalid value for '--x': 6.0 is not in the valid range of 0 to 5.\n"
        in result.output
    )

    @click.command()
    @click.option("--x", type=click.FloatRange(0, 5, clamp=True))
    def clamp(x):
        click.echo(x)

    result = runner.invoke(clamp, ["--x=5.0"])
    assert not result.exception
    assert result.output == "5.0\n"

    result = runner.invoke(clamp, ["--x=6.0"])
    assert not result.exception
    assert result.output == "5\n"

    result = runner.invoke(clamp, ["--x=-1.0"])
    assert not result.exception
    assert result.output == "0\n"
コード例 #2
0
ファイル: cli.py プロジェクト: gwexploratoryaudits/r2b2
def input_audit(contest: Contest,
                alpha: float = None,
                max_fraction_to_draw: float = None,
                audit_type: str = None,
                delta: float = None) -> Audit:
    # Create an audit from user-input.
    click.echo('\nCreate a new Audit')
    click.echo('==================\n')

    if alpha is None:
        alpha = click.prompt('Enter the desired risk limit', type=click.FloatRange(0.0, 1.0))
    if max_fraction_to_draw is None:
        max_fraction_to_draw = click.prompt('Enter the maximum fraction of contest ballots to draw', type=click.FloatRange(0.0, 1.0))
    if audit_type is None:
        audit_type = click.prompt('Select an audit type', type=audit_types)
    if delta is None and audit_type == 'athena':
        delta = click.prompt('Enter the Athena delta value', type=click.FloatRange(0.0))

    if audit_type == 'brla':
        return BRLA(alpha, max_fraction_to_draw, contest)
    elif audit_type == 'minerva':
        return Minerva(alpha, max_fraction_to_draw, contest)
    elif audit_type == 'athena':
        return Athena(alpha, delta, max_fraction_to_draw, contest)
    # TODO: add creation for other types of audits.
    return None
コード例 #3
0
ファイル: test_basic.py プロジェクト: venkatalolla/click
def test_float_range_option(runner):
    @click.command()
    @click.option('--x', type=click.FloatRange(0, 5))
    def cli(x):
        click.echo(x)

    result = runner.invoke(cli, ['--x=5.0'])
    assert not result.exception
    assert result.output == '5.0\n'

    result = runner.invoke(cli, ['--x=6.0'])
    assert result.exit_code == 2
    assert 'Invalid value for "--x": 6.0 is not in the valid range of 0 to 5.\n' \
        in result.output

    @click.command()
    @click.option('--x', type=click.FloatRange(0, 5, clamp=True))
    def clamp(x):
        click.echo(x)

    result = runner.invoke(clamp, ['--x=5.0'])
    assert not result.exception
    assert result.output == '5.0\n'

    result = runner.invoke(clamp, ['--x=6.0'])
    assert not result.exception
    assert result.output == '5\n'

    result = runner.invoke(clamp, ['--x=-1.0'])
    assert not result.exception
    assert result.output == '0\n'
コード例 #4
0
ファイル: test_types.py プロジェクト: iafork/pallets-click
def test_float_range_no_clamp_open():
    with pytest.raises(TypeError):
        click.FloatRange(0, 1, max_open=True, clamp=True)

    sneaky = click.FloatRange(0, 1, max_open=True)
    sneaky.clamp = True

    with pytest.raises(RuntimeError):
        sneaky.convert("1.5", None, None)
コード例 #5
0
ファイル: cli.py プロジェクト: rotkehlxen/suncal
def common_suncal_options(function: Callable) -> Callable:
    """Create decorator for click sub-commands that holds all options that are common to the
    api and ics subcommands."""

    function = click.option(
        "--from",
        "from_date",
        type=ClickDate(),
        help="First date for which to create events.",
        required=True,
    )(function)

    function = click.option(
        "--to",
        "to_date",
        type=ClickDate(),
        help="Last date for which to create events.",
        required=True,
    )(function)

    function = click.option(
        "--event",
        "event_name",
        type=click.Choice(
            ['sunrise', 'sunset', 'golden-hour-morning', 'golden-hour-evening'],
            case_sensitive=False,
        ),
        required=True,
        help="Sun parameter for which to create calendar events.",
    )(function)

    function = click.option(
        "--long",
        "longitude",
        type=click.FloatRange(min=-180.0, max=180.0),
        help="Longitude as float.",
        required=True,
    )(function)

    function = click.option(
        "--lat",
        "latitude",
        type=click.FloatRange(min=-90.0, max=90.0),
        help="Latitude as float.",
        required=True,
    )(function)

    function = click.option('--dev/--no-dev', 'dev_mode', default=False)(
        function
    )

    return function
コード例 #6
0
def create_new_board(random_config, number_of_columns, number_of_rows,
                     config_file, speed, save):
    if config_file:
        grid = initialize_from_file(config_file)
    elif random_config:
        prob = random_config
        click.echo("Probability is %f." % prob)
        grid = initialize_random(prob, number_of_columns, number_of_rows)
    else:
        prob = click.prompt("Enter at least random probability:",
                            type=click.FloatRange(0, 1))
        grid = initialize_random(prob, number_of_columns, number_of_rows)
        click.echo("Probability is %f." % float(prob))
    click.echo("Number of grid columns %d " % grid.shape[0])
    click.echo("Number of grid rows %d " % grid.shape[1])
    if save[0] is not None:
        click.echo("Animation will be saved in %s with %d frames." % save)
    # thread shared values
    state = Value(c_uint, State.RUNNING)
    speed = Value(c_uint, speed)
    # start multi process to run the visualization not in the main thread
    visualize_process = Process(target=visualize_grid,
                                args=[grid, speed, state, save])
    visualize_process.start()
    # user interaction has to run in main thread to read user inputs
    user_interaction = UserInteraction(state)
    user_interaction.start()
    visualize_process.join()
コード例 #7
0
def transfer_tokens(general_config, actor_options, target_address, value):
    """
    Transfer tokens from contract's owner address to another address
    """
    emitter = general_config.emitter
    ADMINISTRATOR, deployer_address, _, local_registry = actor_options.create_actor(
        emitter)

    token_agent = ContractAgency.get_agent(NucypherTokenAgent,
                                           registry=local_registry)
    if not target_address:
        target_address = click.prompt("Enter recipient's checksum address",
                                      type=EIP55_CHECKSUM_ADDRESS)
    if not value:
        stake_value_range = click.FloatRange(min=0, clamp=False)
        value = NU.from_tokens(
            click.prompt(f"Enter value in NU", type=stake_value_range))

    click.confirm(
        f"Transfer {value} from {deployer_address} to {target_address}?",
        abort=True)
    receipt = token_agent.transfer(amount=int(value),
                                   sender_address=deployer_address,
                                   target_address=target_address)
    paint_receipt_summary(emitter=emitter, receipt=receipt)
コード例 #8
0
def transfer_tokens(general_config, actor_options, target_address, value):
    """Transfer tokens from contract's owner address to another address"""

    emitter = general_config.emitter
    ADMINISTRATOR, deployer_address, _, local_registry = actor_options.create_actor(
        emitter)

    token_agent = ContractAgency.get_agent(
        NucypherTokenAgent,
        registry=local_registry)  # type: NucypherTokenAgent
    tokens = NU.from_nunits(token_agent.get_balance(deployer_address))
    emitter.echo(
        DISPLAY_SENDER_TOKEN_BALANCE_BEFORE_TRANSFER.format(
            token_balance=tokens))
    if not target_address:
        target_address = click.prompt(PROMPT_RECIPIENT_CHECKSUM_ADDRESS,
                                      type=EIP55_CHECKSUM_ADDRESS)
    if not value:
        stake_value_range = click.FloatRange(min=0, clamp=False)
        value = NU.from_tokens(
            click.prompt(PROMPT_TOKEN_VALUE, type=stake_value_range))

    confirmation = CONFIRM_TOKEN_TRANSFER.format(
        value=value,
        deployer_address=deployer_address,
        target_address=target_address)
    click.confirm(confirmation, abort=True)
    receipt = token_agent.transfer(amount=int(value),
                                   sender_address=deployer_address,
                                   target_address=target_address)
    paint_receipt_summary(emitter=emitter, receipt=receipt)
コード例 #9
0
ファイル: cleye.py プロジェクト: deathbeds/cleye
def click_type(object: typing.Union[type, tuple],
               default=None) -> typing.Union[type, click.types.ParamType]:
    """Translate python types to click's subset of types."""
    if isinstance(object, typing._GenericAlias):
        return click_type(object.__args__[0], default)
    elif isinstance(object, type):
        if issubclass(object, datetime.datetime):
            return click.DateTime()
        if issubclass(object, typing.Tuple):
            return click.Tuple(object.__args__)
        if issubclass(object, uuid.UUID):
            return click.UUID(default)
        if object is list:
            return
        if issubclass(object, set):
            return click.Choice(object)

        if issubclass(object, pathlib.Path):
            return click.Path()
        if object in {builtins.object, typing.Any}:
            return
        return object
    else:
        if isinstance(object, tuple):
            if all(isinstance(x, int) for x in object[:2]):
                return click.IntRange(*object)
            if all(isinstance(x, float) for x in object[:2]):
                return click.FloatRange(*object)
コード例 #10
0
ファイル: autocli.py プロジェクト: melissawm/pidgy
def click_type(object: typing.Union[type, tuple],
               default=None) -> typing.Union[type, click.types.ParamType]:
    if isinstance(object, type):
        if issubclass(object, datetime.datetime):
            return click.DateTime()
        if issubclass(object, typing.Tuple):
            return click.Tuple(object.__args__)
        if issubclass(object, uuid.UUID):
            return click.UUID(default)
        if object is list:
            return
        if issubclass(object, typing.List):
            return click_type(object.__args__[0], default)
        if issubclass(object, set):
            return click.Choice(object)

        if issubclass(object, pathlib.Path):
            return click.Path()
        return object
    else:
        if isinstance(object, tuple):
            if all(isinstance(x, int) for x in object[:2]):
                return click.IntRange(*object)
            if all(isinstance(x, float) for x in object[:2]):
                return click.FloatRange(*object)
コード例 #11
0
def main():
    dai = Contract.from_explorer("0x6B175474E89094C44Da98b954EedeAC495271d0F")
    dai_deposit = Contract.from_explorer(
        "0xF6f4526a05a38198dBEddFc226d30dbb5419951F")
    dai_vault = Contract.from_explorer(
        "0xBFa4D8AA6d8a379aBFe7793399D3DdaCC5bBECBB")
    user = accounts.load(
        click.prompt("Account", type=click.Choice(accounts.load())))
    # account_name = input(f"What account to use?: ")
    # user = accounts.load(account_name)
    signer = Account.from_key(user.private_key)
    balance = dai.balanceOf(user)
    print("DAI balance:", balance.to("ether"))
    amount = click.prompt("Deposit amount", type=click.FloatRange(min=0))
    amount = min(Wei(f"{amount} ether"), balance)
    permit = build_permit(str(user), str(dai_deposit), dai)
    signed = signer.sign_message(permit)
    if click.confirm("Send transaction?"):
        dai_deposit.deposit(
            amount,
            [user, dai_deposit, 0, 0, True, signed.v, signed.r, signed.s],
            {"from": user},
        )
    vault_balance = dai_vault.balanceOf(user)
    print("yvDAI balance", vault_balance.to("ether"))
コード例 #12
0
def choose_settings() -> tuple[float, float]:
    click.clear()
    click.echo()
    hz = click.prompt(
        click.style("Enter frequency of PWM. [enter] for default 150 hz",
                    fg="green"),
        type=click.FloatRange(0, 10000),
        default=150,
        show_default=False,
    )
    dc = click.prompt(
        click.style("Enter duty cycle percent. [enter] for default 90%",
                    fg="green"),
        type=click.FloatRange(0, 100),
        default=90,
        show_default=False,
    )

    return hz, dc
コード例 #13
0
ファイル: generic_opt.py プロジェクト: univieCUBE/phenotrex
def common_deepnog_options(f):
    """Options added to commands which make use of deepnog."""
    f = click.option(
        '--deepnog_threshold',
        type=click.FloatRange(min=0.0, max=1.0),
        default=None,
        help='The confidence cutoff for feature creation directly from FASTA files.'
             ' Only features identfied in the genome with a confidence greater than'
             ' this are considered.'
    )(f)
    return f
コード例 #14
0
ファイル: deploy.py プロジェクト: gs455/nucypher
def transfer_tokens(  # Admin Actor Options
        provider_uri,
        contract_name,
        config_root,
        poa,
        force,
        etherscan,
        hw_wallet,
        deployer_address,
        registry_infile,
        registry_outfile,
        dev,
        se_test_mode,

        # Other
        target_address,
        value):
    """
    Transfer tokens from contract's owner address to another address
    """
    # Init
    emitter = StdoutEmitter()
    _ensure_config_root(config_root)
    deployer_interface = _initialize_blockchain(poa, provider_uri)

    # Warnings
    _pre_launch_warnings(emitter, etherscan, hw_wallet)

    #
    # Make Authenticated Deployment Actor
    #
    ADMINISTRATOR, deployer_address, local_registry = _make_authenticated_deployment_actor(
        emitter, provider_uri, deployer_address, deployer_interface,
        contract_name, registry_infile, registry_outfile, hw_wallet, dev,
        force, se_test_mode)

    token_agent = ContractAgency.get_agent(NucypherTokenAgent,
                                           registry=local_registry)
    if not target_address:
        target_address = click.prompt("Enter recipient's checksum address",
                                      type=EIP55_CHECKSUM_ADDRESS)
    if not value:
        stake_value_range = click.FloatRange(min=0, clamp=False)
        value = NU.from_tokens(
            click.prompt(f"Enter value in NU", type=stake_value_range))

    click.confirm(
        f"Transfer {value} from {deployer_address} to {target_address}?",
        abort=True)
    receipt = token_agent.transfer(amount=value,
                                   sender_address=deployer_address,
                                   target_address=target_address)
    emitter.echo(f"OK | Receipt: {receipt['transactionHash'].hex()}")
コード例 #15
0
ファイル: mozi_cli.py プロジェクト: MOZI-AI/mozi-service-cli
def cli(j, m, result_count, reduct_knob_building_effort, complexity_ratio,
        enable_fs, fs_algo, fs_target_size, balance, hc_widen_search,
        hc_crossover_pop_size, hc_crossover_min_neighbors, dataset, out):
    """
    :param dataset: The dataset file
    :param out: The dir to save the query.json file
    :return:
    """
    moses_opts_dict = {
        "-j": j,
        "--result-count": result_count,
        "--reduct-knob-building-effort": reduct_knob_building_effort,
        "-m": m,
        "--complexity-ratio": complexity_ratio,
        "--enable-fs": enable_fs,
        "--fs-algo": fs_algo,
        "--fs-target-size": fs_target_size,
        "--balance": balance,
        "--hc-widen-search": hc_widen_search,
        "--hc-crossover-pop-size": hc_crossover_pop_size,
        "--hc-crossover-min-neighbors": hc_crossover_min_neighbors
    }

    moses_opts_str = "".join("{} {} ".format(key, val)
                             for key, val in moses_opts_dict.items())

    output_dict = {"mosesOpts": moses_opts_str + " -W 1"}

    # Prompt cross-val options

    folds = click.prompt("Num of folds: ", default=3)
    test_size = click.prompt("Test size: ",
                             default=0.33,
                             type=click.FloatRange(0, 1))
    seeds = click.prompt("Num of seeds: ", default=2)
    target = click.prompt("Name of the target feature", type=TargetParamType())

    cross_val_opts = {
        "folds": folds,
        "testSize": test_size,
        "randomSeed": seeds
    }

    output_dict["crossValOpts"] = cross_val_opts
    output_dict["target_feature"] = target

    output_dict["file@b64encode@dataset"] = dataset

    file = os.path.join(out, "query.json")
    with open(file, "w") as fp:
        fp.write(json.dumps(output_dict))

    click.echo(click.style("Done!", fg="green"))
コード例 #16
0
    def configure_parameters(self, project_parameters: List[QCParameter],
                             cloud: bool) -> List[OptimizationParameter]:
        """Asks the user which parameters need to be optimized and with what constraints.

        :param project_parameters: the parameters of the project that will be optimized
        :param cloud: True if the optimization will be ran in the cloud, False if not
        :return: the chosen optimization parameters
        """
        results: List[OptimizationParameter] = []

        for parameter in project_parameters:
            if cloud and len(results) == 2:
                self._logger.warn(
                    f"You can optimize up to 2 parameters in the cloud, skipping '{parameter.key}'"
                )
                continue

            if not click.confirm(
                    f"Should the '{parameter.key}' parameter be optimized?",
                    default=True):
                continue

            minimum = click.prompt(f"Minimum value for '{parameter.key}'",
                                   type=click.FLOAT)
            maximum = click.prompt(f"Maximum value for '{parameter.key}'",
                                   type=click.FloatRange(min=minimum))
            step_size = click.prompt(f"Step size for '{parameter.key}'",
                                     type=click.FloatRange(min=0.0),
                                     default=1.0)

            results.append(
                OptimizationParameter(name=parameter.key,
                                      min=minimum,
                                      max=maximum,
                                      step=step_size))

        return results
コード例 #17
0
def bid(general_config, worklock_options, registry_options, force, value):
    emitter = _setup_emitter(general_config)
    if not value:
        if force:
            raise click.MissingParameter("Missing --value.")
        value = int(Web3.fromWei(click.prompt("Enter bid amount in ETH", type=click.FloatRange(min=0)), 'wei'))

    if not worklock_options.bidder_address:
        worklock_options.bidder_address = select_client_account(emitter=emitter,
                                                                provider_uri=general_config.provider_uri)
    registry = registry_options.get_registry(emitter, general_config.debug)
    bidder = worklock_options.create_bidder(registry=registry)

    if not force:
        paint_bidding_notice(emitter=emitter, bidder=bidder)
        click.confirm(f"Place WorkLock bid of {Web3.fromWei(value, 'ether')} ETH?", abort=True)

    receipt = bidder.place_bid(value=value)
    emitter.message("Publishing WorkLock Bid...")

    # Ensure the total bid value is worth a claim that is at
    # least large enough for the minimum stake.
    minimum = bidder.economics.minimum_allowed_locked
    available_claim = bidder.available_claim
    if available_claim < minimum:
        warning = f"Total bid is too small for a claim, please bid more or cancel. " \
                  f"{available_claim} total / {minimum} minimum" \
                  f"(Total must be worth at least {NU.from_nunits(minimum)})"
        emitter.echo(warning, color='yellow')
    else:
        message = f'Current bid: {bidder.get_deposited_eth} | ' \
                  f'Available Claim: {bidder.available_claim} |' \
                  f'Note that available claim value may fluctuate ' \
                  f'until bidding closes and claims are finalized.'
        emitter.echo(message, color='yellow')

    paint_receipt_summary(receipt=receipt, emitter=emitter, chain_name=bidder.staking_agent.blockchain.client.chain_name)
    return  # Exit
コード例 #18
0
ファイル: tfmpc.py プロジェクト: nadia-el/tf-mpc

@cli.command()
@click.argument("env", type=click.Path(exists=True))
@click.option("--online",
              is_flag=True,
              help="Online mode flag.",
              show_default=True)
@click.option("--horizon",
              "-hr",
              type=click.IntRange(min=1),
              default=10,
              help="The number of timesteps.",
              show_default=True)
@click.option("--atol",
              type=click.FloatRange(min=0.0),
              default=5e-3,
              help="Absolute tolerance for convergence.",
              show_default=True)
@click.option("--max-iterations",
              "-miter",
              type=click.IntRange(min=1),
              default=100,
              help="Maximum number of iterations.",
              show_default=True)
@click.option("--logdir",
              type=click.Path(),
              default="/tmp/ilqr/",
              help="Directory used for logging results.",
              show_default=True)
@click.option("--num-samples",
コード例 #19
0
ファイル: test_types.py プロジェクト: iafork/pallets-click
import click


@pytest.mark.parametrize(
    ("type", "value", "expect"),
    [
        (click.IntRange(0, 5), "3", 3),
        (click.IntRange(5), "5", 5),
        (click.IntRange(5), "100", 100),
        (click.IntRange(max=5), "5", 5),
        (click.IntRange(max=5), "-100", -100),
        (click.IntRange(0, clamp=True), "-1", 0),
        (click.IntRange(max=5, clamp=True), "6", 5),
        (click.IntRange(0, min_open=True, clamp=True), "0", 1),
        (click.IntRange(max=5, max_open=True, clamp=True), "5", 4),
        (click.FloatRange(0.5, 1.5), "1.2", 1.2),
        (click.FloatRange(0.5, min_open=True), "0.51", 0.51),
        (click.FloatRange(max=1.5, max_open=True), "1.49", 1.49),
        (click.FloatRange(0.5, clamp=True), "-0.0", 0.5),
        (click.FloatRange(max=1.5, clamp=True), "inf", 1.5),
    ],
)
def test_range(type, value, expect):
    assert type.convert(value, None, None) == expect


@pytest.mark.parametrize(
    ("type", "value", "expect"),
    [
        (click.IntRange(0, 5), "6", "6 is not in the range 0<=x<=5."),
        (click.IntRange(5), "4", "4 is not in the range x>=5."),
コード例 #20
0
ファイル: cli.py プロジェクト: thrinithomas/pyrak811
import click
from rak811 import Mode, RecvEx, Reset
from rak811 import Rak811
from rak811 import Rak811Error
from rak811 import Rak811EventError, Rak811ResponseError, Rak811TimeoutError

# Valid configuration keys for LoRaWan
LW_CONFIG_KEYS = ('dev_addr', 'dev_eui', 'app_eui', 'app_key', 'nwks_key',
                  'apps_key', 'tx_power', 'pwr_level', 'adr', 'dr',
                  'public_net', 'rx_delay1', 'ch_list', 'ch_mask', 'max_chs',
                  'rx2', 'join_cnt', 'nbtrans', 'retrans', 'class', 'duty')

# Valid configuration keys for LoRaP2P
P2P_CONFIG_KEYS = {
    'freq': click.FloatRange(min=860.000, max=929.900, clamp=False),
    'sf': click.IntRange(min=6, max=12, clamp=False),
    'bw': click.IntRange(min=0, max=2, clamp=False),
    'cr': click.IntRange(min=1, max=4, clamp=False),
    'prlen': click.IntRange(min=8, max=65535, clamp=False),
    'pwr': click.IntRange(min=5, max=20, clamp=False)
}


class KeyValueParamTypeLW(click.ParamType):
    """Basic KEY=VALUE pair parameter type for LoRaWan."""

    name = 'key-value-lorawan'

    def convert(self, value, param, ctx):
        try:
コード例 #21
0
@click.option(
    "-c",
    "--compressor",
    default="BZ2",
    type=click.Choice([x.name for x in Compress]),
    show_default=True,
    show_choices=True,
    help="Set the compression method. Some methods perform better,"
    " as they can compress the content much better, but usually"
    " come with the drawback, that they are very slow. "
    "While LZMA has the best compression, Snappy has well compression but"
    " is much faster than LZMA.")
@click.option("-t",
              "--threshold",
              default=0.6,
              type=click.FloatRange(0, 1),
              help="Threshold when sorting interesting items")
@click.option(
    "-s",
    "--size",
    type=int,
    help=
    'exclude specific method below the specific size (specify the minimum size of a method to be used (it is the length (bytes) of the dalvik method)'
)
@click.option("-e",
              "--exclude",
              type=str,
              help="exlude class names (python regex string)")
@click.option("--new/--no-new",
              help="calculate similarity score by including new elements",
              show_default=True)
コード例 #22
0
def options(func: Callable) -> Callable:
    """Having the common app options as a decorator facilitates reuse."""

    # Until https://github.com/pallets/click/issues/926 is fixed the options need to be re-defined
    # for every use
    options_ = [
        option("--version", hidden=True, is_flag=True, allow_from_autoenv=False),
        option(
            "--datadir",
            help="Directory for storing raiden data.",
            default=lambda: os.path.join(os.path.expanduser("~"), ".raiden"),
            type=click.Path(
                exists=False,
                dir_okay=True,
                file_okay=False,
                writable=True,
                resolve_path=True,
                allow_dash=False,
            ),
            show_default=True,
        ),
        option(
            "--config-file",
            help="Configuration file (TOML)",
            default=os.path.join("${datadir}", "config.toml"),
            type=PathRelativePath(
                file_okay=True, dir_okay=False, exists=False, readable=True, resolve_path=True
            ),
            show_default=True,
        ),
        option(
            "--keystore-path",
            help=(
                "If you have a non-standard path for the ethereum keystore directory"
                " provide it using this argument."
            ),
            default=None,
            type=click.Path(exists=True),
            show_default=True,
        ),
        option(
            "--address",
            help=(
                "The ethereum address you would like raiden to use and for which "
                "a keystore file exists in your local system."
            ),
            default=None,
            type=ADDRESS_TYPE,
            show_default=True,
        ),
        option(
            "--password-file",
            help="Text file containing the password for the provided account",
            default=None,
            type=click.File(lazy=True),
            show_default=True,
        ),
        option(
            "--user-deposit-contract-address",
            help="hex encoded address of the User Deposit contract.",
            type=ADDRESS_TYPE,
        ),
        option("--console", help="Start the interactive raiden console", is_flag=True),
        option(
            "--transport",
            help="Transport system to use.",
            type=click.Choice(["matrix"]),
            default="matrix",
            show_default=True,
            hidden=True,
        ),
        option(
            ETH_NETWORKID_OPTION,
            help=(
                "Specify the network name/id of the Ethereum network to run Raiden on.\n"
                "Available networks:\n"
                '"mainnet" - network id: 1\n'
                '"ropsten" - network id: 3\n'
                '"rinkeby" - network id: 4\n'
                '"goerli" - network id: 5\n'
                '"kovan" - network id: 42\n'
                '"<NETWORK_ID>": use the given network id directly\n'
            ),
            type=NetworkChoiceType(
                ["mainnet", "ropsten", "rinkeby", "goerli", "kovan", "<NETWORK_ID>"]
            ),
            default="mainnet",
            show_default=True,
        ),
        option(
            "--environment-type",
            help=(
                "Specify the environment (production or development).\n"
                'The "production" setting adds some safety measures and is mainly intended '
                "for running Raiden on the mainnet.\n"
            ),
            type=EnumChoiceType(Environment),
            default=Environment.PRODUCTION.value,
            show_default=True,
        ),
        option(
            "--accept-disclaimer",
            help="Bypass the experimental software disclaimer prompt",
            is_flag=True,
        ),
        option(
            "--showconfig",
            help="Show all configuration values used to control Raiden's behavior",
            is_flag=True,
        ),
        option(
            "--blockchain-query-interval",
            help="Time interval after which to check for new blocks (in seconds)",
            default=DEFAULT_BLOCKCHAIN_QUERY_INTERVAL,
            show_default=True,
            type=click.FloatRange(min=0.1),
        ),
        option_group(
            "Channel-specific Options",
            option(
                "--default-reveal-timeout",
                help="Sets the default reveal timeout to be used to newly created channels",
                default=DEFAULT_REVEAL_TIMEOUT,
                show_default=True,
                type=click.IntRange(min=20),
            ),
            option(
                "--default-settle-timeout",
                help="Sets the default settle timeout to be used to newly created channels",
                default=DEFAULT_SETTLE_TIMEOUT,
                show_default=True,
                type=click.IntRange(min=20),
            ),
        ),
        option_group(
            "Ethereum Node Options",
            option(
                "--sync-check/--no-sync-check",
                help="Checks if the ethereum node is synchronized against etherscan.",
                default=True,
                show_default=True,
            ),
            option(
                "--gas-price",
                help=(
                    "Set the gas price for ethereum transactions. If not provided "
                    "the normal gas price startegy is used.\n"
                    "Available options:\n"
                    '"fast" - transactions are usually mined within 60 seconds\n'
                    '"normal" - transactions are usually mined within 5 minutes\n'
                    "<GAS_PRICE> - use given gas price\n"
                ),
                type=GasPriceChoiceType(["normal", "fast"]),
                default="fast",
                show_default=True,
            ),
            option(
                ETH_RPC_CONFIG_OPTION,
                help=(
                    '"host:port" address of ethereum JSON-RPC server.\n'
                    "Also accepts a protocol prefix (http:// or https://) with optional port"
                ),
                default="http://127.0.0.1:8545",  # geth default jsonrpc port
                type=str,
                show_default=True,
            ),
        ),
        option_group(
            "Raiden Services Options",
            option(
                "--routing-mode",
                help=(
                    "Specify the routing mode to be used.\n"
                    '"pfs": use the path finding service\n'
                    '"local": use local routing, but send updates to the PFS\n'
                    '"private": use local routing and don\'t send updates to the PFS\n'
                ),
                type=EnumChoiceType(RoutingMode),
                default=RoutingMode.PFS.value,
                show_default=True,
            ),
            option(
                "--pathfinding-service-address",
                help=(
                    "URL to the Raiden path finding service to request paths from.\n"
                    "Example: https://pfs-ropsten.services-dev.raiden.network\n"
                    'Can also be given the "auto" value so that raiden chooses a '
                    "PFS randomly from the service registry contract"
                ),
                default="auto",
                type=str,
                show_default=True,
            ),
            option(
                "--pathfinding-max-paths",
                help="Set maximum number of paths to be requested from the path finding service.",
                default=DEFAULT_PATHFINDING_MAX_PATHS,
                type=int,
                show_default=True,
            ),
            option(
                "--pathfinding-max-fee",
                help="Set max fee per request paid to the path finding service.",
                default=DEFAULT_PATHFINDING_MAX_FEE,
                type=int,
                show_default=True,
            ),
            option(
                "--pathfinding-iou-timeout",
                help="Number of blocks before a new IOU to the path finding service expires.",
                default=DEFAULT_PATHFINDING_IOU_TIMEOUT,
                type=int,
                show_default=True,
            ),
            option(
                "--enable-monitoring",
                help="Enable broadcasting of balance proofs to the monitoring services.",
                default=False,
                is_flag=True,
            ),
        ),
        option_group(
            "Matrix Transport Options",
            option(
                "--matrix-server",
                help=(
                    "Matrix homeserver to use for communication.\n"
                    "Valid values:\n"
                    '"auto" - automatically select a suitable homeserver\n'
                    "A URL pointing to a Raiden matrix homeserver"
                ),
                default="auto",
                type=MatrixServerType(["auto", "<url>"]),
                show_default=True,
            ),
        ),
        option_group(
            "Logging Options",
            option(
                "--log-config",
                help="Log level configuration.\n"
                "Format: [<logger-name-1>]:<level>[,<logger-name-2>:level][,...]",
                type=LOG_LEVEL_CONFIG_TYPE,
                default=":info",
                show_default=True,
            ),
            option(
                "--log-file",
                help="file path for logging to file",
                default=None,
                type=click.Path(dir_okay=False, writable=True, resolve_path=True),
                show_default=True,
            ),
            option("--log-json", help="Output log lines in JSON format", is_flag=True),
            option(
                "--debug-logfile-path",
                help=(
                    "The absolute path to the debug logfile. If not given defaults to:\n"
                    " - OSX: ~/Library/Logs/Raiden/raiden_debug_XXX.log\n"
                    " - Windows: ~/Appdata/Roaming/Raiden/raiden_debug_XXX.log\n"
                    " - Linux: ~/.raiden/raiden_debug_XXX.log\n"
                    "\nIf there is a problem with expanding home it is placed under /tmp"
                ),
                type=click.Path(dir_okay=False, writable=True, resolve_path=True),
            ),
            option(
                "--disable-debug-logfile",
                help=(
                    "Disable the debug logfile feature. This is independent of "
                    "the normal logging setup"
                ),
                is_flag=True,
            ),
        ),
        option_group(
            "RPC Options",
            option(
                "--rpc/--no-rpc",
                help="Start with or without the RPC server.",
                default=True,
                show_default=True,
            ),
            option(
                "--rpccorsdomain",
                help="Comma separated list of domains to accept cross origin requests.",
                default="http://localhost:*/*",
                type=str,
                show_default=True,
            ),
            option(
                "--api-address",
                help='"host:port" for the RPC server to listen on.',
                default=f"127.0.0.1:{DEFAULT_HTTP_SERVER_PORT}",
                type=str,
                show_default=True,
            ),
            option(
                "--web-ui/--no-web-ui",
                help=(
                    "Start with or without the web interface. Requires --rpc. "
                    "It will be accessible at http://<api-address>. "
                ),
                default=True,
                show_default=True,
            ),
        ),
        option_group(
            "Debugging options",
            option(
                "--flamegraph",
                help=("Directory to save stack data used to produce flame graphs."),
                type=click.Path(
                    exists=False,
                    dir_okay=True,
                    file_okay=False,
                    writable=True,
                    resolve_path=True,
                    allow_dash=False,
                ),
                default=None,
            ),
            option("--switch-tracing", help="Enable switch tracing", is_flag=True, default=False),
            option(
                "--unrecoverable-error-should-crash",
                help=(
                    "DO NOT use, unless you know what you are doing. If provided "
                    "along with a production environment setting then all "
                    "unrecoverable errors will lead to a crash and not simply get logged."
                ),
                is_flag=True,
                default=False,
            ),
            option(
                "--log-memory-usage-interval",
                help="Log memory usage every X sec (fractions accepted). [default: disabled]",
                type=float,
                default=0,
            ),
        ),
        option_group(
            "Hash Resolver Options",
            option(
                "--resolver-endpoint",
                help=(
                    "URL of the resolver server that is used to resolve "
                    "a payment hash to a secret. "
                    "Accepts a protocol prefix (http:// or https://) with optional port"
                ),
                default=None,
                type=str,
                show_default=True,
            ),
        ),
        option_group(
            "Mediation Fee Options",
            option(
                "--flat-fee",
                help=(
                    "Sets the flat fee required for every mediation in wei of the "
                    "mediated token for a certain token address. Must be bigger "
                    f"or equal to {FLAT_MED_FEE_MIN}."
                ),
                type=(ADDRESS_TYPE, click.IntRange(min=FLAT_MED_FEE_MIN)),
                multiple=True,
            ),
            option(
                "--proportional-fee",
                help=(
                    "Mediation fee as ratio of mediated amount in parts-per-million "
                    "(10^-6) for a certain token address. "
                    f"Must be in [{PROPORTIONAL_MED_FEE_MIN}, {PROPORTIONAL_MED_FEE_MAX}]."
                ),
                type=(
                    ADDRESS_TYPE,
                    click.IntRange(min=PROPORTIONAL_MED_FEE_MIN, max=PROPORTIONAL_MED_FEE_MAX),
                ),
                multiple=True,
            ),
            option(
                "--proportional-imbalance-fee",
                help=(
                    "Set the worst-case imbalance fee relative to the channels capacity "
                    "in parts-per-million (10^-6) for a certain token address. "
                    f"Must be in [{IMBALANCE_MED_FEE_MIN}, {IMBALANCE_MED_FEE_MAX}]."
                ),
                type=(
                    ADDRESS_TYPE,
                    click.IntRange(min=IMBALANCE_MED_FEE_MIN, max=IMBALANCE_MED_FEE_MAX),
                ),
                multiple=True,
            ),
            option(
                "--cap-mediation-fees/--no-cap-mediation-fees",
                help="Cap the mediation fees to never get negative.",
                default=True,
                show_default=True,
            ),
        ),
    ]

    for option_ in reversed(options_):
        func = option_(func)
    return func
コード例 #23
0
def create(general_config, transacting_staker_options, config_file, force,
           value, lock_periods):
    """
    Initialize a new stake.
    """
    emitter = _setup_emitter(general_config)

    STAKEHOLDER = transacting_staker_options.create_character(
        emitter, config_file)
    blockchain = transacting_staker_options.get_blockchain()

    economics = STAKEHOLDER.economics

    client_account, staking_address = handle_client_account_for_staking(
        emitter=emitter,
        stakeholder=STAKEHOLDER,
        staking_address=transacting_staker_options.staker_options.
        staking_address,
        individual_allocation=STAKEHOLDER.individual_allocation,
        force=force)

    # Dynamic click types (Economics)
    min_locked = economics.minimum_allowed_locked
    stake_value_range = click.FloatRange(
        min=NU.from_nunits(min_locked).to_tokens(), clamp=False)
    stake_duration_range = click.IntRange(min=economics.minimum_locked_periods,
                                          clamp=False)

    #
    # Stage Stake
    #

    if not value:
        token_balance = NU.from_nunits(
            STAKEHOLDER.token_agent.get_balance(staking_address))
        lower_limit = NU.from_nunits(
            STAKEHOLDER.economics.minimum_allowed_locked)
        upper_limit = min(
            token_balance,
            NU.from_nunits(STAKEHOLDER.economics.maximum_allowed_locked))
        value = click.prompt(
            f"Enter stake value in NU "
            f"({lower_limit} - {upper_limit})",
            type=stake_value_range,
            default=upper_limit.to_tokens())
    value = NU.from_tokens(value)

    if not lock_periods:
        min_locktime = STAKEHOLDER.economics.minimum_locked_periods
        default_locktime = STAKEHOLDER.economics.maximum_rewarded_periods
        max_locktime = MAX_UINT16 - STAKEHOLDER.staking_agent.get_current_period(
        )
        prompt = f"Enter stake duration ({min_locktime} - {max_locktime})"
        lock_periods = click.prompt(prompt,
                                    type=stake_duration_range,
                                    default=default_locktime)

    start_period = STAKEHOLDER.staking_agent.get_current_period() + 1
    unlock_period = start_period + lock_periods

    #
    # Review and Publish
    #

    if not force:
        issue_stake_suggestions(value=value, lock_periods=lock_periods)
        painting.paint_staged_stake(emitter=emitter,
                                    stakeholder=STAKEHOLDER,
                                    staking_address=staking_address,
                                    stake_value=value,
                                    lock_periods=lock_periods,
                                    start_period=start_period,
                                    unlock_period=unlock_period)

        confirm_staged_stake(staker_address=staking_address,
                             value=value,
                             lock_periods=lock_periods)

    # Last chance to bail
    click.confirm("Publish staged stake to the blockchain?", abort=True)

    # Authenticate
    password = transacting_staker_options.get_password(blockchain,
                                                       client_account)

    # Consistency check to prevent the above agreement from going stale.
    last_second_current_period = STAKEHOLDER.staking_agent.get_current_period()
    if start_period != last_second_current_period + 1:
        emitter.echo(
            "Current period advanced before stake was broadcasted. Please try again.",
            color='red')
        raise click.Abort

    # Authenticate and Execute
    STAKEHOLDER.assimilate(checksum_address=client_account, password=password)

    new_stake = STAKEHOLDER.initialize_stake(amount=value,
                                             lock_periods=lock_periods)

    painting.paint_staking_confirmation(emitter=emitter,
                                        staker=STAKEHOLDER,
                                        new_stake=new_stake)
コード例 #24
0
ファイル: experiment_1.py プロジェクト: CesarRocha00/evobci
@click.argument('OUTPUTDIR',
                type=click.Path(exists=True, file_okay=False),
                required=True)
@click.option('-ps',
              'pop_size',
              type=click.IntRange(2, None),
              required=True,
              help='Size of the entire population.')
@click.option('-ng',
              'num_gen',
              type=click.IntRange(0, None),
              required=True,
              help='Number of generations to evolve.')
@click.option('-cp',
              'cx_pr',
              type=click.FloatRange(0.0, 1.0),
              default=1.0,
              show_default=True,
              help='Crossover probability.')
@click.option('-ct',
              'cx_type',
              type=click.Choice(['npoint', 'binary'], case_sensitive=True),
              default='binary',
              show_default=True,
              help='Type of crossover to be applied.')
@click.option('-np',
              'num_pts',
              type=click.IntRange(1, None),
              default=1,
              show_default=True,
              help='Number of crossover points.')
コード例 #25
0
    "--dimensions",
    type=int,
    help="Dimensions to use for `michalewicz` and `styblinski_tang` benchmarks."
)
@click.option("--method-name", default="gp-botorch-batch")
@click.option("--num-runs", "-n", default=20)
@click.option("--run-start", default=0)
@click.option("--num-iterations", "-i", default=500)
@click.option("--acquisition-name",
              default="q-EI",
              type=click.Choice(["q-EI", "q-KG"], case_sensitive=False))
# @click.option("--acquisition-optimizer-name", default="lbfgs",
#               type=click.Choice(["lbfgs", "DIRECT", "CMA"]))
@click.option("--gamma",
              default=0.,
              type=click.FloatRange(0., 1.),
              help="Quantile, or mixing proportion.")
@click.option("--num-random-init", default=10)
@click.option("--batch-size", default=4)
@click.option("--num-fantasies", default=128)
@click.option("--mc-samples", default=256)
@click.option("--num-restarts", default=10)
@click.option("--raw-samples", default=512)
@click.option("--noise-variance-init", default=5e-2)
# @click.option('--use-ard', is_flag=True)
# @click.option('--use-input-warping', is_flag=True)
@click.option('--standardize-targets/--no-standardize-targets', default=True)
@click.option("--input-dir",
              default="datasets/",
              type=click.Path(file_okay=False, dir_okay=True),
              help="Input data directory.")
コード例 #26
0
@click.option('--val', '-v', 'validation', type=click.Path(file_okay=False, dir_okay=True), required=True,
              help='Path to validation dataset.')
@click.option('--resume', '-r', type=click.Path(dir_okay=False, file_okay=True), help='Path to the trained checkpoint.')
@click.option('--save_model', '-m', type=click.Path(dir_okay=True, file_okay=False), default='./checkpoints',
              help='Directory to save checkpoints.')
@click.option('--epochs', type=int, default=240, help='Number of epochs.')
@click.option('--bs', type=int, default=16, help='Batch size.')
@click.option('--lr', type=float, default=0.02, help='Initial learning rate.')
@click.option('--loss', type=click.Choice(['cross_entropy', 'focal', 'contrastive', 'triplet']),
              default='cross_entropy', help='Loss function to use.')
@click.option('--freeze/--no-freeze', default=False, help='Whether or not freeze the feature extractor backbone.')
@click.option('--miner', type=click.Choice(['default', 'kernel_7x7', 'temporal', 'one_back_one_ahead',
                                            'euclidean', 'manhattan', 'chebyshev', 'skeleton',
                                            'skeleton_nearest_negative', 'skeleton_temporal']),
              default='default', help='Triplet loss miner.')
@click.option('--margin', type=click.FloatRange(min=0.0, max=1.0), default=0.1, help='Triplet loss margin.')
@click.option('--loss_weight', type=click.FloatRange(min=0.0), default=1.0, help='Weight of triplet loss.')
@click.option('--max_triplets', type=click.IntRange(min=0), default=0,
              help='Maximum number of triplets to mine (0 means take all triplets).')
@click.option('--early-stop/--no-early-stop', default=False, help='Whether or not use the early stopping for training.')
def train_command(frame_num, training, validation, resume, save_model, epochs, bs, lr, loss, freeze, miner, margin,
                  loss_weight, max_triplets, early_stop):
    logger.info('Training started.')
    torch.manual_seed(42)

    temperature = 1.0
    model = 'resnet50'
    model = VOSNet(model=model)
    model = model.to(Config.DEVICE)

    if loss == 'cross_entropy':
コード例 #27
0
ファイル: configuration.py プロジェクト: sdss/jaeger

@configuration.command()
@click.argument("SEED", type=int, required=False)
@click.option("--danger",
              is_flag=True,
              help="Use full range of alpha and beta.")
@click.option(
    "--uniform",
    type=str,
    default=None,
    help="Comma-separated alpha and beta ranges.",
)
@click.option(
    "--collision-buffer",
    type=click.FloatRange(1.6, 3.0),
    help="Custom collision buffer",
)
@click.option(
    "--send-trajectory/--no-send-trajectory",
    help="Send the trajectory to the FPS.",
    default=True,
)
async def random(
    command: Command[JaegerActor],
    fps: FPS,
    seed: int | None = None,
    danger: bool = False,
    uniform: str | None = None,
    collision_buffer: float | None = None,
    send_trajectory: bool = True,
コード例 #28
0
ファイル: dupdel.py プロジェクト: zefiers/dupdel
import os
import time
import hashlib
import click

duplicated = 0
size = 0


@click.command()
@click.argument('dirs', type=click.Path(exists=True), nargs=-1, required=True)
@click.option('--chunk-size', '-c', type=click.IntRange(128, 2**32), default=4096, show_default=True,
              help='The size of every chunk of the file to read and update the checksum. '
                   'This value affects the Memory/CPU Usage as well as the progress speed.')
@click.option('--sleep-time', '-s', type=click.FloatRange(0, 120), default=0.001, show_default=True,
              help='The time to sleep (in seconds) while looping/iterating trow the files and calc the checksum. '
                   'This was made to prevent CPU Leak (100% Usage on some platforms).')
@click.option('--no-delete-empty', '-D', is_flag=True, help='Don\'t delete empty subdirectories.')
@click.option('--separate', '-S', is_flag=True, help='Delete duplicates in each directory separately.')
@click.option('--check-only', '-C', is_flag=True, help='Check only, Don\'t delete anything.')
@click.option('--recursive', '-R', is_flag=True, help='Check files and directories recursively.')
@click.option('--verbose', '-v', count=True, help='Output a diagnostic for every file processed.')
@click.option('--hash-type', '-h', default='sha1',
              type=click.Choice(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'], case_sensitive=False),
              show_default=True, help='The hash type used to check the files\' checksum.')
def dupdel(dirs, chunk_size, sleep_time, no_delete_empty, separate, check_only, recursive, verbose, hash_type):
    """Check duplicated file and delete them using hash checksums."""
    global duplicated, size
    checksums_ = set()

    def get_checksum(file):
コード例 #29
0
def divide(general_config, transacting_staker_options, config_file, force,
           value, lock_periods, index):
    """
    Create a new stake from part of an existing one.
    """

    # Setup
    emitter = _setup_emitter(general_config)
    STAKEHOLDER = transacting_staker_options.create_character(
        emitter, config_file)
    blockchain = transacting_staker_options.get_blockchain()
    economics = STAKEHOLDER.economics
    action_period = STAKEHOLDER.staking_agent.get_current_period()

    client_account, staking_address = handle_client_account_for_staking(
        emitter=emitter,
        stakeholder=STAKEHOLDER,
        staking_address=transacting_staker_options.staker_options.
        staking_address,
        individual_allocation=STAKEHOLDER.individual_allocation,
        force=force)

    # Dynamic click types (Economics)
    min_locked = economics.minimum_allowed_locked
    stake_value_range = click.FloatRange(
        min=NU.from_nunits(min_locked).to_tokens(), clamp=False)

    if transacting_staker_options.staker_options.staking_address and index is not None:  # 0 is valid.
        STAKEHOLDER.stakes = StakeList(
            registry=STAKEHOLDER.registry,
            checksum_address=transacting_staker_options.staker_options.
            staking_address)
        STAKEHOLDER.stakes.refresh()
        current_stake = STAKEHOLDER.stakes[index]
    else:
        current_stake = select_stake(stakeholder=STAKEHOLDER,
                                     emitter=emitter,
                                     divisible=True,
                                     staker_address=client_account)

    #
    # Stage Stake
    #

    # Value
    if not value:
        min_allowed_locked = NU.from_nunits(
            STAKEHOLDER.economics.minimum_allowed_locked)
        max_divide_value = max(min_allowed_locked,
                               current_stake.value - min_allowed_locked)
        value = click.prompt(
            f"Enter target value ({min_allowed_locked} - {str(max_divide_value)})",
            type=stake_value_range)
    value = NU(value, 'NU')

    # Duration
    if not lock_periods:
        max_extension = MAX_UINT16 - current_stake.final_locked_period
        divide_extension_range = click.IntRange(min=1,
                                                max=max_extension,
                                                clamp=False)
        extension = click.prompt(f"Enter number of periods to extend",
                                 type=divide_extension_range)
    else:
        extension = lock_periods

    if not force:
        issue_stake_suggestions(lock_periods=extension, value=value)
        painting.paint_staged_stake_division(emitter=emitter,
                                             stakeholder=STAKEHOLDER,
                                             original_stake=current_stake,
                                             target_value=value,
                                             extension=extension)
        click.confirm("Publish stake division to the blockchain?", abort=True)

    # Authenticate
    password = transacting_staker_options.get_password(blockchain,
                                                       client_account)

    # Consistency check to prevent the above agreement from going stale.
    last_second_current_period = STAKEHOLDER.staking_agent.get_current_period()
    if action_period != last_second_current_period:
        emitter.echo(
            "Current period advanced before stake division was broadcasted. Please try again.",
            red='red')
        raise click.Abort

    # Execute
    STAKEHOLDER.assimilate(checksum_address=current_stake.staker_address,
                           password=password)
    modified_stake, new_stake = STAKEHOLDER.divide_stake(
        stake_index=current_stake.index,
        target_value=value,
        additional_periods=extension)
    emitter.echo('Successfully divided stake', color='green', verbosity=1)
    paint_receipt_summary(emitter=emitter,
                          receipt=new_stake.receipt,
                          chain_name=blockchain.client.chain_name)

    # Show the resulting stake list
    painting.paint_stakes(emitter=emitter, stakeholder=STAKEHOLDER)
コード例 #30
0
from pontomais.calc_time import main as p_calculate
from pontomais.calc_time import time_cards as p_time_cards
from pontomais.clockin import main as p_register
from pontomais.login import login as p_login


@click.group()
def cli():
    pass


@cli.command("login")
@click.option('--login', required=False, help="either CPF or email")
@click.option('--address', required=False, help="Address of where you are working")
@click.option('--latitude', type=click.FloatRange(-90, 90), required=False,
              help="Latitude of the place you are currently working from")
@click.option('--longitude', type=click.FloatRange(-180, 180), required=False,
              help="Longitude of the place you are currently working from")
@click.option('--json-profile', required=False, type=click.File('r'),
              help="a json file with login, address, latitude and longitude already on")
@click.password_option(confirmation_prompt=False)
def get_credentials(login, address, latitude, longitude, json_profile, password):
    """
    Generate a credential file necessary to do almost any action with this client

    if using a json profile to provide the profile, you do not require to add the password on it, the
    password will be asked to be input in a safe manner in this app

    """
    if json_profile: