Command line usage main function.
195994
def main(argv=None):
    """"""
    if float(sys.version[0:3]) < 2.6:
        print("This script requires Python version 2.6 or better.")
        print("This is Python version %s" % sys.version)
        return 0
    if argv is None:
        argv = sys.argv

    import re
    import optparse

    search_doc = lambda r, d: re.search(r, __doc__).group(1) if __doc__ else d
    parser = optparse.OptionParser(
        usage="usage: %prog [options] path",
        description=search_doc("\n\n([^|]*?)\n\n", ''),
        version="%%prog %s" % search_doc(":Version: (.*)", "Unknown"))
    opt = parser.add_option
    opt('-p', '--page', dest='page', type='int', default=-1,
        help="display single page")
    opt('-s', '--series', dest='series', type='int', default=-1,
        help="display series of pages of same shape")
    opt('--noplot', dest='noplot', action='store_true', default=False,
        help="don't display images")
    opt('--interpol', dest='interpol', metavar='INTERPOL', default='bilinear',
        help="image interpolation method")
    opt('--dpi', dest='dpi', type='int', default=96,
        help="set plot resolution")
    opt('--debug', dest='debug', action='store_true', default=False,
        help="raise exception on failures")
    opt('--test', dest='test', action='store_true', default=False,
        help="try read all images in path")
    opt('--doctest', dest='doctest', action='store_true', default=False,
        help="runs the internal tests")
    opt('-v', '--verbose', dest='verbose', action='store_true', default=True)
    opt('-q', '--quiet', dest='verbose', action='store_false')

    settings, path = parser.parse_args()
    path = ' '.join(path)

    if settings.doctest:
        import doctest
        doctest.testmod()
        return 0
    if not path:
        parser.error("No file specified")
    if settings.test:
        test_tifffile(path, settings.verbose)
        return 0

    print("Reading file structure...", end=' ')
    start = time.time()
    try:
        tif = TIFFfile(path)
    except Exception as e:
        if settings.debug:
            raise
        else:
            print("\n", e)
            sys.exit(0)
    print("%.3f ms" % ((time.time()-start) * 1e3))

    if tif.is_ome:
        settings.norgb = True

    images = [(None, tif[0 if settings.page < 0 else settings.page])]
    if not settings.noplot:
        print("Reading image data... ", end=' ')
        notnone = lambda x: next(i for i in x if i is not None)
        start = time.time()
        try:
            if settings.page >= 0:
                images = [(tif.asarray(key=settings.page),
                           tif[settings.page])]
            elif settings.series >= 0:
                images = [(tif.asarray(series=settings.series),
                           notnone(tif.series[settings.series].pages))]
            else:
                images = []
                for i, s in enumerate(tif.series):
                    try:
                        images.append(
                            (tif.asarray(series=i), notnone(s.pages)))
                    except ValueError as e:
                        images.append((None, notnone(s.pages)))
                        if settings.debug:
                            raise
                        else:
                            print("\n* series %i failed: %s... " % (i, e),
                                  end='')
            print("%.3f ms" % ((time.time()-start) * 1e3))
        except Exception as e:
            if settings.debug:
                raise
            else:
                print(e)
    tif.close()

    print("\nTIFF file:", tif)
    print()
    for i, s in enumerate(tif.series):
        print ("Series %i" % i)
        print(s)
        print()
    for i, page in images:
        print(page)
        print(page.tags)
        if page.is_palette:
            print("\nColor Map:", page.color_map.shape, page.color_map.dtype)
        for attr in ('cz_lsm_info', 'cz_lsm_scan_information',
                     'mm_uic_tags', 'mm_header', 'nih_image_header'):
            if hasattr(page, attr):
                print("", attr.upper(), Record(getattr(page, attr)), sep="\n")
        print()

    if images and not settings.noplot:
        try:
            import matplotlib
            matplotlib.use('TkAgg')
            from matplotlib import pyplot
        except ImportError as e:
            warnings.warn("failed to import matplotlib.\n%s" % e)
        else:
            for img, page in images:
                if img is None:
                    continue
                vmin, vmax = None, None
                if page.is_stk:
                    try:
                        vmin = page.mm_uic_tags['min_scale']
                        vmax = page.mm_uic_tags['max_scale']
                    except KeyError:
                        pass
                    else:
                        if vmax <= vmin:
                            vmin, vmax = None, None
                title = "%s\n %s" % (str(tif), str(page))
                imshow(img, title=title, vmin=vmin, vmax=vmax,
                       bitspersample=page.bits_per_sample,
                       photometric=page.photometric,
                       interpolation=settings.interpol,
                       dpi=settings.dpi)
            pyplot.show()
