Parse command line arguments and start main script for analysis.
977411
def main_init():
    """"""
    parser = ArgumentParser(prog="PLIP", description=descript)
    pdbstructure = parser.add_mutually_exclusive_group(required=True)  # Needs either PDB ID or file
    # '-' as file name reads from stdin
    pdbstructure.add_argument("-f", "--file", dest="input", nargs="+", help="Set input file, '-' reads from stdin")
    pdbstructure.add_argument("-i", "--input", dest="pdbid", nargs="+")
    outputgroup = parser.add_mutually_exclusive_group(required=False)  # Needs either outpath or stdout
    outputgroup.add_argument("-o", "--out", dest="outpath", default="./")
    outputgroup.add_argument("-O", "--stdout", dest="stdout", action="store_true", default=False, help="Write to stdout instead of file")
    parser.add_argument("--rawstring", dest="use_raw_string", default=False, action="store_true", help="Use Python raw strings for stdout and stdin")
    parser.add_argument("-v", "--verbose", dest="verbose", default=False, help="Set verbose mode", action="store_true")
    parser.add_argument("-p", "--pics", dest="pics", default=False, help="Additional pictures", action="store_true")
    parser.add_argument("-x", "--xml", dest="xml", default=False, help="Generate report file in XML format",
                        action="store_true")
    parser.add_argument("-t", "--txt", dest="txt", default=False, help="Generate report file in TXT (RST) format",
                        action="store_true")
    parser.add_argument("-y", "--pymol", dest="pymol", default=False, help="Additional PyMOL session files",
                        action="store_true")
    parser.add_argument("--maxthreads", dest="maxthreads", default=multiprocessing.cpu_count(),
                        help="Set maximum number of main threads (number of binding sites processed simultaneously)."
                             "If not set, PLIP uses all available CPUs if possible.",
                        type=int)
    parser.add_argument("--breakcomposite", dest="breakcomposite", default=False,
                        help="Don't combine ligand fragments with covalent bonds but treat them as single ligands for the analysis.",
                        action="store_true")
    parser.add_argument("--altlocation", dest="altlocation", default=False,
                        help="Also consider alternate locations for atoms (e.g. alternate conformations).",
                        action="store_true")
    parser.add_argument("--debug", dest="debug", default=False,
                        help="Turn on DEBUG mode with extended log.",
                        action="store_true")
    parser.add_argument("--nofix", dest="nofix", default=False,
                        help="Turns off fixing of PDB files.",
                        action="store_true")
    parser.add_argument("--nofixfile", dest="nofixfile", default=False,
                        help="Turns off writing files for fixed PDB files.",
                        action="store_true")
    parser.add_argument("--nopdbcanmap", dest="nopdbcanmap", default=False,
                        help="Turns off calculation of mapping between canonical and PDB atom order for ligands.",
                        action="store_true")
    parser.add_argument("--dnareceptor", dest="dnareceptor", default=False,
                        help="Uses the DNA instead of the protein as a receptor for interactions.",
                        action="store_true")
    parser.add_argument("--name", dest="outputfilename", default="report",
                        help="Set a filename for the report TXT and XML files. Will only work when processing single structures.")
    ligandtype = parser.add_mutually_exclusive_group()  # Either peptide/inter or intra mode
    ligandtype.add_argument("--peptides", "--inter", dest="peptides", default=[],
                        help="Allows to define one or multiple chains as peptide ligands or to detect inter-chain contacts",
                        nargs="+")
    ligandtype.add_argument("--intra", dest="intra", help="Allows to define one chain to analyze intra-chain contacts.")
    parser.add_argument("--keepmod", dest="keepmod", default=False,
                        help="Keep modified residues as ligands",
                        action="store_true")
    # Optional threshold arguments, not shown in help
    thr = namedtuple('threshold', 'name type')
    thresholds = [thr(name='aromatic_planarity', type='angle'),
                  thr(name='hydroph_dist_max', type='distance'), thr(name='hbond_dist_max', type='distance'),
                  thr(name='hbond_don_angle_min', type='angle'), thr(name='pistack_dist_max', type='distance'),
                  thr(name='pistack_ang_dev', type='other'), thr(name='pistack_offset_max', type='distance'),
                  thr(name='pication_dist_max', type='distance'), thr(name='saltbridge_dist_max', type='distance'),
                  thr(name='halogen_dist_max', type='distance'), thr(name='halogen_acc_angle', type='angle'),
                  thr(name='halogen_don_angle', type='angle'), thr(name='halogen_angle_dev', type='other'),
                  thr(name='water_bridge_mindist', type='distance'), thr(name='water_bridge_maxdist', type='distance'),
                  thr(name='water_bridge_omega_min', type='angle'), thr(name='water_bridge_omega_max', type='angle'),
                  thr(name='water_bridge_theta_min', type='angle')]
    for t in thresholds:
        parser.add_argument('--%s' % t.name, dest=t.name, type=lambda val: threshold_limiter(parser, val),
                            help=argparse.SUPPRESS)

    arguments = parser.parse_args()
    config.VERBOSE = True if (arguments.verbose or arguments.debug) else False
    config.DEBUG = True if arguments.debug else False
    config.MAXTHREADS = arguments.maxthreads
    config.XML = arguments.xml
    config.TXT = arguments.txt
    config.PICS = arguments.pics
    config.PYMOL = arguments.pymol
    config.STDOUT = arguments.stdout
    config.RAWSTRING = arguments.use_raw_string
    config.OUTPATH = arguments.outpath
    config.OUTPATH = tilde_expansion("".join([config.OUTPATH, '/'])
                                     if not config.OUTPATH.endswith('/') else config.OUTPATH)
    config.BASEPATH = config.OUTPATH  # Used for batch processing
    config.BREAKCOMPOSITE = arguments.breakcomposite
    config.ALTLOC = arguments.altlocation
    config.PEPTIDES = arguments.peptides
    config.INTRA = arguments.intra
    config.NOFIX = arguments.nofix
    config.NOFIXFILE = arguments.nofixfile
    config.NOPDBCANMAP = arguments.nopdbcanmap
    config.KEEPMOD = arguments.keepmod
    config.DNARECEPTOR = arguments.dnareceptor
    config.OUTPUTFILENAME = arguments.outputfilename
    # Make sure we have pymol with --pics and --pymol
    if config.PICS or config.PYMOL:
        try:
            import pymol
        except ImportError:
            write_message("PyMOL is required for --pics and --pymol.\n", mtype='error')
            raise
    # Assign values to global thresholds
    for t in thresholds:
        tvalue = getattr(arguments, t.name)
        if tvalue is not None:
            if t.type == 'angle' and not 0 < tvalue < 180:  # Check value for angle thresholds
                parser.error("Threshold for angles need to have values within 0 and 180.")
            if t.type == 'distance':
                if tvalue > 10:  # Check value for angle thresholds
                    parser.error("Threshold for distances must not be larger than 10 Angstrom.")
                elif tvalue > config.BS_DIST + 1:  # Dynamically adapt the search space for binding site residues
                    config.BS_DIST = tvalue + 1
            setattr(config, t.name.upper(), tvalue)
    # Check additional conditions for interdependent thresholds
    if not config.HALOGEN_ACC_ANGLE > config.HALOGEN_ANGLE_DEV:
        parser.error("The halogen acceptor angle has to be larger than the halogen angle deviation.")
    if not config.HALOGEN_DON_ANGLE > config.HALOGEN_ANGLE_DEV:
        parser.error("The halogen donor angle has to be larger than the halogen angle deviation.")
    if not config.WATER_BRIDGE_MINDIST < config.WATER_BRIDGE_MAXDIST:
        parser.error("The water bridge minimum distance has to be smaller than the water bridge maximum distance.")
    if not config.WATER_BRIDGE_OMEGA_MIN < config.WATER_BRIDGE_OMEGA_MAX:
        parser.error("The water bridge omega minimum angle has to be smaller than the water bridge omega maximum angle")
    expanded_path = tilde_expansion(arguments.input) if arguments.input is not None else None
    main(expanded_path, arguments.pdbid)
