The 'converse' subcommand
970846
def converse(self):
        ''''''

        # Initialize the converse subcommand's argparser
        parser = argparse.ArgumentParser(description='Initiate a conversation with a trained dialogue model')
        self.init_converse_args(parser)

        # Parse the args we got
        args = parser.parse_args(sys.argv[2:])
        args.config = ConfigurationLoader(args.config).load().conversation_config

        print(CLI_DIVIDER + '\n')
        Conversant(**vars(args)).run()
375452
def map_subcommands(self, func):
        

        def crawl(cmd):
            for sc in cmd.subcommands.values():
                yield from crawl(sc)
            yield cmd
        return map(func, crawl(self.root_command))
1293876
def do_speak(self, args):
        """"""
        words = []
        for word in args.words:
            if args.piglatin:
                word = '%s%say' % (word[1:], word[0])
            if args.shout:
                word = word.upper()
            words.append(word)

        repetitions = args.repeat or 1

        color_on = ''
        if args.fg:
            color_on += FG_COLORS[args.fg]
        if args.bg:
            color_on += BG_COLORS[args.bg]
        color_off = Fore.RESET + Back.RESET

        for i in range(min(repetitions, self.maxrepeats)):
            # .poutput handles newlines, and accommodates output redirection too
            self.poutput(color_on + ' '.join(words) + color_off)
1359357
def cmd(send, msg, args):
    
    if not msg:
        msg = gen_word()
    morse = gen_morse(msg)
    if len(morse) > 100:
        send("Your morse is too long. Have you considered Western Union?")
    else:
        send(morse)
390316
def cmdline(executable):
    

    args = [executable.executable]
    indexed_args = []

    for parameter in executable:

        optional = (parameter.type == 'boolean') or parameter.default
        has_value = parameter.type != 'boolean'


        if parameter.longflag:  # use longflag where possible
            flag = "--%s" % parameter.longflag
        elif parameter.flag:
            flag = "-%s VALUE" % parameter.flag
        elif parameter.index:
            flag = parameter.name
            optional = False


        if has_value:
            flag += " VALUE"

        if optional:
            flag = "[" + flag + "]"

        if parameter.index:
            indexed_args.insert(int(parameter.index), flag)
        else:
            args.append(flag)

    return args + indexed_args
118526
public function subRunCommand(): void
    {
        $this->writeln('hello this is: ' . __METHOD__);

        $this->getApp()->subRun('test', $this->input, $this->output);
    }
787096
def arg(*args, **kwargs):
    
    def _arg(f):
        if not hasattr(f, '_subcommand_args'):
            f._subcommand_args = []
        f._subcommand_args.append((args, kwargs))
        return f
    return _arg
270334
def get_subcommand_kwargs(mgr, name, namespace):
    
    subcmd = mgr.get(name)
    subcmd_kwargs = {}
    for opt in list(subcmd.args.values()) + list(subcmd.options.values()):
        if hasattr(namespace, opt.dest):
            subcmd_kwargs[opt.dest] = getattr(namespace, opt.dest)
    return (subcmd, subcmd_kwargs)
972726
def cmdLine(useBasename=False):
    """"""
    qargv = []
    cmdwords = list(sys.argv)
    if useBasename:
        cmdwords[0] = os.path.basename(cmdwords[0])
    for s in cmdwords:
        # any white space or special characters in word so we need quoting?
        if re.search(r'\s|\*|\?', s):
            if "'" in s:
                qargv.append('"%s"' % re.sub('"', "'", s))
            else:
                qargv.append("'%s'" % re.sub("'", '"', s))
        else:
            qargv.append(s)
    cmd = ' '.join(qargv)
    return cmd
