Entry point when executed from command line.
    You can use zxb.py as a module with import, and this
    function won't be executed.
168522
def main(args=None):
    
    api.config.init()
    zxbpp.init()
    zxbparser.init()
    arch.zx48k.backend.init()
    arch.zx48k.Translator.reset()
    asmparse.init()

    # ------------------------------------------------------------
    # Command line parsing
    # ------------------------------------------------------------
    parser = argparse.ArgumentParser(prog='zxb')
    parser.add_argument('PROGRAM', type=str,
                        help='BASIC program file')
    parser.add_argument('-d', '--debug', dest='debug', default=OPTIONS.Debug.value, action='count',
                        help='Enable verbosity/debugging output. Additional -d increase verbosity/debug level')
    parser.add_argument('-O', '--optimize', type=int, default=OPTIONS.optimization.value,
                        help='Sets optimization level. '
                             '0 = None (default level is {0})'.format(OPTIONS.optimization.value))
    parser.add_argument('-o', '--output', type=str, dest='output_file', default=None,
                        help='Sets output file. Default is input filename with .bin extension')
    parser.add_argument('-T', '--tzx', action='store_true',
                        help="Sets output format to tzx (default is .bin)")
    parser.add_argument('-t', '--tap', action='store_true',
                        help="Sets output format to tap (default is .bin)")
    parser.add_argument('-B', '--BASIC', action='store_true', dest='basic',
                        help="Creates a BASIC loader which loads the rest of the CODE. Requires -T ot -t")
    parser.add_argument('-a', '--autorun', action='store_true',
                        help="Sets the program to be run once loaded")
    parser.add_argument('-A', '--asm', action='store_true',
                        help="Sets output format to asm")
    parser.add_argument('-S', '--org', type=str, default=str(OPTIONS.org.value),
                        help="Start of machine code. By default %i" % OPTIONS.org.value)
    parser.add_argument('-e', '--errmsg', type=str, dest='stderr', default=OPTIONS.StdErrFileName.value,
                        help='Error messages file (standard error console by default)')
    parser.add_argument('--array-base', type=int, default=OPTIONS.array_base.value,
                        help='Default lower index for arrays ({0} by default)'.format(OPTIONS.array_base.value))
    parser.add_argument('--string-base', type=int, default=OPTIONS.string_base.value,
                        help='Default lower index for strings ({0} by default)'.format(OPTIONS.array_base.value))
    parser.add_argument('-Z', '--sinclair', action='store_true',
                        help='Enable by default some more original ZX Spectrum Sinclair BASIC features: ATTR, SCREEN$, '
                             'POINT')
    parser.add_argument('-H', '--heap-size', type=int, default=OPTIONS.heap_size.value,
                        help='Sets heap size in bytes (default {0} bytes)'.format(OPTIONS.heap_size.value))
    parser.add_argument('--debug-memory', action='store_true',
                        help='Enables out-of-memory debug')
    parser.add_argument('--debug-array', action='store_true',
                        help='Enables array boundary checking')
    parser.add_argument('--strict-bool', action='store_true',
                        help='Enforce boolean values to be 0 or 1')
    parser.add_argument('--enable-break', action='store_true',
                        help='Enables program execution BREAK detection')
    parser.add_argument('-E', '--emit-backend', action='store_true',
                        help='Emits backend code instead of ASM or binary')
    parser.add_argument('--explicit', action='store_true',
                        help='Requires all variables and functions to be declared before used')
    parser.add_argument('-D', '--define', type=str, dest='defines', action='append',
                        help='Defines de given macro. Eg. -D MYDEBUG or -D NAME=Value')
    parser.add_argument('-M', '--mmap', type=str, dest='memory_map', default=None,
                        help='Generate label memory map')
    parser.add_argument('-i', '--ignore-case', action='store_true',
                        help='Ignore case. Makes variable names are case insensitive')
    parser.add_argument('-I', '--include-path', type=str, default='',
                        help='Add colon separated list of directories to add to include path. e.g. -I dir1:dir2')
    parser.add_argument('--strict', action='store_true',
                        help='Enables strict mode. Force explicit type declaration')
    parser.add_argument('--headerless', action='store_true',
                        help='Header-less mode: omit asm prologue and epilogue')
    parser.add_argument('--version', action='version', version='%(prog)s {0}'.format(VERSION))
    parser.add_argument('--parse-only', action='store_true',
                        help='Only parses to check for syntax and semantic errors')
    parser.add_argument('--append-binary', default=[], action='append',
                        help='Appends binary to tape file (only works with -t or -T)')
    parser.add_argument('--append-headless-binary', default=[], action='append',
                        help='Appends binary to tape file (only works with -t or -T)')

    options = parser.parse_args(args=args)

    # ------------------------------------------------------------
    # Setting of internal parameters according to command line
    # ------------------------------------------------------------

    OPTIONS.Debug.value = options.debug
    OPTIONS.optimization.value = options.optimize
    OPTIONS.outputFileName.value = options.output_file
    OPTIONS.StdErrFileName.value = options.stderr
    OPTIONS.array_base.value = options.array_base
    OPTIONS.string_base.value = options.string_base
    OPTIONS.Sinclair.value = options.sinclair
    OPTIONS.heap_size.value = options.heap_size
    OPTIONS.memoryCheck.value = options.debug_memory
    OPTIONS.strictBool.value = options.strict_bool or OPTIONS.Sinclair.value
    OPTIONS.arrayCheck.value = options.debug_array
    OPTIONS.emitBackend.value = options.emit_backend
    OPTIONS.enableBreak.value = options.enable_break
    OPTIONS.explicit.value = options.explicit
    OPTIONS.memory_map.value = options.memory_map
    OPTIONS.strict.value = options.strict
    OPTIONS.headerless.value = options.headerless

    OPTIONS.org.value = api.utils.parse_int(options.org)
    if OPTIONS.org.value is None:
        parser.error("Invalid --org option '{}'".format(options.org))

    if options.defines:
        for i in options.defines:
            name, val = tuple(i.split('=', 1))
            OPTIONS.__DEFINES.value[name] = val
            zxbpp.ID_TABLE.define(name, lineno=0)

    if OPTIONS.Sinclair.value:
        OPTIONS.array_base.value = 1
        OPTIONS.string_base.value = 1
        OPTIONS.strictBool.value = True
        OPTIONS.case_insensitive.value = True

    if options.ignore_case:
        OPTIONS.case_insensitive.value = True

    debug.ENABLED = OPTIONS.Debug.value

    if int(options.tzx) + int(options.tap) + int(options.asm) + int(options.emit_backend) + \
            int(options.parse_only) > 1:
        parser.error("Options --tap, --tzx, --emit-backend, --parse-only and --asm are mutually exclusive")
        return 3

    if options.basic and not options.tzx and not options.tap:
        parser.error('Option --BASIC and --autorun requires --tzx or tap format')
        return 4

    if options.append_binary and not options.tzx and not options.tap:
        parser.error('Option --append-binary needs either --tap or --tzx')
        return 5

    OPTIONS.use_loader.value = options.basic
    OPTIONS.autorun.value = options.autorun

    if options.tzx:
        OPTIONS.output_file_type.value = 'tzx'
    elif options.tap:
        OPTIONS.output_file_type.value = 'tap'
    elif options.asm:
        OPTIONS.output_file_type.value = 'asm'
    elif options.emit_backend:
        OPTIONS.output_file_type.value = 'ic'

    args = [options.PROGRAM]
    if not os.path.exists(options.PROGRAM):
        parser.error("No such file or directory: '%s'" % args[0])
        return 2

    if OPTIONS.memoryCheck.value:
        OPTIONS.__DEFINES.value['__MEMORY_CHECK__'] = ''
        zxbpp.ID_TABLE.define('__MEMORY_CHECK__', lineno=0)

    if OPTIONS.arrayCheck.value:
        OPTIONS.__DEFINES.value['__CHECK_ARRAY_BOUNDARY__'] = ''
        zxbpp.ID_TABLE.define('__CHECK_ARRAY_BOUNDARY__', lineno=0)

    OPTIONS.include_path.value = options.include_path
    OPTIONS.inputFileName.value = zxbparser.FILENAME = \
        os.path.basename(args[0])

    if not OPTIONS.outputFileName.value:
        OPTIONS.outputFileName.value = \
            os.path.splitext(os.path.basename(OPTIONS.inputFileName.value))[0] + os.path.extsep + \
            OPTIONS.output_file_type.value

    if OPTIONS.StdErrFileName.value:
        OPTIONS.stderr.value = open_file(OPTIONS.StdErrFileName.value, 'wt', 'utf-8')

    zxbpp.setMode('basic')
    zxbpp.main(args)

    if gl.has_errors:
        debug.__DEBUG__("exiting due to errors.")
        return 1  # Exit with errors

    input_ = zxbpp.OUTPUT
    zxbparser.parser.parse(input_, lexer=zxblex.lexer, tracking=True,
                           debug=(OPTIONS.Debug.value > 2))
    if gl.has_errors:
        debug.__DEBUG__("exiting due to errors.")
        return 1  # Exit with errors

    # Optimizations
    optimizer = api.optimize.OptimizerVisitor()
    optimizer.visit(zxbparser.ast)

    # Emits intermediate code
    translator = arch.zx48k.Translator()
    translator.visit(zxbparser.ast)

    if gl.DATA_IS_USED:
        gl.FUNCTIONS.extend(gl.DATA_FUNCTIONS)

    # This will fill MEMORY with pending functions
    func_visitor = arch.zx48k.FunctionTranslator(gl.FUNCTIONS)
    func_visitor.start()

    # Emits data lines
    translator.emit_data_blocks()
    # Emits default constant strings
    translator.emit_strings()
    # Emits jump tables
    translator.emit_jump_tables()

    if OPTIONS.emitBackend.value:
        with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file:
            for quad in translator.dumpMemory(backend.MEMORY):
                output_file.write(str(quad) + '\n')

            backend.MEMORY[:] = []  # Empties memory
            # This will fill MEMORY with global declared variables
            translator = arch.zx48k.VarTranslator()
            translator.visit(zxbparser.data_ast)

            for quad in translator.dumpMemory(backend.MEMORY):
                output_file.write(str(quad) + '\n')
        return 0  # Exit success

    # Join all lines into a single string and ensures an INTRO at end of file
    asm_output = backend.emit(backend.MEMORY)
    asm_output = optimize(asm_output) + '\n'

    asm_output = asm_output.split('\n')
    for i in range(len(asm_output)):
        tmp = backend.ASMS.get(asm_output[i], None)
        if tmp is not None:
            asm_output[i] = '\n'.join(tmp)

    asm_output = '\n'.join(asm_output)

    # Now filter them against the preprocessor again
    zxbpp.setMode('asm')
    zxbpp.OUTPUT = ''
    zxbpp.filter_(asm_output, args[0])

    # Now output the result
    asm_output = zxbpp.OUTPUT.split('\n')
    get_inits(asm_output)  # Find out remaining inits
    backend.MEMORY[:] = []

    # This will fill MEMORY with global declared variables
    translator = arch.zx48k.VarTranslator()
    translator.visit(zxbparser.data_ast)
    if gl.has_errors:
        debug.__DEBUG__("exiting due to errors.")
        return 1  # Exit with errors

    tmp = [x for x in backend.emit(backend.MEMORY) if x.strip()[0] != '#']
    asm_output += tmp
    asm_output = backend.emit_start() + asm_output
    asm_output += backend.emit_end(asm_output)

    if options.asm:  # Only output assembler file
        with open_file(OPTIONS.outputFileName.value, 'wt', 'utf-8') as output_file:
            output(asm_output, output_file)
    elif not options.parse_only:
        fout = StringIO()
        output(asm_output, fout)
        asmparse.assemble(fout.getvalue())
        fout.close()
        asmparse.generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type.value,
                                 binary_files=options.append_binary,
                                 headless_binary_files=options.append_headless_binary)
        if gl.has_errors:
            return 5  # Error in assembly

    if OPTIONS.memory_map.value:
        with open_file(OPTIONS.memory_map.value, 'wt', 'utf-8') as f:
            f.write(asmparse.MEMORY.memory_map)

    return gl.has_errors