237096
def main():
    """"""
    import getopt
    from . import __version__ as VERSION

    try:
        option_list, argument_list = getopt.gnu_getopt(
            sys.argv[1:], 'h',
            ['version', 'help', 'json-module=', 'debug', 'log-file='])

        message = None
        for option, value in option_list:
            if option in ('--version'):
                message = _VERSION % dict(name=os.path.basename(sys.argv[0]),
                                      version=VERSION)
            elif option in ('-h', '--help'):
                message = _HELP % dict(name=os.path.basename(sys.argv[0]))
            elif option in ('--json-module'):
                json.use(module=value)
            elif option in ('--debug'):
                log.setLevel(logging.DEBUG)
            elif option in ('--log-file'):
                if value == '-':
                    handler = logging.StreamHandler(sys.stderr)
                    handler.setFormatter(logging.Formatter(
                        ' -> [%(levelname)s] %(message)s'))
                else:
                    handler = logging.FileHandler(value)
                    handler.setFormatter(logging.Formatter(
                        '[%(asctime)s] [%(levelname)s] %(message)s'))
                log.addHandler(handler)
        if message:
            sys.stdout.write(message)
            sys.stdout.flush()
            sys.exit(0)

    except getopt.GetoptError, error:
        message = '%s\n\nTry `%s --help` for more information.\n' % (
            str(error), os.path.basename(sys.argv[0]))
        sys.stderr.write(message)
        sys.stderr.flush()
        sys.exit(1)

    sys.exit(run())
