Example #1
0
def set_done(todo_id: int = typer.Argument(...)) -> None:
    """Complete a to-do by setting it as done using its TODO_ID."""
    todoer = get_todoer()
    todo, error = todoer.set_done(todo_id)
    if error:
        typer.secho(
            f'Completing to-do # "{todo_id}" failed with "{ERRORS[error]}"',
            fg=typer.colors.RED,
        )
        raise typer.Exit(1)
    else:
        typer.secho(
            f"""to-do # {todo_id} "{todo['Description']}" completed!""",
            fg=typer.colors.GREEN,
        )
Example #2
0
    def build_image(self, push_image: bool = True):
        _info('Building image {} using Docker...'.format(
            typer.style(self._target_image, fg=typer.colors.YELLOW)))
        client = docker.from_env()

        docker_log_prefix = typer.style('Docker', fg=typer.colors.CYAN)

        try:
            context = str(self._context_directory)
            logs = client.api.build(
                path=context,
                dockerfile='Dockerfile',
                tag=self._target_image,
                decode=True,
            )
            for log in logs:
                message = log.get('stream', '').rstrip('\n')
                if message:
                    _info('{}: {}'.format(docker_log_prefix, message))

        except docker.errors.BuildError as e:
            for log in e.build_log:
                message = log.get('message', '').rstrip('\n')
                if message:
                    _error('{}: {}'.format(docker_log_prefix, message))
            _error('{}: {}'.format(docker_log_prefix, e))
            raise typer.Exit(1)

        if not push_image:
            return

        _info('Pushing image {}...'.format(
            typer.style(self._target_image, fg=typer.colors.YELLOW)))

        try:
            response = client.images.push(
                self._target_image, stream=True, decode=True)
            for log in response:
                status = log.get('status', '').rstrip('\n')
                layer = log.get('id', '')
                if status:
                    _info('{}: {} {}'.format(docker_log_prefix, layer, status))
        except docker.errors.BuildError as e:
            _error('{}: {}'.format(docker_log_prefix, e))
            raise e

        _info('Built and pushed component container {}'.format(
            typer.style(self._target_image, fg=typer.colors.YELLOW)))
Example #3
0
def variables(
    device: str = typer.Argument(..., metavar=iden_meta.dev, autocompletion=cli.cache.dev_completion),
    var_value: List[str] = typer.Argument(..., help="comma seperated list 'variable = value, variable2 = value2'"),
    yes: bool = typer.Option(False, "-Y", help="Bypass confirmation prompts - Assume Yes"),
    yes_: bool = typer.Option(False, "-y", hidden=True),
    debug: bool = typer.Option(False, "--debug", envvar="ARUBACLI_DEBUG", help="Enable Additional Debug Logging",),
    default: bool = typer.Option(False, "-d", is_flag=True, help="Use default central account", show_default=False,),
    account: str = typer.Option("central_info",
                                envvar="ARUBACLI_ACCOUNT",
                                help="The Aruba Central Account to use (must be defined in the config)",),
) -> None:
    yes = yes_ if yes_ else yes
    dev = cli.cache.get_dev_identifier(device)
    serial = dev.serial

    vars, vals, get_next = [], [], False
    for var in var_value:
        if var == '=':
            continue
        if '=' not in var:
            if get_next:
                vals += [var]
                get_next = False
            else:
                vars += [var]
                get_next = True
        else:
            _ = var.split('=')
            vars += _[0]
            vals += _[1]
            get_next = False

    if len(vars) != len(vals):
        typer.secho("something went wrong parsing variables.  Unequal length for Variables vs Values")
        raise typer.Exit(1)

    var_dict = {k: v for k, v in zip(vars, vals)}

    msg = "Sending Update" if yes else "Please Confirm: Update"
    typer.secho(f"{msg} {dev.name}|{dev.serial}", fg="cyan")
    [typer.echo(f'    {k}: {v}') for k, v in var_dict.items()]
    if yes or typer.confirm(typer.style("Proceed with these values", fg="cyan")):
        resp = cli.central.request(
            cli.central.update_device_template_variables,
            serial,
            dev.mac,
            var_dict=var_dict)
        typer.secho(str(resp), fg="green" if resp else "red")
