Pare down docopt. Return a minimal dictionary and a set containing runtime arg values.
323990
def get_docargs(self, args=None, prt=None, **kws):
        """"""
        args_user = sys.argv[1:] if args is None else args
        arg_kws = self._get_docargs(args_user, prt)
        if 'intvals' in kws:
            self._set_intvals(arg_kws, kws['intvals'])
        return arg_kws
1004057
def parse(self, args, ignore_help=False):
        """"""
        options = self._default_dict()

        seen = set()

        # Do not alter the arguments. We may need them later.
        args = copy.copy(args)
        while args:
            opt = args.pop(0)

            seen.add(opt)

            if opt in ("--help","-h"):
                if ignore_help:
                    continue
                raise SimoptHelp

            if not opt in self._optiondict:
                raise Usage("Unrecognized option '%s'"%opt)

            attr, typ, num, default, flags, description = self._optiondict[opt]

            if num > len(args):
                raise Usage("Option '%s' requires %d arguments"%(opt,num))

            if num:
                a = args.pop(0)
                try:
                    val = [typ(a) for i in range(num)]
                except ValueError:
                    raise Usage("Invalid argument to option '%s': %s"%(opt,repr(a)))
            else:
                # Boolean flag
                val = [True]

            if typ == bool:
                # A boolean option is simply set to True if given
                options[attr] = True
            elif flags & MULTI:
                # A multi-option adds an item or a tuple to the list
                options[attr] = options.get(attr, list())
                options[attr].append(val[0] if num == 1 else tuple(val))
            else:
                # Other options just set item or tuple
                options[attr] = val[0] if num == 1 else tuple(val)

        # All mandatory options should be seen
        missing = self.mandatory_arguments - seen
        if not ignore_help and missing:
            raise MissingMandatoryError(missing)

        return options
1212902
def convert_to_process_params_dict(opt):
    
    opt = copy.deepcopy(opt)
    for arg, val in vars(opt).items():
        if isinstance(val, DictWithDefaultReturn):
            new_val = []
            for key in val.keys():
                if isinstance(val[key], list):
                    for item in val[key]:
                        if item is not None:
                            new_val.append(':'.join([key, str(item)]))
                else:
                    if val[key] is not None:
                        new_val.append(':'.join([key, str(val[key])]))
            setattr(opt, arg, new_val)
    return vars(opt)
1035239
def trim(args):
    
    p = OptionParser(trim.__doc__)
    p.add_option("-f", dest="first", default=0, type="int",
            help="First base to keep. Default is 1.")
    p.add_option("-l", dest="last", default=0, type="int",
            help="Last base to keep. Default is entire read.")
    opts, args = p.parse_args(args)

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

    fastqfile, = args
    obfastqfile = op.basename(fastqfile)
    fq = obfastqfile.rsplit(".", 1)[0] + ".ntrimmed.fastq"
    if fastqfile.endswith(".gz"):
        fq = obfastqfile.rsplit(".", 2)[0] + ".ntrimmed.fastq.gz"

    cmd = "fastx_trimmer -Q33 "
    if opts.first:
        cmd += "-f {0.first} ".format(opts)
    if opts.last:
        cmd += "-l {0.last} ".format(opts)

    sh(cmd, infile=fastqfile, outfile=fq)
904618
def params(self) -> T.List[DocstringParam]:
        """"""
        return [
            DocstringParam.from_meta(meta)
            for meta in self.meta
            if meta.args[0]
            in {"param", "parameter", "arg", "argument", "key", "keyword"}
        ]
175768
def mini(args):
    
    p = OptionParser(mini.__doc__)
    opts, args = p.parse_args(args)

    if len(args) != 2:
        sys.exit(not p.print_help())

    bamfile, region = args
    get_minibam(bamfile, region)
257651
def parse_options():
    

    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   'k:n:ht:v',
                                   ['kval=',
                                    'size=',
                                    'help',
                                    'type=',
                                    'verb'])
    except getopt.GetoptError as err:
        sys.stderr.write(str(err).capitalize())
        usage()
        sys.exit(1)

    kval = 1
    size = 8
    ftype = 'php'
    verb = False

    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit(0)
        elif opt in ('-k', '--kval'):
            kval = int(arg)
        elif opt in ('-n', '--size'):
            size = int(arg)
        elif opt in ('-t', '--type'):
            ftype = str(arg)
        elif opt in ('-v', '--verb'):
            verb = True
        else:
            assert False, 'Unhandled option: {0} {1}'.format(opt, arg)

    return ftype, kval, size, verb
344286
def parse_args(add_args, docstring):
    """"""

    def run_args():
        """Run any global methods eponymous with args"""
        valuable_args = {k for k, v in args.__dict__.items() if v}
        arg_methods = {globals()[a] for a in valuable_args if a in globals()}
        if not arg_methods:
            return
        for method in arg_methods:
            method()
        raise SystemExit(_exit_ok)

    parser = argparse.ArgumentParser(
        description=docstring and docstring.splitlines()[0] or "No docstring")
    result = add_args(parser)
    parser = result if result else parser
    parser.add_argument('-v', '--version', action='store_true',
                        help='Show version [default: %s]' % __version__)
    # parser.add_argument('-q', '--quiet', action='store_true',
    # help='Do not show stdout')
    # parser.add_argument('-Q', '--quiet_errors', action='store_true',
    # help='Do not show stderr')
    global args  # pylint: disable=global-statement
    args = parser.parse_args()
    run_args()
    return args
229190
def items_lower(self):
        '''
        
        '''
        return ((key, val[1]) for key, val in six.iteritems(self._data))
