inspect the command-line-args and give them to appBase
486800
def _inspectArguments(self, args):
        """"""
        if args:
            self.exec_path = PathStr(args[0])
        else:
            self.exec_path = None

        session_name = None
        args = args[1:]

        openSession = False
        for arg in args:
            if arg in ('-h', '--help'):
                self._showHelp()
            elif arg in ('-d', '--debug'):
                print('RUNNGING IN DEBUG-MODE')
                self.opts['debugMode'] = True
            elif arg in ('-l', '--log'):
                print('CREATE LOG')
                self.opts['createLog'] = True
            elif arg in ('-s', '--server'):
                self.opts['server'] = True
            elif arg in ('-o', '--open'):
                openSession = True
            elif openSession:
                session_name = arg
            else:
                print("Argument '%s' not known." % arg)
                return self._showHelp()
        return session_name
715106
def _add_cli_args(self):
        """"""

        # Optional cli arguments
        self._arg_parser.add_argument('-l', '--list',
                                      action='store_true',
                                      help='List installed sprockets apps')

        self._arg_parser.add_argument('-s', '--syslog',
                                      action='store_true',
                                      help='Log to syslog')

        self._arg_parser.add_argument('-v', '--verbose',
                                      action='count',
                                      help=('Verbose logging output, use -vv '
                                            'for DEBUG level logging'))

        self._arg_parser.add_argument('--version',
                                      action='version',
                                      version='sprockets v%s ' % __version__)

        # Controller sub-parser
        subparsers = self._arg_parser.add_subparsers(dest='controller',
                                                          help=DESCRIPTION)

        # Iterate through the controllers and add their cli arguments
        for key in self._controllers:
            help_text = self._get_controller_help(key)
            sub_parser = subparsers.add_parser(key, help=help_text)
            try:
                self._controllers[key].add_cli_arguments(sub_parser)
            except AttributeError:
                LOGGER.debug('%s missing add_cli_arguments()', key)

        # The application argument
        self._arg_parser.add_argument('application',
                                      action="store",
                                      help='The sprockets app to run')
