Main interface function for the command line.
191117
def main():
    """"""
    # Setup logging for the command line
    name = os.path.splitext(os.path.basename(__file__))[0]
    logging.basicConfig(
        format="%(asctime)s [%(process)s] %(levelname)s {} - %(message)s".format(name),
        level=logging.INFO)

    # Program arguments
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--edges", metavar="FILENAME", required=True,
                        help="input network edges file in TSV format")
    parser.add_argument("--output-clusters", metavar="FILENAME", required=True,
                        help="output clusters file in JSON format")
    parser.add_argument("--oslom-output", metavar="DIRECTORY", required=True,
                        help="output directory for OSLOM files")
    parser.add_argument("--min-cluster-size", metavar="INTEGER", type=int,
                        default=DEF_MIN_CLUSTER_SIZE,
                        help="minimum cluster size (default: %(default)s)")
    parser.add_argument("--oslom-exec", metavar="EXECUTABLE",
                        default=DEF_OSLOM_EXEC,
                        help="OSLOM executable program to use "
                             "(default: %(default)s)")
    parser.add_argument("oslom_args", metavar="OSLOM_ARG", nargs="*",
                        default=DEF_OSLOM_ARGS,
                        help="argument to pass to OSLOM (don't pass '-f' !) "
                             "(default: %(default)s)")

    # Run OSLOM with parsed arguments
    sys.exit(not run(parser.parse_args()))
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
615208
def main(argv=None):
    """"""

    # If we're invoked directly (runwith ...), we'll get None here.
    if argv is None:
        argv = sys.argv[1:]

    # Parse command-line arguments.
    argv = cli.parse_args(argv)

    # Translate CLI arguments to Popen options.
    options = {}
    for k in ('stdin', 'stdout', 'stderr', 'cwd'):
        v = getattr(argv, k, None)
        if v:
            options[k] = v

    # Start the child process.
    try:
        process = subprocess.Popen(
            argv.command, **options
        )
    except OSError:
        print('Invalid command %r.' % argv.command)
        sys.exit(2)

    # Wait for the child process to complete.
    thread = threading.Thread(target=process.wait)
    thread.start()
    if argv.time_limit is None:
        thread.join()
    else:
        thread.join(argv.time_limit.total_seconds())
    if thread.is_alive() and argv.grace_time:
        process.send_signal(SIGKILL)
        thread.join(argv.grace_time.total_seconds())
    if thread.is_alive():
        process.terminate()
        thread.join()
    status = process.returncode
    assert status is not None

    # Forward exit code.
    return status
679620
def main():
    """"""
    parser = argparse.ArgumentParser()
    group_tcp = parser.add_argument_group('TCP')
    group_tcp.add_argument('--tcp', dest='mode', action='store_const', const=PROP_MODE_TCP, help="Set tcp mode")
    group_tcp.add_argument('--host', dest='hostname', help="Specify hostname", default='')
    group_tcp.add_argument('--port', dest='port', help="Specify port", default=23, type=int)
    group_serial = parser.add_argument_group('Serial')
    group_serial.add_argument('--serial', dest='mode', action='store_const', const=PROP_MODE_SERIAL, help="Set serial mode")
    group_serial.add_argument('--interface', dest='interface', help="Specify interface", default='')
    group_file = parser.add_argument_group('File')
    group_file.add_argument('--file', dest='mode', action='store_const', const=PROP_MODE_FILE, help="Set file mode")
    group_file.add_argument('--name', dest='file', help="Specify file name", default='')
    args = parser.parse_args()

    kwb = KWBEasyfire(args.mode, args.hostname, args.port, args.interface, 0, args.file)
    kwb.run_thread()
    time.sleep(5)
    kwb.stop_thread()
    print(kwb)
467307
def main():
    
    if sys.argv[1:]:  # called with input arguments
        copy(' '.join(sys.argv[1:]))
    elif not sys.stdin.isatty():  # piped in input
        copy(''.join(sys.stdin.readlines()).rstrip('\n'))
    else:  # paste output
        print(paste())
