Helper function to create the command-line argument parser for faaspact_verifier.  Return the
    parsed arguments as a Namespace object if successful. Exits the program if unsuccessful or if
    the help message is printed.
331003
def _parse_args() -> argparse.Namespace:
    
    description = ('Run pact verifier tests against a faas microservice.')
    parser = argparse.ArgumentParser(description=description)

    parser.add_argument('--host',
                        default=os.environ.get('PACT_BROKER_HOST'),
                        help='Pact broker host. (default=env.PACT_BROKER_HOST)')

    parser.add_argument('--username',
                        default=os.environ.get('PACT_BROKER_USERNAME'),
                        help='Pact broker username. (default=env.PACT_BROKER_USERNAME)')

    parser.add_argument('--password',
                        default=os.environ.get('PACT_BROKER_PASSWORD'),
                        help='Pact broker password. (default=env.PACT_BROKER_PASSWORD)')

    parser.add_argument('-f', '--faasport-module',
                        default=os.environ.get('FAASPORT_MODULE'),
                        help='Python path to faasport module. (default=env.FAASPORT_MODULE)')

    parser.add_argument('-p', '--provider',
                        default=os.environ.get('PACT_PROVIDER'),
                        help='Name of the provider. (default=env.PACT_PROVIDER)')

    parser.add_argument('--publish-results',
                        action='store_true',
                        default=False,
                        help='If true, publish verification results to the broker.')

    parser.add_argument('--provider-version',
                        required=False,
                        help='The version of the provider. Defaults to the current git SHA.')

    parser.add_argument('--github-pr',
                        required=False,
                        help=('Url of associated github PR. If PR body has line '
                              '"feature-pacts: x y ...", those feature-pacts will be added to '
                              '--failon tags.'))

    parser.add_argument('--failon',
                        action='append',
                        default=['master'],
                        help=('If verification fails for a pact with one of these tags, this script'
                              ' will fail.'))

    args = parser.parse_args()

    if not args.provider_version:
        args.provider_version = _current_commit_sha()

    if not args.host:
        raise parser.error('Missing host')

    if not args.username:
        raise parser.error('Missing username')

    if not args.password:
        raise parser.error('Missing password')

    if not args.faasport_module:
        raise parser.error('Missing faasport_module')

    if not args.provider:
        raise parser.error('Missing provider')

    return args