1359017
def run(self, cmd):
        """"""
        import __main__
        dikt = __main__.__dict__
        return self.runctx(cmd, dikt, dikt)
1287588
def main():
    """"""
    import colorama
    import argparse
    import logging
    import sys
    import os

    parser = argparse.ArgumentParser(prog="gulpless",
                                     description="Simple build system.")
    parser.add_argument("-v", "--version",
                        action="version",
                        version="%(prog)s 0.7.6")
    parser.add_argument("-d", "--directory",
                        action="store",
                        default=os.getcwd(),
                        help="Look for `build.py` in this folder (defaults to "
                             "the current directory)")
    parser.add_argument("mode",
                        action="store",
                        choices=["build", "interactive"],
                        default="interactive",
                        metavar="mode",
                        nargs="?",
                        help="If `interactive` (the default), will wait for "
                             "filesystem events and attempt to keep the input "
                             "and output folders in sync. If `build`, it will "
                             "attempt to build all updated files, then exit.")

    args = parser.parse_args()
    os.chdir(args.directory)
    sys.path.append(os.getcwd())

    if os.environ.get("TERM") == "cygwin":
        # colorama doesn't play well with git bash
        del os.environ["TERM"]
        colorama.init()
        os.environ["TERM"] = "cygwin"
    else:
        colorama.init()

    try:
        old, sys.dont_write_bytecode = sys.dont_write_bytecode, True
        import build
    except ImportError:
        sys.exit("No `build.py` found in current folder.")
    finally:
        sys.dont_write_bytecode = old

    try:
        logging.basicConfig(level=build.LOGGING,
                            format="%(message)s")
    except AttributeError:
        logging.basicConfig(level=logging.INFO,
                            format="%(message)s")

    reactor = Reactor(build.SRC, build.DEST)
    for handler in build.HANDLERS:
        reactor.add_handler(handler)
    reactor.run(args.mode == "build")
