Main program entry point for parsing command line arguments
973339
def main(argv=None):
    """"""
    parser = argparse.ArgumentParser(description="Parser benchmark")

    parser.add_argument("--debug", default=False, action="store_true", help="Enable debugging")
    parser.add_argument("--repetitions", type=int, default=10, help="Number of repetitions")
    parser.add_argument("--line-count", type=int, default=5000, help="Number of lines to parse")

    args = parser.parse_args(argv)
    run(args)
1345405
def main(argv=None):
    

    if argv is None:
        argv = sys.argv

    # setup command line parser
    parser = U.OptionParser(version="%prog version: $Id$",
                            usage=usage,
                            description=globals()["__doc__"])
    group = U.OptionGroup(parser, "dedup-specific options")

    group.add_option("--output-stats", dest="stats", type="string",
                     default=False,
                     help="Specify location to output stats")

    parser.add_option_group(group)

    # add common options (-h/--help, ...) and parse command line
    (options, args) = U.Start(parser, argv=argv)

    U.validateSamOptions(options, group=False)

    if options.random_seed:
        np.random.seed(options.random_seed)

    if options.stdin != sys.stdin:
        in_name = options.stdin.name
        options.stdin.close()
    else:
        raise ValueError("Input on standard in not currently supported")

    if options.stdout != sys.stdout:
        if options.no_sort_output:
            out_name = options.stdout.name
        else:
            out_name = U.getTempFilename(dir=options.tmpdir)
            sorted_out_name = options.stdout.name
        options.stdout.close()
    else:
        if options.no_sort_output:
            out_name = "-"
        else:
            out_name = U.getTempFilename(dir=options.tmpdir)
            sorted_out_name = "-"

    if not options.no_sort_output:  # need to determine the output format for sort
        if options.out_sam:
            sort_format = "sam"
        else:
            sort_format = "bam"

    if options.in_sam:
        in_mode = "r"
    else:
        in_mode = "rb"

    if options.out_sam:
        out_mode = "wh"
    else:
        out_mode = "wb"

    if options.stats and options.ignore_umi:
        raise ValueError("'--output-stats' and '--ignore-umi' options"
                         " cannot be used together")

    infile = pysam.Samfile(in_name, in_mode)
    outfile = pysam.Samfile(out_name, out_mode, template=infile)

    if options.paired:
        outfile = sam_methods.TwoPassPairWriter(infile, outfile)

    nInput, nOutput, input_reads, output_reads = 0, 0, 0, 0

    if options.detection_method:
        bam_features = detect_bam_features(infile.filename)

        if not bam_features[options.detection_method]:
            if sum(bam_features.values()) == 0:
                raise ValueError(
                    "There are no bam tags available to detect multimapping. "
                    "Do not set --multimapping-detection-method")
            else:
                raise ValueError(
                    "The chosen method of detection for multimapping (%s) "
                    "will not work with this bam. Multimapping can be detected"
                    " for this bam using any of the following: %s" % (
                        options.detection_method, ",".join(
                            [x for x in bam_features if bam_features[x]])))

    gene_tag = options.gene_tag
    metacontig2contig = None

    if options.chrom:
        inreads = infile.fetch(reference=options.chrom)

    else:
        if options.per_contig and options.gene_transcript_map:
            metacontig2contig = sam_methods.getMetaContig2contig(
                infile, options.gene_transcript_map)
            metatag = "MC"
            inreads = sam_methods.metafetcher(infile, metacontig2contig, metatag)
            gene_tag = metatag

        else:
            inreads = infile.fetch()

    # set up ReadCluster functor with methods specific to
    # specified options.method
    processor = network.ReadDeduplicator(options.method)

    bundle_iterator = sam_methods.get_bundles(
        options,
        metacontig_contig=metacontig2contig)

    if options.stats:
        # set up arrays to hold stats data
        stats_pre_df_dict = {"UMI": [], "counts": []}
        stats_post_df_dict = {"UMI": [], "counts": []}
        pre_cluster_stats = []
        post_cluster_stats = []
        pre_cluster_stats_null = []
        post_cluster_stats_null = []
        topology_counts = collections.Counter()
        node_counts = collections.Counter()
        read_gn = umi_methods.random_read_generator(
            infile.filename, chrom=options.chrom,
            barcode_getter=bundle_iterator.barcode_getter)

    for bundle, key, status in bundle_iterator(inreads):

        nInput += sum([bundle[umi]["count"] for umi in bundle])

        while nOutput >= output_reads + 100000:
            output_reads += 100000
            U.info("Written out %i reads" % output_reads)

        while nInput >= input_reads + 1000000:
            input_reads += 1000000
            U.info("Parsed %i input reads" % input_reads)

        if options.stats:
            # generate pre-dudep stats
            average_distance = umi_methods.get_average_umi_distance(bundle.keys())
            pre_cluster_stats.append(average_distance)
            cluster_size = len(bundle)
            random_umis = read_gn.getUmis(cluster_size)
            average_distance_null = umi_methods.get_average_umi_distance(random_umis)
            pre_cluster_stats_null.append(average_distance_null)

        if options.ignore_umi:
            for umi in bundle:
                nOutput += 1
                outfile.write(bundle[umi]["read"])

        else:

            # dedup using umis and write out deduped bam
            reads, umis, umi_counts = processor(
                bundle=bundle,
                threshold=options.threshold)

            for read in reads:
                outfile.write(read)
                nOutput += 1

            if options.stats:

                # collect pre-dudupe stats
                stats_pre_df_dict['UMI'].extend(bundle)
                stats_pre_df_dict['counts'].extend(
                    [bundle[UMI]['count'] for UMI in bundle])

                # collect post-dudupe stats
                post_cluster_umis = [bundle_iterator.barcode_getter(x)[0] for x in reads]
                stats_post_df_dict['UMI'].extend(umis)
                stats_post_df_dict['counts'].extend(umi_counts)

                average_distance = umi_methods.get_average_umi_distance(post_cluster_umis)
                post_cluster_stats.append(average_distance)

                cluster_size = len(post_cluster_umis)
                random_umis = read_gn.getUmis(cluster_size)
                average_distance_null = umi_methods.get_average_umi_distance(random_umis)
                post_cluster_stats_null.append(average_distance_null)

    outfile.close()

    if not options.no_sort_output:
        # sort the output
        pysam.sort("-o", sorted_out_name, "-O", sort_format, out_name)
        os.unlink(out_name)  # delete the tempfile

    if options.stats:

        # generate the stats dataframe
        stats_pre_df = pd.DataFrame(stats_pre_df_dict)
        stats_post_df = pd.DataFrame(stats_post_df_dict)

        # tally the counts per umi per position
        pre_counts = collections.Counter(stats_pre_df["counts"])
        post_counts = collections.Counter(stats_post_df["counts"])
        counts_index = list(set(pre_counts.keys()).union(set(post_counts.keys())))
        counts_index.sort()
        with U.openFile(options.stats + "_per_umi_per_position.tsv", "w") as outf:
            outf.write("counts\tinstances_pre\tinstances_post\n")
            for count in counts_index:
                values = (count, pre_counts[count], post_counts[count])
                outf.write("\t".join(map(str, values)) + "\n")

        # aggregate stats pre/post per UMI
        agg_pre_df = aggregateStatsDF(stats_pre_df)
        agg_post_df = aggregateStatsDF(stats_post_df)

        agg_df = pd.merge(agg_pre_df, agg_post_df, how='left',
                          left_index=True, right_index=True,
                          sort=True, suffixes=["_pre", "_post"])

        # TS - if count value not observed either pre/post-dedup,
        # merge will leave an empty cell and the column will be cast as a float
        # see http://pandas.pydata.org/pandas-docs/dev/missing_data.html
        # --> Missing data casting rules and indexing
        # so, back fill with zeros and convert back to int
        agg_df = agg_df.fillna(0).astype(int)

        agg_df.index = [x.decode() for x in agg_df.index]
        agg_df.index.name = 'UMI'
        agg_df.to_csv(options.stats + "_per_umi.tsv", sep="\t")

        # bin distances into integer bins
        max_ed = int(max(map(max, [pre_cluster_stats,
                                   post_cluster_stats,
                                   pre_cluster_stats_null,
                                   post_cluster_stats_null])))

        cluster_bins = range(-1, int(max_ed) + 2)

        def bin_clusters(cluster_list, bins=cluster_bins):
            ''' take list of floats and return bins'''
            return np.digitize(cluster_list, bins, right=True)

        def tallyCounts(binned_cluster, max_edit_distance):
            ''' tally counts per bin '''
            return np.bincount(binned_cluster,
                               minlength=max_edit_distance + 3)

        pre_cluster_binned = bin_clusters(pre_cluster_stats)
        post_cluster_binned = bin_clusters(post_cluster_stats)
        pre_cluster_null_binned = bin_clusters(pre_cluster_stats_null)
        post_cluster_null_binned = bin_clusters(post_cluster_stats_null)

        edit_distance_df = pd.DataFrame(
            {"unique": tallyCounts(pre_cluster_binned, max_ed),
             "unique_null": tallyCounts(pre_cluster_null_binned, max_ed),
             options.method: tallyCounts(post_cluster_binned, max_ed),
             "%s_null" % options.method: tallyCounts(post_cluster_null_binned, max_ed),
             "edit_distance": cluster_bins},
            columns=["unique", "unique_null", options.method,
                     "%s_null" % options.method, "edit_distance"])

        # TS - set lowest bin (-1) to "Single_UMI"
        edit_distance_df['edit_distance'][0] = "Single_UMI"

        edit_distance_df.to_csv(options.stats + "_edit_distance.tsv",
                                index=False, sep="\t")

    # write footer and output benchmark information.
    U.info(
        "Reads: %s" % ", ".join(["%s: %s" % (x[0], x[1]) for x in
                                 bundle_iterator.read_events.most_common()]))

    U.info("Number of reads out: %i" % nOutput)

    if not options.ignore_umi:  # otherwise processor has not been used
        U.info("Total number of positions deduplicated: %i" %
               processor.UMIClusterer.positions)
        if processor.UMIClusterer.positions > 0:
            U.info("Mean number of unique UMIs per position: %.2f" %
                   (float(processor.UMIClusterer.total_umis_per_position) /
                    processor.UMIClusterer.positions))
            U.info("Max. number of unique UMIs per position: %i" %
                   processor.UMIClusterer.max_umis_per_position)
        else:
            U.warn("The BAM did not contain any valid "
                   "reads/read pairs for deduplication")

    U.Stop()
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()
503428
def main():
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-o", "--out", help="Output results to a file instead of stdout", default=None)
    parser.add_argument("-p", "--path", help="Specifies the target directory to search in", default=os.getcwd())
    options = parser.parse_args()

    try:
        scanner = Scanner(path=options.path, output=options.out)
        scanner.run()
        scanner.output()
        
    except ScannerException as e:
        print("[!] Error, %s" % str(e))
        exit(1)