1110503
def parse_args(self, argv):
        
        desc = 'Report on AWS service limits and usage via boto3, optionally ' \
               'warn about any services with usage nearing or exceeding their' \
               ' limits. For further help, see ' \
               '<http://awslimitchecker.readthedocs.org/>'
        # ###### IMPORTANT license notice ##########
        # Pursuant to Sections 5(b) and 13 of the GNU Affero General Public
        # License, version 3, this notice MUST NOT be removed, and MUST be
        # displayed to ALL USERS of this software, even if they interact with
        # it remotely over a network.
        #
        # See the "Development" section of the awslimitchecker documentation
        # (docs/source/development.rst or
        # <http://awslimitchecker.readthedocs.org/en/latest/development.html> )
        # for further information.
        # ###### IMPORTANT license notice ##########
        epilog = 'awslimitchecker is AGPLv3-licensed Free Software. Anyone ' \
                 'using this program, even remotely over a network, is ' \
                 'entitled to a copy of the source code. Use `--version` for ' \
                 'information on the source code location.'
        p = argparse.ArgumentParser(description=desc, epilog=epilog)
        p.add_argument('-S', '--service', action='store', nargs='*',
                       help='perform action for only the specified service name'
                            '; see -s|--list-services for valid names')
        p.add_argument('--skip-service', action='append', default=[],
                       dest='skip_service',
                       help='avoid performing actions for the specified service'
                            ' name; see -s|--list-services for valid names')
        p.add_argument('--skip-check', action='append', default=[],
                       dest='skip_check',
                       help='avoid performing actions for the specified check'
                            ' name')
        p.add_argument('-s', '--list-services', action='store_true',
                       default=False,
                       help='print a list of all AWS service types that '
                            'awslimitchecker knows how to check')
        p.add_argument('-l', '--list-limits', action='store_true',
                       default=False,
                       help='print all AWS effective limits in "service_name/'
                       'limit_name" format')
        p.add_argument('--list-defaults', action='store_true', default=False,
                       help='print all AWS default limits in "service_name/'
                       'limit_name" format')
        p.add_argument('-L', '--limit', action=StoreKeyValuePair,
                       help='override a single AWS limit, specified in '
                       '"service_name/limit_name=value" format; can be '
                       'specified multiple times.')
        p.add_argument('-u', '--show-usage', action='store_true',
                       default=False,
                       help='find and print the current usage of all AWS '
                       'services with known limits')
        p.add_argument('--iam-policy', action='store_true',
                       default=False,
                       help='output a JSON serialized IAM Policy '
                       'listing the required permissions for '
                       'awslimitchecker to run correctly.')
        p.add_argument('-W', '--warning-threshold', action='store',
                       type=int, default=80,
                       help='default warning threshold (percentage of '
                       'limit); default: 80')
        p.add_argument('-C', '--critical-threshold', action='store',
                       type=int, default=99,
                       help='default critical threshold (percentage of '
                       'limit); default: 99')
        p.add_argument('-P', '--profile', action='store', dest='profile_name',
                       type=str, default=None,
                       help='Name of profile in the AWS cross-sdk credentials '
                            'file to use credentials from; similar to the '
                            'corresponding awscli option')
        p.add_argument('-A', '--sts-account-id', action='store',
                       type=str, default=None,
                       help='for use with STS, the Account ID of the '
                       'destination account (account to assume a role in)')
        p.add_argument('-R', '--sts-account-role', action='store',
                       type=str, default=None,
                       help='for use with STS, the name of the IAM role to '
                       'assume')
        p.add_argument('-E', '--external-id', action='store', type=str,
                       default=None, help='External ID to use when assuming '
                       'a role via STS')
        p.add_argument('-M', '--mfa-serial-number', action='store', type=str,
                       default=None, help='MFA Serial Number to use when '
                       'assuming a role via STS')
        p.add_argument('-T', '--mfa-token', action='store', type=str,
                       default=None, help='MFA Token to use when assuming '
                       'a role via STS')
        p.add_argument('-r', '--region', action='store',
                       type=str, default=None,
                       help='AWS region name to connect to; required for STS')
        p.add_argument('--skip-ta', action='store_true', default=False,
                       help='do not attempt to pull *any* information on limits'
                       ' from Trusted Advisor')
        g = p.add_mutually_exclusive_group()
        g.add_argument('--ta-refresh-wait', dest='ta_refresh_wait',
                       action='store_true', default=False,
                       help='If applicable, refresh all Trusted Advisor '
                            'limit-related checks, and wait for the refresh to'
                            ' complete before continuing.')
        g.add_argument('--ta-refresh-trigger', dest='ta_refresh_trigger',
                       action='store_true', default=False,
                       help='If applicable, trigger refreshes for all Trusted '
                            'Advisor limit-related checks, but do not wait for '
                            'them to finish refreshing; trigger the refresh '
                            'and continue on (useful to ensure checks are '
                            'refreshed before the next scheduled run).')
        g.add_argument('--ta-refresh-older', dest='ta_refresh_older',
                       action='store', type=int, default=None,
                       help='If applicable, trigger refreshes for all Trusted '
                            'Advisor limit-related checks with results more '
                            'than this number of seconds old. Wait for the '
                            'refresh to complete before continuing.')
        p.add_argument('--ta-refresh-timeout', dest='ta_refresh_timeout',
                       type=int, action='store', default=None,
                       help='If waiting for TA checks to refresh, wait up to '
                            'this number of seconds before continuing on '
                            'anyway.')
        p.add_argument('--no-color', action='store_true', default=False,
                       help='do not colorize output')
        p.add_argument('--no-check-version', action='store_false', default=True,
                       dest='check_version',
                       help='do not check latest version at startup')
        p.add_argument('-v', '--verbose', dest='verbose', action='count',
                       default=0,
                       help='verbose output. specify twice for debug-level '
                       'output.')
        p.add_argument('-V', '--version', dest='version', action='store_true',
                       default=False,
                       help='print version number and exit.')
        args = p.parse_args(argv)
        args.ta_refresh_mode = None
        if args.ta_refresh_wait:
            args.ta_refresh_mode = 'wait'
        elif args.ta_refresh_trigger:
            args.ta_refresh_mode = 'trigger'
        elif args.ta_refresh_older is not None:
            args.ta_refresh_mode = args.ta_refresh_older
        return args
1247880
def _get_args_name_from_parser(parser):
    
    # Retrieve the 'action' destination of the method parser i.e. its
    # argument name. The HelpAction is ignored.
    return [action.dest for action in parser._actions if not
            isinstance(action, argparse._HelpAction)]