95444
def main(argv=None, input_stream=stdin, output_stream=stdout,
         error_stream=stderr):
    """"""
    args = _parse_args(argv)
    args_dict = args.__dict__.copy()
    inline_str = args_dict.pop('inline')
    modules = args_dict.pop('modules')

    func = get_inline_func(inline_str, modules, **args_dict)

    return cbox.main(
        func=func, argv=[], input_stream=input_stream,
        output_stream=output_stream, error_stream=error_stream, exit=False,
    )
315224
def main(args=None):
    
    _parse_args(args)
    streamsx._streams._version._mismatch_check('streamsx.topology.context')
    srp = pkg_resources.working_set.find(pkg_resources.Requirement.parse('streamsx'))
    if srp is not None:
        srv = srp.parsed_version
        location = srp.location
        spkg = 'package'
    else:
        srv = streamsx._streams._version.__version__
        location = os.path.dirname(streamsx._streams._version.__file__)
        location = os.path.dirname(location)
        location = os.path.dirname(location)
        tk_path = (os.path.join('com.ibm.streamsx.topology', 'opt', 'python', 'packages'))
        spkg = 'toolkit' if location.endswith(tk_path) else 'unknown'

    print('streamsx==' + str(srv) + ' (' + spkg + ')')
    print('  location: ' + str(location))
    print('Python version:' + str(sys.version))
    print('PYTHONHOME=' + str(os.environ.get('PYTHONHOME', 'unset')))
    print('PYTHONPATH=' + str(os.environ.get('PYTHONPATH', 'unset')))
    print('PYTHONWARNINGS=' + str(os.environ.get('PYTHONWARNINGS', 'unset')))
    print('STREAMS_INSTALL=' + str(os.environ.get('STREAMS_INSTALL', 'unset')))
    print('JAVA_HOME=' + str(os.environ.get('JAVA_HOME', 'unset')))
    return 0
