Main entry point for iotile-ship recipe runner.

    This is the iotile-ship command line program.

    Args:
        argv (list of str): An optional set of command line
            parameters.  If not passed, these are taken from
            sys.argv.
488507
def main(argv=None):
    

    if argv is None:
        argv = sys.argv[1:]

    parser = build_args()
    args = parser.parse_args(args=argv)

    recipe_name, _ext = os.path.splitext(os.path.basename(args.recipe))

    rm = RecipeManager()
    rm.add_recipe_folder(os.path.dirname(args.recipe), whitelist=[os.path.basename(args.recipe)])
    recipe = rm.get_recipe(recipe_name)

    if args.archive is not None:
        print("Archiving recipe into %s" % args.archive)
        recipe.archive(args.archive)
        return 0

    if args.info:
        print(recipe)
        return 0

    variables = load_variables(args.define, args.config)

    success = 0

    start_time = time.time()

    if args.loop is None:
        try:
            recipe.run(variables)
            success += 1
        except IOTileException as exc:
            print("Error running recipe: %s" % str(exc))
            return 1
    else:
        while True:
            value = input("Enter value for loop variable %s (return to stop): " % args.loop)

            if value == '':
                break

            local_vars = dict(**variables)
            local_vars[args.loop] = value

            try:
                recipe.run(local_vars)
                success += 1
            except IOTileException as exc:
                print("--> ERROR processing loop variable %s: %s" % (value, str(exc)))

    end_time = time.time()
    total_time = end_time - start_time

    if success == 0:
        per_time = 0.0
    else:
        per_time = total_time / success

    print("Performed %d runs in %.1f seconds (%.1f seconds / run)" % (success, total_time, per_time))
    return 0
1360241
def main(argv=None):
    '''
    
    '''
    # Get command line arguments
    parser = argparse.ArgumentParser(
        description="Takes one or more file paths and reports their detected \
                     encodings",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        conflict_handler='resolve')
    parser.add_argument('input',
                        help='File whose encoding we would like to determine.',
                        type=argparse.FileType('rb'), nargs='*',
                        default=[sys.stdin])
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(__version__))
    args = parser.parse_args(argv)

    for f in args.input:
        if f.isatty():
            print("You are running chardetect interactively. Press " +
                  "CTRL-D twice at the start of a blank line to signal the " +
                  "end of your input. If you want help, run chardetect " +
                  "--help\n", file=sys.stderr)
        print(description_of(f, f.name))