89491
def parse_command_line_parameters(argv=None):
    
    usage =\
        'usage: %prog [options] input_sequences_filepath'
    version = 'Version: %prog ' + __version__
    parser = OptionParser(usage=usage, version=version)

    parser.add_option('-o', '--output_fp', action='store',
                      type='string', dest='output_fp', help='Path to store ' +
                      'output file [default: generated from input_sequences_filepath]')

    parser.add_option('-c', '--min_confidence', action='store',
                      type='float', dest='min_confidence', help='minimum confidence ' +
                      'level to return a classification [default: %default]')

    parser.set_defaults(verbose=False, min_confidence=0.80)

    opts, args = parser.parse_args(argv)
    if len(args) != 1:
        parser.error('Exactly one argument is required.')

    return opts, args
739714
def parse_command_line(argv):
    
    import textwrap

    example = textwrap.dedent("""
    Examples:
    # Simple string substitution (-e). Will show a diff. No changes applied.
    {0} -e "re.sub('failIf', 'assertFalse', line)" *.py

    # File level modifications (-f). Overwrites the files in place (-w).
    {0} -w -f fixer:fixit *.py

    # Will change all test*.py in subdirectories of tests.
    {0} -e "re.sub('failIf', 'assertFalse', line)" -s tests test*.py
    """).format(os.path.basename(argv[0]))
    formatter_class = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(description="Python mass editor",
                                     epilog=example,
                                     formatter_class=formatter_class)
    parser.add_argument("-V", "--version", action="version",
                        version="%(prog)s {}".format(__version__))
    parser.add_argument("-w", "--write", dest="dry_run",
                        action="store_false", default=True,
                        help="modify target file(s) in place. "
                        "Shows diff otherwise.")
    parser.add_argument("-v", "--verbose", dest="verbose_count",
                        action="count", default=0,
                        help="increases log verbosity (can be specified "
                        "multiple times)")
    parser.add_argument("-e", "--expression", dest="expressions", nargs=1,
                        help="Python expressions applied to target files. "
                        "Use the line variable to reference the current line.")
    parser.add_argument("-f", "--function", dest="functions", nargs=1,
                        help="Python function to apply to target file. "
                        "Takes file content as input and yield lines. "
                        "Specify function as [module]:?<function name>.")
    parser.add_argument("-x", "--executable", dest="executables", nargs=1,
                        help="Python executable to apply to target file.")
    parser.add_argument("-s", "--start", dest="start_dirs",
                        help="Directory(ies) from which to look for targets.")
    parser.add_argument("-m", "--max-depth-level", type=int, dest="max_depth",
                        help="Maximum depth when walking subdirectories.")
    parser.add_argument("-o", "--output", metavar="FILE",
                        type=argparse.FileType("w"), default=sys.stdout,
                        help="redirect output to a file")
    parser.add_argument("-g", "--generate", metavar="FILE", type=str,
                        help="generate input file suitable for -f option")
    parser.add_argument("--encoding", dest="encoding",
                        help="Encoding of input and output files")
    parser.add_argument("--newline", dest="newline",
                        help="Newline character for output files")
    parser.add_argument("patterns", metavar="pattern",
                        nargs="*",  # argparse.REMAINDER,
                        help="shell-like file name patterns to process.")
    arguments = parser.parse_args(argv[1:])

    if not (arguments.expressions or
            arguments.functions or
            arguments.generate or
            arguments.executables):
        parser.error(
            '--expression, --function, --generate or --executable missing')

    # Sets log level to WARN going more verbose for each new -V.
    log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
    return arguments
1186265
function verifyNamespace(namespace) {
	if (namespace && typeof namespace !== 'string') {
		const msg = util.format('Namespace must be a non-empty string: %j', namespace);
		logger.error('verifyNamespace:', msg);
		throw new Error(msg);
	}
}
412334
def callfunc(self, argv=None):
        
        if not self.checked:
            self.check_arguments()
            self.checked = True
        namespace = self.parentparser.parse_args(argv or sys.argv[1:])
        return self.func(**vars(namespace))