1010097
def main():
    
    arguments = docopt(main.__doc__)

    if arguments.get('--version'):
        print('with {}'.format(withtool.__version__))
        sys.exit()

    while True:
        sub = yield from get_prompt(arguments['<command>'])
        call = '{cmd} {sub}'.format(cmd=arguments['<command>'], sub=sub)
        run(call)
1115226
def main():
    
    p = OptionParser(main.__doc__)
    p.add_option("-g", "--graphic", default=False, action="store_true",
            help="Create boilerplate for a graphic script")

    opts, args = p.parse_args()
    if len(args) != 1:
        sys.exit(not p.print_help())

    script, = args
    imports = graphic_imports if opts.graphic else default_imports
    app = graphic_app if opts.graphic else default_app
    template = default_template.format(imports, app)
    write_file(script, template)

    message = "template writes to `{0}`".format(script)
    if opts.graphic:
        message = "graphic " + message
    message = message[0].upper() + message[1:]
    logging.debug(message)
662836
def main():
    """"""

    if '--' in sys.argv:
        cli_args = sys.argv[1:sys.argv.index('--')]
        backend_args = sys.argv[sys.argv.index('--') + 1:]
    else:
        cli_args = sys.argv[1:]
        backend_args = []

    args = _cmdline_parser.parse_args(cli_args)
    debug = False
    if args.verbose is None:
        logging_level = logging.WARNING
    elif args.verbose == 1:
        logging_level = logging.INFO
    elif args.verbose == 2:
        logging_level = logging.DEBUG
        debug = True
    else:
        print('error: I can only be so garrulous, try -vv.', file=sys.stderr)
        sys.exit(1)

    logging.basicConfig(level=logging_level)

    if args.spec and args.spec[0].startswith('+') and args.spec[0].endswith('.py'):
        # Hack: Special case for defining a spec in Python for testing purposes
        # Use this if you want to define a Stone spec using a Python module.
        # The module should should contain an api variable that references a
        # :class:`stone.api.Api` object.
        try:
            api = imp.load_source('api', args.api[0]).api  # pylint: disable=redefined-outer-name
        except ImportError as e:
            print('error: Could not import API description due to:',
                  e, file=sys.stderr)
            sys.exit(1)
    else:
        if args.spec:
            specs = []
            read_from_stdin = False
            for spec_path in args.spec:
                if spec_path == '-':
                    read_from_stdin = True
                elif not spec_path.endswith('.stone'):
                    print("error: Specification '%s' must have a .stone extension."
                          % spec_path,
                          file=sys.stderr)
                    sys.exit(1)
                elif not os.path.exists(spec_path):
                    print("error: Specification '%s' cannot be found." % spec_path,
                          file=sys.stderr)
                    sys.exit(1)
                else:
                    with open(spec_path) as f:
                        specs.append((spec_path, f.read()))
            if read_from_stdin and specs:
                print("error: Do not specify stdin and specification files "
                      "simultaneously.", file=sys.stderr)
                sys.exit(1)

        if not args.spec or read_from_stdin:
            specs = []
            if debug:
                print('Reading specification from stdin.')

            if six.PY2:
                UTF8Reader = codecs.getreader('utf8')
                sys.stdin = UTF8Reader(sys.stdin)
                stdin_text = sys.stdin.read()
            else:
                stdin_buffer = sys.stdin.buffer  # pylint: disable=no-member,useless-suppression
                stdin_text = io.TextIOWrapper(stdin_buffer, encoding='utf-8').read()

            parts = stdin_text.split('namespace')
            if len(parts) == 1:
                specs.append(('stdin.1', parts[0]))
            else:
                specs.append(
                    ('stdin.1', '%snamespace%s' % (parts.pop(0), parts.pop(0))))
                while parts:
                    specs.append(('stdin.%s' % (len(specs) + 1),
                                  'namespace%s' % parts.pop(0)))

        if args.filter_by_route_attr:
            route_filter, route_filter_errors = parse_route_attr_filter(
                args.filter_by_route_attr, debug)
            if route_filter_errors:
                print('Error(s) in route filter:', file=sys.stderr)
                for err in route_filter_errors:
                    print(err, file=sys.stderr)
                sys.exit(1)

        else:
            route_filter = None

        if args.route_whitelist_filter:
            with open(args.route_whitelist_filter) as f:
                route_whitelist_filter = json.loads(f.read())
        else:
            route_whitelist_filter = None

        try:
            # TODO: Needs version
            api = specs_to_ir(specs, debug=debug,
                              route_whitelist_filter=route_whitelist_filter)
        except InvalidSpec as e:
            print('%s:%s: error: %s' % (e.path, e.lineno, e.msg), file=sys.stderr)
            if debug:
                print('A traceback is included below in case this is a bug in '
                      'Stone.\n', traceback.format_exc(), file=sys.stderr)
            sys.exit(1)
        if api is None:
            print('You must fix the above parsing errors for generation to '
                  'continue.', file=sys.stderr)
            sys.exit(1)

        if args.whitelist_namespace_routes:
            for namespace_name in args.whitelist_namespace_routes:
                if namespace_name not in api.namespaces:
                    print('error: Whitelisted namespace missing from spec: %s' %
                          namespace_name, file=sys.stderr)
                    sys.exit(1)
            for namespace in api.namespaces.values():
                if namespace.name not in args.whitelist_namespace_routes:
                    namespace.routes = []
                    namespace.route_by_name = {}
                    namespace.routes_by_name = {}

        if args.blacklist_namespace_routes:
            for namespace_name in args.blacklist_namespace_routes:
                if namespace_name not in api.namespaces:
                    print('error: Blacklisted namespace missing from spec: %s' %
                          namespace_name, file=sys.stderr)
                    sys.exit(1)
                else:
                    namespace = api.namespaces[namespace_name]
                    namespace.routes = []
                    namespace.route_by_name = {}
                    namespace.routes_by_name = {}

        if route_filter:
            for namespace in api.namespaces.values():
                filtered_routes = []
                for route in namespace.routes:
                    if route_filter.eval(route):
                        filtered_routes.append(route)

                namespace.routes = []
                namespace.route_by_name = {}
                namespace.routes_by_name = {}
                for route in filtered_routes:
                    namespace.add_route(route)

        if args.attribute:
            attrs = set(args.attribute)
            if ':all' in attrs:
                attrs = {field.name for field in api.route_schema.fields}
        else:
            attrs = set()

        for namespace in api.namespaces.values():
            for route in namespace.routes:
                for k in list(route.attrs.keys()):
                    if k not in attrs:
                        del route.attrs[k]

        # Remove attrs that weren't specified from the route schema
        for field in api.route_schema.fields[:]:
            if field.name not in attrs:
                api.route_schema.fields.remove(field)
                del api.route_schema._fields_by_name[field.name]
            else:
                attrs.remove(field.name)

        # Error if specified attr isn't even a field in the route schema
        if attrs:
            attr = attrs.pop()
            print('error: Attribute not defined in stone_cfg.Route: %s' %
                  attr, file=sys.stderr)
            sys.exit(1)

    if args.backend in _builtin_backends:
        backend_module = __import__(
            'stone.backends.%s' % args.backend, fromlist=[''])
    elif not os.path.exists(args.backend):
        print("error: Backend '%s' cannot be found." % args.backend,
              file=sys.stderr)
        sys.exit(1)
    elif not os.path.isfile(args.backend):
        print("error: Backend '%s' must be a file." % args.backend,
              file=sys.stderr)
        sys.exit(1)
    elif not Compiler.is_stone_backend(args.backend):
        print("error: Backend '%s' must have a .stoneg.py extension." %
              args.backend, file=sys.stderr)
        sys.exit(1)
    else:
        # A bit hacky, but we add the folder that the backend is in to our
        # python path to support the case where the backend imports other
        # files in its local directory.
        new_python_path = os.path.dirname(args.backend)
        if new_python_path not in sys.path:
            sys.path.append(new_python_path)
        try:
            backend_module = imp.load_source('user_backend', args.backend)
        except Exception:
            print("error: Importing backend '%s' module raised an exception:" %
                  args.backend, file=sys.stderr)
            raise

    c = Compiler(
        api,
        backend_module,
        backend_args,
        args.output,
        clean_build=args.clean_build,
    )
    try:
        c.build()
    except BackendException as e:
        print('%s: error: %s raised an exception:\n%s' %
              (args.backend, e.backend_name, e.traceback),
              file=sys.stderr)
        sys.exit(1)

    if not sys.argv[0].endswith('stone'):
        # If we aren't running from an entry_point, then return api to make it
        # easier to do debugging.
        return api