171119
def main():
    """""""
    parser = argparse.ArgumentParser(description='Do something awesome')
    parser.add_argument('input_file', nargs=1,
                        type=argparse.FileType('r'))
    parser.add_argument('-o', '--outfile', nargs='?',
                        type=argparse.FileType('w'), default=sys.stdout)
    args = parser.parse_args()

    print(json_to_csv(args.input_file[0].read()), file=args.outfile)
263115
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="tastic"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if varname == "import":
            varname = "iimport"
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/tastic/tastic.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    # CALL FUNCTIONS/OBJECTS
    if sort or archive:

        ws = workspace(
            log=log,
            settings=settings,
            fileOrWorkspacePath=pathToFileOrWorkspace
        )
    if sort:
        ws.sort()
    if archive:
        ws.archive_done()

    if sync:
        tp = syncc(
            log=log,
            settings=settings,
            workspaceRoot=pathToWorkspace,
            workspaceName=workspaceName,
            syncFolder=pathToSyncFolder,
            editorialRootPath=editorialRootPath,
            includeFileTags=fileTagsFlag
        )
        tp.sync()

    if reminders:
        r = reminderss(
            log=log,
            settings=settings
        )
        r.import_list(
            listName=listName,
            pathToTaskpaperDoc=pathToTaskpaperDoc
        )

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
222250
def main(argv=None):
    """"""
    if argv is None:
        argv = sys.argv[1:]
    usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:])
    version = 'Nosey ' + __version__

    # Parse options
    args = docopt(usage, argv=argv, version=version)

    # Execute
    return watch(args['<directory>'], args['--clear'])
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)
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
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
51146
def main(argv=None):
  """"""

  if argv is None:
    argv = sys.argv

  try:
    opts, args = getopt.getopt(argv[1:], 'h', ['help'])
  except getopt.error as msg:
    raise Usage(msg)

  for opt, _ in opts:
    if opt in ('-h', '--help'):
      print(__doc__)
      print(help_msg)
      return 0

  if not args or len(args) > 4:
    raise Usage('Invalid arguments.')

  # If we have an argument, parse content of file and display as a template.
  # Template displayed will match input template, minus any comment lines.
  with open(args[0], 'r') as template:
    fsm = TextFSM(template)
    print('FSM Template:\n%s\n' % fsm)

    if len(args) > 1:
      # Second argument is file with example cli input.
      # Prints parsed tabular result.
      with open(args[1], 'r') as f:
        cli_input = f.read()

      table = fsm.ParseText(cli_input)
      print('FSM Table:')
      result = str(fsm.header) + '\n'
      for line in table:
        result += str(line) + '\n'
      print(result, end='')

  if len(args) > 2:
    # Compare tabular result with data in third file argument.
    # Exit value indicates if processed data matched expected result.
    with open(args[2], 'r') as f:
      ref_table = f.read()

    if ref_table != result:
      print('Data mis-match!')
      return 1
    else:
      print('Data match!')
361262
def main():
    
    command = Command.lookup(args.get(0))

    if len(args) == 0 or args.contains(('-h', '--help', 'help')):
        display_info(args)
        sys.exit(1)

    elif args.contains(('-v', '--version')):
        display_version()
        sys.exit(1)

    elif command:
        arg = args.get(0)
        args.remove(arg)
        command.__call__(command, args)
        sys.exit()

    else:
        show_error(colored.red('Error! Unknown command \'{0}\'.\n'
                               .format(args.get(0))))
        display_info(args)
        sys.exit(1)
973339
def main(argv=None):
    """"""
    parser = argparse.ArgumentParser(description="Parser benchmark")

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

    args = parser.parse_args(argv)
    run(args)