92899
def main(argv=None):
    
    # Prepare arguments
    parser = argparse.ArgumentParser(
        prog="pelix.shell.remote",
        parents=[make_common_parser()],
        description="Pelix Remote Shell ({} SSL support)".format(
            "with" if ssl is not None else "without"
        ),
    )

    # Remote shell options
    group = parser.add_argument_group("Remote Shell options")
    group.add_argument(
        "-a",
        "--address",
        default="localhost",
        help="The remote shell binding address",
    )
    group.add_argument(
        "-p",
        "--port",
        type=int,
        default=9000,
        help="The remote shell binding port",
    )

    if ssl is not None:
        # Remote Shell TLS options
        group = parser.add_argument_group("TLS Options")
        group.add_argument("--cert", help="Path to the server certificate file")
        group.add_argument(
            "--key",
            help="Path to the server key file "
            "(can be omitted if the key is in the certificate)",
        )
        group.add_argument(
            "--key-password",
            help="Password of the server key."
            "Set to '-' for a password request.",
        )
        group.add_argument(
            "--ca-chain",
            help="Path to the CA chain file to authenticate clients",
        )

    # Local options
    group = parser.add_argument_group("Local options")
    group.add_argument(
        "--no-input",
        action="store_true",
        help="Run without input (for daemon mode)",
    )

    # Parse them
    args = parser.parse_args(argv)

    # Handle arguments
    init = handle_common_arguments(args)

    # Set the initial bundles
    bundles = [
        "pelix.ipopo.core",
        "pelix.shell.core",
        "pelix.shell.ipopo",
        "pelix.shell.remote",
    ]
    bundles.extend(init.bundles)

    # Start a Pelix framework
    framework = pelix.framework.create_framework(
        utilities.remove_duplicates(bundles), init.properties
    )
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate configured components
    init.instantiate_components(framework.get_bundle_context())

    # Instantiate a Remote Shell, if necessary
    with use_ipopo(context) as ipopo:
        rshell_name = "remote-shell"
        try:
            ipopo.get_instance_details(rshell_name)
        except ValueError:
            # Component doesn't exist, we can instantiate it.

            if ssl is not None:
                # Copy parsed arguments
                ca_chain = args.ca_chain
                cert = args.cert
                key = args.key

                # Normalize the TLS key file password argument
                if args.key_password == "-":
                    import getpass

                    key_password = getpass.getpass(
                        "Password for {}: ".format(args.key or args.cert)
                    )
                else:
                    key_password = args.key_password
            else:
                # SSL support is missing:
                # Ensure the SSL arguments are defined but set to None
                ca_chain = None
                cert = None
                key = None
                key_password = None

            # Setup the component
            rshell = ipopo.instantiate(
                pelix.shell.FACTORY_REMOTE_SHELL,
                rshell_name,
                {
                    "pelix.shell.address": args.address,
                    "pelix.shell.port": args.port,
                    "pelix.shell.ssl.ca": ca_chain,
                    "pelix.shell.ssl.cert": cert,
                    "pelix.shell.ssl.key": key,
                    "pelix.shell.ssl.key_password": key_password,
                },
            )

            # Avoid loose reference to the password
            del key_password
        else:
            logging.error(
                "A remote shell component (%s) is already "
                "configured. Abandon.",
                rshell_name,
            )
            return 1

    # Prepare a banner
    host, port = rshell.get_access()
    try:
        if args.no_input:
            # No input required: just print the access to the shell
            print("Remote shell bound to:", host, "- port:", port)

            try:
                while not framework.wait_for_stop(1):
                    # Awake from wait every second to let KeyboardInterrupt
                    # exception to raise
                    pass
            except KeyboardInterrupt:
                print("Got Ctrl+C: exiting.")
                return 127
        else:
            # Prepare interpreter variables
            variables = {
                "__name__": "__console__",
                "__doc__": None,
                "__package__": None,
                "framework": framework,
                "context": context,
                "use_ipopo": use_ipopo,
            }

            banner = (
                "{lines}\nPython interpreter with Pelix Remote Shell\n"
                "Remote shell bound to: {host}:{port}\n{lines}\n"
                "Python version: {version}\n".format(
                    lines="-" * 80, version=sys.version, host=host, port=port
                )
            )

            # Run an interpreter
            _run_interpreter(variables, banner)
    finally:
        # Stop the framework
        framework.stop()
557925
def run_from_argv(self, argv):
        
        if (len(argv) > 2 and not argv[2].startswith('-') and
                argv[2] in self.subcommands.keys()):
            subcommand = argv[2]
            klass = self.get_subcommand(subcommand)
            parser = OptionParser(
                prog=argv[0],
                usage=klass.usage('{0} {1}'.format(argv[1], subcommand)),
                version=klass.get_version(), option_list=klass.option_list)
            options, args = parser.parse_args(argv[3:])
            args = [subcommand] + args
        else:
            parser = self.create_parser(argv[0], argv[1])
            options, args = parser.parse_args(argv[2:])

        handle_default_options(options)
        self.execute(*args, **options.__dict__)
