Entry point for the script
5639
def main():
    """"""

    desc = 'Converts between geodetic, modified apex, quasi-dipole and MLT'
    parser = argparse.ArgumentParser(description=desc, prog='apexpy')

    parser.add_argument('source', metavar='SOURCE',
                        choices=['geo', 'apex', 'qd', 'mlt'],
                        help='Convert from {geo, apex, qd, mlt}')
    parser.add_argument('dest', metavar='DEST',
                        choices=['geo', 'apex', 'qd', 'mlt'],
                        help='Convert to {geo, apex, qd, mlt}')
    desc = 'YYYY[MM[DD[HHMMSS]]] date/time for IGRF coefficients, time part '
    desc += 'required for MLT calculations'
    parser.add_argument('date', metavar='DATE', help=desc)
    parser.add_argument('--height', dest='height', default=0, metavar='HEIGHT',
                        type=float, help='height for conversion')
    parser.add_argument('--refh', dest='refh', metavar='REFH', type=float,
                        default=0,
                        help='reference height for modified apex coordinates')

    parser.add_argument('-i', '--input', dest='file_in', metavar='FILE_IN',
                        type=argparse.FileType('r'), default=STDIN,
                        help='input file (stdin if none specified)')
    parser.add_argument('-o', '--output', dest='file_out', metavar='FILE_OUT',
                        type=argparse.FileType('wb'), default=STDOUT,
                        help='output file (stdout if none specified)')

    args = parser.parse_args()

    array = np.loadtxt(args.file_in, ndmin=2)

    if 'mlt' in [args.source, args.dest] and len(args.date) < 14:
        desc = 'full date/time YYYYMMDDHHMMSS required for MLT calculations'
        raise ValueError(desc)
    if 9 <= len(args.date) <= 13:
        desc = 'full date/time must be given as YYYYMMDDHHMMSS, not ' + \
               'YYYYMMDDHHMMSS'[:len(args.date)]
        raise ValueError(desc)
    datetime = dt.datetime.strptime(args.date,
                                    '%Y%m%d%H%M%S'[:len(args.date)-2])
    A = apexpy.Apex(date=datetime, refh=args.refh)
    lats, lons = A.convert(array[:, 0], array[:, 1], args.source, args.dest,
                           args.height, datetime=datetime)
    np.savetxt(args.file_out, np.column_stack((lats, lons)), fmt='%.8f')
349585
def main(args=None):
    
    parser = ArgumentParser(
        prog='baseline',
        description=DESCRIPTION)

    parser.add_argument(
        'path', nargs='*',
        help='module or directory path')

    parser.add_argument(
        '--movepath', help='location to move script updates')

    parser.add_argument(
        '-w', '--walk', action='store_true',
        help='recursively walk directories')

    args = parser.parse_args(args)

    paths = args.path or ['.']

    paths = [path for pattern in paths for path in glob(pattern)]

    if args.walk:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            for root, _dirs, files in os.walk(dirpath):
                paths += (os.path.join(root, filename) for filename in files)
    else:
        for dirpath in (p for p in paths if os.path.isdir(p)):
            paths += (os.path.join(dirpath, pth) for pth in os.listdir(dirpath))

    update_paths = [
        os.path.relpath(p) for p in paths if p.lower().endswith(UPDATE_EXT)]

    exitcode = 0

    if update_paths:
        script_paths = [pth[:-len(UPDATE_EXT)] + '.py' for pth in update_paths]

        print('Found updates for:')
        for path in script_paths:
            print('  ' + path)
        print()

        if not args.movepath:
            try:
                input('Hit [ENTER] to update, [Ctrl-C] to cancel ')
            except KeyboardInterrupt:
                print()
                print('Update canceled.')
                exitcode = 1
            else:
                print()

        if exitcode == 0:
            for script_path, update_path in zip(script_paths, update_paths):
                if args.movepath:
                    script_path = os.path.join(args.movepath, script_path)
                    if update_path.startswith('..'):
                        raise RuntimeError(
                            'destination outside of move path: ' + script_path)
                    script_dirpath = os.path.dirname(script_path)
                    if not os.path.isdir(script_dirpath):
                        os.makedirs(script_dirpath)
                with open(update_path) as update:
                    new_content = update.read()
                with open(script_path, 'w') as script:
                    script.write(new_content)
                os.remove(update_path)
                print(update_path + ' -> ' + script_path)

    return exitcode