Example #4
0
def remove(
    # fmt: off
    source: pathlib.Path = typer.Argument(..., help="the source directory"),
    glob: str = typer.Option(
        "**/*", help="The glob pattern to use for matching contents"),
    dry_run: bool = typer.Option(
        False, help="Perform all actions without doing the actual copying"),
    workers: int = typer.Option(
        MAX_NUM_CORES, help="The number of processes to use while copying"),
    # fmt: on
) -> None:
    """
    Remove contents of `source` directory using multiple processes (one per file).

    If you need to filter out some of the contents use the `--glob` option. E.g. `--glob **/*.nc`
    will remove all the NetCDF files under `source` and nothing else.
    """
    typer.echo(locals())
    source = source.expanduser().resolve()
    # In order to remove a directory it must be empty.
    # Therefore we need to make sure that we remove files before directories
    files, directories = partition_paths(source.glob(glob))
    if dry_run:
        for path in files + directories:
            typer.echo(f"Delete: {path}")
    else:
        # remove files
        func_kwargs = [dict(path=path) for path in files]
        results_files = multiprocess(func=remove_file,
                                     func_kwargs=func_kwargs,
                                     n_workers=workers,
                                     print_exceptions=False)
        # remove directories
        func_kwargs = [dict(path=path) for path in directories]
        results_dirs = multiprocess(func=remove_dir,
                                    func_kwargs=func_kwargs,
                                    n_workers=workers,
                                    print_exceptions=False)
        # combine results to check exceptions
        exceptions = {
            r.exception
            for r in (results_files + results_dirs) if r.exception
        }
        if len(exceptions) > 1:
            typer.echo("There were exceptions while deleting files")
            for exc in exceptions:
                typer.echo(exc)
            raise typer.Exit(code=1)
Example #5
0
def import_vlan(
    key: str = typer.Argument(..., help="The Key from stored_tasks with vlan details to import"),
    import_file: str = typer.Argument(None, exists=True),
    file: Path = typer.Option(None, exists=True,),
    default: bool = typer.Option(False, "-d", is_flag=True, help="Use default central account",
                                 callback=cli.default_callback),
    debug: bool = typer.Option(False, "--debug", envvar="ARUBACLI_DEBUG", help="Enable Additional Debug Logging",
                               callback=cli.debug_callback),
    account: str = typer.Option("central_info",
                                envvar="ARUBACLI_ACCOUNT",
                                help="The Aruba Central Account to use (must be defined in the config)",
                                callback=cli.account_name_callback),
) -> None:
    """Add VLAN from stored_tasks file.

    This is the same as `cencli batch add-vlan key`, but command: add_vlan
    is implied only need to provide key

    """
    import_file = file or import_file or config.stored_tasks_file
    if import_file == config.stored_tasks_file and not key:
        typer.echo("key is required when using the default import file")

    data = config.get_file_data(import_file)
    if key:
        if hasattr(data, "dict"):  # csv
            data = data.dict  # TODO not tested in csv form
            data = {k: data[k] for k in data if data.get("key", "") == key}
        else:
            data = data.get(key)

    if data:
        args = data.get("arguments", [])
        kwargs = data.get("options", {})
        _msg = (
            f"\n{typer.style('add-vlan', fg='bright_green')}"
            f'\n{typer.style("  settings:", fg="cyan")}'
            f"\n    args: {', '.join(args)}\n    kwargs: {', '.join([f'{k}={v}' for k, v in kwargs.items()])}"
        )
        typer.echo(f"{_msg}")
        confirm_msg = typer.style("Proceed?", fg="bright_green")
        if typer.confirm(confirm_msg):
            add_vlan(*args, **kwargs)
        else:
            raise typer.Abort()
    else:
        typer.secho(f"{key} Not found in {import_file}")
        raise typer.Exit(1)
