Pare down docopt. Return a minimal dictionary and a set containing runtime arg values.
540717
def _get_docargs(self, args_user, prt):
        """"""
        if prt is not None:
            print("DocOptParse BEFORE docopt: {}".format(args_user))
        docargs = docopt(self.doc, args_user)
        if prt is not None:
            print("DocOptParse AFTER  docopt: {}".format(docargs))
        kwargs_doc = {re.sub(r'^-{1,2}', '', k):v for k, v in docargs.items()}
        self._chk_docopt_kws(kwargs_doc, args_user)
        kwargs_usr = get_kwargs(kwargs_doc, self.exp_keys, self.exp_elems)
        if prt is not None:
            print("DocOptParse AFTER  pared: {}".format(kwargs_usr))
        for key in ['taxid']:
            if key in kwargs_usr:
                kwargs_usr[key] = int(kwargs_usr[key])
        if prt is not None:
            print("DocOptParse AFTER  edited/checked: {}".format(kwargs_usr))
        return kwargs_usr
825128
def docopt_cmd(func):
    
    def helper_fn(self, arg):
        '''helper function for docopt'''
        try:
            opt = docopt(helper_fn.__doc__, arg)
        except DocoptExit as exception:
            # The DocoptExit is thrown when the args do not match.
            # We print a message to the user and the usage block.
            print 'Invalid Command!'
            print exception
            return
        except SystemExit:
            # The SystemExit exception prints the usage for --help
            # We do not need to do the print here.
            return
        return func(self, opt)
    helper_fn.__name__ = func.__name__
    helper_fn.__doc__ = func.__doc__
    helper_fn.__dict__.update(func.__dict__)
    return helper_fn
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)
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
1305955
function (opts, cb) {
      var self = this
      opts = opts || {}
      var root = opts.root || RootKey
      var _cb = function (err, doc) {
        if (err) {
          cb(err, ERR.config.FA_LIST_CONFIG)
        } else {
          if (!doc) {
            if (opts.all) return cb(null, {})
            return cb(null, [])
          }
          if (opts.all) {
            for (var key in doc) {
              var _doc = self._parse(doc[key])
              if (_doc.value) {
                doc[key] = _doc.value
              } else {
                delete doc[key]
              }
            }
          }
          cb(null, doc)
        }
      }
      if (opts.all) {
        mq.hgetall(root, _cb)
      } else {
        mq.hkeys(root, _cb)
      }
    }
310815
def _args_to_dict(func, args):
    """"""
    if sys.version_info >= (3, 0):
        arg_count = func.__code__.co_argcount
        arg_names = func.__code__.co_varnames[:arg_count]
    else:
        arg_count = func.func_code.co_argcount
        arg_names = func.func_code.co_varnames[:arg_count]

    arg_value_list = list(args)
    arguments = dict((arg_name, arg_value_list[i])
                     for i, arg_name in enumerate(arg_names)
                     if i < len(arg_value_list))
    return arguments
584605
def rm(args):
    
    p = OptionParser(rm.__doc__)
    opts, args = p.parse_args(args)

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

    store, = args
    contents = glob_s3(store)
    for c in contents:
        rm_s3(c)
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()
349563
def parse_docstring(docstring, cls=None):
    
    def_arg_dict = lambda: {'description': None,
                            'type_name': None,
                            'required': False,
                            }
    description, fields_lines = split_docstring(docstring)
    arguments_dict = defaultdict(def_arg_dict)
    return_value_types = []
    #parse fields
    return_description = ''
    for docstring_line in fields_lines:
        if _ignored_field(docstring_line):
            continue
        #parse inherits
        if docstring_line.startswith('@inherits'):
            if not cls:
                raise MethodParsingException()
            inherit_tmp = docstring_line.split(None, 1)[1]
            inherit_str = inherit_tmp.split(':class:', 1)[1]
            result = _parse_inherit(cls, inherit_str)

            description = description or result['description']
            for arg_name, update_dict in result['arguments'].items():
                arguments_dict[arg_name].update(update_dict)
            return_value_types = result['return']['type_name']
            return_description = result['return']['description']
        #parse return value
        elif docstring_line.startswith(':rtype:'):
            class_name = __get_class_name(cls)
            types_str = docstring_line.split(None, 1)[1]
            return_value_types = types_str.replace('\n', '').strip(':').strip()
            if return_value_types.startswith('class:`.'):
                return_value_types = return_value_types.replace('class:`.', 'class:`'+class_name+'.')
        #parse return description
        elif docstring_line.startswith(':return:'):
            return_description = docstring_line.split(None, 1)[1].strip()
        #parse arguments
        else:
            arg_name, update_dict = _parse_docstring_field(cls, docstring_line)
            arguments_dict[arg_name].update(update_dict)
    #check fields
    _check_arguments_dict(arguments_dict)
    if not return_value_types:
        raise MethodParsingException('Can not get return types for method')
    return {'description': description,
            'arguments': arguments_dict,
            'return': {'description': return_description,
                       'type_name': return_value_types}}
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
561132
def some(args):
    
    p = OptionParser(some.__doc__)
    opts, args = p.parse_args(args)

    if len(args) not in (2, 3):
        sys.exit(not p.print_help())

    idsfile, afastq, = args[:2]
    bfastq = args[2] if len(args) == 3 else None

    ids = DictFile(idsfile, valuepos=None)

    ai = iter_fastq(open(afastq))
    arec = next(ai)
    if bfastq:
        bi = iter_fastq(open(bfastq))
        brec = next(bi)

    while arec:
        if arec.name[1:] in ids:
            print(arec)
            if bfastq:
                print(brec)

        arec = next(ai)
        if bfastq:
            brec = next(bi)