105738
def main():
    """"""
    # Dynamically determine all the providers available and gather command line arguments.
    parsed_args = generate_cli_main_parser().parse_args()

    log_level = logging.getLevelName(parsed_args.log_level)
    logging.basicConfig(stream=sys.stdout, level=log_level,
                        format='%(message)s')
    logger.debug('Arguments: %s', parsed_args)

    # In the CLI context, will get configuration interactively:
    #   * from the command line
    #   * from the environment variables
    #   * from lexicon configuration files found in given --config-dir (default is current dir)
    config = ConfigResolver()
    config.with_args(parsed_args).with_env().with_config_dir(parsed_args.config_dir)

    client = Client(config)

    results = client.execute()

    handle_output(results, parsed_args.output, config.resolve('lexicon:action'))
114393
def main(argv, version=DEFAULT_VERSION):
    """"""
    tarball = download_setuptools()
    _install(tarball, _build_install_args(argv))
1090557
def main():
    ''''''

    import sys
    import argparse

    stdout = buffer(sys.stdout)

    parser = argparse.ArgumentParser(description=main.__doc__)
    parser.add_argument(
        'file',
        metavar='FILE',
        nargs='?',
        type=argparse.FileType('r'),
        default='-')
    parser.add_argument(
        '-d', '--decode', action='store_true', help='decode data')
    parser.add_argument(
        '-c',
        '--check',
        action='store_true',
        help='append a checksum before encoding')

    args = parser.parse_args()
    fun = {
        (False, False): b58encode,
        (False, True): b58encode_check,
        (True, False): b58decode,
        (True, True): b58decode_check
    }[(args.decode, args.check)]

    data = buffer(args.file).read().rstrip(b'\n')

    try:
        result = fun(data)
    except Exception as e:
        sys.exit(e)

    if not isinstance(result, bytes):
        result = result.encode('ascii')

    stdout.write(result)
175671
def cmd_start(self, argv, help):
        """"""
        parser = argparse.ArgumentParser(
            prog="%s start" % self.progname,
            description=help,
        )
        instances = self.get_instances(command='start')
        parser.add_argument("instance", nargs=1,
                            metavar="instance",
                            help="Name of the instance from the config.",
                            choices=sorted(instances))
        parser.add_argument("-o", "--override", nargs="*", type=str,
                            dest="overrides", metavar="OVERRIDE",
                            help="Option to override in instance config for startup script (name=value).")
        args = parser.parse_args(argv)
        overrides = self._parse_overrides(args)
        overrides['instances'] = self.instances
        instance = instances[args.instance[0]]
        instance.hooks.before_start(instance)
        result = instance.start(overrides)
        instance.hooks.after_start(instance)
        if result is None:
            return
        instance.status()
724591
def run_analysis(self, argv):
        """"""
        args = self._parser.parse_args(argv)


        sedfile = args.sed_file

        if is_not_null(args.config):
            configfile = os.path.join(os.path.dirname(sedfile), args.config)
        else:
            configfile = os.path.join(os.path.dirname(sedfile), 'config.yaml')

        nbins = _get_enum_bins(configfile)

        first = args.seed
        last = first + args.nsims
        flist = [sedfile.replace("_SEED.fits", "_%06i.fits" % seed)
                 for seed in range(first, last)]
        outfile = args.outfile
        summaryfile = args.summaryfile


        outtable = fill_output_table(
            flist, "SED", CollectSED.collist, nbins=nbins)

        if is_not_null(outfile):
            outtable.write(outfile)

        if is_not_null(summaryfile):
            summary = summarize_sed_results(outtable)
            summary.write(summaryfile)