581737
def main(argv):  # pylint: disable=W0613
    '''
    
    '''
    thin_path = os.path.join(OPTIONS.saltdir, THIN_ARCHIVE)
    if os.path.isfile(thin_path):
        if OPTIONS.checksum != get_hash(thin_path, OPTIONS.hashfunc):
            need_deployment()
        unpack_thin(thin_path)
        # Salt thin now is available to use
    else:
        if not sys.platform.startswith('win'):
            scpstat = subprocess.Popen(['/bin/sh', '-c', 'command -v scp']).wait()
            if scpstat != 0:
                sys.exit(EX_SCP_NOT_FOUND)

        if os.path.exists(OPTIONS.saltdir) and not os.path.isdir(OPTIONS.saltdir):
            sys.stderr.write(
                'ERROR: salt path "{0}" exists but is'
                ' not a directory\n'.format(OPTIONS.saltdir)
            )
            sys.exit(EX_CANTCREAT)

        if not os.path.exists(OPTIONS.saltdir):
            need_deployment()

        code_checksum_path = os.path.normpath(os.path.join(OPTIONS.saltdir, 'code-checksum'))
        if not os.path.exists(code_checksum_path) or not os.path.isfile(code_checksum_path):
            sys.stderr.write('WARNING: Unable to locate current code checksum: {0}.\n'.format(code_checksum_path))
            need_deployment()
        with open(code_checksum_path, 'r') as vpo:
            cur_code_cs = vpo.readline().strip()
        if cur_code_cs != OPTIONS.code_checksum:
            sys.stderr.write('WARNING: current code checksum {0} is different to {1}.\n'.format(cur_code_cs,
                                                                                                OPTIONS.code_checksum))
            need_deployment()
        # Salt thin exists and is up-to-date - fall through and use it

    salt_call_path = os.path.join(OPTIONS.saltdir, 'salt-call')
    if not os.path.isfile(salt_call_path):
        sys.stderr.write('ERROR: thin is missing "{0}"\n'.format(salt_call_path))
        need_deployment()

    with open(os.path.join(OPTIONS.saltdir, 'minion'), 'w') as config:
        config.write(OPTIONS.config + '\n')
    if OPTIONS.ext_mods:
        ext_path = os.path.join(OPTIONS.saltdir, EXT_ARCHIVE)
        if os.path.exists(ext_path):
            unpack_ext(ext_path)
        else:
            version_path = os.path.join(OPTIONS.saltdir, 'ext_version')
            if not os.path.exists(version_path) or not os.path.isfile(version_path):
                need_ext()
            with open(version_path, 'r') as vpo:
                cur_version = vpo.readline().strip()
            if cur_version != OPTIONS.ext_mods:
                need_ext()
    # Fix parameter passing issue
    if len(ARGS) == 1:
        argv_prepared = ARGS[0].split()
    else:
        argv_prepared = ARGS

    salt_argv = [
        get_executable(),
        salt_call_path,
        '--retcode-passthrough',
        '--local',
        '--metadata',
        '--out', 'json',
        '-l', 'quiet',
        '-c', OPTIONS.saltdir
    ]

    try:
        if argv_prepared[-1].startswith('--no-parse='):
            salt_argv.append(argv_prepared.pop(-1))
    except (IndexError, TypeError):
        pass

    salt_argv.append('--')
    salt_argv.extend(argv_prepared)

    sys.stderr.write('SALT_ARGV: {0}\n'.format(salt_argv))

    # Only emit the delimiter on *both* stdout and stderr when completely successful.
    # Yes, the flush() is necessary.
    sys.stdout.write(OPTIONS.delimiter + '\n')
    sys.stdout.flush()
    if not OPTIONS.tty:
        sys.stderr.write(OPTIONS.delimiter + '\n')
        sys.stderr.flush()
    if OPTIONS.cmd_umask is not None:
        old_umask = os.umask(OPTIONS.cmd_umask)  # pylint: disable=blacklisted-function
    if OPTIONS.tty:
        proc = subprocess.Popen(salt_argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        # Returns bytes instead of string on python 3
        stdout, _ = proc.communicate()
        sys.stdout.write(stdout.decode(encoding=get_system_encoding(), errors="replace"))
        sys.stdout.flush()
        retcode = proc.returncode
        if OPTIONS.wipe:
            shutil.rmtree(OPTIONS.saltdir)
    elif OPTIONS.wipe:
        retcode = subprocess.call(salt_argv)
        shutil.rmtree(OPTIONS.saltdir)
    else:
        retcode = subprocess.call(salt_argv)
    if OPTIONS.cmd_umask is not None:
        os.umask(old_umask)  # pylint: disable=blacklisted-function
    return retcode
853188
def command_line(argv):
    
    arguments = parse_command_line(argv)
    if arguments.generate:
        generate_fixer_file(arguments.generate)
    paths = edit_files(arguments.patterns,
                       expressions=arguments.expressions,
                       functions=arguments.functions,
                       executables=arguments.executables,
                       start_dirs=arguments.start_dirs,
                       max_depth=arguments.max_depth,
                       dry_run=arguments.dry_run,
                       output=arguments.output,
                       encoding=arguments.encoding,
                       newline=arguments.newline)
    # If the output is not sys.stdout, we need to close it because
    # argparse.FileType does not do it for us.
    is_sys = arguments.output in [sys.stdout, sys.stderr]
    if not is_sys and isinstance(arguments.output, io.IOBase):
        arguments.output.close()
    return paths
145663
def main(argv):
    
    init()

    if OPTIONS.StdErrFileName.value:
        OPTIONS.stderr.value = open('wt', OPTIONS.StdErrFileName.value)

    asmlex.FILENAME = OPTIONS.inputFileName.value = argv[0]
    input_ = open(OPTIONS.inputFileName.value, 'rt').read()
    assemble(input_)
    generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type)