497356
def main():
    
    # Catch the CTRL-C signal
    signal.signal(signal.SIGINT, __signal_handler)

    # Log Glances and psutil version
    logger.info('Start Glances {}'.format(__version__))
    logger.info('{} {} and psutil {} detected'.format(
        platform.python_implementation(),
        platform.python_version(),
        psutil_version))

    # Share global var
    global core

    # Create the Glances main instance
    core = GlancesMain()
    config = core.get_config()
    args = core.get_args()

    # Glances can be ran in standalone, client or server mode
    start(config=config, args=args)
919176
def main(
    output_file: str,
    entry_point: Optional[str],
    console_script: Optional[str],
    python: Optional[str],
    site_packages: Optional[str],
    compressed: bool,
    compile_pyc: bool,
    extend_pythonpath: bool,
    pip_args: List[str],
) -> None:
    

    if not pip_args and not site_packages:
        sys.exit(NO_PIP_ARGS_OR_SITE_PACKAGES)

    if output_file is None:
        sys.exit(NO_OUTFILE)

    # check for disallowed pip arguments
    for disallowed in DISALLOWED_ARGS:
        for supplied_arg in pip_args:
            if supplied_arg in disallowed:
                sys.exit(
                    DISALLOWED_PIP_ARGS.format(
                        arg=supplied_arg, reason=DISALLOWED_ARGS[disallowed]
                    )
                )

    with TemporaryDirectory() as working_path:
        tmp_site_packages = Path(working_path, "site-packages")

        if site_packages:
            shutil.copytree(site_packages, tmp_site_packages)

        if pip_args:
            # install deps into staged site-packages
            pip.install(["--target", str(tmp_site_packages)] + list(pip_args))

        # if entry_point is a console script, get the callable
        if entry_point is None and console_script is not None:
            try:
                entry_point = find_entry_point(tmp_site_packages, console_script)

            except KeyError:
                if not Path(tmp_site_packages, "bin", console_script).exists():
                    sys.exit(NO_ENTRY_POINT.format(entry_point=console_script))

        # create runtime environment metadata
        env = Environment(
            build_id=str(uuid.uuid4()),
            entry_point=entry_point,
            script=console_script,
            compile_pyc=compile_pyc,
            extend_pythonpath=extend_pythonpath,
        )

        Path(working_path, "environment.json").write_text(env.to_json())

        # create bootstrapping directory in working path
        bootstrap_target = Path(working_path, "_bootstrap")
        bootstrap_target.mkdir(parents=True, exist_ok=True)

        # copy bootstrap code
        copy_bootstrap(bootstrap_target)

        # create the zip
        builder.create_archive(
            Path(working_path),
            target=Path(output_file).expanduser(),
            interpreter=python or _interpreter_path(),
            main="_bootstrap:bootstrap",
            compressed=compressed,
        )
995485
def main():
    """"""
    # check logging
    log_level = os.environ.get('LOG_LEVEL', 'INFO')
    logging.basicConfig(level=getattr(logging, log_level),
                        format='%(asctime)s %(name)s[%(levelname)s] %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')

    current_path = os.path.abspath('.')
    if current_path not in sys.path:
        sys.path.insert(0, current_path)
    argcomplete.autocomplete(ARG_PARSER)
    args = ARG_PARSER.parse_args()
    args.func(args)
267010
def run(entry_point, drivers, loop = None):
    ''' 
    '''
    program = setup(entry_point, drivers)
    dispose = program.run()
    if loop == None:
        loop = asyncio.get_event_loop()

    loop.run_forever()
    dispose()