1139693
def toDict(self):
		

		# Init the dictionary we will return
		dRet = {
			"__type__": self._type
		}

		# If there is a regex associated, add it
		if self._regex:
			dRet['__regex__'] = str(self._regex)

		# Else if there were options associated, add them
		elif self._options:
			dRet['__options__'] = self._options

		# Else check for min and max and add if either are found
		else:
			if self._minimum:
				dRet['__minimum__'] = self._minimum
			if self._maximum:
				dRet['__maximum__'] = self._maximum

		# Get the parents dict and add it to the return
		dRet.update(super(Node,self).toDict())

		# Return
		return dRet
22388
def option(current_kwargs, **kwargs):
    

    tmp_kwargs = dict((key, current_kwargs.get(key)) for key, value in kwargs.items())
    current_kwargs.update(kwargs)
    yield
    current_kwargs.update(tmp_kwargs)
854454
def split_args(self, arg_dict):
        
        pos_args = []
        for arg in self.args:
            pos_args.append(arg_dict[arg.name])
            del arg_dict[arg.name]
        return pos_args, arg_dict
634053
def parse_options(arguments=None):
    
    if arguments is None:
        arguments = sys.argv[1:]
    if isinstance(arguments, str):
        arguments = arguments.split()
    if isinstance(arguments, argparse.Namespace):
        return arguments
    parser = create_args_parser()
    args = parser.parse_args(arguments)
    # pprint(args.__dict__)

    args.dialect = args.dialect.lower()
    if args.dialect not in ['lisp', 'newlisp', 'clojure', 'scheme', 'all', '']:
        parser.error("`{0}' is not a recognized dialect".format(args.dialect))

    args.backup_dir = os.path.expanduser(args.backup_dir)
    if not os.path.exists(args.backup_dir):
        parser.error("Directory `{0}' does not exist".format(args.backup_dir))

    if len(args.files) > 1 and args.output_file:
        parser.error('Cannot use the -o flag when more than one file is specified')

    if not args.files:
        # Indentation from standard input
        if args.modify and not args.output_file:
            args.modify = False
        args.backup = False
        args.warning = False

    if args.output_diff:
        # If someone requests a diff we assume he/she doesn't want the file to be
        # modified
        args.modify = False

    return args
1241666
def parse_options():
    """"""

    server, username, password, auto_update_soa = False, False, False, False

    prs = argparse.ArgumentParser(description='usage')
    prs.add_argument('-v', '--version', action='version',
                     version=__version__)
    if os.environ.get('HOME'):
        config_file = os.environ.get('HOME') + '/.tdclirc'
        if os.path.isfile(config_file):
            (server, username,
             password, auto_update_soa) = check_config(config_file)

    conn = dict(server=server, username=username,
                password=password, auto_update_soa=auto_update_soa)

    subprs = prs.add_subparsers(help='commands')

    # Convert and print JSON
    parse_show(subprs)

    # Retrieve records
    parse_get(subprs, conn)

    # Create record
    parse_create(subprs, conn)

    # Create bulk_records
    parse_bulk_create(subprs, conn)

    # Delete record
    parse_delete(subprs, conn)

    # Delete bulk_records
    parse_bulk_delete(subprs, conn)

    # Update a record
    parse_update(subprs, conn)

    # Update SOA serial
    parse_update_soa(subprs, conn)

    # Create zone
    parse_create_zone(subprs, conn)

    # Delete zone
    parse_delete_zone(subprs, conn)

    # Retrieve template
    parse_get_tmpl(subprs, conn)

    # Delete template
    parse_delete_tmpl(subprs, conn)

    args = prs.parse_args()
    return args
602261
def getopt ( opt )
      result = { :n => '', :t => '', }
      if opt.length > OPTION_PREFIX_LONG.length then
        if opt[0, OPTION_PREFIX_LONG.length] == OPTION_PREFIX_LONG then
          result[:n] = opt[OPTION_PREFIX_LONG.length, opt.length]
          result[:t] = OPTION_PREFIX_LONG
          return result
        end
      end
      if opt.length > OPTION_PREFIX_SHORT.length then
        if opt[0, OPTION_PREFIX_SHORT.length] == OPTION_PREFIX_SHORT then
          result[:n] = opt[OPTION_PREFIX_SHORT.length, opt.length]
          result[:t] = OPTION_PREFIX_SHORT
          return result 
        end
      end
      return result
    end
1261615
def _chk_docopts(self, kws):
        """"""
        # outfile should contain .png, .png, etc.
        outfile = kws['outfile']
        if len(kws) == 2 and os.path.basename(kws['obo']) == "go-basic.obo" and \
            kws['outfile'] == self.dflt_outfile:
            self._err("NO GO IDS SPECFIED", err=False)
        if 'obo' in outfile:
            self._err("BAD outfile({O})".format(O=outfile))
        if 'gaf' in kws and 'gene2go' in kws:
            self._err("SPECIFY ANNOTAIONS FROM ONE FILE")
        if 'gene2go' in kws:
            if 'taxid' not in kws:
                self._err("SPECIFIY taxid WHEN READ NCBI'S gene2go FILE")
630763
def arguments(self, args):
        """"""
        self.args = args
        self.manage_flags()
        self.filename = self.args[0]
        if len(self.args) == 1 and self.args[0] in self.options[:2]:
            print(self.help.__doc__)
        elif len(self.args) == 1 and self.args[0] in self.options[2:4]:
            self.version()
        elif len(self.args) == 2 and self.args[0] in self.options[4:5]:
            self.filename = self.args[1]
            self.remove()
        elif len(self.args) == 2 and self.args[0] in self.options[6:7]:
            self.filename = self.args[1]
            self.remove()
        elif len(self.args) == 1:
            if os.path.isfile(self.args[0]):
                self.remove()
            else:
                self.not_access()
        else:
            self.usage()