Creates beautiful command-line interfaces.
        See https://github.com/docopt/docopt
193919
def docopt_arguments():
    
    doc = """Projy: Create templated project.

    Usage: projy <template> <project> [<substitution>...]
           projy -i | --info <template>
           projy -l | --list
           projy -h | --help
           projy -v | --version

    Options:
        -i, --info      Print information on a specific template.
        -l, --list      Print available template list.
        -h, --help      Show this help message and exit.
        -v, --version   Show program's version number and exit.
    """
    from projy.docopt import docopt
    return docopt(doc, argv=sys.argv[1:], version='0.1')
1013180
def _generate_create_callable(name, display_name, arguments, regex, doc, supported, post_arguments, is_action):
    
    def f(self, *args, **kwargs):
        for key, value in args[-1].items():
            if type(value) == file:
                return self._put_or_post_multipart('POST', self._generate_url(regex, args[:-1]), args[-1])
        return self._put_or_post_json('POST', self._generate_url(regex, args[:-1]), args[-1])
    if is_action:
        f.__name__ = str(name)
    else:
        f.__name__ = str('create_%s' % name)
    f.__doc__ = doc
    f._resource_uri = regex
    f._get_args = arguments
    f._put_or_post_args = post_arguments
    f.resource_name = display_name
    f.is_api_call = True
    f.is_supported_api = supported
    return f
1252129
def main():
    
    from optparse import OptionParser, OptionGroup
    from os import sep
    from os.path import basename, getsize
    from sys import argv, exit as sysExit
    from chardet import detect
    from codecs import BOM_UTF8, open as codecsOpen

    def optParse():
        """
        Parses command line options.

        Generally we're supporting all the command line options that doxypy.py
        supports in an analogous way to make it easy to switch back and forth.
        We additionally support a top-level namespace argument that is used
        to trim away excess path information.
        """

        parser = OptionParser(prog=basename(argv[0]))

        parser.set_usage("%prog [options] filename")
        parser.add_option(
            "-a", "--autobrief",
            action="store_true", dest="autobrief",
            help="parse the docstring for @brief description and other information"
        )
        parser.add_option(
            "-c", "--autocode",
            action="store_true", dest="autocode",
            help="parse the docstring for code samples"
        )
        parser.add_option(
            "-n", "--ns",
            action="store", type="string", dest="topLevelNamespace",
            help="specify a top-level namespace that will be used to trim paths"
        )
        parser.add_option(
            "-t", "--tablength",
            action="store", type="int", dest="tablength", default=4,
            help="specify a tab length in spaces; only needed if tabs are used"
        )
        parser.add_option(
            "-s", "--stripinit",
            action="store_true", dest="stripinit",
            help="strip __init__ from namespace"
        )
        parser.add_option(
            "-O", "--object-respect",
            action="store_true", dest="object_respect",
            help="By default, doxypypy hides object class from class dependencies even if class inherits explictilty from objects (new-style class), this option disable this."
        )
        group = OptionGroup(parser, "Debug Options")
        group.add_option(
            "-d", "--debug",
            action="store_true", dest="debug",
            help="enable debug output on stderr"
        )
        parser.add_option_group(group)

        ## Parse options based on our definition.
        (options, filename) = parser.parse_args()

        # Just abort immediately if we are don't have an input file.
        if not filename:
            stderr.write("No filename given." + linesep)
            sysExit(-1)

        # Turn the full path filename into a full path module location.
        fullPathNamespace = filename[0].replace(sep, '.')[:-3]
        # Use any provided top-level namespace argument to trim off excess.
        realNamespace = fullPathNamespace
        if options.topLevelNamespace:
            namespaceStart = fullPathNamespace.find(options.topLevelNamespace)
            if namespaceStart >= 0:
                realNamespace = fullPathNamespace[namespaceStart:]
        if options.stripinit:
            realNamespace = realNamespace.replace('.__init__', '')
        options.fullPathNamespace = realNamespace

        return options, filename[0]

    # Figure out what is being requested.
    (options, inFilename) = optParse()

    # Figure out encoding of input file.
    numOfSampleBytes = min(getsize(inFilename), 32)
    sampleBytes = open(inFilename, 'rb').read(numOfSampleBytes)
    sampleByteAnalysis = detect(sampleBytes)
    encoding = sampleByteAnalysis['encoding'] or 'ascii'

    # Switch to generic versions to strip the BOM automatically.
    if sampleBytes.startswith(BOM_UTF8):
        encoding = 'UTF-8-SIG'
    if encoding.startswith("UTF-16"):
        encoding = "UTF-16"
    elif encoding.startswith("UTF-32"):
        encoding = "UTF-32"

    # Read contents of input file.
    if encoding == 'ascii':
        inFile = open(inFilename)
    else:
        inFile = codecsOpen(inFilename, encoding=encoding)
    lines = inFile.readlines()
    inFile.close()
    # Create the abstract syntax tree for the input file.
    astWalker = AstWalker(lines, options, inFilename)
    astWalker.parseLines()
    # Output the modified source.
    print(astWalker.getLines())