Example #6
0
def run(command: str, error_msg: str) -> None:
    """Prepare documentation and run command.

    Args:
        command: Command to execute after preparing documentation.
        error_msg: Error message if command fails.
    """

    repo_path = pathlib.Path(__file__).parents[1]
    copy_files(repo_path)

    try:
        subprocess.run(args=command, shell=True, check=True)
    except subprocess.CalledProcessError:
        typer.secho(f"Error: {error_msg}", fg=typer.colors.RED, err=True)
        raise typer.Exit(1)
Example #7
0
def user_check(
    username: str,
    root: Optional[Path] = typer.Option(None),
):
    """ Check username and password combo """

    password = typer.prompt(f"Enter password for {username}", hide_input=True)
    password = password.strip()

    token = get_user_store(root).authenticate(username, password)

    if token:
        typer.echo("Success: Username and password combination was valid")
    else:
        typer.echo("FAIL: Username and password combination was NOT valid")
        typer.Exit(1)
Example #8
0
def diff(
    project_dir: Path = typer.Option(
        Path("."), "--project-dir", "-p", help="Path to the project directory.", show_default=False
    ),
    exit_code: bool = typer.Option(
        False, "--exit-code", "-e", help="Exit with status 1 on non-empty diff.", show_default=False
    ),
    checkout: Optional[str] = typer.Option(
        None,
        "--checkout",
        "-c",
        help=("The git reference to check against. Supports branches, tags and commit hashes."),
    ),
) -> None:
    if not _commands.diff(project_dir=project_dir, exit_code=exit_code, checkout=checkout):
        raise typer.Exit(1)
Example #9
0
def config(
        context: typer.Context,
        config_key: str,
        config_value: str,
        _global: bool = typer.Option(False, '--global'),
):
    config = context.default_map.get('config')
    infer_type = context.default_map.get('infer_type', True)

    if config is None:
        raise typer.Exit(1)

    config._cli_callback(config_key,
                         config_value,
                         _global=_global,
                         infer_type=infer_type)
Example #10
0
def report() -> None:
    all_events = event_repository.list_today()

    if len(all_events) == 0:
        typer.echo("Nothing reported today yet :(")
        raise typer.Exit()

    typer.secho("Tasks", bold=True, fg=typer.colors.BRIGHT_CYAN)
    typer.secho("-" * 30 + "\n", bold=True, fg=typer.colors.BRIGHT_CYAN)

    print_report(all_events)

    typer.secho("\nTimeline", bold=True, fg=typer.colors.BRIGHT_CYAN)
    typer.secho("-" * 30 + "\n", bold=True, fg=typer.colors.BRIGHT_CYAN)

    timeline(all_events)
Example #11
0
def tyranno_main(
    version: bool = False,
    info: bool = False,
):
    """
    Tyrannosaurus.
    Tyrannosaurus can create new modern Python projects from a template
    and synchronize metadata across the project.

    Args:
        version: Write version and exit
        info: Write info and exit (same as 'tyrannosaurus info')
    """
    if version or info:
        Msg.write_info()
        raise typer.Exit()
Example #12
0
def ensure_model_dir(model_dir_path: Union[Path, None] = None) -> Path:
    """Checks for a local model dir and creates one if not found"""
    if not model_dir_path:
        app_dir = typer.get_app_dir(APP_NAME)
        model_dir: Path = Path(app_dir) / "models"
    else:
        model_dir = Path(model_dir_path) / "models"
    if not (model_dir.exists() and model_dir.is_dir()):
        typer.echo(f"Creating directory for storing models in {model_dir}...")
        try:
            model_dir.mkdir(parents=True)
        except PermissionError as e:  # pragma: no cover
            typer.echo(f"{model_dir} is not writeable: {e}")
            raise typer.Exit(code=1)
    typer.echo(f"Models stored in {model_dir}")
    return model_dir