1281947
def parse_cli_args():
    
    # get config paths
    home_path = os.path.expanduser("~")
    xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config".format(home_path))
    xdg_dirs_path = os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg")

    # get i3status path
    try:
        with open(os.devnull, "w") as devnull:
            command = ["which", "i3status"]
            i3status_path = (
                subprocess.check_output(command, stderr=devnull).decode().strip()
            )
    except subprocess.CalledProcessError:
        i3status_path = None

    # get window manager
    with open(os.devnull, "w") as devnull:
        if subprocess.call(["pgrep", "i3"], stdout=devnull) == 0:
            wm = "i3"
        else:
            wm = "sway"

    # i3status config file default detection
    # respect i3status' file detection order wrt issue #43
    i3status_config_file_candidates = [
        "{}/py3status/config".format(xdg_home_path),
        "{}/i3status/config".format(xdg_home_path),
        "{}/i3/i3status.conf".format(xdg_home_path),  # custom
        "{}/.i3status.conf".format(home_path),
        "{}/.i3/i3status.conf".format(home_path),  # custom
        "{}/i3status/config".format(xdg_dirs_path),
        "/etc/i3status.conf",
    ]
    for fn in i3status_config_file_candidates:
        if os.path.isfile(fn):
            i3status_config_file_default = fn
            break
    else:
        # if files does not exists, defaults to ~/.i3/i3status.conf
        i3status_config_file_default = i3status_config_file_candidates[3]

    class Parser(argparse.ArgumentParser):
        # print usages and exit on errors
        def error(self, message):
            print("\x1b[1;31merror: \x1b[0m{}".format(message))
            self.print_help()
            self.exit(1)

        # hide choices on errors
        def _check_value(self, action, value):
            if action.choices is not None and value not in action.choices:
                raise argparse.ArgumentError(
                    action, "invalid choice: '{}'".format(value)
                )

    class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
        def _format_action_invocation(self, action):
            metavar = self._format_args(action, action.dest.upper())
            return "{} {}".format(", ".join(action.option_strings), metavar)

    # command line options
    parser = Parser(
        description="The agile, python-powered, i3status wrapper",
        formatter_class=HelpFormatter,
    )
    parser.add_argument(
        "-b",
        "--dbus-notify",
        action="store_true",
        dest="dbus_notify",
        help="send notifications via dbus instead of i3-nagbar",
    )
    parser.add_argument(
        "-c",
        "--config",
        action="store",
        default=i3status_config_file_default,
        dest="i3status_config_path",
        help="load config",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-d",
        "--debug",
        action="store_true",
        help="enable debug logging in syslog and --log-file",
    )
    parser.add_argument(
        "-g",
        "--gevent",
        action="store_true",
        dest="gevent",
        help="enable gevent monkey patching",
    )
    parser.add_argument(
        "-i",
        "--include",
        action="append",
        dest="include_paths",
        help="append additional user-defined module paths",
        metavar="PATH",
    )
    parser.add_argument(
        "-l",
        "--log-file",
        action="store",
        dest="log_file",
        help="enable logging to FILE",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-s",
        "--standalone",
        action="store_true",
        dest="standalone",
        help="run py3status without i3status",
    )
    parser.add_argument(
        "-t",
        "--timeout",
        action="store",
        default=60,
        dest="cache_timeout",
        help="default module cache timeout in seconds",
        metavar="INT",
        type=int,
    )
    parser.add_argument(
        "-m",
        "--disable-click-events",
        action="store_true",
        dest="disable_click_events",
        help="disable all click events",
    )
    parser.add_argument(
        "-u",
        "--i3status",
        action="store",
        default=i3status_path,
        dest="i3status_path",
        help="specify i3status path",
        metavar="PATH",
        type=str,
    )
    parser.add_argument(
        "-v",
        "--version",
        action="store_true",
        dest="print_version",
        help="show py3status version and exit",
    )
    parser.add_argument(
        "--wm",
        action="store",  # add comment to preserve formatting
        dest="wm",
        metavar="WINDOW_MANAGER",
        default=wm,
        choices=["i3", "sway"],
        help="specify window manager i3 or sway",
    )

    # deprecations
    parser.add_argument("-n", "--interval", help=argparse.SUPPRESS)

    # parse options, command, etc
    options = parser.parse_args()

    # make versions
    options.python_version = python_version()
    options.version = version
    if options.print_version:
        msg = "py3status version {version} (python {python_version}) on {wm}"
        print(msg.format(**vars(options)))
        parser.exit()

    # get wm
    options.wm_name = options.wm
    options.wm = {
        "i3": {"msg": "i3-msg", "nag": "i3-nagbar"},
        "sway": {"msg": "swaymsg", "nag": "swaynag"},
    }[options.wm]

    # make it i3status if None
    if not options.i3status_path:
        options.i3status_path = "i3status"

    # make include path to search for user modules if None
    if not options.include_paths:
        options.include_paths = [
            "{}/py3status/modules".format(xdg_home_path),
            "{}/i3status/py3status".format(xdg_home_path),
            "{}/i3/py3status".format(xdg_home_path),
            "{}/.i3/py3status".format(home_path),
        ]

    include_paths = []
    for path in options.include_paths:
        path = os.path.abspath(path)
        if os.path.isdir(path) and os.listdir(path):
            include_paths.append(path)
    options.include_paths = include_paths

    # defaults
    del options.interval
    del options.print_version
    options.minimum_interval = 0.1  # minimum module update interval
    options.click_events = not options.__dict__.pop("disable_click_events")

    # all done
    return options
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
827426
def get_args():
    

    parser = argparse.ArgumentParser(
        description="Provision multiple VM's through mist.io. You can get "
        "information returned with the name of the virtual machine created "
        "and its main mac and ip address in IPv4 format. A post-script can be "
        "specified for post-processing.")
    parser.add_argument('-b', '--basename', nargs=1, required=True,
                        help='Basename of the newly deployed VMs',
                        dest='basename', type=str)
    parser.add_argument('-d', '--debug', required=False,
                        help='Enable debug output', dest='debug',
                        action='store_true')
    parser.add_argument('-i', '--print-ips', required=False,
                        help='Enable IP output', dest='ips',
                        action='store_true')
    parser.add_argument('-m', '--print-macs', required=False,
                        help='Enable MAC output', dest='macs',
                        action='store_true')
    parser.add_argument('-l', '--log-file', nargs=1, required=False,
                        help='File to log to (default = stdout)',
                        dest='logfile', type=str)
    parser.add_argument('-n', '--number', nargs=1, required=False,
                        help='Amount of VMs to deploy (default = 1)',
                        dest='quantity', type=int, default=[1])
    parser.add_argument('-M', '--monitoring', required=False,
                        help='Enable monitoring on the virtual machines',
                        dest='monitoring', action='store_true')
    parser.add_argument('-B', '--backend-name', required=False,
                        help='The name of the backend to use for provisioning.'
                        ' Defaults to the first available backend',
                        dest='backend_name', type=str)
    parser.add_argument('-I', '--image-id', required=True,
                        help='The image to deploy', dest='image_id')
    parser.add_argument('-S', '--size-id', required=True,
                        help='The id of the size/flavor to use',
                        dest='size_id')
    parser.add_argument('-N', '--networks', required=False, nargs='+',
                        help='The ids of the networks to assign to the VMs',
                        dest='networks')
    parser.add_argument('-s', '--post-script', nargs=1, required=False,
                        help='Script to be called after each VM is created and'
                        ' booted.', dest='post_script', type=str)
    parser.add_argument('-P', '--script-params', nargs=1, required=False,
                        help='Script to be called after each VM is created and'
                        ' booted.', dest='script_params', type=str)
    parser.add_argument('-H', '--host', required=False,
                        help='mist.io instance to connect to', dest='host',
                        type=str, default='https://mist.io')
    parser.add_argument('-u', '--user', nargs=1, required=False,
                        help='email registered to mist.io', dest='username',
                        type=str)
    parser.add_argument('-p', '--password', nargs=1, required=False,
                        help='The password with which to connect to the host. '
                        'If not specified, the user is prompted at runtime for'
                        ' a password', dest='password', type=str)
    parser.add_argument('-v', '--verbose', required=False,
                        help='Enable verbose output', dest='verbose',
                        action='store_true')
    parser.add_argument('-w', '--wait-max', nargs=1, required=False,
                        help='Maximum amount of seconds to wait when gathering'
                        ' information (default = 600)', dest='maxwait',
                        type=int, default=[600])
    parser.add_argument('-f', '--associate-floating-ip', required=False, action='store_true',
                        help='Auto-associates floating ips to vms in Openstack backens',
                        dest='associate_floating_ip',)
    args = parser.parse_args()
    return args