388255
def main():
    """"""
    args = docopt(__doc__, version=__version__, options_first=True)

    # Validate args.
    s = Schema({
        six.text_type: bool,
        '--config-file': Or(None, str),
        '<args>': list,
        '<command>': Or(str, lambda _: 'help'),
    })
    try:
        args = s.validate(args)
    except SchemaError as exc:
        print('{0}\n{1}'.format(str(exc), printable_usage(__doc__)), file=sys.stderr)
        sys.exit(1)

    # Get subcommand.
    cmd = args['<command>']
    if cmd in cmd_aliases:
        cmd = cmd_aliases[cmd]

    if (cmd == 'help') or (not cmd):
        if not args['<args>']:
            sys.exit(print(__doc__.strip(), file=sys.stderr))
        else:
            ia_module = load_ia_module(args['<args>'][0])
            sys.exit(print(ia_module.__doc__.strip(), file=sys.stderr))

    if cmd != 'configure' and args['--config-file']:
        if not os.path.isfile(args['--config-file']):
            print('--config-file should be a readable file.\n{0}'.format(
                printable_usage(__doc__)), file=sys.stderr)
            sys.exit(1)

    argv = [cmd] + args['<args>']

    config = dict()
    if args['--log']:
        config['logging'] = {'level': 'INFO'}
    elif args['--debug']:
        config['logging'] = {'level': 'DEBUG'}

    if args['--insecure']:
        config['general'] = dict(secure=False)

    session = get_session(config_file=args['--config-file'],
                          config=config,
                          debug=args['--debug'])

    ia_module = load_ia_module(cmd)
    try:
        sys.exit(ia_module.main(argv, session))
    except IOError as e:
        # Handle Broken Pipe errors.
        if e.errno == errno.EPIPE:
            sys.stderr.close()
            sys.stdout.close()
            sys.exit(0)
        else:
            raise
380656
def main(argv=None):
  
  try:
    _name_of_script, filepath = argv
  except ValueError:
    raise ValueError(argv)
  print_accuracies(filepath=filepath, test_start=FLAGS.test_start,
                   test_end=FLAGS.test_end, which_set=FLAGS.which_set,
                   nb_iter=FLAGS.nb_iter, base_eps_iter=FLAGS.base_eps_iter,
                   batch_size=FLAGS.batch_size)
41569
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=True,
        projectName="sloancone",
        tunnel=False
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # 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,))

    # set options interactively if user requests
    if "interactiveFlag" in locals() and interactiveFlag:

        # load previous settings
        moduleDirectory = os.path.dirname(__file__) + "/resources"
        pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
        try:
            with open(pathToPickleFile):
                pass
            previousSettingsExist = True
        except:
            previousSettingsExist = False
        previousSettings = {}
        if previousSettingsExist:
            previousSettings = pickle.load(open(pathToPickleFile, "rb"))

        # x-raw-input
        # x-boolean-raw-input
        # x-raw-input-with-default-value-from-previous-settings

        # save the most recently used requests
        pickleMeObjects = []
        pickleMe = {}
        theseLocals = locals()
        for k in pickleMeObjects:
            pickleMe[k] = theseLocals[k]
        pickle.dump(pickleMe, open(pathToPickleFile, "wb"))

    # CALL FUNCTIONS/OBJECTS

    # call the worker function
    if search:
        cs = cone_search(
            log=log,
            ra=ra,
            dec=dec,
            searchRadius=float(arcsecRadius),
            nearest=nearestFlag,
            outputFormat=outputFormat,
            galaxyType=galaxyType
        )
        results = cs.get()
        print results

    # covered = True | False | 999 (i.e. not sure)
    if covered:
        check = check_coverage(
            log=log,
            ra=ra,
            dec=dec
        ).get()
        print check

    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
1187975
def main():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument('input',
                        metavar='INPUT',
                        help='Input directory with PNG files')
    parser.add_argument('output', nargs='?',
                        metavar='OUTPUT',
                        help='Output directory')
    parser.add_argument('--apikey',
                        metavar='APIKEY',
                        default=find_apikey(),
                        help='TinyPNG API Key')

    args = parser.parse_args()
    _main(args)