931010
def init_argparser(self, argparser):
        

        def prepare_argparser():
            if argparser in self.argparser_details:
                return False
            result = self.argparser_details[argparser] = ArgumentParserDetails(
                {}, {}, {})
            return result

        def to_module_attr(ep):
            return '%s:%s' % (ep.module_name, '.'.join(ep.attrs))

        def register(name, runtime, entry_point):
            subparser = commands.add_parser(
                name, help=inst.description,
            )
            # Have to specify this separately because otherwise the
            # subparser will not have a proper description when it is
            # invoked as the root.
            subparser.description = inst.description

            # Assign values for version reporting system
            setattr(subparser, ATTR_ROOT_PKG, getattr(
                argparser, ATTR_ROOT_PKG, self.package_name))
            subp_info = []
            subp_info.extend(getattr(argparser, ATTR_INFO, []))
            subp_info.append((subparser.prog, entry_point.dist))
            setattr(subparser, ATTR_INFO, subp_info)

            try:
                try:
                    runtime.init_argparser(subparser)
                except RuntimeError as e:
                    # first attempt to filter out recursion errors; also if
                    # the stack frame isn't available the complaint about
                    # bad validation doesn't apply anyway.
                    frame = currentframe()
                    if (not frame or 'maximum recursion depth' not in str(
                            e.args)):
                        raise

                    if (not isinstance(runtime, Runtime) or (type(
                            runtime).entry_point_load_validated.__code__ is
                            Runtime.entry_point_load_validated.__code__)):
                        # welp, guess some other thing blew up then, or
                        # that the problem is definitely not caused by
                        # this runtime implementation.
                        # TODO figure out how to log this nicer via the
                        # self.log_debug_error without exploding the
                        # console like Megumin would have done.
                        raise

                    # assume the overridden method didn't do everything
                    # correctly then; would be great if there is a way
                    # to ensure that our thing would have been called.
                    cls = type(runtime)
                    logger.critical(
                        "Runtime subclass at entry_point '%s' has override "
                        "'entry_point_load_validated' without filtering out "
                        "its parent classes; this can be addressed by calling "
                        "super(%s.%s, self).entry_point_load_validated("
                        "entry_point) in its implementation, or simply don't "
                        "override that method to avoid infinite recursion.",
                        entry_point, cls.__module__, cls.__name__,
                    )
                    exc = RuntimeError(
                        "%r has an invalid 'entry_point_load_validated' "
                        "implementation: insufficient protection against "
                        "infinite recursion into self not provided" % runtime
                    )
                    # for Python 3 to not blow it up.
                    exc.__suppress_context__ = True
                    raise exc
            except Exception as e:
                self.log_debug_error(
                    "cannot register entry_point '%s' from '%s' as a "
                    "subcommand to '%s': %s: %s",
                    entry_point, entry_point.dist, argparser.prog,
                    e.__class__.__name__, e
                )
                # this is where naughty things happen: will be poking at
                # the parser internals to undo the damage that was done
                # first, pop the choices_actions as a help was provided
                commands._choices_actions.pop()
                # then pop the name that was mapped.
                commands._name_parser_map.pop(name)
            else:
                # finally record the completely initialized subparser
                # into the structure here if successful.
                subparsers[name] = subparser
                runtimes[name] = runtime
                entry_points[name] = entry_point

        details = prepare_argparser()
        if not details:
            logger.debug(
                'argparser %r has already been initialized against runner %r',
                argparser, self,
            )
            return
        subparsers, runtimes, entry_points = details

        super(Runtime, self).init_argparser(argparser)

        commands = argparser.add_subparsers(
            dest=self.action_key, metavar='<command>')
        # Python 3.7 has required set to True, which is correct in most
        # cases but this disables the manual handling for cases where a
        # command was not provided; also this generates a useless error
        # message that simply states "<command> is required" and forces
        # the program to exit.  As the goal of this suite of classes is
        # to act as a helpful CLI front end, force required to be False
        # to keep our manual handling and management of subcommands.
        # Setting this as a property for compatibility with Python<3.7,
        # as only in Python>=3.7 the add_subparsers can accept required
        # as an argument.
        commands.required = False

        for entry_point in self.iter_entry_points():
            inst = self.entry_point_load_validated(entry_point)
            if not inst:
                continue

            if entry_point.name in runtimes:
                reg_ep = entry_points[entry_point.name]
                reg_rt = runtimes[entry_point.name]

                if reg_rt is inst:
                    # this is fine, multiple packages declared the same
                    # thing with the same name.
                    logger.debug(
                        "duplicated registration of command '%s' via entry "
                        "point '%s' ignored; registered '%s', confict '%s'",
                        entry_point.name, entry_point, reg_ep.dist,
                        entry_point.dist,
                    )
                    continue

                logger.error(
                    "a calmjs runtime command named '%s' already registered.",
                    entry_point.name
                )
                logger.info("conflicting entry points are:")
                logger.info(
                    "'%s' from '%s' (registered)", reg_ep, reg_ep.dist)
                logger.info(
                    "'%s' from '%s' (conflict)", entry_point, entry_point.dist)
                # Fall back name should work if the class/instances are
                # stable.
                name = to_module_attr(entry_point)

                if name in runtimes:
                    # Maybe this is the third time this module is
                    # registered.  Test for its identity.
                    if runtimes[name] is not inst:
                        # Okay someone is having a fun time here mucking
                        # with data structures internal to here, likely
                        # (read hopefully) due to testing or random
                        # monkey patching (or module level reload).
                        logger.critical(
                            "'%s' is already registered but points to a "
                            "completely different instance; please try again "
                            "with verbose logging and note which packages are "
                            "reported as conflicted; alternatively this is a "
                            "forced situation where this Runtime instance has "
                            "been used or initialized improperly.",
                            name
                        )
                    else:
                        logger.debug(
                            "fallback command '%s' is already registered.",
                            name
                        )
                    continue

                logger.error(
                    "falling back to using full instance path '%s' as command "
                    "name, also registering alias for registered command", name
                )
                register(to_module_attr(reg_ep), reg_rt, reg_ep)
            else:
                name = entry_point.name

            register(name, inst, entry_point)
