create synopsis from main parser
322224
def create_main_synopsis(self, parser):
        
        self.add_usage(parser.usage, parser._actions,
                       parser._mutually_exclusive_groups, prefix='')
        usage = self._format_usage(None, parser._actions,
                                   parser._mutually_exclusive_groups, '')

        usage = usage.replace('%s ' % self._prog, '')
        usage = '.SH SYNOPSIS\n \\fB%s\\fR %s\n' % (self._markup(self._prog),
                                                    usage)
        return usage
570172
def main(argv=sys.argv[1:]):
    """"""
    usage = 'usage: %prog [options] FILE\n\n' + __doc__
    parser = OptionParser(usage)

    # options
    parser.add_option("-f", "--force",
                      action='store_true', default=False,
                      help="make changes even if they cannot undone before saving the new file")
    parser.add_option("-m", "--min_level",
                      default='NONE',
                      help="minimum level of logging statements to modify [default: no minimum]")
    parser.add_option("-M", "--max_level",
                      default='NONE',
                      help="maximum level of logging statements to modify [default: no maximum]")
    parser.add_option("-o", "--output-file",
                      default=None,
                      help="where to output the result [default: overwrite the input file]")
    parser.add_option("-r", "--restore",
                      action='store_true', default=False,
                      help="restore logging statements previously commented out and replaced with pass statements")
    parser.add_option("-v", "--verbose",
                      action='store_true', default=False,
                      help="print informational messages about changes made")

    (options, args) = parser.parse_args(argv)
    if len(args) != 1:
        parser.error("expected 1 argument but got %d arguments: %s" % (len(args), ' '.join(args)))
    input_fn = args[0]
    if not options.output_file:
        options.output_file = input_fn

    # validate min/max level
    LEVEL_CHOICES = LEVELS + ['NONE']
    min_level_value = 0 if options.min_level == 'NONE' else get_level_value(options.min_level)
    if options.min_level is None:
        parser.error("min level must be an integer or one of these values: %s" % ', '.join(LEVEL_CHOICES))
    max_level_value = sys.maxint if options.max_level == 'NONE' else get_level_value(options.max_level)
    if options.max_level is None:
        parser.error("max level must be an integer or one of these values: %s" % ', '.join(LEVEL_CHOICES))

    if options.verbose:
        logging.getLogger().setLevel(logging.INFO)

    try:
        return modify_logging(input_fn, options.output_file,
                              min_level_value, max_level_value,
                              options.restore, options.force)
    except IOError as e:
        logging.error(str(e))
        return -1
525787
String generateSynopsis() {
        synopsisOptions = buildSynopsisOptions(opts, arg, domain);
        StringBuilder synopsisBuilder = new StringBuilder();
        if (parentName != null) {
            synopsisBuilder.append(parentName).append(" ");
        }
        synopsisBuilder.append(commandName);
        if (isOperation && !opts.isEmpty()) {
            synopsisBuilder.append("(");
        } else {
            synopsisBuilder.append(" ");
        }
        boolean hasOptions = arg != null || !opts.isEmpty();
        if (hasActions && hasOptions) {
            synopsisBuilder.append(" [");
        }
        if (hasActions) {
            synopsisBuilder.append(" <action>");
        }
        if (hasActions && hasOptions) {
            synopsisBuilder.append(" ] || [");
        }
        SynopsisOption opt;
        while ((opt = retrieveNextOption(synopsisOptions, false)) != null) {
            String content = addSynopsisOption(opt);
            if (content != null) {
                synopsisBuilder.append(content.trim());
                if (isOperation) {
                    if (!synopsisOptions.isEmpty()) {
                        synopsisBuilder.append(",");
                    } else {
                        synopsisBuilder.append(")");
                    }
                }
                synopsisBuilder.append(" ");
            }
        }
        if (hasActions && hasOptions) {
            synopsisBuilder.append(" ]");
        }
        return synopsisBuilder.toString();
    }