1096410
def main(argv, stdin, stdout):
    """"""
    if len(argv) > 1 and argv[1:3] == ["compile", "markov"]:
        algo = load_markov(argv, stdin)
        print(algo.compile(), file=stdout)
    elif len(argv) == 4 and argv[1:3] == ["run", "markov"]:
        algo = load_markov(argv, stdin)
        for line in stdin:
            print(algo.execute(''.join(line.split())), file=stdout)

    elif len(argv) > 1 and argv[1:3] == ["compile", "turing"]:
        machine = load_turing(argv, stdin)
        print(machine.compile(), file=stdout)
    elif len(argv) == 4 and argv[1:3] == ["run", "turing"]:
        machine = load_turing(argv, stdin)
        for line in stdin:
            print(machine.execute(line), file=stdout)

    elif len(argv) == 2 and argv[1] == "test":
        path = os.path.abspath(os.path.dirname(__file__))
        argv[1] = path
        pytest.main()
    elif len(argv) == 2 and argv[1] == "version":
        print("TuringMarkov", VERSION, file=stdout)

    else:
        print(USAGE, file=stdout)
        if not (len(argv) == 2 and argv[1] == "help"):
            exit(1)
553309
def main():
    
    args = parser.parse_args()
    try:
        function = args.func
    except AttributeError:
        parser.print_usage()
        parser.exit(1)
    function(vars(args))
358973
def main(argv=None):
  """"""

  if argv is None:
    argv = sys.argv

  try:
    opts, args = getopt.getopt(argv[1:], 'dhs', ['nodelay', 'help', 'size'])
  except getopt.error as msg:
    raise Usage(msg)

  # Print usage and return, regardless of presence of other args.
  for opt, _ in opts:
    if opt in ('-h', '--help'):
      print(__doc__)
      print(help_msg)
      return 0

  isdelay = False
  for opt, _ in opts:
    # Prints the size of the terminal and returns.
    # Mutually exclusive to the paging of text and overrides that behaviour.
    if opt in ('-s', '--size'):
      print('Length: %d, Width: %d' % TerminalSize())
      return 0
    elif opt in ('-d', '--delay'):
      isdelay = True
    else:
      raise Usage('Invalid arguments.')

  # Page text supplied in either specified file or stdin.

  if len(args) == 1:
    with open(args[0]) as f:
      fd = f.read()
  else:
    fd = sys.stdin.read()
  Pager(fd, delay=isdelay).Page()
591091
def main():
    
    if len(argv) < 2:
        print 'Usage: %s fst_file [optional: save_file]' % argv[0]
        return
    flex_a = Flexparser()
    mma = flex_a.yyparse(argv[1])
    mma.minimize()
    print mma
    if len(argv) == 3:
        mma.save(argv[2])
974217
def main(argv):
    """"""
    del argv  # Unused
    flags.mark_flag_as_required('load_file')

    run_game(
        load_file=FLAGS.load_file,
        selfplay_dir=FLAGS.selfplay_dir,
        holdout_dir=FLAGS.holdout_dir,
        holdout_pct=FLAGS.holdout_pct,
        sgf_dir=FLAGS.sgf_dir)
317559
def __main():
    '''
    '''
    if len(sys.argv) < 3:
        sys.stderr.write('usage: {0} <detail|list> <system|system+user>\n'.format(sys.argv[0]))
        sys.exit(64)
    user_pkgs = False
    version_only = False
    if six.text_type(sys.argv[1]) == 'list':
        version_only = True
    if six.text_type(sys.argv[2]) == 'system+user':
        user_pkgs = True
    import salt.utils.json
    import timeit

    def run():
        '''
        Main run code, when this module is run directly
        '''
        pkg_list = WinSoftware(user_pkgs=user_pkgs, version_only=version_only)
        print(salt.utils.json.dumps(pkg_list.data, sort_keys=True, indent=4))  # pylint: disable=superfluous-parens
        print('Total: {}'.format(len(pkg_list)))  # pylint: disable=superfluous-parens

    print('Time Taken: {}'.format(timeit.timeit(run, number=1)))
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)