928484
def to_args(self):
        
        def has_value(name, value):
            """ Test for non-null option values.
            """
            null_values = ("False", "None", "[]", '""', "''", "0")
            if not value or value in null_values:
                return False
            if name in _arg_defaults:
                if str(value) == str(_arg_defaults[name]):
                    return False
            return True

        def filter_opt(name, value):
            """ Filter out preset and null-valued options.
            """
            if name in ("add_preset", "del_preset", "desc", "note"):
                return False
            return has_value(name, value)

        def argify(name, value):
            """ Convert sos option notation to command line arguments.
            """
            # Handle --verbosity specially
            if name.startswith("verbosity"):
                arg = "-" + int(value) * "v"
                return arg

            name = name.replace("_", "-")

            value = ",".join(value) if _is_seq(value) else value

            if value is not True:
                opt = "%s %s" % (name, value)
            else:
                opt = name

            arg = "--" + opt if len(opt) > 1 else "-" + opt
            return arg

        opt_items = sorted(self.dict().items(), key=lambda x: x[0])
        return [argify(n, v) for (n, v) in opt_items if filter_opt(n, v)]
380416
def lower_dict(d):
    """"""

    _d = {}

    for k, v in d.items():
        try:
            _d[k.lower()] = v
        except AttributeError:
            _d[k] = v

    return _d
251319
def parse_options(self, prog_name, arguments):
        """"""
        # Don't want to load configuration to just print the version,
        # so we handle --version manually here.
        if '--version' in arguments:
            self.exit_status(self.version, fh=sys.stdout)
        parser = self.create_parser(prog_name)
        options, args = parser.parse_args(arguments)
        return options, args
232965
def getKwdArgs(self, flatten = False):
        

        # Start with a full deep-copy.  What complicates this method is the
        # idea of sub-sections.  This dict can have dicts as values, and so on.
        dcopy = self.dict() # ConfigObj docs say this is a deep-copy

        # First go through the dict removing all positional args
        for idx,scope,name in self._posArgs:
            theDict, val = findScopedPar(dcopy, scope, name)
            # 'theDict' may be dcopy, or it may be a dict under it
            theDict.pop(name)

        # Then go through the dict removing all hidden items ('_item_name_')
        for k in list(dcopy.keys()):
            if isHiddenName(k):
                dcopy.pop(k)

        # Done with the nominal operation
        if not flatten:
            return dcopy

        # They have asked us to flatten the structure - to bring all parameters
        # up to the top level, even if they are in sub-sections.  So we look
        # for values that are dicts.  We will throw something if we end up
        # with name collisions at the top level as a result of this.
        return flattenDictTree(dcopy)
788148
def parse_options(given, available):
    """"""
    for key, value in sorted(given.items()):
        if not value:
            continue
        if key in available:
            yield "--{0}={1}".format(key, value)
783310
def form_option(str_opt):
    '''
    '''

    str_base = '#cmdoption-arg-'
    str_opt_x = str_base+str_opt.lower()\
        .replace('_', '-')\
        .replace('(', '-')\
        .replace(')', '')
    return str_opt_x