248271
def main():
    
    # Define Parser object and add to jobTree
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawTextHelpFormatter)

    # Generate subparsers
    subparsers = parser.add_subparsers(dest='command')
    subparsers.add_parser('generate-config',
                          help='Generates an editable config in the current working directory.')
    subparsers.add_parser('generate-manifest',
                          help='Generates an editable manifest in the current working directory.')
    subparsers.add_parser('generate',
                          help='Generates a config and manifest in the current working directory.')

    # Run subparser
    parser_run = subparsers.add_parser('run', help='Runs the GATK germline pipeline')
    parser_run.add_argument('--config',
                            required=True,
                            type=str,
                            help='Path to the (filled in) config file, generated with '
                                 '"generate-config".')
    parser_run.add_argument('--manifest',
                            type=str,
                            help='Path to the (filled in) manifest file, generated with '
                                 '"generate-manifest".\nDefault value: "%(default)s".')
    parser_run.add_argument('--sample',
                            default=None,
                            nargs=2,
                            type=str,
                            help='Input sample identifier and BAM file URL or local path')
    parser_run.add_argument('--output-dir',
                            default=None,
                            help='Path/URL to output directory')
    parser_run.add_argument('-s', '--suffix',
                            default=None,
                            help='Additional suffix to add to the names of the output files')
    parser_run.add_argument('--preprocess-only',
                            action='store_true',
                            help='Only runs preprocessing steps')

    Job.Runner.addToilOptions(parser_run)
    options = parser.parse_args()

    cwd = os.getcwd()
    if options.command == 'generate-config' or options.command == 'generate':
        generate_file(os.path.join(cwd, 'config-toil-germline.yaml'), generate_config)
    if options.command == 'generate-manifest' or options.command == 'generate':
        generate_file(os.path.join(cwd, 'manifest-toil-germline.tsv'), generate_manifest)
    elif options.command == 'run':
        # Program checks
        for program in ['curl', 'docker']:
            require(next(which(program)),
                    program + ' must be installed on every node.'.format(program))

        require(os.path.exists(options.config), '{} not found. Please run "generate-config"'.format(options.config))

        # Read sample manifest
        samples = []
        if options.manifest:
            samples.extend(parse_manifest(options.manifest))

        # Add BAM sample from command line
        if options.sample:
            uuid, url = options.sample
            # samples tuple: (uuid, url, paired_url, rg_line)
            # BAM samples should not have as paired URL or read group line
            samples.append(GermlineSample(uuid, url, None, None))

        require(len(samples) > 0,
                'No samples were detected in the manifest or on the command line')

        # Parse inputs
        inputs = {x.replace('-', '_'): y for x, y in
                  yaml.load(open(options.config).read()).iteritems()}

        required_fields = {'genome_fasta',
                           'output_dir',
                           'run_bwa',
                           'sorted',
                           'snp_filter_annotations',
                           'indel_filter_annotations',
                           'preprocess',
                           'preprocess_only',
                           'run_vqsr',
                           'joint_genotype',
                           'run_oncotator',
                           'cores',
                           'file_size',
                           'xmx',
                           'suffix'}

        input_fields = set(inputs.keys())
        require(input_fields > required_fields,
                'Missing config parameters:\n{}'.format(', '.join(required_fields - input_fields)))

        if inputs['output_dir'] is None:
            inputs['output_dir'] = options.output_dir

        require(inputs['output_dir'] is not None,
                'Missing output directory PATH/URL')

        if inputs['suffix'] is None:
            inputs['suffix'] = options.suffix if options.suffix else ''

        if inputs['preprocess_only'] is None:
            inputs['preprocess_only'] = options.preprocess_only

        if inputs['run_vqsr']:
            # Check that essential VQSR parameters are present
            vqsr_fields = {'g1k_snp', 'mills', 'dbsnp', 'hapmap', 'omni'}
            require(input_fields > vqsr_fields,
                    'Missing parameters for VQSR:\n{}'.format(', '.join(vqsr_fields - input_fields)))

        # Check that hard filtering parameters are present. If only running preprocessing steps, then we do
        # not need filtering information.
        elif not inputs['preprocess_only']:
            hard_filter_fields = {'snp_filter_name', 'snp_filter_expression',
                                  'indel_filter_name', 'indel_filter_expression'}
            require(input_fields > hard_filter_fields,
                    'Missing parameters for hard filtering:\n{}'.format(', '.join(hard_filter_fields - input_fields)))

            # Check for falsey hard filtering parameters
            for hard_filter_field in hard_filter_fields:
                require(inputs[hard_filter_field], 'Missing %s value for hard filtering, '
                                                   'got %s.' % (hard_filter_field, inputs[hard_filter_field]))

        # Set resource parameters
        inputs['xmx'] = human2bytes(inputs['xmx'])
        inputs['file_size'] = human2bytes(inputs['file_size'])
        inputs['cores'] = int(inputs['cores'])

        inputs['annotations'] = set(inputs['snp_filter_annotations'] + inputs['indel_filter_annotations'])

        # HaplotypeCaller test data for testing
        inputs['hc_output'] = inputs.get('hc_output', None)

        # It is a toil-scripts convention to store input parameters in a Namespace object
        config = argparse.Namespace(**inputs)

        root = Job.wrapJobFn(run_gatk_germline_pipeline, samples, config)
        Job.Runner.startToil(root, options)