358034
def main(argv=None):
    
    if argv is None:
        argv = sys.argv

    parser = OptionParser()

    parser.add_option('-v', '--verbose', dest="verbose", action="count",
        default=2, help="be chattier (stackable)")
    def quiet(option, opt_str, value, parser):
        parser.values.verbose -= 1
    parser.add_option('-q', '--quiet', action="callback", callback=quiet,
        help="be less chatty (stackable)")

    parser.add_option('-r', action="store_true", dest="real_path",
        default=False, help="dereference symlinks")
    parser.add_option('-b', action="store_true", dest="show_directory",
        default=False, help="show directory instead of filename")
    parser.add_option('-i', '--hide-init', action="store_true", dest="hide_init",
        default=False, help="show directory if the module ends in __init__.py")
    parser.add_option('-s', '--source', action="store_true", dest="find_source",
        default=False, help="find .py files for .pyc/.pyo files")
    parser.add_option('--ver', action="store_true", dest="find_version",
        default=False, help="find the version of the named package, not the location on disk")

    opts, args = parser.parse_args()

    verbose = max(0, min(4, opts.verbose))
    log_levels = (logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG)
    logging.basicConfig()
    log.setLevel(log_levels[verbose])

    if opts.find_version:
        find_version(*args)
    else:
        kwargs = dict((fld, getattr(opts, fld)) for fld
            in ('real_path', 'show_directory', 'find_source', 'hide_init'))
        identify_modules(*args, **kwargs)

    return 0
102029
def run_from_argv(self, prog, subcommand, global_options, argv):
        
        self.prog_name = prog
        parser = self.create_parser(prog, subcommand)
        options, args = parser.parse_args(argv)
        self.global_options = global_options
        self.options = options
        self.args = args
        self.execute(args, options, global_options)
291090
def main(argv=None):
    
    # Get command line arguments, validate them, and normalize them
    opts = cmdparse.parse_args(argv)
    assert validate_opts.validate(opts)
    opts = normalize_opts.normalize(opts)

    if opts.verbose:
        # Update client: print input and output directories
        messages.print_input_output(opts)

    file_paths = fileparse.get_file_list(opts)
    assert validate_files.validate(file_paths, opts)

    if opts.verbose and opts.is_dir:
        # Update client: print files that will be parsed
        messages.print_files(opts, file_paths)

    # For now, only using default GitHub Markdown for parsing
    # Collect tag/anchor combinations
    collector = make_github_markdown_collector(opts)
    anchors, duplicate_tags = collector.collect(file_paths)
    assert validate_anchors.validate(anchors, duplicate_tags, opts)

    # Write files using previously found AnchorHub tags and generated anchors
    writer = make_github_markdown_writer(opts)
    counter = writer.write(file_paths, anchors, opts)

    if opts.verbose:
        if opts.is_dir:
            # Update client: print files that had modifications
            messages.print_modified_files(opts, anchors)
        # Print summary statistics
        messages.print_summary_stats(counter)
1014914
def process_command_line(argv):
    
    setup = {}
    for handler in ACCEPTED_ARG_HANDLERS:
        setup[handler.arg_name] = handler.default_val
    setup['file'] = ''
    setup['qt-support'] = ''

    i = 0
    del argv[0]
    while i < len(argv):
        handler = ARGV_REP_TO_HANDLER.get(argv[i])
        if handler is not None:
            handler.handle_argv(argv, i, setup)

        elif argv[i].startswith('--qt-support'):
            # The --qt-support is special because we want to keep backward compatibility:
            # Previously, just passing '--qt-support' meant that we should use the auto-discovery mode
            # whereas now, if --qt-support is passed, it should be passed as --qt-support=<mode>, where
            # mode can be one of 'auto', 'none', 'pyqt5', 'pyqt4', 'pyside'.
            if argv[i] == '--qt-support':
                setup['qt-support'] = 'auto'

            elif argv[i].startswith('--qt-support='):
                qt_support = argv[i][len('--qt-support='):]
                valid_modes = ('none', 'auto', 'pyqt5', 'pyqt4', 'pyside')
                if qt_support not in valid_modes:
                    raise ValueError("qt-support mode invalid: " + qt_support)
                if qt_support == 'none':
                    # On none, actually set an empty string to evaluate to False.
                    setup['qt-support'] = ''
                else:
                    setup['qt-support'] = qt_support
            else:
                raise ValueError("Unexpected definition for qt-support flag: " + argv[i])

            del argv[i]

        elif argv[i] == '--file':
            # --file is special because it's the last one (so, no handler for it).
            del argv[i]
            setup['file'] = argv[i]
            i = len(argv) # pop out, file is our last argument

        elif argv[i] == '--DEBUG':
            from pydevd import set_debug
            del argv[i]
            set_debug(setup)

        else:
            raise ValueError("Unexpected option: " + argv[i])
    return setup