356607
def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
    """"""
    args = parse_args(argv)

    if args["--debug"]:
        logging.basicConfig(
            format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
        )
    logger.debug(args)

    config_file: typing.Union[Path, None]
    if args["init"]:
        config_file = Path(args["<config_file>"] or CONFIG_FILE)
        init_config(config_file)
    else:
        config_file = Path(args["<config_file>"]) if args["<config_file>"] else None
        if args["edit"]:
            edit_config(config_file)
        elif args["allow"]:
            allow_config(config_file)
        elif args["deny"]:
            deny_config(config_file)

    mod = use_file(Path(args["--file"]) if args["--file"] else None)
    if hasattr(mod, "setup"):
        mod.setup()  # type: ignore

    if args["--name"]:
        if args["--name"] not in _config_registry:
            print_error(f'Invalid --name: "{args["--name"]}"')
            sys.exit(1)
        config_dict = _config_registry[args["--name"]]
        logger.debug(f'Using named config: "{args["--name"]}"')
        logger.debug(config_dict)
    else:
        config_dict = _cfg
    # Allow default shell to be overriden by command-line argument
    shell_name = args["--shell"]
    if shell_name:
        config_dict["shell"] = SHELL_MAP.get(shell_name.lower(), AutoShell)
    logger.debug(f"Starting with config {config_dict}")
    start(**config_dict)

    if hasattr(mod, "teardown"):
        mod.teardown()  # type: ignore
    sys.exit(0)