223372
def main():
    """"""

    cleanup_and_exit = sys.exit # Function to do cleanup and exit before the import.
    exit_code = 0

    # Imports are done here inside the try block so some ugly (and useless)
    # traceback info is avoided on user's ^C (KeyboardInterrupt, EOFError on Windows).
    try:
        from . import external_program_calls as ex # Creates tmp dir as side effect.
        cleanup_and_exit = ex.cleanup_and_exit # Switch to the real one, deletes temp dir.

        from . import main_pdfCropMargins # Imports external_program_calls, don't do first.
        main_pdfCropMargins.main_crop() # Run the actual program.

    except (KeyboardInterrupt, EOFError): # Windows raises EOFError on ^C.
        print("\nGot a KeyboardInterrupt, cleaning up and exiting...\n",
              file=sys.stderr)

    except SystemExit:
        exit_code = sys.exc_info()[1]
        print()

    except:
        # Echo back the unexpected error so the user can see it.
        print("\nCaught an unexpected exception in the pdfCropMargins program.",
                                                               file=sys.stderr)
        print("Unexpected error: ", sys.exc_info()[0], file=sys.stderr)
        print("Error message   : ", sys.exc_info()[1], file=sys.stderr)
        print()
        exit_code = 1
        import traceback
        max_traceback_length = 30
        traceback.print_tb(sys.exc_info()[2], limit=max_traceback_length)
        # raise # Re-raise the error.

    finally:
        # Some people like to hit multiple ^C chars, which kills cleanup.
        # Call cleanup again each time.
        for i in range(30): # Give up after 30 tries.
            try:
                cleanup_and_exit(exit_code)
            except (KeyboardInterrupt, EOFError):
                continue