303256
def main():
    """"""
    # Initialize logging to the terminal.
    coloredlogs.install()
    # Prepare for command line argument parsing.
    action = show_matching_entry
    program_opts = dict(exclude_list=[])
    show_opts = dict(filters=[], use_clipboard=is_clipboard_supported())
    verbosity = 0
    # Parse the command line arguments.
    try:
        options, arguments = getopt.gnu_getopt(
            sys.argv[1:],
            "elnp:f:x:vqh",
            ["edit", "list", "no-clipboard", "password-store=", "filter=", "exclude=", "verbose", "quiet", "help"],
        )
        for option, value in options:
            if option in ("-e", "--edit"):
                action = edit_matching_entry
            elif option in ("-l", "--list"):
                action = list_matching_entries
            elif option in ("-n", "--no-clipboard"):
                show_opts["use_clipboard"] = False
            elif option in ("-p", "--password-store"):
                stores = program_opts.setdefault("stores", [])
                stores.append(PasswordStore(directory=value))
            elif option in ("-f", "--filter"):
                show_opts["filters"].append(value)
            elif option in ("-x", "--exclude"):
                program_opts["exclude_list"].append(value)
            elif option in ("-v", "--verbose"):
                coloredlogs.increase_verbosity()
                verbosity += 1
            elif option in ("-q", "--quiet"):
                coloredlogs.decrease_verbosity()
                verbosity -= 1
            elif option in ("-h", "--help"):
                usage(__doc__)
                return
            else:
                raise Exception("Unhandled option! (programming error)")
        if not (arguments or action == list_matching_entries):
            usage(__doc__)
            return
    except Exception as e:
        warning("Error: %s", e)
        sys.exit(1)
    # Execute the requested action.
    try:
        show_opts["quiet"] = verbosity < 0
        kw = show_opts if action == show_matching_entry else {}
        action(QuickPass(**program_opts), arguments, **kw)
    except PasswordStoreError as e:
        # Known issues don't get a traceback.
        logger.error("%s", e)
        sys.exit(1)
    except KeyboardInterrupt:
        # If the user interrupted an interactive prompt they most likely did so
        # intentionally, so there's no point in generating more output here.
        sys.exit(1)
86268
def main(args=None):
    """"""
    if args is None:
        args = sys.argv[1:]

    # Parse command-line
    args = docopt(__doc__, argv=args)

    # Parse arguments
    path, address = resolve(args['<path>'], args['<address>'])
    host, port = split_address(address)

    # Validate arguments
    if address and not (host or port):
        print 'Error: Invalid address', repr(address)
        return

    # Default values
    if path is None:
        path = '.'
    if host is None:
        host = 'localhost'
    if port is None:
        port = 5000

    # Run server
    print ' * Serving %s on http://%s:%s/' % (path, host, port)
1360157
def main():
    """"""

    options, input_file = _parse_options()

    if (options.debug):
        run(input_file, options)
    else:
        try:
            run(input_file, options)
        except Exception as e:
            sys.stderr.write("Error: %s\n" % e)
            sys.exit(1)
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())
366140
def main():
    
    global program, args, ret
    print(os.getcwd())
    ret = 0
    if '--help' in sys.argv or '-h' in sys.argv or len(sys.argv) == 1:
        print(__doc__)
    else:
        program = sys.argv[1]
        args = sys.argv[2:]
        if args:
            ret = subprocess.call([program] + args)
        else:
            ret = subprocess.call([program])
    print('\nProcess terminated with exit code %d' % ret)
    prompt = 'Press ENTER to close this window...'
    if sys.version_info[0] == 3:
        input(prompt)
    else:
        raw_input(prompt)
    sys.exit(ret)