Example #13
0
def run(
    target: Optional[str] = typer.Argument(default=None,
                                           help="sketch directory or file"),
    editor: Optional[str] = typer.Option(
        None,
        "-e",
        "--editor",
        metavar="EDITOR",
        envvar="VSK_EDITOR",
        help="open the sketch file in EDITOR",
    ),
    fullscreen: bool = typer.Option(
        False,
        envvar="VSK_FULLSCREEN",
        help="display the viewer fullscreen on the second screen if available",
    ),
) -> None:
    """Execute, display and monitor changes on a sketch.

    This command loads a sketch and opens an interactive viewer display the result. The viewer
    will refresh the display each time the sketch file is saved. If the sketch defines any
    parameters, they will be displayed by the viewer and may be interactively changed.

    TARGET may either point at a Python file or at a directory. If omitted, the current
    directory is assumed. When TARGET points at a directory, this command looks for a single
    Python file whose name starts wit `sketch_`. If none are found, it will look for a single
    Python file with arbitrary name. If no or multiple candidates are found, the command will
    fail.

    If the --editor option is provided or the VSK_EDITOR environment variable is set, the
    sketch file will be opened with the corresponding editor.

    If the --fullscreen option is provided or the VSK_FULLSCREEN environment variable is set,
    and a second screen is available, the viewer is opened in fullscreen on the second monitor.
    """
    try:
        path = _find_sketch_script(target)
    except ValueError as err:
        print_error("Sketch could not be found: ", str(err))
        raise typer.Exit(code=1)

    print_info("Running sketch: ", str(path))

    if editor is not None and editor != "":
        os.system(f"{editor} {path}")

    show(str(path), second_screen=fullscreen)
Example #14
0
def main(
    what: str = typer.Argument(
        ...,
        help=(
            "Text to say. If your input text contains spaces, you will need to wrap it with "
            "quotes."
        ),
    ),
    width: Optional[int] = typer.Option(
        None, "--width", "-W", help="Width of speech bubble (number of characters)."
    ),
    think: bool = typer.Option(False, "--think", "-t", help="Use thought bubble."),
    whisper: bool = typer.Option(False, "--whisper", "-w", help="Use whisper bubble."),
    no_ascii: bool = typer.Option(
        False, "--no-ascii", "-n", help="Text-only with no ASCII art. Ignores width option."
    ),
    random_seed: Optional[int] = typer.Option(None, "--random-seed", "-s", help="Random seed."),
    version: bool = typer.Option(
        False,
        "--version",
        callback=version_callback,
        is_eager=True,
        help="Show spongebobsay version and exit.",
        show_default=False,
    ),
):
    """Generate an ASCII picture of Spongebob saying something provided by the user, but in Mocking
    Spongebob case.

    geNerATe aN AScIi pICtuRE of sPoNGebOB sAyIng SOMeThIng ProvIDeD by THe usER, BuT iN mOcKing
    SpONGeboB caSE.
    """
    if sum([think, whisper, no_ascii]) > 1:
        typer.echo("Error: Only one of --think, --whisper, or --no-ascii can be used at a time.")
        raise typer.Exit(code=2)

    random.seed(random_seed)
    if think:
        out = spongebobthink(what=what, print_=False, width=width)
    elif whisper:
        out = spongebobwhisper(what=what, print_=False, width=width)
    elif no_ascii:
        out = tospongebob(what)
    else:
        out = spongebobsay(what=what, print_=False, width=width)

    typer.echo(out)
Example #15
0
def add(
    description: List[str] = typer.Argument(...),
    priority: int = typer.Option(2, "--priority", "-p", min=1, max=3),
) -> None:
    """Add a new to-do with a DESCRIPTION."""
    todoer = get_todoer()
    todo, error = todoer.add(description, priority)
    if error:
        typer.secho(f'Adding to-do failed with "{ERRORS[error]}"',
                    fg=typer.colors.RED)
        raise typer.Exit(1)
    else:
        typer.secho(
            f"""to-do: "{todo['Description']}" was added """
            f"""with priority: {priority}""",
            fg=typer.colors.GREEN,
        )
Example #16
0
def fromrle(file: Path = None,
            colrle: str = typer.Option("rle"),
            colsize: str = typer.Option("size"),
            colimg: str = typer.Option("image_name")) -> None:
    """
    Convert RLE format of masks to .PNG. \n
    --file    File with RLE labels\n
    --colrle  Column in dataframe with rles\n
    --colsize Column in dataframe with size for each mask\n
    --colimg  Column in dataframe with name of corresponding image\n
    """

    if not file:
        typer.echo("Provide path to .csv file with encoded masks")
        typer.Exit()
    else:
        main_frommrle(str(file), colrle, colsize, colimg)