775330
def command_parser():
    

    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)
                )

    # make parser
    parser = Parser(formatter_class=argparse.RawTextHelpFormatter)

    # parser: add verbose, version
    for short, name, msg in INFORMATION:
        short = "-%s" % short
        arg = "--%s" % name
        parser.add_argument(short, arg, action="store_true", help=msg)

    # make subparsers // ALIAS_DEPRECATION: remove metavar later
    metavar = "{click,list,refresh}"
    subparsers = parser.add_subparsers(dest="command", metavar=metavar)
    sps = {}

    # subparsers: add click, list, refresh... hide docstring
    data = {"formatter_class": argparse.RawTextHelpFormatter}
    for name, msg, nargs in SUBPARSERS:
        data.update({"epilog": EPILOGS[name], "help": msg})
        # don't show docstring in py3-cmd --help
        if name in ["docstring"]:
            del data["help"]
        sps[name] = subparsers.add_parser(name, **data)
        sps[name].add_argument(nargs=nargs, dest="module", help="module name")

    # ALIAS_DEPRECATION: subparsers: add click (aliases)
    buttons = {
        "leftclick": 1,
        "middleclick": 2,
        "rightclick": 3,
        "scrollup": 4,
        "scrolldown": 5,
    }
    for name in sorted(buttons):
        sps[name] = subparsers.add_parser(name)
        sps[name].add_argument(nargs="+", dest="module", help="module name")

    # click subparser: add button, index, width, height, relative_{x,y}, x, y
    sp = sps["click"]
    for name, msg in CLICK_OPTIONS:
        arg = "--{}".format(name)
        if name == "button":
            sp.add_argument(arg, metavar="INT", type=int, help=msg, default=1)
        elif name == "index":
            sp.add_argument(arg, metavar="INDEX", help=msg)
        elif name == "modifiers":
            sp.add_argument(arg, metavar="KEY", help=msg)
        else:
            sp.add_argument(arg, metavar="INT", type=int, help=msg)

    # docstring subparser: add check, diff, update
    sp = sps["docstring"]
    for name, msg in DOCSTRING_OPTIONS:
        arg = "--{}".format(name)
        sp.add_argument(arg, action="store_true", help=msg)

    # refresh subparser: add all
    sp = sps["refresh"]
    for name, msg in REFRESH_OPTIONS:
        arg = "--{}".format(name)
        sp.add_argument(arg, action="store_true", help=msg)

    # list subparser: add all, core, user, full
    sp = sps["list"]
    for short, name, msg in LIST_OPTIONS:
        name = "--{}".format(name)
        if short:
            short = "-{}".format(short)
            sp.add_argument(short, name, action="store_true", help=msg)
        else:
            sp.add_argument(name, action="store_true", help=msg)

    # parse args, post-processing
    options = parser.parse_args()

    if options.command == "click":
        # cast string index to int
        if options.index:
            try:
                options.index = int(options.index)
            except ValueError:
                pass
        # specify modifiers, optionally joined by plus signs
        if options.modifiers:
            options.modifiers = options.modifiers.split("+")
        else:
            options.modifiers = []
    elif options.command == "refresh":
        # refresh all
        # ALL_DEPRECATION
        if options.module is None:
            options.module = []
        # end
        valid = False
        if options.all:  # keep this
            options.command = "refresh_all"
            options.module = []
            valid = True
        if "all" in options.module:  # remove this later
            options.command = "refresh_all"
            options.module = []
            valid = True
        if not options.module and not valid:
            sps["refresh"].error("missing positional or optional arguments")
    elif options.command in ["list", "docstring"]:
        parse_list_or_docstring(options, sps)
        parser.exit()
    elif options.version:
        # print version
        from platform import python_version
        from py3status.version import version

        print("py3status {} (python {})".format(version, python_version()))
        parser.exit()
    elif not options.command:
        parser.error("too few arguments")

    # ALIAS_DEPRECATION
    alias = options.command in buttons

    # py3-cmd click 3 dpms ==> py3-cmd click --button 3 dpms
    new_modules = []
    for index, name in enumerate(options.module):
        if name.isdigit():
            if alias:
                continue
            if not index:  # zero index
                options.button = int(name)
        else:
            new_modules.append(name)

    # ALIAS_DEPRECATION: Convert (click) aliases to buttons
    if alias:
        options.button = buttons[options.command]
        options.command = "click"

    if options.command == "click" and not new_modules:
        sps[options.command].error("too few arguments")
    options.module = new_modules

    return options