795886
def main(args=None):
    
    parser = argument_parser()
    args = parser.parse_args(args)

    # If 'func' isn't present, something is misconfigured above or no (positional) arg was given.
    if not hasattr(args, 'func'):
        args = parser.parse_args(['help'])  # show help

    # Convert argparse.Namespace into dict and clean it up.
    # We can then pass it directly to the helper function.
    kwargs = vars(args)

    # handle the '--dev' option
    if kwargs.pop('dev') or os.environ.get('QUILT_DEV_MODE', '').strip().lower() == 'true':
        # Enables CLI ctrl-c tracebacks, and whatever anyone else uses it for
        quilt._DEV_MODE = True
    else:
        # Disables CLI ctrl-c tracebacks, etc.
        quilt._DEV_MODE = False

    func = kwargs.pop('func')

    try:
        func(**kwargs)
        return 0
    except QuiltException as ex:
        print(ex.message, file=sys.stderr)
        return 1
    except requests.exceptions.ConnectionError as ex:
        print("Failed to connect: %s" % ex, file=sys.stderr)
        return 1
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
572900
def import_(zone, path):
    '''
    
    '''
    ret = {'status': True}

    # create from file
    _dump_cfg(path)
    res = __salt__['cmd.run_all']('zonecfg -z {zone} -f {path}'.format(
        zone=zone,
        path=path,
    ))
    ret['status'] = res['retcode'] == 0
    ret['message'] = res['stdout'] if ret['status'] else res['stderr']
    if ret['message'] == '':
        del ret['message']
    else:
        ret['message'] = _clean_message(ret['message'])

    return ret