Example #17
0
def getDynamicDomain(environment: str = "sss"):
    domain = backplane["domain"]
    if environment == "production":
        try:
            f = requests.request("GET", "https://ifconfig.me")
            ip = f.text.replace(".", "-")

            domain = f"{ip}.ns0.co"
        except Exception as e:
            typer.secho(
                f"Couldn't determine dynamic domain: {e}",
                err=True,
                fg=typer.colors.RED,
            )
            raise typer.Exit(code=1)

    return domain
def delete(path: str) -> None:
    """
    Delete an entry from Azure Table Storage.
    """

    azure_full_url = utils.create_azure_url("AZURE_DELETESHORTURL_URL", path)

    # GET request
    try:
        r = requests.get(azure_full_url)
    except:
        print(emoji.emojize(":x:  ", use_aliases=True), end="", flush=True)
        typer.echo("Something went wrong when submitting GET request!")
        raise typer.Exit(-1)

    # write result
    utils.print_response_status(r)
Example #19
0
def verify_spec(model_yaml: Path):
    try:
        spec_data = yaml.load(model_yaml)
    except Exception as e:
        pprint(e)
        code = 1
    else:
        try:
            verify_model_data(spec_data)
        except ValidationError as e:
            pprint(e.messages)
            code = 1
        else:
            code = 0
            print(f"successfully verified model {model_yaml}")

    raise typer.Exit(code=code)
Example #20
0
def _list_services():
    # The Python 3 runit dir ends up in /diracos
    for runit_dir in ["ServerInstallDIR/runit", "ServerInstallDIR/diracos/runit"]:
        cmd = _build_docker_cmd("server")
        cmd += [
            "bash",
            "-c",
            f'cd {runit_dir}/ && for fn in */*/log/current; do echo "$(dirname "$(dirname "$fn")")"; done',
        ]
        ret = subprocess.run(cmd, check=False, stdout=subprocess.PIPE, text=True)
        if not ret.returncode:
            return runit_dir, ret.stdout.split()
    else:
        typer.secho("Failed to find list of available services", err=True, fg=c.RED)
        typer.secho(f"stdout was: {ret.stdout!r}", err=True)
        typer.secho(f"stderr was: {ret.stderr!r}", err=True)
        raise typer.Exit(1)
Example #21
0
def serve(scripts_dir: pathlib.Path = typer.Argument(
    "scripts",
    file_okay=False,
    dir_okay=True,
    readable=True,
    resolve_path=True,
    help="The directory that will contain the output"),
          port: int = typer.Option(
              9000,
              help="The port where the panel server will be listening to")
          ) -> None:
    cmd = f"panel serve --port {port} --log-level trace --allow-websocket-origin localhost:{port} {scripts_dir}"
    if not scripts_dir.exists():
        msg = f"The provided scripts_dir does not exist: {scripts_dir}"
        typer.echo(msg)
        raise typer.Exit(1)
    subprocess.run(shlex.split(cmd), check=True)
Example #22
0
def build(
    file: Path = file_default,
    output_dir: Path = typer.Argument(Path('site'),
                                      file_okay=False,
                                      dir_okay=True,
                                      readable=True),
):
    print(f'executing {file} and saving output to {output_dir}...')
    start = time()
    try:
        main.build(file, output_dir, dev=dev_mode)
    except ExecException as exc:
        print(exc.format('shell'))
        print(f'build failed after {time() - start:0.3f}s')
        raise typer.Exit(1)
    else:
        print(f'build completed in {time() - start:0.3f}s')