1365986
def makeParser():
    """"""
    # TODO: Add environment variable (all + selection)
    parser = argparse.ArgumentParser(
        description="Starts a parallel program using SCOOP.",
        prog="{0} -m scoop".format(sys.executable),
    )
    group = parser.add_mutually_exclusive_group()
    group.add_argument('--hosts', '--host',
                       help="The list of hosts. The first host will execute "
                            "the origin. (default is 127.0.0.1)",
                       metavar="Address",
                       nargs='*')
    group.add_argument('--hostfile',
                       help="The hostfile name",
                       metavar="FileName")
    parser.add_argument('--path', '-p',
                        help="The path to the executable on remote hosts "
                             "(default is local directory)",
                        default=os.getcwd())
    parser.add_argument('--nice',
                        type=int,
                        metavar="NiceLevel",
                        help="*nix niceness level (-20 to 19) to run the "
                             "executable")
    parser.add_argument('--verbose', '-v',
                        action='count',
                        help="Verbosity level of this launch script (-vv for "
                             "more)",
                        default=1)
    parser.add_argument('--quiet', '-q',
                        action='store_true')
    parser.add_argument('-n',
                        help="Total number of workers to launch on the hosts. "
                             "Workers are spawned sequentially over the hosts. "
                             "(ie. -n 3 with 2 hosts will spawn 2 workers on "
                             "the first host and 1 on the second.) (default: "
                             "Number of CPUs on current machine)",
                        type=int,
                        metavar="NumberOfWorkers")
    parser.add_argument('-b',
                        help="Total number of brokers to launch on the hosts. "
                             "Brokers are spawned sequentially over the hosts. "
                             "(ie. -b 3 with 2 hosts will spawn 2 brokers on "
                             "the first host and 1 on the second.) (default: "
                             "1)",
                        type=int,
                        default=1,
                        metavar="NumberOfBrokers")
    parser.add_argument('--rsh',
                        help="Use RSH instead of SSH for the launching process. "
                             "Not compatible with --tunnel flag.",
                        action='store_true')
    parser.add_argument('--ssh-executable',
                        help="Name of the ssh executable. (default: 'ssh')",
                        default="ssh",
                        metavar="SSHExecutable")
    parser.add_argument('--tunnel',
                        help="Activate ssh tunnels to route toward the broker "
                             "sockets over remote connections (may eliminate "
                             "routing problems and activate encryption but "
                             "slows down communications)",
                        action='store_true')
    parser.add_argument('--external-hostname',
                        nargs=1,
                        help="The externally routable hostname / ip of this "
                             "machine. (defaults to the local hostname)",
                        metavar="Address")
    parser.add_argument('--python-interpreter',
                        nargs=1,
                        help="The python interpreter executable with which to "
                             "execute the script",
                        default=[sys.executable],
                        metavar="Path")
    parser.add_argument('--pythonpath',
                        nargs=1,
                        help="The PYTHONPATH environment variable (default is "
                             "current PYTHONPATH)",
                        default=[os.environ.get('PYTHONPATH', '')])
    parser.add_argument('--prolog',
                        nargs=1,
                        help="Absolute Path to a shell script or executable "
                             "that will be executed at the launch of every "
                             "worker",
                        default=[None])
    parser.add_argument('--debug',
                        help=argparse.SUPPRESS,
                        action='store_true')
    parser.add_argument('--profile',
                        help=("Turn on the profiling. SCOOP will call "
                        "cProfile.run on the executable for every worker and"
                        " will produce files in directory profile/ named "
                        "workerX where X is the number of the worker."),
                        action='store_true')
    parser.add_argument('--backend',
                        help="Choice of communication backend",
                        choices=['ZMQ', 'TCP'],
                        default='ZMQ')
    parser.add_argument('executable',
                        nargs='?',
                        help='The executable to start with SCOOP')
    parser.add_argument('args',
                        nargs=argparse.REMAINDER,
                        help='The arguments to pass to the executable',
                        default=[],
                        metavar="args")
    return parser