1138703
def add_command_line_options_optparse(cls, optparser):
        """"""

        def set_parameter(option, opt, value, parser):
            """callback function for OptionParser"""
            cls.config[opt] = value
            if opt == "--stomp-conf":
                cls.load_configuration_file(value)

        optparser.add_option(
            "--stomp-host",
            metavar="HOST",
            default=cls.defaults.get("--stomp-host"),
            help="Stomp broker address, default '%default'",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-port",
            metavar="PORT",
            default=cls.defaults.get("--stomp-port"),
            help="Stomp broker port, default '%default'",
            type="int",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-user",
            metavar="USER",
            default=cls.defaults.get("--stomp-user"),
            help="Stomp user, default '%default'",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-pass",
            metavar="PASS",
            default=cls.defaults.get("--stomp-pass"),
            help="Stomp password",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-prfx",
            metavar="PRE",
            default=cls.defaults.get("--stomp-prfx"),
            help="Stomp namespace prefix, default '%default'",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
        optparser.add_option(
            "--stomp-conf",
            metavar="CNF",
            default=cls.defaults.get("--stomp-conf"),
            help="Stomp configuration file containing connection information, disables default values",
            type="string",
            nargs=1,
            action="callback",
            callback=set_parameter,
        )
1035375
def parse_command_line():
    

    import argparse

    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + __version__,
                        help="Show version number and exit.")
    parser.add_argument('input_filename',
                        metavar='INPUT_FILE',
                        type=str,
                        help='Path of the input file to be preprocessed')
    parser.add_argument('-q',
                        '--quiet',
                        dest='should_be_quiet',
                        action='store_true',
                        default=False,
                        help="Disables verbose logging")
    parser.add_argument('-L',
                        '--log-level',
                        '--logging-level',
                        dest='logging_level',
                        choices=[
                            'DEBUG',
                            'INFO',
                            'WARNING',
                            'ERROR',
                            'CRITICAL',
                            'NONE',
                            ],
                        default='INFO',
                        help="Logging level.")
    parser.add_argument('-o',
                        '--output',
                        metavar="OUTPUT_FILE",
                        dest='output_filename',
                        default=None,
                        help='Output file name (default STDOUT)')
    parser.add_argument('-f',
                        '--force',
                        dest='should_force_overwrite',
                        action='store_true',
                        default=False,
                        help='Force overwrite existing output file.')
    parser.add_argument('-D',
                        '--define',
                        metavar="EXPR",
                        dest='definitions',
                        action='append',
                        help="""\
Define a variable for preprocessing. <define>
can simply be a variable name (in which case it
will be true) or it can be of the form
<var>=<val>. An attempt will be made to convert
<val> to an integer so -D 'FOO=0' will create a
false value.""")
    parser.add_argument('-I',
                        '--include',
                        metavar="DIR_PATH",
                        dest='include_paths',
                        action='append',
                        default=['.'],
                        help='Add a directory to the include path for #include directives.')
    parser.add_argument('-k',
                        '--keep-lines',
                        dest='should_keep_lines',
                        action='store_true',
                        default=False,
                        help='''\
Emit empty lines for preprocessor statement
lines and skipped output lines. This allows line
numbers to stay constant.''')
    parser.add_argument('-s',
                        '--substitute',
                        dest='should_substitute',
                        action='store_true',
                        default=False,
                        help='''\
Substitute #defines into emitted lines.
(Disabled by default to avoid polluting strings)''')
    parser.add_argument('--default-content-type',
                        metavar="CONTENT_TYPE",
                        dest='default_content_type',
                        default=None,
                        help='If the content type of the file cannot be determined this will be used. (Default: an error is raised)')
    parser.add_argument('-c',
                        '--content-types-path',
                        '--content-types-config',
                        metavar="PATH",
                        dest='content_types_config_files',
                        default=[],
                        action='append',
                        help="""\
Specify a path to a content.types file to assist
with file type determination. Use the -p or -P flags
to display content types as read by pepe.""")
    parser.add_argument('-p',
                        '--print-content-types',
                        dest='should_print_content_types',
                        action='store_true',
                        default=False,
                        help='Display content types and exit.')
    parser.add_argument('-P',
                        '--print-content-types-config',
                        dest='should_print_content_types_config',
                        action='store_true',
                        default=False,
                        help='Display content types configuration and exit.')
    return parser.parse_args()