880220
def main():
    

    metator_args = sys.argv[1:]
    entry_point = pkg_resources.resource_filename("metator", "bin/metator.sh")

    try:
        metator_process = subprocess.Popen((entry_point, *metator_args))
    except PermissionError:  # some issues occured for non-bash users
        metator_process = subprocess.Popen(
            (entry_point, *metator_args), shell=True
        )
    metator_process.wait()
821635
def main():
    

    # Parse arguments and configure application instance.
    arguments, parser = parse_arguments()

    # Start iterating
    store = RevisionStore()
    sys.stdout.write("Iterating over %d items.\n" % arguments.number)

    for i in xrange(arguments.number):
        key = chr(65 + (i % 26))
        value = [key * (i % 26), key * (i % 13), key * (i % 5)]

        store.add(key, value)

    # Wait for an enter
    if arguments.pause:
        sys.stdout.write("Done!")
        sys.stdin.readline()
578858
def IPYTHON_MAIN():
    """"""
    import pkg_resources

    runner_frame = inspect.getouterframes(inspect.currentframe())[-2]
    return (
        getattr(runner_frame, "function", None)
        == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__
    )
527635
def main():
    
    # Define Parser object and add to toil
    parser = build_parser()
    Job.Runner.addToilOptions(parser)
    args = parser.parse_args()
    # Store inputs from argparse
    inputs = {'sra': args.sra,
              'dbgap_key': args.dbgap_key,
              'ssec': args.ssec,
              's3_dir': args.s3_dir,
              'single_end': args.single_end,
              'sudo': args.sudo}
    # Sanity checks
    if args.ssec:
        assert os.path.isfile(args.ssec)
    if args.sra:
        assert os.path.isfile(args.sra)
    if args.dbgap_key:
        assert os.path.isfile(args.dbgap_key)
    # Start Pipeline
    Job.Runner.startToil(Job.wrapJobFn(start_batch, inputs), args)
1180539
def main():
    
    args = _parse_args()
    _init_logging(args.verbose)
    client = _from_args(args)
    client.submit_error(args.description, args.extra,
                        default_message=args.default_message)
1196888
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="transientNamer"
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # 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,))

    if search or new or cone:
        if ra:
            tns = transientNamer.search(
                log=log,
                ra=ra,
                dec=dec,
                radiusArcsec=arcsecRadius,
                comments=withCommentsFlag
            )
        if name:
            tns = transientNamer.search(
                log=log,
                name=name,
                comments=withCommentsFlag
            )
        if discInLastDays:
            tns = transientNamer.search(
                log=log,
                discInLastDays=discInLastDays,
                comments=withCommentsFlag
            )

        # Recursively create missing directories
        if outputFlag and not os.path.exists(outputFlag):
            os.makedirs(outputFlag)

        if tableNamePrefix:
            sources, phot, spec, files = tns.mysql(
                tableNamePrefix=tableNamePrefix, dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 1
        elif not render or render == "table":
            sources, phot, spec, files = tns.table(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 4
        elif render == "csv":
            sources, phot, spec, files = tns.csv(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 1
        elif render == "json":
            sources, phot, spec, files = tns.json(dirPath=outputFlag)
            numSources = len(sources.split("{")) - 1
        elif render == "yaml":
            sources, phot, spec, files = tns.yaml(dirPath=outputFlag)
            numSources = len(sources.split("\n-"))
        elif render == "markdown":
            sources, phot, spec, files = tns.markdown(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 2

        if numSources == 1:
            print "%(numSources)s transient found" % locals()
        elif numSources > 1:
            print "%(numSources)s transients found" % locals()

        if not outputFlag:
            print "\n# Matched Transients"
            print sources
            print "\n# Transient Photometry"
            print phot
            print "\n# Transient Spectra"
            print spec
            print "\n# Transient Supplementary Files"
            print files
            print "\n# Original TNS Search URL"
            print tns.url
        # CALL FUNCTIONS/OBJECTS

    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
1057468
def main():
    """"""
    import sys

    output = []
    line = sys.stdin.readline()

    while line:
        line = line.strip("\n")
        output.append(transform(line))

        line = sys.stdin.readline()
    output.reverse()
    print("\n".join(output))