790803
def parse_args(args):
    ''' 
    '''
    parser = argparse.ArgumentParser()
    parser.add_argument('config_file', nargs='?',
                        help='Configuration yaml file', default=None)
    parser.add_argument(
        '--log', '-l',
        help='Logging level (e.g. DEBUG, INFO, WARNING, ERROR, CRITICAL)',
        default='INFO')
    args_parsed = parser.parse_args(args)
    if not args_parsed.config_file:
        parser.error("You have to specify "
                     "a configuration file")  # pragma: no cover, sysexit
    return args_parsed
1374662
def parse_args(args, cfg):
    
    prog = pathlib.Path(sys.argv[0]).parts[-1].replace('.py', '')
    prog_version = "%%(prog)s %s" % versionner.__version__

    # pylint: disable=invalid-name
    p = argparse.ArgumentParser(prog=prog, description='Helps manipulating version of the project')
    p.add_argument('--file', '-f', dest='version_file', type=str,
        default=cfg.version_file,
        help="path to file where version is saved")
    p.add_argument('--version', '-v', action="version", version=prog_version)
    p.add_argument('--date-format', type=str,
        default=cfg.date_format,
        help="Date format used in project files")
    p.add_argument('--verbose', action="store_true",
        help="Be more verbose if it's possible")

    sub = p.add_subparsers(dest='command')

    p_init = sub.add_parser('init', aliases=commands.get_aliases_for('init'),
        help="Create new version file")
    p_init.add_argument('value', nargs='?', type=str,
        default=cfg.default_init_version,
        help="Initial version")
    p_init.add_argument('--vcs-engine', type=str,
        default=cfg.vcs_engine,
        help="Select VCS engine (only git is supported currently)", )
    p_init.add_argument('--vcs-commit-message', '-m', type=str,
        default=cfg.vcs_commit_message,
        help="Commit message used when committing changes")
    p_init.add_argument('--commit', '-c', action='store_true',
        help="Commit changes done by `up` command (only if there is no changes in repo before)")

    p_up = sub.add_parser('up', aliases=commands.get_aliases_for('up'),
        help="Increase version")
    p_up.add_argument('--vcs-engine', type=str,
        default=cfg.vcs_engine,
        help="Select VCS engine (only git is supported currently)", )
    p_up.add_argument('--vcs-commit-message', '-m', type=str,
        default=cfg.vcs_commit_message,
        help="Commit message used when committing changes")
    p_up.add_argument('--commit', '-c', action='store_true',
        help="Commit changes done by `up` command (only if there is no changes in repo before)")
    p_up.add_argument('value', nargs='?', type=int,
        default=cfg.default_increase_value,
        help="Increase version by this value (default: %d)" % cfg.default_increase_value)

    p_up_gr = p_up.add_mutually_exclusive_group()
    p_up_gr.add_argument('--major', '-j', action="store_true",
        help="increase major part of version" + (" (project default)" if cfg.up_part == 'major' else ""))
    p_up_gr.add_argument('--minor', '-n', action="store_true",
        help="increase minor part of version" + (" (project default)" if cfg.up_part == 'minor' else ""))
    p_up_gr.add_argument('--patch', '-p', action="store_true",
        help="increase patch part of version" + (" (project default)" if cfg.up_part == 'patch' else ""))

    p_set = sub.add_parser('set', aliases=commands.get_aliases_for('set'),
        help="Set version to specified one")
    p_set.add_argument('--major', '-j', type=int,
        help="set major part of version to MAJOR")
    p_set.add_argument('--minor', '-n', type=int,
        help="set minor part of version to MINOR")
    p_set.add_argument('--patch', '-p', type=int,
        help="set patch part of version to PATCH")
    p_set.add_argument('--prerelease', '-r', type=str,
        help="set prerelease part of version to PRERELEASE")
    p_set.add_argument('--build', '-b', type=str,
        help="set build part of version to BUILD")
    p_set.add_argument('--vcs-engine', type=str,
        default=cfg.vcs_engine,
        help="Select VCS engine (only git is supported currently)", )
    p_set.add_argument('--vcs-commit-message', '-m', type=str,
        default=cfg.vcs_commit_message,
        help="Commit message used when committing changes")
    p_set.add_argument('--commit', '-c', action='store_true',
        help="Commit changes done by `set` command (only if there is no changes in repo before)")
    p_set.add_argument('value', nargs='?', type=str,
        help="set version to this value")

    p_tag = sub.add_parser('tag', aliases=commands.get_aliases_for('tag'),
        help="Create VCS tag with current version")
    p_tag.add_argument('--vcs-tag-param', dest='vcs_tag_params', type=str, action="append",
        help="Additional params for VCS for \"tag\" command")

    sub.add_parser('read', aliases=commands.get_aliases_for('read'),
        help="Read current version")

    args = p.parse_args(args)

    cfg.command = args.command
    cfg.version_file = pathlib.Path(args.version_file).absolute()
    cfg.date_format = args.date_format
    cfg.verbose = args.verbose

    version_file_requirement = 'doesn\'t matter'
    if cfg.command == 'init':
        version_file_requirement = 'none'

        cfg.commit = args.commit
        cfg.vcs_engine = args.vcs_engine
        cfg.vcs_commit_message = args.vcs_commit_message
        cfg.value = args.value

    elif cfg.command == 'up':
        version_file_requirement = 'required'

        cfg.commit = args.commit
        cfg.vcs_engine = args.vcs_engine
        cfg.vcs_commit_message = args.vcs_commit_message
        cfg.value = args.value
        if args.major:
            cfg.up_part = 'major'
        elif args.minor:
            cfg.up_part = 'minor'
        elif args.patch:
            cfg.up_part = 'patch'

    elif cfg.command == 'set':
        version_file_requirement = 'required'

        cfg.commit = args.commit
        cfg.vcs_engine = args.vcs_engine
        cfg.vcs_commit_message = args.vcs_commit_message

        if args.value:
            cfg.value = args.value
        else:
            cfg.value = (
                args.major, args.minor, args.patch,
                args.prerelease, args.build
            )

            if all(value is None for value in cfg.value):
                p.error("Version is not specified")

    elif cfg.command == 'tag':
        version_file_requirement = 'required'

        cfg.vcs_tag_params = args.vcs_tag_params or []

    elif cfg.command is None:
        cfg.command = 'read'
        version_file_requirement = 'required'

    if version_file_requirement == 'required':
        if not cfg.version_file.exists():
            p.error("Version file \"%s\" doesn't exists" % cfg.version_file)
    elif version_file_requirement == 'none':
        if cfg.version_file.exists():
            p.error("Version file \"%s\" already exists" % cfg.version_file)