263115
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="tastic"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if varname == "import":
            varname = "iimport"
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/tastic/tastic.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    # CALL FUNCTIONS/OBJECTS
    if sort or archive:

        ws = workspace(
            log=log,
            settings=settings,
            fileOrWorkspacePath=pathToFileOrWorkspace
        )
    if sort:
        ws.sort()
    if archive:
        ws.archive_done()

    if sync:
        tp = syncc(
            log=log,
            settings=settings,
            workspaceRoot=pathToWorkspace,
            workspaceName=workspaceName,
            syncFolder=pathToSyncFolder,
            editorialRootPath=editorialRootPath,
            includeFileTags=fileTagsFlag
        )
        tp.sync()

    if reminders:
        r = reminderss(
            log=log,
            settings=settings
        )
        r.import_list(
            listName=listName,
            pathToTaskpaperDoc=pathToTaskpaperDoc
        )

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
120706
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="polyglot"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # for k, v in locals().iteritems():
    #     print k, v

    if not destinationFolder:
        destinationFolder = os.getcwd()
    if not filenameFlag:
        filenameFlag = False
    if not cleanFlag:
        readability = False
    else:
        readability = True

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/polyglot/polyglot.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if pdf and url:
        filepath = printpdf.printpdf(
            log=log,
            settings=settings,
            url=url,
            folderpath=destinationFolder,
            title=filenameFlag,
            append=False,
            readability=readability
        ).get()

    if html and url:

        cleaner = htmlCleaner.htmlCleaner(
            log=log,
            settings=settings,
            url=url,
            outputDirectory=destinationFolder,
            title=filenameFlag,  # SET TO FALSE TO USE WEBPAGE TITLE,
            style=cleanFlag,  # add polyglot's styling to the HTML document
            metadata=True,  # include metadata in generated HTML (e.g. title),
            h1=True  # include title as H1 at the top of the doc
        )
        filepath = cleaner.clean()

    if epub:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        epub = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="epub",
            outputDirectory=destinationFolder
        )
        filepath = epub.get()

    if mobi:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import ebook
        mobi = ebook(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag,
            bookFormat="mobi",
            outputDirectory=destinationFolder,
        )
        filepath = mobi.get()

    if kindle:
        if url:
            iinput = url
        else:
            iinput = docx
        from polyglot import kindle
        sender = kindle(
            log=log,
            settings=settings,
            urlOrPath=iinput,
            title=filenameFlag
        )
        success = sender.send()

    if kindleNB2MD:
        basename = os.path.basename(notebook)
        extension = os.path.splitext(basename)[1]
        filenameNoExtension = os.path.splitext(basename)[0]
        if destinationFolder:
            filepath = destinationFolder + "/" + filenameNoExtension + ".md"
        else:
            filepath = notebook.replace("." + extension, ".md")
        from polyglot.markdown import kindle_notebook
        nb = kindle_notebook(
            log=log,
            kindleExportPath=notebook,
            outputPath=filepath
        )
        nb.convert()

    if openFlag:
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
610971
def main():
    

    args = get_command_line_arguments()
    args.css_file = args.css_file if foundations.common.path_exists(args.css_file) else CSS_FILE
    return reStructuredText_to_html(args.input,
                                    args.output,
                                    args.css_file)