Example #23
0
    def read_excel_file(self) -> DataFrame:
        try:
            logging.info(f"Reading Excel file: {self.filename}")
            dataframe = pd.read_excel(
                os.path.join(GlobalSettings.acquisition_folder, self.filename),
                header=None if self.header is None else self.header,
                names=None if self.names is None else self.names,
                index_col=None if self.index_col is None else self.index_col,
                usecols=tuple(self.columns_to_use),
                convert_float=False,
                skiprows=self.skiprows,
                dtype=str,
                engine=self.engine)

            # name columns properly
            logging.debug(f"{self.filename}: naming columns")
            dataframe.columns = self.columns_input_names

            # clear whitespaces
            dataframe.part_no = dataframe.part_no.str.strip()
            dataframe.price = dataframe.price.str.strip()

            if self.alternative_parts == 1:
                dataframe.ss = dataframe.ss.str.strip()

            # change price strings to floats
            logging.debug(f"{self.filename}: changing price to floats")
            dataframe.price = dataframe.price.str.replace(",", ".")
            dataframe.price = pd.to_numeric(dataframe.price)

            # clear part_no column from floats (if occur)
            logging.debug(f"{self.filename}: clearing part_no column")
            dataframe.part_no = dataframe.part_no.astype(str)
            dataframe.part_no = dataframe.part_no.str.replace(r'[.][0]$',
                                                              '',
                                                              regex=True)

            return dataframe

        except Exception as er:
            message = "Error when reading Excel file!"
            logging.critical(er)
            logging.critical(message)
            typer.echo(message)
            raise typer.Exit()
Example #24
0
def run_model(flip: bool = typer.Option(True,
                                        help="Flips the webcam horizontally")):
    """
    Runs the previously trained model
    """

    classifier = load_classifier()
    labels = load_label_dict()
    model = init_model()
    cap = init_webcam()

    word = " "
    last_time = datetime.utcnow()

    for frame in web_img_gen(cap, flip):
        img_time = datetime.utcnow()
        img = process_image(frame)
        prediction = model.predict(img[np.newaxis, ...])
        probs = tf.nn.softmax(prediction).numpy()
        res = classifier.predict(probs)[0]
        prob = classifier.predict_proba(probs)[0]

        label = get_label(labels, res)
        add_text_to_frame(frame, f"{label} conf: {prob}")

        isnt_empty_label = not (label == "empty")
        is_good_prob = prob[res] > 0.99
        enough_time_passed = (img_time - last_time).seconds > 1
        is_different_letter = not (label == word[-1])

        if (isnt_empty_label and is_good_prob and enough_time_passed
                and is_different_letter):
            word += label
            last_time = datetime.utcnow()
            typer.echo(word)
            cv2.imwrite(f"{label}.jpg", frame)

        cv2.imshow("frame", frame)
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break

    typer.echo(f"Recorded word: {word}")
    speak = wincl.Dispatch("SAPI.SpVoice")
    speak.Speak(word)
    typer.Exit()
Example #25
0
def main(
    incidents_csv: Path = DEFAULT_INCIDENTS,
    submission_csv: Path = DEFAULT_SUBMISSION,
    json_report: bool = False,
):
    """
    Given a raw incidents file and a submission file, calculate the score that the submission
    would receive if submitted.
    """
    for expected_file in (incidents_csv, submission_csv):
        if not expected_file.exists():
            raise typer.Exit(f"file not found: {expected_file}")

    logger.info(f"reading incidents from {incidents_csv} ...")
    incidents = pd.read_csv(incidents_csv, index_col=0)

    logger.info(f"reading submission from {submission_csv} ...")
    submission = pd.read_csv(submission_csv, index_col=INDEX_COLS)
    logger.info(f"read dataframe with {len(submission):,} rows")

    logger.info("computing ground truth ...")
    ground_truth = get_ground_truth(incidents, submission)
    logger.info(f"read dataframe with {len(ground_truth):,} rows")

    scorer = Deid2Metric()
    overall_score, row_scores = scorer.score(
        ground_truth.values, submission.values, return_individual_scores=True
    )
    logger.success(f"OVERALL SCORE: {overall_score}")

    if json_report:
        row_outcomes = []
        for idx, score in zip(submission.index, row_scores):
            epsilon, neighborhood, year, month = idx
            row_outcomes.append(
                {
                    "epsilon": epsilon,
                    "neighborhood": neighborhood,
                    "year": year,
                    "month": month,
                    "score": score,
                }
            )
        result = {"score": overall_score, "details": row_outcomes}
        print(json.dumps(result, indent=2))