1165525
def create_parser(self, prog_name, subcommand):
        
        parser = optparse.OptionParser(
            prog=prog_name,
            usage=self.usage(subcommand),
            version=self.get_version(),
            option_list=self.get_option_list())
        for name, description, option_list in self.get_option_groups():
            group = optparse.OptionGroup(parser, name, description);
            list(map(group.add_option, option_list))
            parser.add_option_group(group)
        return parser
252593
def from_dict(cls, d):
        """"""
        synopses = [tuple(map(Role.from_dict, synopsis))
                    for synopsis in d.get('synopses', [])]
        return cls(d['predicate'], tuple(d['parents']), synopses)
721028
def main(reactor):
    """"""
    parser = argparse.ArgumentParser(
        description='Fetch a URI or series of URIs and print a title '
                    'or summary for each.',
        epilog='If no URIs are passed on the command line, they are '
               'read from standard input, one per line.')
    parser.add_argument(
        'uris', metavar='URI', nargs='*', help='URI to fetch')
    parser.add_argument(
        '-H', '--hostname-tag', action='store_true',
        help='prefix titles with a hostname tag')
    args = parser.parse_args()
    uris = args.uris or imap(lambda x: x.strip(), sys.stdin)
    finished = DeferredList([
        fetch_title(uri.decode(locale.getpreferredencoding()),
                    hostname_tag=args.hostname_tag, friendly_errors=True)
        for uri in uris])
    finished.addCallback(print_and_exit)
    return finished
1068129
def main():
    
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument("path", nargs="+", help="File or directory path")
    parser.add_argument("--exclude", nargs="+", help="Exclude glob patterns")
    parser.add_argument(
        "--no-recursive",
        dest="recursive",
        action="store_false",
        help="Search directories recursively",
    )
    parser.add_argument(
        "--ignore-invalid", action="store_true", help="Ignore invalid paths"
    )
    parser.add_argument(
        "--pycharm", action="store_true", help="Enable PyCharm integration"
    )
    parser.add_argument(
        "--diff",
        dest="show_diff",
        action="store_true",
        help="Show diff and do not modify any files",
    )
    parser.add_argument(
        "--dry-run", action="store_true", help="Process files but do not write results"
    )
    parser.add_argument("--debug", action="store_true", help="Debug level logging")

    args = parser.parse_args()
    d1_common.util.log_setup(args.debug)

    repo_path = d1_dev.util.find_repo_root_by_path(__file__)
    repo = git.Repo(repo_path)

    specified_file_path_list = get_specified_file_path_list(args)
    tracked_path_list = list(d1_dev.util.get_tracked_files(repo))
    format_path_list = sorted(
        set(specified_file_path_list).intersection(tracked_path_list)
    )

    progress_logger.start_task_type("Format modules", len(format_path_list))

    for i, format_path in enumerate(format_path_list):
        progress_logger.start_task("Format modules", i)
        format_all_docstr(args, format_path)

    progress_logger.end_task_type("Format modules")