1170933
def main(args=None):
    
    parser = ArgumentParser()
    parser.add_argument('-v', '--version',
                        action='version', version=CLI_VERSION)

    parsers = parser.add_subparsers(dest='dtype')

    text.create_arg_parser(parsers.add_parser('text'))
    if image is not None:
        image.create_arg_parser(parsers.add_parser('image'))

    if len(sys.argv if args is None else args) <= 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args(args)
    dtype = globals()[args.dtype]
    try:
        set_args(args)
        cmd = getattr(dtype, 'cmd_' + args.command)
        cmd(args)
    except ValueError as err:
        print(str(err), file=sys.stderr)
        sys.exit(1)
951733
def main(args):
    

    parser = argparse.ArgumentParser(usage="python -m premailer [options]")

    parser.add_argument(
        "-f",
        "--file",
        nargs="?",
        type=argparse.FileType("r"),
        help="Specifies the input file.  The default is stdin.",
        default=sys.stdin,
        dest="infile",
    )

    parser.add_argument(
        "-o",
        "--output",
        nargs="?",
        type=argparse.FileType("w"),
        help="Specifies the output file.  The default is stdout.",
        default=sys.stdout,
        dest="outfile",
    )

    parser.add_argument("--base-url", default=None, type=str, dest="base_url")

    parser.add_argument(
        "--remove-internal-links",
        default=True,
        help="Remove links that start with a '#' like anchors.",
        dest="preserve_internal_links",
    )

    parser.add_argument(
        "--exclude-pseudoclasses",
        default=False,
        help="Pseudo classes like p:last-child', p:first-child, etc",
        action="store_true",
        dest="exclude_pseudoclasses",
    )

    parser.add_argument(
        "--preserve-style-tags",
        default=False,
        help="Do not delete <style></style> tags from the html document.",
        action="store_true",
        dest="keep_style_tags",
    )

    parser.add_argument(
        "--remove-star-selectors",
        default=True,
        help="All wildcard selectors like '* {color: black}' will be removed.",
        action="store_false",
        dest="include_star_selectors",
    )

    parser.add_argument(
        "--remove-classes",
        default=False,
        help="Remove all class attributes from all elements",
        action="store_true",
        dest="remove_classes",
    )

    parser.add_argument(
        "--capitalize-float-margin",
        default=False,
        help="Capitalize float and margin properties for outlook.com compat.",
        action="store_true",
        dest="capitalize_float_margin",
    )

    parser.add_argument(
        "--strip-important",
        default=False,
        help="Remove '!important' for all css declarations.",
        action="store_true",
        dest="strip_important",
    )

    parser.add_argument(
        "--method",
        default="html",
        dest="method",
        help="The type of html to output. 'html' for HTML, 'xml' for XHTML.",
    )

    parser.add_argument(
        "--base-path",
        default=None,
        dest="base_path",
        help="The base path for all external stylsheets.",
    )

    parser.add_argument(
        "--external-style",
        action="append",
        dest="external_styles",
        help="The path to an external stylesheet to be loaded.",
    )

    parser.add_argument(
        "--css-text",
        action="append",
        dest="css_text",
        help="CSS text to be applied to the html.",
    )

    parser.add_argument(
        "--disable-basic-attributes",
        dest="disable_basic_attributes",
        help="Disable provided basic attributes (comma separated)",
        default=[],
    )

    parser.add_argument(
        "--disable-validation",
        default=False,
        action="store_true",
        dest="disable_validation",
        help="Disable CSSParser validation of attributes and values",
    )

    parser.add_argument(
        "--pretty",
        default=False,
        action="store_true",
        help="Pretty-print the outputted HTML.",
    )

    parser.add_argument(
        "--encoding", default="utf-8", help="Output encoding. The default is utf-8"
    )

    options = parser.parse_args(args)

    if options.disable_basic_attributes:
        options.disable_basic_attributes = options.disable_basic_attributes.split()

    html = options.infile.read()
    if hasattr(html, "decode"):  # Forgive me: Python 2 compatability
        html = html.decode("utf-8")

    p = Premailer(
        html=html,
        base_url=options.base_url,
        preserve_internal_links=options.preserve_internal_links,
        exclude_pseudoclasses=options.exclude_pseudoclasses,
        keep_style_tags=options.keep_style_tags,
        include_star_selectors=options.include_star_selectors,
        remove_classes=options.remove_classes,
        strip_important=options.strip_important,
        external_styles=options.external_styles,
        css_text=options.css_text,
        method=options.method,
        base_path=options.base_path,
        disable_basic_attributes=options.disable_basic_attributes,
        disable_validation=options.disable_validation,
    )
    options.outfile.write(
        p.transform(encoding=options.encoding, pretty_print=options.pretty)
    )
    return 0