118209
def main(argv=None):
    """"""
    parser = ArgumentParser(prog="pygenstub")
    parser.add_argument("--version", action="version", version="%(prog)s " + __version__)
    parser.add_argument("files", nargs="*", help="generate stubs for given files")
    parser.add_argument(
        "-m",
        "--module",
        action="append",
        metavar="MODULE",
        dest="modules",
        default=[],
        help="generate stubs for given modules",
    )
    parser.add_argument(
        "-o", "--output", metavar="PATH", dest="out_dir", help="change the output directory"
    )
    parser.add_argument(
        "--generic", action="store_true", default=False, help="generate generic stubs"
    )
    parser.add_argument("--debug", action="store_true", help="enable debug messages")

    argv = argv if argv is not None else sys.argv
    arguments = parser.parse_args(argv[1:])

    # set debug mode
    if arguments.debug:
        logging.basicConfig(level=logging.DEBUG)
        _logger.debug("running in debug mode")

    out_dir = arguments.out_dir if arguments.out_dir is not None else ""
    if (out_dir == "") and (len(arguments.modules) > 0):
        print("Output directory must be given when generating stubs for modules.")
        sys.exit(1)

    modules = []
    for path in arguments.files:
        paths = Path(path).glob("**/*.py") if Path(path).is_dir() else [Path(path)]
        for source in paths:
            if str(source).startswith(os.path.pardir):
                source = source.absolute().resolve()
            if (out_dir != "") and source.is_absolute():
                source = source.relative_to(source.root)
            destination = Path(out_dir, source.with_suffix(".pyi"))
            modules.append((source, destination))

    for mod_name in arguments.modules:
        modules.extend(get_pkg_paths(mod_name, out_dir))

    for source, destination in modules:
        _logger.info("generating stub for %s to path %s", source, destination)
        with source.open() as f:
            code = f.read()
        try:
            stub = get_stub(code, generic=arguments.generic)
        except Exception as e:
            print(source, "-", e, file=sys.stderr)
            continue

        if stub != "":
            if not destination.parent.exists():
                destination.parent.mkdir(parents=True)
            with destination.open("w") as f:
                f.write("# " + EDIT_WARNING + "\n\n" + stub)
690868
def main():
    """"""
    parser = build_command_parser()
    options = parser.parse_args()
    file_pointer = options.filename
    input_format = options.input_format

    with file_pointer:
        json_data = json.load(file_pointer)

    if input_format == SIMPLE_JSON:
        report = Report(json_data)
    elif input_format == EXTENDED_JSON:
        report = Report(
            json_data.get('messages'),
            json_data.get('stats'),
            json_data.get('previous'))

    print(report.render(), file=options.output)
170187
def main():
    """"""
    parser = argparse.ArgumentParser(description='Compose a yaml file.')
    parser.add_argument(
        'root',
        type=argparse.FileType('r'),
        help='The root yaml file to compose.'
    )

    args = parser.parse_args()

    result = yaml.load(args.root, Loader=ComposeLoader)

    print(yaml.dump(result))
936336
def main(cls):
        """"""
        cmd = cls()
        cmd._parse_args()
        cmd._setup_logging()
        response = cmd._run()
        output = cmd._handle_response(response)
        if output is not None:
            print(output)
160756
def main():
  
  parser = argparse.ArgumentParser(description='A distributed test framework')
  parser.add_argument('testfile',
      help='The file that is used to determine the test suite run')
  parser.add_argument('--test-only',
      nargs='*',
      dest='test_list',
      help='run only the named tests to help debug broken tests')
  parser.add_argument('--machine-list',
      nargs='*',
      dest='machine_list',
      help='''mapping of logical host names to physical names allowing the same
              test suite to run on different hardware, each argument is a pair
              of logical name and physical name separated by a =''')
  parser.add_argument('--config-overrides',
      nargs='*',
      dest='config_overrides',
      help='''config overrides at execution time, each argument is a config with
              its value separated by a =. This has the highest priority of all
              configs''')
  parser.add_argument('-d', '--output-dir',
      dest='output_dir',
      help='''Directory to write output files and logs. Defaults to the current
              directory.''')
  parser.add_argument("--log-level", dest="log_level", help="Log level (default INFO)", default="INFO")
  parser.add_argument("--console-log-level", dest="console_level", help="Console Log level (default ERROR)",
                      default="ERROR")
  parser.add_argument("--nopassword", action='store_true', dest="nopassword", help="Disable password prompt")
  parser.add_argument("--user", dest="user", help="user to run the test as (defaults to current user)")
  args = parser.parse_args()
  try:
    call_main(args)
  except ValueError:
    #We only sys.exit here, as call_main is used as part of a unit test
    #and should not exit the system
    sys.exit(1)