365145
def parse_arguments(argv):
    """"""
    parser = argparse.ArgumentParser(description=__doc__.format(__version__))
    parser.add_argument('--application', '-a',
                        dest='application',
                        choices=scraper.APPLICATIONS,
                        default='firefox',
                        metavar='APPLICATION',
                        help='The name of the application to download, default: "%(default)s"')
    parser.add_argument('--base_url',
                        dest='base_url',
                        default=scraper.BASE_URL,
                        metavar='BASE_URL',
                        help='The base url to be used, default: "%(default)s"')
    parser.add_argument('--build-number',
                        dest='build_number',
                        type=int,
                        metavar='BUILD_NUMBER',
                        help='Number of the build (for candidate, daily, and tinderbox builds)')
    parser.add_argument('--debug-build',
                        dest='debug_build',
                        action='store_true',
                        help='Download a debug build (for tinderbox, and try builds)')
    parser.add_argument('--destination', '-d',
                        dest='destination',
                        default=os.getcwd(),
                        metavar='DESTINATION',
                        help='Directory or file name to download the '
                             'file to, default: current working directory')
    parser.add_argument('--extension',
                        dest='extension',
                        metavar='EXTENSION',
                        help='File extension of the build (e.g. "zip"), default: '
                             'the standard build extension on the platform.')
    parser.add_argument('--locale', '-l',
                        dest='locale',
                        metavar='LOCALE',
                        help='Locale of the application, default: "en-US" or "multi"')
    parser.add_argument('--log-level',
                        action='store',
                        dest='log_level',
                        default=logging.INFO,
                        metavar='LOG_LEVEL',
                        help='Threshold for log output (default: INFO')
    parser.add_argument('--password',
                        dest='password',
                        metavar='PASSWORD',
                        help='Password for basic HTTP authentication.')
    parser.add_argument('--platform', '-p',
                        dest='platform',
                        choices=scraper.PLATFORM_FRAGMENTS.keys(),
                        metavar='PLATFORM',
                        help='Platform of the application')
    parser.add_argument('--print-url',
                        dest='print_url',
                        action='store_true',
                        help='Print final URL instead of downloading the file.')
    parser.add_argument('--retry-attempts',
                        dest='retry_attempts',
                        default=0,
                        type=int,
                        metavar='RETRY_ATTEMPTS',
                        help='Number of times the download will be attempted in '
                             'the event of a failure, default: %(default)s')
    parser.add_argument('--retry-delay',
                        dest='retry_delay',
                        default=10.,
                        type=float,
                        metavar='RETRY_DELAY',
                        help='Amount of time (in seconds) to wait between retry '
                             'attempts, default: %(default)s')
    parser.add_argument('--revision',
                        dest='revision',
                        help='Revision of the build (for daily, tinderbox, and try builds)')
    parser.add_argument('--stub',
                        dest='is_stub_installer',
                        action='store_true',
                        help='Stub installer (Only applicable to Windows builds).')
    parser.add_argument('--timeout',
                        dest='timeout',
                        type=float,
                        metavar='TIMEOUT',
                        help='Amount of time (in seconds) until a download times out.')
    parser.add_argument('--type', '-t',
                        dest='scraper_type',
                        choices=factory.scraper_types.keys(),
                        default='release',
                        metavar='SCRAPER_TYPE',
                        help='Type of build to download, default: "%(default)s"')
    parser.add_argument('--url',
                        dest='url',
                        metavar='URL',
                        help='URL to download. Note: Reserved characters (such '
                             'as &) must be escaped or put in quotes otherwise '
                             'CLI output may be abnormal.')
    parser.add_argument('--username',
                        dest='username',
                        metavar='USERNAME',
                        help='Username for basic HTTP authentication.')
    parser.add_argument('--version', '-v',
                        dest='version',
                        metavar='VERSION',
                        help='Version of the application to be downloaded for release '
                             'and candidate builds (special values: %s)' % ', '.join(
                                scraper.RELEASE_AND_CANDIDATE_LATEST_VERSIONS.keys()))

    # Group for daily builds
    group = parser.add_argument_group('Daily builds', 'Extra options for daily builds.')
    group.add_argument('--branch',
                       dest='branch',
                       default='mozilla-central',
                       metavar='BRANCH',
                       help='Name of the branch, default: "%(default)s"')
    group.add_argument('--build-id',
                       dest='build_id',
                       metavar='BUILD_ID',
                       help='ID of the build to download.')
    group.add_argument('--date',
                       dest='date',
                       metavar='DATE',
                       help='Date of the build, default: latest build')

    return vars(parser.parse_args(argv))