218578
def main(args=None, prog=None):
    """"""
    args = args if args is not None else sys.argv[1:]
    prog = prog if prog is not None else sys.argv[0]
    # Prevent broken pipe exception from being raised.
    signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    stdin = sys.stdin.buffer if hasattr(sys.stdin, 'buffer') else sys.stdin
    p = argparse.ArgumentParser(prog=prog)
    p.add_argument('-o', '--output', metavar='PATH',
                   type=argparse.FileType('w'), default=sys.stdout,
                   help='Write output to PATH')
    p.add_argument('--api', help='Match API', default=None)
    p.add_argument('--profile', help='Match profile', default=None)
    p.add_argument('--support', default=None,
                   help='Match extension support string')
    g = p.add_mutually_exclusive_group()
    g.add_argument('--list-apis', action='store_true', dest='list_apis',
                   help='List apis in registry', default=False)
    g.add_argument('--list-profiles', action='store_true', default=False,
                   dest='list_profiles', help='List profiles in registry')
    g.add_argument('--list-supports', action='store_true',
                   dest='list_supports', default=False,
                   help='List extension support strings')
    p.add_argument('registry', type=argparse.FileType('rb'), nargs='?',
                   default=stdin, help='Registry path')
    args = p.parse_args(args)
    o = args.output
    try:
        registry = load(args.registry)
        if args.list_apis:
            for x in sorted(registry.get_apis()):
                print(x, file=o)
            return 0
        elif args.list_profiles:
            for x in sorted(registry.get_profiles()):
                print(x, file=o)
            return 0
        elif args.list_supports:
            for x in sorted(registry.get_supports()):
                print(x, file=o)
            return 0
        apis = group_apis(registry, None, None, args.api, args.profile,
                          args.support)
        for api in apis:
            print('#ifndef', api.name, file=o)
            print('#define', api.name, file=o)
            print(api.text, file=o)
            print('#endif', file=o)
            print('', file=o)
    except:
        e = sys.exc_info()[1]
        print(prog, ': error: ', e, sep='', file=sys.stderr)
        return 1
    return 0
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
301199
def main(args=sys.argv):
    

    parser = create_optparser(args[0])
    return cli(parser.parse_args(args[1:]))