1353729
def _parse_command_line_arguments():
    
    global config
    # Get command line args for vispy
    argnames = ['vispy-backend=', 'vispy-gl-debug', 'vispy-glir-file=',
                'vispy-log=', 'vispy-help', 'vispy-profile=', 'vispy-cprofile',
                'vispy-dpi=', 'vispy-audit-tests']
    try:
        opts, args = getopt.getopt(sys.argv[1:], '', argnames)
    except getopt.GetoptError:
        opts = []
    # Use them to set the config values
    for o, a in opts:
        if o.startswith('--vispy'):
            if o == '--vispy-backend':
                config['default_backend'] = a
                logger.info('vispy backend: %s', a)
            elif o == '--vispy-gl-debug':
                config['gl_debug'] = True
            elif o == '--vispy-glir-file':
                config['glir_file'] = a
            elif o == '--vispy-log':
                if ',' in a:
                    verbose, match = a.split(',')
                else:
                    verbose = a
                    match = None
                config['logging_level'] = a
                set_log_level(verbose, match)
            elif o == '--vispy-profile':
                config['profile'] = a
            elif o == '--vispy-cprofile':
                _enable_profiling()
            elif o == '--vispy-help':
                print(VISPY_HELP)
            elif o == '--vispy-dpi':
                config['dpi'] = int(a)
            elif o == '--vispy-audit-tests':
                config['audit_tests'] = True
            else:
                logger.warning("Unsupported vispy flag: %s" % o)
155223
def create_parser(self, prog_name, subcommand):
        
        if not self.use_argparse:
            self.__class__.option_list = TestCommand.option_list + self.custom_options
        parser = super(Command, self).create_parser(prog_name, subcommand)
        return parser
1337937
def load_args(self, args, clargs):
        
        # Parse All Arguments
        args = self.parser.parse_args(args=clargs, namespace=args)

        # Print the help information if no subcommand is given
        # subcommand is required for operation
        if args.subcommand is None:
            self.parser.print_help()
            args = None

        return args
908522
def parse_args():
    
    parser = argparse.ArgumentParser(description="Converts, and downloads a vm by name from vCenter to OVF in specified"
                                                 " directory, then uploads the image as an AMI. AMI will be uploaded "
                                                 "using specified AWS profile, to specified regions. ")
    parser.add_argument('-i', '--vcenter_host', type=str, required=True, help='Hostname or Ip of vCenter API of VM')
    parser.add_argument('-u', '--vcenter_user', type=str, required=True, help='Username for vCenter authentication')
    parser.add_argument('-p', '--vcenter_pass', type=str, required=True, help='Password for authentication to vCenter API')
    parser.add_argument('-n', '--vm_name', type=str, required=True, help='Name of the VM in vCenter')
    parser.add_argument('-d', '--directory', type=str, default=tempfile.mkdtemp(),
                        help='Directory to save the vmdk temp file (defaults to temp location')
    parser.add_argument('-w', '--vcenter_port', type=str, default='443',
                        help='Port to use for communication to vcenter api. Default is 443')
    args = parser.parse_args()
    validate_args(args)
    return args