320258
def create_parser():
    """"""
    parser = argparse.ArgumentParser(description=docstring_summary(__doc__),
                                     prog='autopep8')
    parser.add_argument('--version', action='version',
                        version='%(prog)s {} ({})'.format(
                            __version__, _get_package_version()))
    parser.add_argument('-v', '--verbose', action='count',
                        default=0,
                        help='print verbose messages; '
                             'multiple -v result in more verbose messages')
    parser.add_argument('-d', '--diff', action='store_true',
                        help='print the diff for the fixed source')
    parser.add_argument('-i', '--in-place', action='store_true',
                        help='make changes to files in place')
    parser.add_argument('--global-config', metavar='filename',
                        default=DEFAULT_CONFIG,
                        help='path to a global pep8 config file; if this file '
                             'does not exist then this is ignored '
                             '(default: {})'.format(DEFAULT_CONFIG))
    parser.add_argument('--ignore-local-config', action='store_true',
                        help="don't look for and apply local config files; "
                             'if not passed, defaults are updated with any '
                             "config files in the project's root directory")
    parser.add_argument('-r', '--recursive', action='store_true',
                        help='run recursively over directories; '
                             'must be used with --in-place or --diff')
    parser.add_argument('-j', '--jobs', type=int, metavar='n', default=1,
                        help='number of parallel jobs; '
                             'match CPU count if value is less than 1')
    parser.add_argument('-p', '--pep8-passes', metavar='n',
                        default=-1, type=int,
                        help='maximum number of additional pep8 passes '
                             '(default: infinite)')
    parser.add_argument('-a', '--aggressive', action='count', default=0,
                        help='enable non-whitespace changes; '
                             'multiple -a result in more aggressive changes')
    parser.add_argument('--experimental', action='store_true',
                        help='enable experimental fixes')
    parser.add_argument('--exclude', metavar='globs',
                        help='exclude file/directory names that match these '
                             'comma-separated globs')
    parser.add_argument('--list-fixes', action='store_true',
                        help='list codes for fixes; '
                        'used by --ignore and --select')
    parser.add_argument('--ignore', metavar='errors', default='',
                        help='do not fix these errors/warnings '
                             '(default: {})'.format(DEFAULT_IGNORE))
    parser.add_argument('--select', metavar='errors', default='',
                        help='fix only these errors/warnings (e.g. E4,W)')
    parser.add_argument('--max-line-length', metavar='n', default=79, type=int,
                        help='set maximum allowed line length '
                             '(default: %(default)s)')
    parser.add_argument('--line-range', '--range', metavar='line',
                        default=None, type=int, nargs=2,
                        help='only fix errors found within this inclusive '
                             'range of line numbers (e.g. 1 99); '
                             'line numbers are indexed at 1')
    parser.add_argument('--indent-size', default=DEFAULT_INDENT_SIZE,
                        type=int, help=argparse.SUPPRESS)
    parser.add_argument('--hang-closing', action='store_true',
                        help='hang-closing option passed to pycodestyle')
    parser.add_argument('--exit-code', action='store_true',
                        help='change to behavior of exit code.'
                             ' default behavior of return value, 0 is no '
                             'differences, 1 is error exit. return 2 when'
                             ' add this option. 2 is exists differences.')
    parser.add_argument('files', nargs='*',
                        help="files to format or '-' for standard in")

    return parser
180598
def main (args):
  
  if (len(args) != 2):
    print(main.__doc__)
    sys.exit(1);

  # create the document
  doc = libsedml.SedDocument();
  doc.setLevel(1);
  doc.setVersion(3);

  # create a data description
  
  ddesc = doc.createDataDescription()
  ddesc.setId('data1')
  ddesc.setName('Oscli Timecourse data')
  ddesc.setSource('foo.numl')
  
  # create data source 
  dsource = ddesc.createDataSource()
  dsource.setId('dataS1')
  
  # create slice 
  slice = dsource.createSlice()
  slice.setReference('SpeciesIds')
  slice.setValue('S1')
  
  # specify mapping
  timeDesc = libsedml.CompositeDescription()
  timeDesc.setIndexType('double')
  timeDesc.setId('time')
  timeDesc.setName('time')
  
  speciesDesc = timeDesc.createCompositeDescription()
  speciesDesc.setIndexType('string')
  speciesDesc.setId('SpeciesIds')
  speciesDesc.setName('SpeciesIds')
  
  concentrationDesc = speciesDesc.createAtomicDescription()
  concentrationDesc.setValueType("double")
  concentrationDesc.setName("Concentrations")
  
  dimDesc = ddesc.createDimensionDescription()
  dimDesc.append(timeDesc)
  
  # write the document
  libsedml.writeSedML(doc, args[1]);