10662
def get_args(path, *args, work_tree=True, bare=False):
    
    base = [ 'git' ]
    if path:
        base.append('-C')
        base.append(path)
        if bare:
            base.append('--bare')
            base.append("--git-dir="+path)
        else:
            base.append("--git-dir="+os.path.join(path, ".git"))
        if work_tree:
            base.append("--work-tree="+path)
    for arg in args:
        base.append(arg)
    return base
958464
def _get_command_args(self, command, args):
        ''''''
        command_args = {}
        command_argument_names =\
            command.__code__.co_varnames[:command.__code__.co_argcount]

        for varname in command_argument_names:
            if varname == 'args':
                command_args['args'] = args
            elif varname in self.provide_args:
                command_args[varname] = self.provide_args[varname]
            else:
                command_args[varname] = getattr(args, varname)
        return command_args
456744
def get_args():
    
    """

    description = "The Daemon send various value for zabbix_sender."
    parser = argparse.ArgumentParser(description)

    parser.add_argument('--config', '-c',
                        default='conf/defaults.cfg',
                        help='Specify "defaults.cfg" file'
                        )

    parser.add_argument('--debug-mode', '-d',
                        action='store_true',
                        help='Turn on debug mode',
                        dest='debug_mode'
                        )

    parser.add_argument('--pid-file', '-p',
                        default=os.path.join(
                            os.path.abspath(os.path.curdir),
                            'blackbird.pid'
                        ),
                        help='pid file location',
                        dest='pid_file'
                        )

    parser.add_argument('--foreground', '-f',
                        default=True,
                        action='store_false',
                        help='Turn on foreground mode',
                        dest='detach_process'
                        )

    parser.add_argument('--version', '-V',
                        default=False,
                        action='store_true',
                        help='Show version information',
                        dest='show_version'
                        )

    args = parser.parse_args()
    args.pid_file = is_pid(args.pid_file)

    return parser.parse_args()
545945
def parse_known_args():
    
    parser = ArgumentParser()
    parser.add_argument("-l", "--loop", type=int, help="Loop every X seconds")
    parser.add_argument('-V', '--version',
                        action='store_true',
                        dest='version',
                        help='Print the version number and exit')
    parser.add_argument("-u", "--update",
                        action='store_true',
                        dest="update",
                        help="Update the software from online repo")
    parser.add_argument("-p", "--problem",
                        action='store_true',
                        dest="problem",
                        help="Report a problem")
    parser.add_argument("-m", "--memory",
                        action='store_true',
                        dest="memory",
                        help="Run memory tests")
    args, otherthings = parser.parse_known_args()
    return args, otherthings, parser
756499
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="ERROR",
        options_first=True
    )
    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 the worker function
    # x-if-settings-or-database-credientials
    if cone and filelist:
        import codecs
        pathToReadFile = pathToCoordinateList
        readFile = codecs.open(pathToReadFile, encoding='utf-8', mode='r')

        listOfCoordinates = []
        for line in readFile.readlines():
            line = line.strip()
            [ra, dec] = line.split()
            listOfCoordinates.append(str(ra) + " " + str(dec))
        search = conesearch(
            log=log,
            radiusArcsec=radiusArcsec,
            nearestOnly=nearestFlag,
            unclassified=unclassifiedFlag,
            listOfCoordinates=listOfCoordinates,
            outputFilePath=outPutFile,
            verbose=verboseFlag,
            redshift=redshiftFlag)
    elif cone:
        search = conesearch(
            log=log,
            ra=ra,
            dec=dec,
            radiusArcsec=radiusArcsec,
            nearestOnly=nearestFlag,
            unclassified=unclassifiedFlag,
            outputFilePath=outPutFile,
            verbose=verboseFlag,
            redshift=redshiftFlag
        )
    elif obj:
        search = namesearch(
            log=log,
            names=objectName,
            verbose=verboseFlag,
            outputFilePath=outPutFile
        )
    search.get()

    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
1047173
def parse_args():
    '''  '''

    parser = argparse.ArgumentParser(prog='setup_tree_modules', usage='%(prog)s [opts]')
    parser.add_argument('-v', '--verbose', action='store_true', dest='verbose',
                        help='Print extra information.', default=False)
    parser.add_argument('-r', '--root', action='store', dest='root', default=os.getenv('SAS_BASE_DIR'),
                        help='Override the value of $SAS_BASE_DIR.', metavar='SAS_BASE_DIR')
    parser.add_argument('-t', '--treedir', action='store', dest='treedir', default=os.getenv('TREE_DIR'),
                        help='Override the value of $TREE_DIR.', metavar='TREE_DIR')
    parser.add_argument('-m', '--modulesdir', action='store', dest='modulesdir', default=os.getenv('MODULES_DIR'),
                        help='Your modules directory', metavar='MODULES_DIR')
    parser.add_argument('-e', '--env', action='store_true', dest='env',
                        help='Create tree environment symlinks.', default=False)
    parser.add_argument('-i', '--mirror', action='store_true', dest='mirror',
                        help='Use the mirror site (SAM) instead.')
    parser.add_argument('-o', '--only', action='store', dest='only', metavar='[xxx].cfg',
                        default=None, help='create links for only the specified tree config.')

    opts = parser.parse_args()

    return opts
754425
def _parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=_CliFormatter)
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='Enable verbose output.')

    fb_group = parser.add_argument_group('FogBugz arguments')
    fb_group.add_argument(
        '-u', '--url', help=(
            'URL for bugzscout requests to be sent. Should be something '
            'like .../scoutSubmit.asp.'))
    fb_group.add_argument(
        '--user', help='User to designate when submitting via bugzscout.')
    fb_group.add_argument(
        '--project', help='Fogbugz project to file cases under.')
    fb_group.add_argument(
        '--area', help='Fogbugz area to file cases under.')

    error_group = parser.add_argument_group('error arguments')
    error_group.add_argument('-e', '--extra',
                             help='Extra data to send with error.')
    error_group.add_argument('--default-message',
                             help='Set default message if case is new.')
    error_group.add_argument('description',
                             help=('Description of error. Will be matched '
                                   'against existing cases.'))

    parser.set_defaults(**_defaults())

    return parser.parse_args()
11332
def _parse_args(args: List[str]) -> _SetArgumentsRunConfig:
    
    parser = argparse.ArgumentParser(
        prog="gitlab-set-variables", description="Tool for setting a GitLab project's build variables")
    add_common_arguments(parser, project=True)
    parser.add_argument("source", nargs="+", type=str,
                        help="File to source build variables from. Can be a ini file, JSON file or a shell script "
                             "containing 'export' statements")

    arguments = parser.parse_args(args)
    return _SetArgumentsRunConfig(arguments.source, arguments.project, arguments.url, arguments.token, arguments.debug)
1033196
def run_args(args):
    
    return main(filename      = args.get('MDFILE')
               ,theme         = args.get('-t', 'random')
               ,cols          = args.get('-c')
               ,from_txt      = args.get('-f')
               ,c_theme       = args.get('-T')
               ,c_no_guess    = args.get('-x')
               ,do_html       = args.get('-H')
               ,no_colors     = args.get('-A')
               ,display_links = args.get('-L'))