976199
def get_arg_parse():
    """"""
    # Create parser object:
    objParser = argparse.ArgumentParser()

    # Add argument to namespace -config file path:
    objParser.add_argument('-config', required=True,
                           metavar='/path/to/config.csv',
                           help='Absolute file path of config file with \
                                 parameters for pRF analysis. Ignored if in \
                                 testing mode.'
                           )

    # Add argument to namespace -prior results file path:
    objParser.add_argument('-strPthPrior', required=True,
                           metavar='/path/to/my_prior_res',
                           help='Absolute file path of prior pRF results. \
                                 Ignored if in testing mode.'
                           )

    # Add argument to namespace -varNumOpt1 flag:
    objParser.add_argument('-varNumOpt1', required=True, type=int,
                           metavar='N1',
                           help='Number of radial positions.'
                           )

    # Add argument to namespace -varNumOpt2 flag:
    objParser.add_argument('-varNumOpt2', required=True, type=int,
                           metavar='N2',
                           help='Number of angular positions.'
                           )

    # Add argument to namespace -varNumOpt3 flag:
    objParser.add_argument('-varNumOpt3', default=None, metavar='N3',
                           help='Max displacement in radial direction.'
                           )

    # Add argument to namespace -lgcRstrCentre flag:
    objParser.add_argument('-lgcRstrCentre', dest='lgcRstrCentre',
                           action='store_true', default=False,
                           help='Restrict fitted models to stimulated area.')

    objParser.add_argument('-strPathHrf', default=None, required=False,
                           metavar='/path/to/custom_hrf_parameter.npy',
                           help='Path to npy file with custom hrf parameters. \
                           Ignored if in testing mode.')

    objParser.add_argument('-supsur', nargs='+',
                           help='List of floats that represent the ratio of \
                                 size neg surround to size pos center.',
                           type=float, default=None)

    # Namespace object containign arguments and values:
    objNspc = objParser.parse_args()

    return objNspc
1044012
def parse_arguments():
    
    # Pull a few settings from the environment, should they exist
    base_dn = os.environ['PUDL_BASE_DN'] if 'PUDL_BASE_DN' in os.environ \
              else 'OU=Departments,DC=example,DC=com'
    domain = os.environ['PUDL_DOMAIN'].upper() if 'PUDL_DOMAIN' in os.environ else 'EXAMPLE'
    page_size = os.environ['PUDL_PAGE_SIZE'].upper() if 'PUDL_PAGE_SIZE' in os.environ else 300
    tls_no_verify = bool(os.environ['PUDL_TLS_NO_VERIFY'].lower().capitalize()) \
                    if 'PUDL_TLS_NO_VERIFY' in os.environ else False

    parser = argparse.ArgumentParser(prog='pudl',
                                     description='A script for interacting with Active ' + \
                                     'Directory, leveraging python-ldap')
    parser.add_argument('-V', '--version', action='version', version='pudl v' + pudl_version,
                        help="Print the version number and exit")
    subparsers = parser.add_subparsers(dest='subcommand', help='Sub-command help')
    parser_common = subparsers.add_parser('common', add_help=False)
    parser_common.add_argument('--user', '-u', action='store', dest='user',
                               help='The ldap user (bind dn) to connect as. ' + \
                               'The full DN will work, or often, just the CN may be ' + \
                               'sufficient, such as "John Smith", or more commonly, ' + \
                               'specify the domain and sAMAccountName. Defaults to ' + \
                               '{0}\\username.  The domain '.format(domain) + \
                               'portion may be overridden with PUDL_DOMAIN',
                               default='{0}\\{1}'.format(domain, getpass.getuser()))
    parser_common.add_argument('--password', '-p', action='store',
                               dest='password', help="The connecting user's password")
    parser_common.add_argument('--host', '-H', action='store',
                               dest='host', help='The AD/LDAP host, defaults to ldap',
                               default='ldap')
    parser_common.add_argument('--port', '-P', action='store', dest='port',
                               help='The ldap port, defaults to 389.  389 is ' + \
                               'is the standard port', type=int, default=389)
    parser_common.add_argument('--page-size', '-s', action='store', dest='page_size',
                               help='The ldap results are paged, specify the ' + \
                               'number of results per page, defaults to ' + \
                               '{0}. May be overridden with PUDL_PAGE_SIZE'.format(page_size),
                               type=int, default=page_size)
    parser_common.add_argument('--base-dn', '-b', action='store',
                               dest='base_dn', default=base_dn,
                               help="The Base DN to use, defaults to {0}. ".format(base_dn) + \
                               "May be overridden with PUDL_BASE_DN")
    parser_common.add_argument('--attribute', '-a', action='append',
                               dest='attributes', metavar='ATTRIBUTE',
                               help="Attributes to include in results objects.  Note that " + \
                               "any nested objects return all attributes.  Maybe be used " + \
                               "multiple times, and if not specified, all " + \
                               "attributes are included in top-level objects")
    parser_common.add_argument('--grep', '-g', action='append', dest='grep',
                               help='Filter results to only those matching the specified ' + \
                               'regular expression (compares against all attributes). ' + \
                               'May be used multiple times')
    parser_common.add_argument('--attributes-only', '-A', action='store_true',
                               dest='attributes_only', help="Only display a list of attributes " + \
                               "that are present for the object type returned by the LDAP query")
    parser_common.add_argument('--output-format', '-f', action='store', dest='output_format',
                               choices=['json', 'yaml'], default='json',
                               help="Output format, defaults to json.")
    parser_common.add_argument('--verbose', '-v', action='store_true', dest='verbose',
                               help='Turn on verbose output', default=False)
    parser_common.add_argument('--debug', '-d', action='store_true', dest='debug', default=False,
                               help="Print out debugging information, very chatty")
    parser_common.add_argument('--tls-no-verify', '-V', action='store_true',
                               dest='tls_no_verify',
                               default=tls_no_verify, help="Don't verify the authenticity " + \
                               "of the server's certificate, defaults to " + \
                               "{0} and may be overridden with ".format(tls_no_verify) + \
                               "PUDL_TLS_NO_VERIFY")
    parser_user = subparsers.add_parser('user', parents=[parser_common], conflict_handler='resolve',
                                        help='Pull user objects from AD')
    parser_user.add_argument(nargs="*", dest='samaccountnames',
                             help='sAMAccountNames for any user objects that are to be ' + \
                             'looked up. If unspecified, returns all users under the base ' + \
                             'DN provided')
    parser_user.add_argument('--explicit-membership-only', '-e', action='store_true',
                             dest='explicit_membership_only', default=False,
                             help="Only show membership for users that is explicit, " + \
                             "not taking into account group nesting.  Defaults to False")
    parser_group = subparsers.add_parser('group', parents=[parser_common],
                                         conflict_handler='resolve',
                                         help='Pull group objects from AD')
    parser_group.add_argument(nargs="*", dest='samaccountnames',
                              help="sAMAccountNames for any group objects that are to be " + \
                              'looked up. If unspecified, returns all groups under the base ' + \
                              'DN provided. sAMAccountName may not be present in group ' + \
                              'objects in modern AD schemas')
    parser_group.add_argument('--explicit-membership-only', '-e', action='store_true',
                              dest='explicit_membership_only', default=False,
                              help="Only show membership for users that is explicit, " + \
                              "not taking into account group nesting.  Defaults to False")
    parser_computer = subparsers.add_parser('computer', parents=[parser_common],
                                            conflict_handler='resolve',
                                            help='Pull computer objects from AD')
    parser_computer.add_argument(nargs="*", dest='samaccountnames',
                                 help="sAMAccountNames for any computer objects that are to be " + \
                                 'looked up. If unspecified, returns all computers under ' + \
                                 'the base DN provided.')

    # sphinx is not add_help=False aware...
    del subparsers.choices['common']

    return parser