985406
def entrypoint(args=None):
    

    mondrian.setup(excepthook=True)
    logger = logging.getLogger()
    logger.setLevel(settings.LOGGING_LEVEL.get())

    parser = argparse.ArgumentParser()
    parser.add_argument("--debug", "-D", action="store_true")

    subparsers = parser.add_subparsers(dest="command")
    subparsers.required = True

    commands = {}

    def register_extension(ext):
        nonlocal commands

        try:
            parser = subparsers.add_parser(ext.name)
            if isinstance(ext.plugin, type) and issubclass(ext.plugin, BaseCommand):
                # current way, class based.
                cmd = ext.plugin()
                cmd.add_arguments(parser)
                cmd.__name__ = ext.name
                commands[ext.name] = cmd.handle
            else:
                # old school, function based.
                commands[ext.name] = ext.plugin(parser)
        except Exception:
            logger.exception("Error while loading command {}.".format(ext.name))

    from stevedore import ExtensionManager

    mgr = ExtensionManager(namespace="bonobo.commands")
    mgr.map(register_extension)

    parsed_args = parser.parse_args(args).__dict__

    if parsed_args.pop("debug", False):
        settings.DEBUG.set(True)
        settings.LOGGING_LEVEL.set(logging.DEBUG)
        logger.setLevel(settings.LOGGING_LEVEL.get())

    logger.debug("Command: " + parsed_args["command"] + " Arguments: " + repr(parsed_args))

    # Get command handler, execute, rince.
    command = commands[parsed_args.pop("command")]
    command(**parsed_args)

    return 0