851395
def main():
    
    parser = argparse.ArgumentParser(
        description='Performs option handling operations from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-action", metavar="action", dest="action", required=True,
                        help="The action to perform on the options: join=create single string, "\
                             "split=create array from quoted option, code=generate code from options")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="The option(s) to process")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)

    jvm.start(jars, packages=True)

    try:
        if parsed.action == "join":
            output = "cmdline = \"" + backquote(join_options(parsed.option)) + "\""
        elif parsed.action == "split" and len(parsed.option) == 1:
            output = "options = [\n"
            opts = split_options(parsed.option[0])
            for idx, opt in enumerate(opts):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]"
        elif parsed.action == "code":
            options = parsed.option[:]
            cname = None
            # classname + options?
            if options[0].find(".") > -1:
                cname = options[0]
                options = options[1:]
            output = "options = [ \n"
            for idx, opt in enumerate(options):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]\n"
            if cname is not None:
                output += 'handler = OptionHandler(JavaObject.new_instance("' + cname + '"))\n'
                output += 'handler.options = options\n'
        else:
            raise Exception("Unsupported action: " + parsed.action)
        if output is not None:
            print(output)
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
452604
function makeOptions(IOD, IODOpts, apiType, reqOpts) {
	var path = IodU.makePath(IOD, IODOpts, apiType)
	var method = apiType === IOD.TYPES.JOB || !_.isEmpty(IODOpts.files) ?
		'post' : IODOpts.method.toLowerCase()

	return _.defaults({
		url: IOD.host + ':' + IOD.port + path,
		path: path,
		method: method,

		// For 'get' request use request `qs` property.
		qs: method === 'get' ?
			_.defaults({ apiKey: IOD.apiKey }, exports.prepareParams(IODOpts.params)) : undefined,

		// For 'post' request with no files use `form` property
		form: method === 'post' && !IODOpts.files ?
			_.defaults({ apiKey: IOD.apiKey }, exports.prepareParams(IODOpts.params)) : undefined
	}, reqOpts, IOD.reqOpts)
}
858629
def process_args_from_command_line(self):
        """"""
        # Yes, this is ugly, but we don't want to interfere with setup.py's own
        # option handling
        opts_to_remove = []
        for idx, option in enumerate(sys.argv):
            if not option.startswith("--"):
                continue
            if option == "--static":
                opts_to_remove.append(idx)
                self.static_extension = True
            elif option == "--no-download":
                opts_to_remove.append(idx)
                self.download_igraph_if_needed = False
            elif option == "--no-pkg-config":
                opts_to_remove.append(idx)
                self.use_pkgconfig = False
            elif option == "--no-progress-bar":
                opts_to_remove.append(idx)
                self.show_progress_bar = False
            elif option == "--no-wait":
                opts_to_remove.append(idx)
                self.wait = False                
            elif option.startswith("--c-core-version"):
                opts_to_remove.append(idx)
                if option == "--c-core-version":
                    value = sys.argv[idx+1]
                    opts_to_remove.append(idx+1)
                else:
                    value = option.split("=", 1)[1]
                self.c_core_versions = [value]
            elif option.startswith("--c-core-url"):
                opts_to_remove.append(idx)
                if option == "--c-core-url":
                    value = sys.argv[idx+1]
                    opts_to_remove.append(idx+1)
                else:
                    value = option.split("=", 1)[1]
                self.c_core_url = value

        for idx in reversed(opts_to_remove):
            sys.argv[idx:(idx+1)] = []
502775
def make(parser):
    """"""
    s = parser.add_subparsers(
        title='commands',
        metavar='COMMAND',
        help='description',
        )

    def gen_pass_f(args):
        gen_pass()
    gen_pass_parser = s.add_parser('gen-pass', help='generate the password')
    gen_pass_parser.set_defaults(func=gen_pass_f)

    def cmd_f(args):
        cmd(args.user, args.hosts.split(','), args.key_filename, args.password, args.run)
    cmd_parser = s.add_parser('cmd', help='run command line on the target host')
    cmd_parser.add_argument('--run', help='the command running on the remote node', action='store', default=None, dest='run')
    cmd_parser.set_defaults(func=cmd_f)
1010097
def main():
    
    arguments = docopt(main.__doc__)

    if arguments.get('--version'):
        print('with {}'.format(withtool.__version__))
        sys.exit()

    while True:
        sub = yield from get_prompt(arguments['<command>'])
        call = '{cmd} {sub}'.format(cmd=arguments['<command>'], sub=sub)
        run(call)
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)
603255
def main():
    """"""
    actions = []
    try:
        # Parse the command line arguments.
        options, arguments = getopt.getopt(sys.argv[1:], 'cdh', [
            'convert', 'to-html', 'demo', 'help',
        ])
        # Map command line options to actions.
        for option, value in options:
            if option in ('-c', '--convert', '--to-html'):
                actions.append(functools.partial(convert_command_output, *arguments))
                arguments = []
            elif option in ('-d', '--demo'):
                actions.append(demonstrate_colored_logging)
            elif option in ('-h', '--help'):
                usage(__doc__)
                return
            else:
                assert False, "Programming error: Unhandled option!"
        if not actions:
            usage(__doc__)
            return
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    for function in actions:
        function()
581324
def simulate(args):
    
    p = OptionParser(simulate.__doc__)
    p.set_outfile()
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    idsfile, = args
    fp = open(idsfile)
    fw = must_open(opts.outfile, "w")
    for row in fp:
        name, size = row.split()
        size = int(size)
        simulate_one(fw, name, size)
    fp.close()
896876
def cli(ctx, report, semantic, rcfile):
    
    ctx.obj = {
        'report': report,
        'semantic': semantic,
        'rcfile': rcfile,
    }