Example #26
0
def init(
    name: str = typer.Option("test",
                             "-n",
                             "--name",
                             help="Project name prefix"),
    workdir: str = typer.Option(tempfile.gettempdir(),
                                "-w",
                                "--workdir",
                                help="Project directory"),
    delim: str = typer.Option("_", help="sample name delimiter"),
    loglevel: LogLevel = typer.Option(LogLevel.INFO, help="logging level"),
    force: bool = typer.Option(False, help="overwrite existing"),
    data: List[Path] = typer.Argument(
        ...,
        show_default=False,
        exists=True,  # <- prob should be false for moving json files.
        dir_okay=True,
        file_okay=True,
        resolve_path=False,
        allow_dash=True,
        help=("File path(s) to input fastq/a data files")),
):
    """
    Initialize a kmerkit project from fastq/a input files.

    Creates a JSON project file in <workdir>/<name>.json. Sample
    names are parsed from input filenames by splitting on the last
    occurrence of the optional 'delim' character (default is '_').
    Paired reads are automatically detected from _R1 and _R2 in names.
    Multiple files can be selected using regular expressions for the
    data filepath input, or by listing multiple filepaths. Examples:

    kmerkit init -n test -w /tmp ./data/fastqs/*.gz\n
    kmerkit init -n test -w /tmp ./data-1/A.fastq ./data-2/B.fastq
    """
    # parse the fastq_dict from string
    set_loglevel(loglevel)
    fastq_dict = get_fastq_dict_from_path(None, data, delim)
    try:
        init_project(name=name,
                     workdir=workdir,
                     fastq_dict=fastq_dict,
                     force=force)
    except KmerkitError:
        typer.Exit()
Example #27
0
def reset_password(
    username: str,
    root: Optional[Path] = typer.Option(None),
    force: bool = typer.Option(False, "--force", "-f"),
):
    """ Reset user's password """

    if not force:
        typer.confirm(
            f"Reset {username}'s password. Are you sure?", abort=True
        )

    new_password = get_user_store(root).reset_password(username)
    if new_password:
        typer.echo(f"User ('{username}') new password: {new_password}")
    else:
        typer.echo(f"User ('{username}') not found")
        typer.Exit(1)
Example #28
0
def get_running_games(apikey: str) -> Dict:
    """Return a list of running games for a user."""
    payload = {"apikey": apikey}
    response = requests.post("https://api.planets.nu/account/mygames",
                             data=payload)
    if response.status_code == 200:
        json_doc = response.json()
        games = {}
        if "games" in json_doc:
            for game in json_doc["games"]:
                if game["game"]["statusname"] == "Running":
                    games[str(game["game"]["id"])] = {
                        "name": game["game"]["name"],
                        "race": game["player"]["id"],
                    }
        return games
    logger.error("Failed to get running games from planets.nu.")
    raise typer.Exit()
Example #29
0
    async def send_commands(self, group_dev: str, cli_cmds: list = None):
        if ":" in group_dev and len(group_dev) == 17:
            key = "node_name"
        else:
            key = "group_name"

        url = "/caasapi/v1/exec/cmd"

        if not config.customer_id:
            typer.secho(f"customer_id attribute not found in {config.file}")
            raise typer.Exit(1)
        else:
            params = {"cid": config.customer_id, key: group_dev}
            json_data = {"cli_cmds": cli_cmds or []}

            return await self.central.post(url,
                                           params=params,
                                           json_data=json_data)
Example #30
0
def cli():
    """
    View ChristisCLI Configuration
    """
    cliConfigPath = get_christis_cli_config_location()

    if (not Path(cliConfigPath).is_file()):
        typer.echo(
            "ERROR: The cli.yaml file can't be found please use CLI to generate it!",
            err=True)
        raise typer.Exit(code=1)

    typer.echo("Open CLI Configuration File in {0}".format(cliConfigPath))
    typer.echo("\n")
    with open(cliConfigPath) as cli:
        # Here f is the file-like object
        read_data = cli.read()
        typer.echo(read_data)