663897
def main(argv=None):
    
    signal.signal(
        signal.SIGINT,
        lambda *args: sys.exit(_SIGNAL_EXIT_CODE_BASE + signal.SIGINT))

    if hasattr(signal, 'SIGINFO'):
        signal.signal(
            getattr(signal, 'SIGINFO'),
            lambda *args: report_progress(sys.stderr))

    try:
        return docopt_subcommands.main(
            commands=dsc,
            argv=argv,
            doc_template=DOC_TEMPLATE,
            exit_at_end=False)
    except docopt.DocoptExit as exc:
        print(exc, file=sys.stderr)
        return ExitCode.USAGE
    except FileNotFoundError as exc:
        print(exc, file=sys.stderr)
        return ExitCode.NO_INPUT
    except PermissionError as exc:
        print(exc, file=sys.stderr)
        return ExitCode.NO_PERM
    except cosmic_ray.config.ConfigError as exc:
        print(repr(exc), file=sys.stderr)
        if exc.__cause__ is not None:
            print(exc.__cause__, file=sys.stderr)
        return ExitCode.CONFIG
    except subprocess.CalledProcessError as exc:
        print('Error in subprocess', file=sys.stderr)
        print(exc, file=sys.stderr)
        return exc.returncode
114901
def main(argv=None):
    
    if not argv:
        argv = sys.argv[1:]
    try:
        global COMMAND_LINE_FLAG
        COMMAND_LINE_FLAG = True
        parser = argparse.ArgumentParser(description=_HELP_TEXT)
        parser.add_argument('command', nargs='?', default=None,
                            help="One of 'ls', 'rm', 'put' or 'get'.")
        parser.add_argument('path', nargs='?', default=None,
                            help="Use when a file needs referencing.")
        parser.add_argument('target', nargs='?', default=None,
                            help="Use to specify a target filename.")
        args = parser.parse_args(argv)
        if args.command == 'ls':
            list_of_files = ls()
            if list_of_files:
                print(' '.join(list_of_files))
        elif args.command == 'rm':
            if args.path:
                rm(args.path)
            else:
                print('rm: missing filename. (e.g. "ufs rm foo.txt")')
        elif args.command == 'put':
            if args.path:
                put(args.path, args.target)
            else:
                print('put: missing filename. (e.g. "ufs put foo.txt")')
        elif args.command == 'get':
            if args.path:
                get(args.path, args.target)
            else:
                print('get: missing filename. (e.g. "ufs get foo.txt")')
        else:
            # Display some help.
            parser.print_help()
    except Exception as ex:
        # The exception of no return. Print exception information.
        print(ex)
128071
def main(argv=None):
    
    args = None
    cmd = None

    try:
        args = parse_args(argv)

        if args.quiet:
            logger.setLevel(logging.CRITICAL)

        elif args.verbose:
            logger.setLevel(logging.DEBUG)

        cmd = args.func(args)
        ret = cmd.run_cmd()
    except KeyboardInterrupt:
        logger.exception("interrupted by the user")
        ret = 252
    except NotDvcRepoError:
        logger.exception("")
        ret = 253
    except DvcParserError:
        ret = 254
    except Exception:  # pylint: disable=broad-except
        logger.exception("unexpected error")
        ret = 255

    Analytics().send_cmd(cmd, args, ret)

    return ret
562983
public static void main(String[] argv) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		
			new ParticleEditor();
		} catch (Exception e) {
			Log.error(e);
		}
	}
1273391
def main(args: Sequence[str] = None) -> int:
    

    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)-15s | %(levelname)-8s | %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
    logging.getLogger('von_anchor').setLevel(logging.WARNING)
    logging.getLogger('indy').setLevel(logging.ERROR)

    if args is None:
        args = sys.argv[1:]

    if len(sys.argv) == 2:
        try:
            return do_wait(setnym(sys.argv[1]))
        except VonAnchorError as vax:
            print(str(vax))
            return 1
    else:
        usage()
        return 1
484543
def main():
    
    parser = argparse.ArgumentParser(description='Longclaw CLI')
    subparsers = parser.add_subparsers()
    start = subparsers.add_parser('start', help='Create a Wagtail+Longclaw project')
    start.add_argument('project_name', help='Name of the project')
    start.set_defaults(func=create_project)

    build = subparsers.add_parser('build', help='Build the front-end assets for Longclaw')
    build.set_defaults(func=build_assets)

    args = parser.parse_args()

    # Python 3 lost the default behaviour to fall back to printing
    # help if a subparser is not selected.
    # See: https://bugs.python.org/issue16308
    # So we must explicitly catch the error thrown on py3 if
    # no commands given to longclaw
    try:
        args.func(args)
    except AttributeError:
        parser.print_help()
        sys.exit(0)