944966
def run(self, cmd):
        
        # TODO: can this be removed ?
        import __main__
        main_dict = __main__.__dict__
        return self.runctx(cmd, main_dict, main_dict)
68392
def main(argv=sys.argv):
    """"""
    parser = setup_parser()

    (opts, args) = parser.parse_args(argv[1:])

    if not args:
        parser.error('A package path is required.')

    rootpath, excludes = args[0], args[1:]
    if not opts.destdir:
        parser.error('An output directory is required.')
    if opts.header is None:
        opts.header = path.normpath(rootpath).split(path.sep)[-1]
    if opts.suffix.startswith('.'):
        opts.suffix = opts.suffix[1:]
    if not path.isdir(rootpath):
        print >>sys.stderr, '%s is not a directory.' % rootpath
        sys.exit(1)
    if not path.isdir(opts.destdir):
        if not opts.dryrun:
            os.makedirs(opts.destdir)
    rootpath = path.normpath(path.abspath(rootpath))
    excludes = normalize_excludes(rootpath, excludes)
    modules = recurse_tree(rootpath, excludes, opts)
    if opts.full:
        from sphinx import quickstart as qs
        modules.sort()
        prev_module = ''
        text = ''
        for module in modules:
            if module.startswith(prev_module + '.'):
                continue
            prev_module = module
            text += '   %s\n' % module
        d = dict(
            path = opts.destdir,
            sep  = False,
            dot  = '_',
            project = opts.header,
            author = opts.author or 'Author',
            version = opts.version or '',
            release = opts.release or opts.version or '',
            suffix = '.' + opts.suffix,
            master = 'index',
            epub = True,
            ext_autodoc = True,
            ext_viewcode = True,
            makefile = True,
            batchfile = True,
            mastertocmaxdepth = opts.maxdepth,
            mastertoctree = text,
        )
        if not opts.dryrun:
            qs.generate(d, silent=True, overwrite=opts.force)
    elif not opts.notoc:
        create_modules_toc_file(modules, opts)
673758
def do_import(self):
        """"""
        tmp_import = None
        try:
            if self.args[0].startswith('@') and self.args[0] != '@-':
                import_file = os.path.expanduser(self.args[0][1:])
                if not os.path.isfile(import_file):
                    self.parser.error("File not found (or not a file): {}".format(import_file))
                args = (xmlrpc.NOHASH, os.path.abspath(import_file))
            else:
                script_text = '\n'.join(self.args + [''])
                if script_text == '@-\n':
                    script_text = sys.stdin.read()

                with tempfile.NamedTemporaryFile(suffix='.rc', prefix='rtxmlrpc-', delete=False) as handle:
                    handle.write(script_text)
                    tmp_import = handle.name
                args = (xmlrpc.NOHASH, tmp_import)

            self.execute(self.open(), 'import', args)
        finally:
            if tmp_import and os.path.exists(tmp_import):
                os.remove(tmp_import)
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