626847
def create_argument_parser():
    
    parser = argparse.ArgumentParser(prog='haas')
    parser.add_argument('--version', action='version',
                        version='%(prog)s {0}'.format(haas.__version__))
    verbosity = parser.add_mutually_exclusive_group()
    verbosity.add_argument('-v', '--verbose', action='store_const', default=1,
                           dest='verbosity', const=2, help='Verbose output')
    verbosity.add_argument('-q', '--quiet', action='store_const', const=0,
                           dest='verbosity', help='Quiet output')
    parser.add_argument('-f', '--failfast', action='store_true', default=False,
                        help='Stop on first fail or error')
    parser.add_argument('-c', '--catch', dest='catch_interrupt',
                        action='store_true', default=False,
                        help=('(Ignored) Catch ctrl-C and display results so '
                              'far'))
    parser.add_argument('-b', '--buffer', action='store_true', default=False,
                        help='Buffer stdout and stderr during tests')
    parser.add_argument(
        'start', nargs='*', default=[os.getcwd()],
        help=('One or more directories or dotted package/module names from '
              'which to start searching for tests'))
    parser.add_argument('-p', '--pattern', default='test*.py',
                        help="Pattern to match tests ('test*.py' default)")
    parser.add_argument('-t', '--top-level-directory', default=None,
                        help=('Top level directory of project (defaults to '
                              'start directory)'))
    _add_log_level_option(parser)
    return parser
144549
def get_argument_parser():
    
    desc = 'Generate a sample sheet based on a GEO series matrix.'
    parser = cli.get_argument_parser(desc=desc)

    g = parser.add_argument_group('Input and output files')

    g.add_argument(
        '-s', '--series-matrix-file', type=cli.str_type, required=True,
        metavar=cli.file_mv, help='The GEO series matrix file.'
    )

    g.add_argument(
        '-o', '--output-file', type=cli.str_type,
        required=True,
        metavar=cli.file_mv, help='The output file.'
    )

    g.add_argument(
        '-e', '--encoding', type=cli.str_type,
        metavar=cli.str_mv, default='UTF-8',
        help='The encoding of the series matrix file. [UTF-8]'
    )

    cli.add_reporting_args(parser)

    return parser