63235
def main():
    
    parser = argparse.ArgumentParser(description=__description__)
    parser.add_argument(
        '-V', '--version', dest='version', action='store_true',
        help="show version")
    parser.add_argument(
        '--log-level', default='INFO',
        help="Specify logging level, default is INFO.")
    parser.add_argument('har_source_file', nargs='?',
        help="Specify HAR source file")
    parser.add_argument(
        '-2y', '--to-yml', '--to-yaml',
        dest='to_yaml', action='store_true',
        help="Convert to YAML format, if not specified, convert to JSON format by default.")
    parser.add_argument(
        '--filter', help="Specify filter keyword, only url include filter string will be converted.")
    parser.add_argument(
        '--exclude',
        help="Specify exclude keyword, url that includes exclude string will be ignored, multiple keywords can be joined with '|'")

    args = parser.parse_args()

    if args.version:
        print("{}".format(__version__))
        exit(0)

    log_level = getattr(logging, args.log_level.upper())
    logging.basicConfig(level=log_level)

    har_source_file = args.har_source_file
    if not har_source_file or not har_source_file.endswith(".har"):
        logging.error("HAR file not specified.")
        sys.exit(1)

    output_file_type = "YML" if args.to_yaml else "JSON"
    HarParser(
        har_source_file, args.filter, args.exclude
    ).gen_testcase(output_file_type)

    return 0
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()
761311
def main(*arguments):
    

    from argparse import ArgumentParser, RawDescriptionHelpFormatter
    from textwrap import dedent

    parser = ArgumentParser(
        description=dedent(main.__doc__), formatter_class=RawDescriptionHelpFormatter
    )
    parser.add_argument(
        "--version",
        action="version",
        version="%(prog)s {}".format(natsort.__version__),
    )
    parser.add_argument(
        "-p",
        "--paths",
        default=False,
        action="store_true",
        help="Interpret the input as file paths.  This is not "
        "strictly necessary to sort all file paths, but in cases "
        'where there are OS-generated file paths like "Folder/" '
        'and "Folder (1)/", this option is needed to make the '
        'paths sorted in the order you expect ("Folder/" before '
        '"Folder (1)/").',
    )
    parser.add_argument(
        "-f",
        "--filter",
        nargs=2,
        type=float,
        metavar=("LOW", "HIGH"),
        action="append",
        help="Used for keeping only the entries that have a number "
        "falling in the given range.",
    )
    parser.add_argument(
        "-F",
        "--reverse-filter",
        nargs=2,
        type=float,
        metavar=("LOW", "HIGH"),
        action="append",
        dest="reverse_filter",
        help="Used for excluding the entries that have a number "
        "falling in the given range.",
    )
    parser.add_argument(
        "-e",
        "--exclude",
        type=float,
        action="append",
        help="Used to exclude an entry that contains a specific number.",
    )
    parser.add_argument(
        "-r",
        "--reverse",
        action="store_true",
        default=False,
        help="Returns in reversed order.",
    )
    parser.add_argument(
        "-t",
        "--number-type",
        "--number_type",
        dest="number_type",
        choices=("int", "float", "real", "f", "i", "r"),
        default="int",
        help='Choose the type of number to search for. "float" will search '
        'for floating-point numbers.  "int" will only search for '
        'integers. "real" is a shortcut for "float" with --sign. '
        '"i" is a synonym for "int", "f" is a synonym for '
        '"float", and "r" is a synonym for "real".'
        "The default is %(default)s.",
    )
    parser.add_argument(
        "--nosign",
        default=False,
        action="store_false",
        dest="signed",
        help='Do not consider "+" or "-" as part of a number, i.e. do not '
        "take sign into consideration. This is the default.",
    )
    parser.add_argument(
        "-s",
        "--sign",
        default=False,
        action="store_true",
        dest="signed",
        help='Consider "+" or "-" as part of a number, i.e. '
        "take sign into consideration. The default is unsigned.",
    )
    parser.add_argument(
        "--noexp",
        default=True,
        action="store_false",
        dest="exp",
        help="Do not consider an exponential as part of a number, i.e. 1e4, "
        'would be considered as 1, "e", and 4, not as 10000.  This only '
        "effects the --number-type=float.",
    )
    parser.add_argument(
        "-l",
        "--locale",
        action="store_true",
        default=False,
        help="Causes natsort to use locale-aware sorting. You will get the "
        "best results if you install PyICU.",
    )
    parser.add_argument(
        "entries",
        nargs="*",
        default=sys.stdin,
        help="The entries to sort. Taken from stdin if nothing is given on "
        "the command line.",
    )
    args = parser.parse_args(arguments or None)

    # Make sure the filter range is given properly. Does nothing if no filter
    args.filter = check_filters(args.filter)
    args.reverse_filter = check_filters(args.reverse_filter)

    # Remove trailing whitespace from all the entries
    entries = [e.strip() for e in args.entries]

    # Sort by directory then by file within directory and print.
    sort_and_print_entries(entries, args)
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)
1283821
def Main():
  
  argument_parser = argparse.ArgumentParser(description=(
      'Calculates a message digest hash for every file in a directory or '
      'storage media image.'))

  argument_parser.add_argument(
      '--output_file', '--output-file', dest='output_file', action='store',
      metavar='source.hashes', default=None, help=(
          'path of the output file, default is to output to stdout.'))

  argument_parser.add_argument(
      'source', nargs='?', action='store', metavar='image.raw',
      default=None, help='path of the directory or storage media image.')

  options = argument_parser.parse_args()

  if not options.source:
    print('Source value is missing.')
    print('')
    argument_parser.print_help()
    print('')
    return False

  logging.basicConfig(
      level=logging.INFO, format='[%(levelname)s] %(message)s')

  if options.output_file:
    output_writer = FileOutputWriter(options.output_file)
  else:
    output_writer = StdoutWriter()

  try:
    output_writer.Open()
  except IOError as exception:
    print('Unable to open output writer with error: {0!s}.'.format(
        exception))
    print('')
    return False

  return_value = True
  mediator = command_line.CLIVolumeScannerMediator()
  recursive_hasher = RecursiveHasher(mediator=mediator)

  try:
    base_path_specs = recursive_hasher.GetBasePathSpecs(options.source)
    if not base_path_specs:
      print('No supported file system found in source.')
      print('')
      return False

    recursive_hasher.CalculateHashes(base_path_specs, output_writer)

    print('')
    print('Completed.')

  except errors.ScannerError as exception:
    return_value = False

    print('')
    print('[ERROR] {0!s}'.format(exception))

  except errors.UserAbort as exception:
    return_value = False

    print('')
    print('Aborted.')

  output_writer.Close()

  return return_value