473038
def generate_results_subparser(subparsers):
    """"""
    parser = subparsers.add_parser(
        'results', description=constants.RESULTS_DESCRIPTION,
        epilog=constants.RESULTS_EPILOG, formatter_class=ParagraphFormatter,
        help=constants.RESULTS_HELP)
    utils.add_common_arguments(parser)
    parser.set_defaults(func=results)
    be_group = parser.add_argument_group('bifurcated extend')
    be_group.add_argument('-b', '--bifurcated-extend',
                          dest='bifurcated_extend', metavar='CORPUS',
                          help=constants.RESULTS_BIFURCATED_EXTEND_HELP)
    be_group.add_argument('--max-be-count', dest='bifurcated_extend_size',
                          help=constants.RESULTS_BIFURCATED_EXTEND_MAX_HELP,
                          metavar='COUNT', type=int)
    parser.add_argument('-e', '--extend', dest='extend',
                        help=constants.RESULTS_EXTEND_HELP, metavar='CORPUS')
    parser.add_argument('--excise', help=constants.RESULTS_EXCISE_HELP,
                        metavar='NGRAM', type=str)
    parser.add_argument('-l', '--label', dest='label',
                        help=constants.RESULTS_LABEL_HELP, metavar='LABEL')
    parser.add_argument('--min-count', dest='min_count',
                        help=constants.RESULTS_MINIMUM_COUNT_HELP,
                        metavar='COUNT', type=int)
    parser.add_argument('--max-count', dest='max_count',
                        help=constants.RESULTS_MAXIMUM_COUNT_HELP,
                        metavar='COUNT', type=int)
    parser.add_argument('--min-count-work', dest='min_count_work',
                        help=constants.RESULTS_MINIMUM_COUNT_WORK_HELP,
                        metavar='COUNT', type=int)
    parser.add_argument('--max-count-work', dest='max_count_work',
                        help=constants.RESULTS_MAXIMUM_COUNT_WORK_HELP,
                        metavar='COUNT', type=int)
    parser.add_argument('--min-size', dest='min_size',
                        help=constants.RESULTS_MINIMUM_SIZE_HELP,
                        metavar='SIZE', type=int)
    parser.add_argument('--max-size', dest='max_size',
                        help=constants.RESULTS_MAXIMUM_SIZE_HELP,
                        metavar='SIZE', type=int)
    parser.add_argument('--min-works', dest='min_works',
                        help=constants.RESULTS_MINIMUM_WORK_HELP,
                        metavar='COUNT', type=int)
    parser.add_argument('--max-works', dest='max_works',
                        help=constants.RESULTS_MAXIMUM_WORK_HELP,
                        metavar='COUNT', type=int)
    parser.add_argument('--ngrams', dest='ngrams',
                        help=constants.RESULTS_NGRAMS_HELP, metavar='NGRAMS')
    parser.add_argument('--reciprocal', action='store_true',
                        help=constants.RESULTS_RECIPROCAL_HELP)
    parser.add_argument('--reduce', action='store_true',
                        help=constants.RESULTS_REDUCE_HELP)
    parser.add_argument('--relabel', help=constants.RESULTS_RELABEL_HELP,
                        metavar='CATALOGUE')
    parser.add_argument('--remove', help=constants.RESULTS_REMOVE_HELP,
                        metavar='LABEL', type=str)
    parser.add_argument('--sort', action='store_true',
                        help=constants.RESULTS_SORT_HELP)
    utils.add_tokenizer_argument(parser)
    parser.add_argument('-z', '--zero-fill', dest='zero_fill',
                        help=constants.RESULTS_ZERO_FILL_HELP,
                        metavar='CORPUS')
    parser.add_argument('results', help=constants.RESULTS_RESULTS_HELP,
                        metavar='RESULTS')
    unsafe_group = parser.add_argument_group(
        constants.RESULTS_UNSAFE_GROUP_TITLE,
        constants.RESULTS_UNSAFE_GROUP_DESCRIPTION)
    unsafe_group.add_argument('--add-label-count', action='store_true',
                              help=constants.RESULTS_ADD_LABEL_COUNT_HELP)
    unsafe_group.add_argument('--add-label-work-count', action='store_true',
                              help=constants.RESULTS_ADD_LABEL_WORK_COUNT_HELP)
    unsafe_group.add_argument('--collapse-witnesses', action='store_true',
                              help=constants.RESULTS_COLLAPSE_WITNESSES_HELP)
    unsafe_group.add_argument('--group-by-ngram', dest='group_by_ngram',
                              help=constants.RESULTS_GROUP_BY_NGRAM_HELP,
                              metavar='CATALOGUE')
    unsafe_group.add_argument('--group-by-witness', action='store_true',
                              help=constants.RESULTS_GROUP_BY_WITNESS_HELP)
1365952
def main():
    """"""

    # Parse command line arguments
    argp = _cli_argument_parser()
    args = argp.parse_args()

    # setup logging
    logging.basicConfig(
        level=args.loglevel,
        format="%(levelname)s %(message)s")

    console.display("Collecting documentation from files")
    collector_metrics = metrics.Metrics()
    docs = collector.parse(args.path, args.trace_parser,
                           metrics=collector_metrics)
    collector_metrics.display()

    console.display("Rendering documentation")

    try:
        if args.output:
            template = renderer.template_from_filename(args.output)
        else:
            template = "json"
        out = renderer.render(docs, template)
    except ValueError as err:
        logging.error(err)
        sys.exit(1)
    except TemplateNotFound as err:
        logging.error(
            "Template `{}` not found. Available templates are: {}".format(
                err.name, renderer.list_templates()))
        sys.exit(1)

    if not args.output:
        print(out)
    else:
        console.display("Writing documentation to", args.output)
        with io.open(args.output, "w", encoding="utf-8") as fp:
            fp.write(out)