297592
def main(arguments=None):
    
    # setup the command-line util settings

    dev_flag = False

    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="rockAtlas"
    )
    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/rockAtlas/rockAtlas.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 bookkeeping:
        from rockAtlas.bookkeeping import bookkeeper
        bk = bookkeeper(
            log=log,
            settings=settings,
            fullUpdate=fullFlag
        )
        bk.clean_all()

    if astorb:
        from rockAtlas.orbital_elements import astorb
        oe = astorb(
            log=log,
            settings=settings
        )
        oe.refresh()

    if pyephem:

        from rockAtlas.positions import pyephemPositions
        pyeph = pyephemPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        pyeph.get(singleSnapshot=oneFlag)

    if orbfit:
        from rockAtlas.positions import orbfitPositions
        oe = orbfitPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        oe.get(singleExposure=oneFlag)

    if cache:
        from rockAtlas.phot import download
        data = download(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        data.get(days=days)

    if dophot:
        from rockAtlas.phot import dophotMatch
        dp = dophotMatch(
            log=log,
            settings=settings
        )
        dp.get()

    if cycle:
        from rockAtlas.phot import download
        from rockAtlas.positions import pyephemPositions
        from rockAtlas.positions import orbfitPositions
        from rockAtlas.phot import dophotMatch
        from fundamentals.mysql import readquery

        # INITIAL ACTIONS
        # SETUP ALL DATABASE CONNECTIONS
        from rockAtlas import database
        db = database(
            log=log,
            settings=settings
        )
        dbConns, dbVersions = db.connect()
        atlas3DbConn = dbConns["atlas3"]
        atlas4DbConn = dbConns["atlas4"]
        atlasMoversDBConn = dbConns["atlasMovers"]

        while True:

            if dev_flag:
                o = " and dev_flag = 1"
            else:
                o = " "

            sqlQuery = u"""
                select distinct floor(mjd) from (
select mjd from atlas_exposures where dophot_match = 0 %(o)s
union all
select mjd from day_tracker where processed = 0 %(o)s) as a;
            """ % locals()
            rows = readquery(
                log=log,
                sqlQuery=sqlQuery,
                dbConn=atlasMoversDBConn,
                quiet=False
            )

            if len(rows) == 0:
                if dev_flag:
                    print "Processing of the ATLAS development dataset is now complete and up to date"
                else:
                    print "Processing of ATLAS data is now complete and up to date"
                break

            start_time = time.time()

            data = download(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            data.get(days=days)

            print "%d seconds to download ATLAS cache of %s days\n" % (time.time() - start_time, days)
            start_time = time.time()

            pyeph = pyephemPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            pyeph.get()

            print "%d seconds to generate pyephem snapshots\n" % (time.time() - start_time,)
            start_time = time.time()

            oe = orbfitPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            oe.get()

            print "%d seconds to generate orbfit positions\n" % (time.time() - start_time,)
            start_time = time.time()

            dp = dophotMatch(
                log=log,
                settings=settings
            )
            dp.get()

            print "%d seconds to extract dophot measurements\n" % (time.time() - start_time,)
            start_time = time.time()

    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
787223
def main():
    """"""
    options, command = parser()

    # logging
    root_logger = logging.getLogger()
    for log_handler in root_logger.handlers:
        root_logger.removeHandler(log_handler)
    root_logger = None
    numeric_loglevel = getattr(logging, options.debug_level.upper(), None)
    logformat = '%(levelname)s:%(module)s:%(message)s'
    logging.basicConfig(level=numeric_loglevel, filename=options.logfile,
                        filemode='w', format=logformat)

    # locate alot config files
    cpath = options.config
    if options.config is None:
        xdg_dir = get_xdg_env('XDG_CONFIG_HOME',
                              os.path.expanduser('~/.config'))
        alotconfig = os.path.join(xdg_dir, 'alot', 'config')
        if os.path.exists(alotconfig):
            cpath = alotconfig

    try:
        settings.read_config(cpath)
        settings.read_notmuch_config(options.notmuch_config)
    except (ConfigError, OSError, IOError) as e:
        print('Error when parsing a config file. '
              'See log for potential details.')
        sys.exit(e)

    # store options given by config swiches to the settingsManager:
    if options.colour_mode:
        settings.set('colourmode', options.colour_mode)

    # get ourselves a database manager
    indexpath = settings.get_notmuch_setting('database', 'path')
    indexpath = options.mailindex_path or indexpath
    dbman = DBManager(path=indexpath, ro=options.read_only)

    # determine what to do
    if command is None:
        try:
            cmdstring = settings.get('initial_command')
        except CommandParseError as err:
            sys.exit(err)
    elif command.subcommand in _SUBCOMMANDS:
        cmdstring = ' '.join(options.command)

    # set up and start interface
    UI(dbman, cmdstring)

    # run the exit hook
    exit_hook = settings.get_hook('exit')
    if exit_hook is not None:
        exit_hook()
491282
def main(self):
        
        parser = self.init_parser()
        self.args = parser.parse_args()

        if self.args.debug:
            coloredlogs.install(level=logging.DEBUG, fmt=LOG_FORMAT)

        self.work()
1271954
def main(args):
    
    start = time.time()
    output = get(args)
    _safe_exit(start, output)
1142749
def main():
    
    parser = getBasicOptionParser()
    initializeOptions(parser)
    options = parseBasicOptions(parser)
    checkOptions(options, parser)
    config = Config()
    config.setOptions(options)
    jobStore = Toil.resumeJobStore(config.jobStore)
    stats = getStats(jobStore)
    collatedStatsTag = processData(jobStore.config, stats)
    reportData(collatedStatsTag, options)
758653
def main():
    
    configParser = FileParser()
    logging.config.dictConfig(
        configParser.load_from_file(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'settings', 'logging.yml'))
    )
    ApiDoc().main()
1134707
def main():
    
    global args, server_address

    # parse the command line arguments
    parser = ArgumentParser(description=__doc__)
    parser.add_argument(
        "host", nargs='?',
        help="address of host (default %r)" % (SERVER_HOST,),
        default=SERVER_HOST,
        )
    parser.add_argument(
        "port", nargs='?', type=int,
        help="server port (default %r)" % (SERVER_PORT,),
        default=SERVER_PORT,
        )
    parser.add_argument(
        "--hello", action="store_true",
        default=False,
        help="send a hello message",
        )
    parser.add_argument(
        "--connect-timeout", nargs='?', type=int,
        help="idle connection timeout",
        default=CONNECT_TIMEOUT,
        )
    parser.add_argument(
        "--idle-timeout", nargs='?', type=int,
        help="idle connection timeout",
        default=IDLE_TIMEOUT,
        )
    args = parser.parse_args()

    if _debug: _log.debug("initialization")
    if _debug: _log.debug("    - args: %r", args)

    # extract the server address and port
    host = args.host
    port = args.port
    server_address = (host, port)
    if _debug: _log.debug("    - server_address: %r", server_address)

    # build the stack
    this_console = ConsoleClient()
    if _debug: _log.debug("    - this_console: %r", this_console)

    this_middle_man = MiddleMan()
    if _debug: _log.debug("    - this_middle_man: %r", this_middle_man)

    this_director = TCPClientDirector(
        connect_timeout=args.connect_timeout,
        idle_timeout=args.idle_timeout,
        )
    if _debug: _log.debug("    - this_director: %r", this_director)

    bind(this_console, this_middle_man, this_director)
    bind(MiddleManASE(), this_director)

    # create a task manager for scheduled functions
    task_manager = TaskManager()
    if _debug: _log.debug("    - task_manager: %r", task_manager)

    # don't wait to connect
    deferred(this_director.connect, server_address)

    # send hello maybe
    if args.hello:
        deferred(this_middle_man.indication, PDU(b'Hello, world!\n'))

    if _debug: _log.debug("running")

    run()

    if _debug: _log.debug("fini")