799184
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="fundmentals"
    )
    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,))

    if successFlag and successFlag.lower() == "none":
        successFlag = None
    if failureFlag and failureFlag.lower() == "none":
        failureFlag = None

    directory_script_runner(
        log=log,
        pathToScriptDirectory=pathToDirectory,
        databaseName=databaseName,
        loginPath=loginPath,
        successRule=successFlag,
        failureRule=failureFlag
    )

    return
357141
def _main(args, prog_name):
  """"""
  # get options and arguments
  ui = getUI(prog_name, args)

  if ui.optionIsSet("test"):
    # just run unit tests
    unittest.main(argv=[sys.argv[0]])
  elif ui.optionIsSet("help"):
    # just show help
    ui.usage()
  else:
    verbose = ui.optionIsSet("verbose")

    # know there are exactly two arguments, because we specified this in the
    # UI description.
    regions_fn = ui.getArgument(0)
    to_count_fn = ui.getArgument(1)

    # get output handle
    out_fh = sys.stdout
    if ui.optionIsSet("output"):
      out_fh = open(ui.getValue("output"), "w")

    # norm?
    norm = ui.optionIsSet("normalize")

    # get anchor point
    anch = ANCHOR_START
    if ui.optionIsSet("anchor"):
      if ui.getValue("anchor") == "5-prime":
        anch = ANCHOR_5PRIME

    res = process_anchor_start(regions_fn, to_count_fn, anchor_to=anch,
                               normalize=norm, verbose=verbose)
    write_output(res, out_fh, verbose=verbose)