89703
def main(arguments=None):
    

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

    # CALL FUNCTIONS/OBJECTS

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/rockfinder/rockfinder.yaml"
        cmd = """open %(filepath)s""" % locals()
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        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
        return

    if where and orbfitFlag:
        from rockfinder import orbfit_ephemeris
        eph = orbfit_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            settings=settings,
            verbose=extraFlag
        )
    else:
        from rockfinder import jpl_horizons_ephemeris
        eph = jpl_horizons_ephemeris(
            log=log,
            objectId=objectId,
            mjd=mjd,
            obscode=obscode,
            verbose=extraFlag
        )

    dataSet = list_of_dictionaries(
        log=log,
        listOfDictionaries=eph
    )
    # xfundamentals-render-list-of-dictionaries

    output = dataSet.table(filepath=None)
    if csv:
        output = dataSet.csv(filepath=None)
    elif json:
        output = dataSet.json(filepath=None)
    elif yaml:
        output = dataSet.yaml(filepath=None)
    elif md:
        output = dataSet.markdown(filepath=None)
    elif rst:
        output = dataSet.reST(filepath=None)

    print output

    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
1315205
def main(argv=None):
    
    if not argv:
        argv = sys.argv[1:]

    parser = argparse.ArgumentParser(description=_HELP_TEXT)
    parser.add_argument('input', nargs='?', default=None)
    parser.add_argument('output', nargs='?', default=None)
    parser.add_argument('--version', action='version',
                        version='%(prog)s ' + get_version())
    args = parser.parse_args(argv)

    if not args.input:
        print("No file specified", file=sys.stderr)
        sys.exit(1)

    try:
        with open(args.input, 'r') as f:
            res = mangle(f.read())
            if not args.output:
                print(res, end='')
            else:
                with open(args.output, 'w') as o:
                    o.write(res)
    except Exception as ex:
        print("Error mangling {}: {!s}".format(args.input, ex),
              file=sys.stderr)
        sys.exit(1)
334691
def main():
    """"""

    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('source', help="location of the downloaded repos")
    parser.add_argument('destination', help="location of the extracted files")
    parser.add_argument(
        '-t', '--nb-test-files', help="number of testing files per language",
        type=int, default=5000)
    parser.add_argument(
        '-l', '--nb-learn-files', help="number of learning files per language",
        type=int, default=10000)
    parser.add_argument(
        '-r', '--remove', help="remove repos that cannot be read",
        action='store_true', default=False)
    parser.add_argument(
        '-d', '--debug', default=False, action='store_true',
        help="show debug messages")

    args = parser.parse_args()
    config_logging(args.debug)

    source = Path(args.source)
    destination = Path(args.destination)
    nb_test = args.nb_test_files
    nb_learn = args.nb_learn_files
    remove = args.remove

    repos = _find_repos(source)
    split_repos = _split_repos(repos, nb_test, nb_learn)
    split_files = _find_files(*split_repos, nb_test, nb_learn, remove)
    _unzip_all(*split_files, destination)
    LOGGER.info("Files saved into %s", destination)
    LOGGER.debug("Exit OK")
301199
def main(args=sys.argv):
    

    parser = create_optparser(args[0])
    return cli(parser.parse_args(args[1:]))
48024
def main(manual_args=None):
    """"""
    parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.set_defaults(func=parser.print_help)
    add_debug(parser)
    parser.add_argument(
        '-s',
        '--short-log',
        action='store_const',
        const=SHORT_LOGGING_FORMAT,
        default=LOGGING_FORMAT,
        help='Truncated logging format')
    parser.add_argument('-v', '--version', action='store_true', help=print_version.__doc__)

    subparsers = parser.add_subparsers(title='Commands', description='Available activies')

    add_infra(subparsers)
    add_pipeline(subparsers)
    add_rebuild(subparsers)
    add_autoscaling(subparsers)
    add_validate(subparsers)

    CliArgs = collections.namedtuple('CliArgs', ['parsed', 'extra'])

    parsed, extra = parser.parse_known_args(args=manual_args)
    args = CliArgs(parsed, extra)

    logging.basicConfig(format=args.parsed.short_log)

    package, *_ = __package__.split('.')
    logging.getLogger(package).setLevel(args.parsed.debug)

    LOG.debug('Arguments: %s', args)

    if args.parsed.version:
        args.parsed.func = print_version

    try:
        args.parsed.func(args)
    except (AttributeError, TypeError):
        args.parsed.func()