688547
def _sendDDEcommand(self, cmd, timeout=None):
        """"""
        reply = self.conversation.Request(cmd, timeout)
        if self.pyver > 2:
            reply = reply.decode('ascii').rstrip()
        return reply
246591
def set_subcommands(func, parser):
    
    if hasattr(func, '__subcommands__') and func.__subcommands__:
        sub_parser = parser.add_subparsers(
            title=SUBCOMMANDS_LIST_TITLE, dest='subcommand',
            description=SUBCOMMANDS_LIST_DESCRIPTION.format(
                func.__cmd_name__),
            help=func.__doc__)
        for sub_func in func.__subcommands__.values():
            parser = get_parser(sub_func, sub_parser)
            for args, kwargs in get_shared(sub_func):
                parser.add_argument(*args, **kwargs)
    else:
        for args, kwargs in get_shared(func):
            parser.add_argument(*args, **kwargs)
182301
def help_message(sender, command_name) #:nodoc:
      if command_name.nil? || command_name.length == 0
        # Display help for all commands
        help_message = "I understand the following commands:\n\n"

        @commands[:meta].sort.each do |command|
          # Thank you, Hash.sort
          command = command[1]

          if !command[:is_alias] && (command[:is_public] || master?(sender))
            command[:syntax].each { |syntax| help_message += "#{syntax}\n" }
            help_message += "  #{command[:description]}\n\n"
          end
        end
      else
        # Display help for the given command
        command = @commands[:meta][command_name]

        if command.nil?
          help_message = "I don't understand '#{command_name}' Try saying" +
              " 'help' to see what commands I understand."
        else
          help_message = ''
          command[:syntax].each { |syntax| help_message += "#{syntax}\n" }
          help_message += "  #{command[:description]} "
        end
      end

      help_message
    end
714539
def cmdline(argv, flags):
    """"""
    rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags])
    return parse(argv, rules)
706526
def cmd(send, msg, args):
    
    if not msg:
        send("Choose what?")
        return
    choices = msg.split(' or ')
    action = [
        'draws a slip of paper from a hat and gets...', 'says eenie, menie, miney, moe and chooses...', 'picks a random number and gets...',
        'rolls dice and gets...', 'asks a random person and gets...', 'plays rock, paper, scissors, lizard, spock and gets...'
    ]
    send("%s %s" % (choice(action), choice(choices)), 'action')
994642
def show_help(self):
        
        output = [
            'Usage %s subcommand [options] [args]' % self.prog_name,
            '',
            'Available commands:',
            '',
        ]
        for cmd in self.get_commands():
            output.append('  %s' % cmd)
        output += ['', '']
        self.stdout.write(u'\n'.join(output))
236096
def complete_help_subcommand(self, text: str, line: str, begidx: int, endidx: int) -> List[str]:
        """"""

        # Get all tokens through the one being completed
        tokens, _ = self.tokens_for_completion(line, begidx, endidx)

        if not tokens:
            return []

        # Must have at least 3 args for 'help command sub-command'
        if len(tokens) < 3:
            return []

        # Find where the command is by skipping past any flags
        cmd_index = 1
        for cur_token in tokens[cmd_index:]:
            if not cur_token.startswith('-'):
                break
            cmd_index += 1

        if cmd_index >= len(tokens):
            return []

        command = tokens[cmd_index]
        matches = []

        # Check if this is a command with an argparse function
        func = self.cmd_func(command)
        if func and hasattr(func, 'argparser'):
            completer = AutoCompleter(getattr(func, 'argparser'), self)
            matches = completer.complete_command_help(tokens[cmd_index:], text, line, begidx, endidx)

        return matches