1242992
def main(argv=None):
    """"""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('collated_html', type=argparse.FileType('r'),
                        help='Path to the collated html'
                             ' file (use - for stdin)')
    parser.add_argument('-d', '--dump-tree', action='store_true',
                        help='Print out parsed model tree.')

    parser.add_argument('-o', '--output', type=argparse.FileType('w+'),
                        help='Write out epub of parsed tree.')

    parser.add_argument('-i', '--input', type=argparse.FileType('r'),
                        help='Read and copy resources/ for output epub.')

    args = parser.parse_args(argv)

    if args.input and args.output == sys.stdout:
        raise ValueError('Cannot output to stdout if reading resources')

    from cnxepub.collation import reconstitute
    binder = reconstitute(args.collated_html)

    if args.dump_tree:
        print(pformat(cnxepub.model_to_tree(binder)),
              file=sys.stdout)
    if args.output:
        cnxepub.adapters.make_epub(binder, args.output)

    if args.input:
        args.output.seek(0)
        zout = ZipFile(args.output, 'a', ZIP_DEFLATED)
        zin = ZipFile(args.input, 'r')
        for res in zin.namelist():
            if res.startswith('resources'):
                zres = zin.open(res)
                zi = zin.getinfo(res)
                zout.writestr(zi, zres.read(), ZIP_DEFLATED)
        zout.close()

    # TODO Check for documents that have no identifier.
    #      These should likely be composite-documents
    #      or the the metadata got wiped out.
    # docs = [x for x in cnxepub.flatten_to(binder, only_documents_filter)
    #         if x.ident_hash is None]

    return 0
367771
def cli(family_file, family_type, to_json, to_madeline, to_ped, to_dict, 
        outfile, logfile, loglevel):
    """"""
    from pprint import pprint as pp
    
    my_parser = FamilyParser(family_file, family_type)
    
    if to_json:
        if outfile:
            outfile.write(my_parser.to_json())
        else:
            print(my_parser.to_json())
    elif to_madeline:
        for line in my_parser.to_madeline():
            if outfile:
                outfile.write(line + '\n')
            else:
                print(line)
            
    elif to_ped:
        for line in my_parser.to_ped():
            if outfile:
                outfile.write(line + '\n')
            else:
                print(line)
            
    elif to_dict:
        pp(my_parser.to_dict())
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
207650
def ListParsersAndPlugins(self):
    """"""
    parsers_information = parsers_manager.ParsersManager.GetParsersInformation()

    table_view = views.ViewsFactory.GetTableView(
        self._views_format_type, column_names=['Name', 'Description'],
        title='Parsers')

    for name, description in sorted(parsers_information):
      table_view.AddRow([name, description])
    table_view.Write(self._output_writer)

    parser_names = parsers_manager.ParsersManager.GetNamesOfParsersWithPlugins()
    for parser_name in parser_names:
      plugins_information = (
          parsers_manager.ParsersManager.GetParserPluginsInformation(
              parser_filter_expression=parser_name))

      table_title = 'Parser plugins: {0:s}'.format(parser_name)
      table_view = views.ViewsFactory.GetTableView(
          self._views_format_type, column_names=['Name', 'Description'],
          title=table_title)
      for name, description in sorted(plugins_information):
        table_view.AddRow([name, description])
      table_view.Write(self._output_writer)

    title = 'Parser presets'
    if self._presets_file:
      source_path = os.path.dirname(os.path.dirname(os.path.dirname(
          os.path.abspath(__file__))))

      presets_file = self._presets_file
      if presets_file.startswith(source_path):
        presets_file = presets_file[len(source_path) + 1:]

      title = '{0:s} ({1:s})'.format(title, presets_file)

    presets_information = parsers_manager.ParsersManager.GetPresetsInformation()

    table_view = views.ViewsFactory.GetTableView(
        self._views_format_type, column_names=['Name', 'Parsers and plugins'],
        title=title)
    for name, description in sorted(presets_information):
      table_view.AddRow([name, description])
    table_view.Write(self._output_writer)