543795
def get_cxflow_arg_parser(add_common_arguments: bool=False) -> ArgumentParser:
    
    # create parser
    main_parser = ArgumentParser('cxflow',
                                 description='cxflow: lightweight framework for machine learning with '
                                             'focus on modularization, re-usability and rapid experimenting.',
                                 epilog='For more info see <https://cognexa.github.io/cxflow>')

    main_parser.add_argument('--version', action='version', help='Print cxflow version and quit.',
                             version='cxflow {}'.format(pkg_resources.get_distribution('cxflow').version))
    subparsers = main_parser.add_subparsers(help='cxflow commands')

    # create train sub-parser
    train_parser = subparsers.add_parser('train', description='Start cxflow training from the ``config_file``.')
    train_parser.set_defaults(subcommand='train')
    train_parser.add_argument('config_file', help='path to the config file')

    # create resume sub-parser
    resume_parser = subparsers.add_parser('resume', description='Resume cxflow training from the ``config_path``.')
    resume_parser.set_defaults(subcommand='resume')
    resume_parser.add_argument('config_path', help='path to the config file or the directory in which it is stored')
    resume_parser.add_argument('restore_from', nargs='?', default=None,
                               help='information passed to the model constructor (backend-specific); '
                                    'usually a directory in which the trained model is stored')

    # create predict sub-parser (deprecated)
    predict_parser = subparsers.add_parser('predict', description='Run prediction with the given ``config_path``.')
    predict_parser.set_defaults(subcommand='predict')
    predict_parser.add_argument('config_path', help='path to the config file or the directory in which it is stored')
    predict_parser.add_argument('restore_from', nargs='?', default=None,
                                help='information passed to the model constructor (backend-specific); usually a '
                                     'directory in which the trained model is stored')

    # create eval sub-parser
    eval_parser = subparsers.add_parser('eval', description='Evaluate the given model on the specified data stream.')
    eval_parser.set_defaults(subcommand='eval')
    eval_parser.add_argument('stream_name', help='stream name to be evaluated')
    eval_parser.add_argument('model_path', help='model path to be evaluated')
    eval_parser.add_argument('--config', '-c', nargs='?', default=None, help='optional config path to be used')

    # create dataset sub-parser
    dataset_parser = subparsers.add_parser('dataset', description='Invoke arbitrary dataset method.')
    dataset_parser.set_defaults(subcommand='dataset')
    dataset_parser.add_argument('method', help='name of the method to be invoked')
    dataset_parser.add_argument('config_file', help='path to the config file')

    # create grid-search sub-parser
    gridsearch_parser = subparsers.add_parser('gridsearch', description='Do parameter grid search (experimental).')
    gridsearch_parser.set_defaults(subcommand='gridsearch')
    gridsearch_parser.add_argument('script', help='Script to be grid-searched')
    gridsearch_parser.add_argument('params', nargs='*', help='Params to be tested. Format: name:type=[value1,value2]. '
                                                             'Type is optional')
    gridsearch_parser.add_argument('--dry-run', action='store_true', help='Only print command output instead '
                                                                          'of executing it right away')

    # create ls sub-parser
    ls_parser = subparsers.add_parser('ls', description='List training log dirs in the given path.')
    ls_parser.set_defaults(subcommand='ls')
    ls_parser.add_argument('dir', nargs='?', default=CXF_DEFAULT_LOG_DIR,
                           help='path to the log directory to be listed')
    ls_parser.add_argument('-l', '--long', action='store_true', help='use long listing format')
    ls_parser.add_argument('-a', '--all', action='store_true', help='include trainings with no epochs done')
    ls_parser.add_argument('-r', '--recursive', action='store_true',
                           help='list all the dirs recursively, stop at training dirs')
    ls_parser.add_argument('-v', '--verbose', action='store_true',
                           help='print more verbose output, applicable only when a single train dir is listed')

    # create prune sub-parser
    prune_parser = subparsers.add_parser('prune', description='Prune training log dirs in the given path without finished epochs.')
    prune_parser.set_defaults(subcommand='prune')
    prune_parser.add_argument('dir', nargs='?', default=CXF_DEFAULT_LOG_DIR,
                           help='path to the log directory to be pruned')
    prune_parser.add_argument('-e', '--epochs', default=1, type=int,
                              help='keep only training log dirs having at least this many completed epochs, default 1')
    prune_parser.add_argument('-s', '--subdirs', action='store_true',
                              help='delete all subdirectories in training directories')

    # add common arguments
    if add_common_arguments:
        for parser in [main_parser, train_parser, resume_parser, predict_parser, dataset_parser, eval_parser]:
            parser.add_argument('--output_root', '-o', default='./log', help='output directory')
            parser.add_argument('--verbose', '-v', action='store_true', help='increase verbosity to level DEBUG')

    return main_parser