Modifies the command arguments to match the
        strictness of the redis client.
492613
def _normalize_command_args(self, command, *args):
        
        if command == 'zadd' and not self.strict and len(args) >= 3:
            # Reorder score and name
            zadd_args = [x for tup in zip(args[2::2], args[1::2]) for x in tup]
            return [args[0]] + zadd_args

        if command in ('zrangebyscore', 'zrevrangebyscore'):
            # expected format is: <command> name min max start num with_scores score_cast_func
            if len(args) <= 3:
                # just plain min/max
                return args

            start, num = None, None
            withscores = False

            for i, arg in enumerate(args[3:], 3):
                # keywords are case-insensitive
                lower_arg = self._encode(arg).lower()

                # handle "limit"
                if lower_arg == b"limit" and i + 2 < len(args):
                    start, num = args[i + 1], args[i + 2]

                # handle "withscores"
                if lower_arg == b"withscores":
                    withscores = True

            # do not expect to set score_cast_func

            return args[:3] + (start, num, withscores)

        return args
969007
def convert_old_commands(commands, annotate=True):
    """"""
    from rez.config import config
    from rez.utils.logging_ import print_debug

    def _repl(s):
        return s.replace('\\"', '"')

    def _encode(s):
        # this replaces all occurrances of '\"' with '"', *except* for those
        # occurrances of '\"' that are within double quotes, which themselves
        # are not escaped. In other words, the string:
        # 'hey "there \"you\" " \"dude\" '
        # ..will convert to:
        # 'hey "there \"you\" " "dude" '
        s_new = ''
        prev_i = 0

        for m in within_unescaped_quotes_regex.finditer(s):
            s_ = s[prev_i:m.start()]
            s_new += _repl(s_)

            s_new += s[m.start():m.end()]
            prev_i = m.end()

        s_ = s[prev_i:]
        s_new += _repl(s_)
        return repr(s_new)

    loc = []

    for cmd in commands:
        if annotate:
            txt = "OLD COMMAND: %s" % cmd
            line = "comment(%s)" % _encode(txt)
            loc.append(line)

        cmd = convert_old_command_expansions(cmd)
        toks = cmd.strip().split()

        try:
            if toks[0] == "export":
                var, value = cmd.split(' ', 1)[1].split('=', 1)
                for bookend in ('"', "'"):
                    if value.startswith(bookend) and value.endswith(bookend):
                        value = value[1:-1]
                        break

                # As the only old-style commands were Linux/Bash based,
                # we assume using the default separator ":" is ok - we don't
                # need to use os.pathsep as we don't expected to see a
                # Windows path here.
                separator = config.env_var_separators.get(var, ":")

                # This is a special case.  We don't want to include "';'" in
                # our env var separators map as it's not really the correct
                # behaviour/something we want to promote.  It's included here for
                # backwards compatibility only, and to not propogate elsewhere.
                if var == "CMAKE_MODULE_PATH":
                    value = value.replace("'%s'" % separator, separator)
                    value = value.replace('"%s"' % separator, separator)
                    value = value.replace(":", separator)

                parts = value.split(separator)
                parts = [x for x in parts if x]
                if len(parts) > 1:
                    idx = None
                    var1 = "$%s" % var
                    var2 = "${%s}" % var
                    if var1 in parts:
                        idx = parts.index(var1)
                    elif var2 in parts:
                        idx = parts.index(var2)
                    if idx in (0, len(parts) - 1):
                        func = "appendenv" if idx == 0 else "prependenv"
                        parts = parts[1:] if idx == 0 else parts[:-1]
                        val = separator.join(parts)
                        loc.append("%s('%s', %s)" % (func, var, _encode(val)))
                        continue

                loc.append("setenv('%s', %s)" % (var, _encode(value)))
            elif toks[0].startswith('#'):
                loc.append("comment(%s)" % _encode(' '.join(toks[1:])))
            elif toks[0] == "alias":
                match = re.search("alias (?P<key>.*?)=(?P<value>.*)", cmd)
                key = match.groupdict()['key'].strip()
                value = match.groupdict()['value'].strip()
                if (value.startswith('"') and value.endswith('"')) or \
                        (value.startswith("'") and value.endswith("'")):
                    value = value[1:-1]
                loc.append("alias('%s', %s)" % (key, _encode(value)))
            else:
                # assume we can execute this as a straight command
                loc.append("command(%s)" % _encode(cmd))
        except:
            # if anything goes wrong, just fall back to bash command
            loc.append("command(%s)" % _encode(cmd))

    rex_code = '\n'.join(loc)
    if config.debug("old_commands"):
        br = '-' * 80
        msg = textwrap.dedent(
            """
            %s
            OLD COMMANDS:
            %s

            NEW COMMANDS:
            %s
            %s
            """) % (br, '\n'.join(commands), rex_code, br)
        print_debug(msg)
    return rex_code
286627
def fix_command(known_args):
    """"""
    settings.init(known_args)
    with logs.debug_time('Total'):
        logs.debug(u'Run with settings: {}'.format(pformat(settings)))
        raw_command = _get_raw_command(known_args)

        try:
            command = types.Command.from_raw_script(raw_command)
        except EmptyCommand:
            logs.debug('Empty command, nothing to do')
            return

        corrected_commands = get_corrected_commands(command)
        selected_command = select_command(corrected_commands)

        if selected_command:
            selected_command.run(command)
        else:
            sys.exit(1)
399043
def cmd(
        name,
        fun=None,
        arg=(),
        **kwargs):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'comment': '',
           'result': True}
    if fun is None:
        fun = name
    client = salt.wheel.WheelClient(__opts__)
    low = {'fun': fun,
            'arg': arg,
            'kwargs': kwargs}
    client.cmd_async(low)
    return ret
51042
def match(command, options, args):
    """"""
    build = ""
    possible = commands
    for l in command:
        build += l
        possible = filter(lambda w: w.startswith(build), possible)
    
    if len(possible) == 0:
        raise ArgError("Command invalid: %s" % command)
    
    if len(possible) > 1:
        raise ArgError("Ambiguous command: %s" % command)

    command = possible.pop()

    if not num_args[command](len(args)):
        raise ArgError("Bad number of args for command %s" % command)

    return command
597512
def encode(cls, command):
        

        args = []
        for arg in command.args:
            if not isinstance(arg, str):
                arg = str(arg)

            if "," in arg or arg.startswith(" ") or arg.endswith(" ") or arg.startswith("hex:"):
                arg = "hex:{}".format(hexlify(arg.encode('utf-8')).decode('utf-8'))

            args.append(arg)

        argstr = ""

        if len(args) > 0:
            argstr = " {" + ",".join(args) + "}"

        return command.name + argstr
29037
def redis(self):
        """"""
        if self._redis is None:
            self._redis = redis.StrictRedis(host=self.args.redis_host, port=self.args.redis_port)
        return self._redis
1112618
def update_args(self, args):
        
        for cfg in args:
            keys, v = cfg.split('=', maxsplit=1)
            keylist = keys.split('.')

            dic = self
            for i, k in enumerate(keylist[:-1]):
                assert k in dir(dic), "Unknown config key: {}".format(keys)
                dic = getattr(dic, k)
            key = keylist[-1]

            oldv = getattr(dic, key)
            if not isinstance(oldv, str):
                v = eval(v)
            setattr(dic, key, v)
678424
def validate_args(**args):
	
	if not args['query']:
		print("\nMissing required query argument.")
		sys.exit()

	for key in DEFAULTS:
		if key not in args:
			args[key] = DEFAULTS[key]

	return args
679494
def _expand_args(command):
    """"""

    # Prepare arguments.
    if isinstance(command, STR_TYPES):
        if sys.version_info[0] == 2:
            splitter = shlex.shlex(command.encode("utf-8"))
        elif sys.version_info[0] == 3:
            splitter = shlex.shlex(command)
        else:
            splitter = shlex.shlex(command.encode("utf-8"))
        splitter.whitespace = "|"
        splitter.whitespace_split = True
        command = []

        while True:
            token = splitter.get_token()
            if token:
                command.append(token)
            else:
                break

        command = list(map(shlex.split, command))

    return command
779441
def sanitize_args(cmd: List[str]) -> List[str]:
    
    sanitized = []
    for idx, fieldname in enumerate(cmd):
        def _is_password(cmdstr):
            return 'wifi-sec.psk' in cmdstr\
                or 'password' in cmdstr.lower()
        if idx > 0 and _is_password(cmd[idx-1]):
            sanitized.append('****')
        else:
            sanitized.append(fieldname)
    return sanitized
917068
def extend(self, cli_api, command_prefix="", sub_command="", **kwargs):
        """"""
        if sub_command and command_prefix:
            raise ValueError('It is not currently supported to provide both a command_prefix and sub_command')

        if sub_command:
            self.commands[sub_command] = cli_api
        else:
            for name, command in cli_api.commands.items():
                self.commands["{}{}".format(command_prefix, name)] = command
704723
def repl_command(fxn):
    

    @functools.wraps(fxn)
    def wrapper(self, arglist):
        """Wraps the command method"""
        args = []
        kwargs = {}
        if arglist:
            for arg in shlex.split(arglist):
                if "=" in arg:
                    split = arg.split("=", 1)
                    kwargs[split[0]] = split[1]
                else:
                    args.append(arg)
        return fxn(self, *args, **kwargs)

    return wrapper
257124
def update(self, argv):
        """"""

        if len(argv) == 0: 
            error("Command requires an index name", 2)
        name = argv[0]

        if name not in self.service.indexes:
            error("Index '%s' does not exist" % name, 2)
        index = self.service.indexes[name]

        # Read index metadata and construct command line parser rules that 
        # correspond to each editable field.

        # Request editable fields
        fields = self.service.indexes.itemmeta().fields.optional

        # Build parser rules
        rules = dict([(field, {'flags': ["--%s" % field]}) for field in fields])

        # Parse the argument vector
        opts = cmdline(argv, rules)

        # Execute the edit request
        index.update(**opts.kwargs)
309306
def validate(self, value, redis):
        '''
        
        '''
        # cleanup
        if type(value) == str:
            value = value.strip()

        value = self.value_or_default(value)

        # validation
        self.validate_required(value)

        if self.regex and not re.match(self.regex, value, flags=re.ASCII):
            raise InvalidFieldError(self.name)

        if self.forbidden and value in self.forbidden:
            raise ReservedFieldError(self.name)

        if self.allowed and value not in self.allowed:
            raise InvalidFieldError(self.name)

        if self.index:
            key = self.key()

            old = debyte_string(redis.hget(key, value))
            old_value = getattr(self.obj, self.name)

            if old is not None and old != self.obj.id:
                raise NotUniqueFieldError(self.name)
            elif old_value != value:
                self.obj._old[self.name] = old_value

        return value
967837
def remap_args(input_args, remap):
    
    out_args = input_args
    for dest_key, src_keys in remap.items():
        remap_value = None
        if isinstance(src_keys, str):
            src_keys = [src_keys]

        for key in src_keys:
            if key in input_args:
                remap_value = input_args[key]
                break

        if remap_value is not None:
            if out_args is input_args:
                out_args = {**input_args}
            out_args[dest_key] = remap_value

    return out_args
834634
def _setup_install_commands_from_kwargs(kwargs, keys=tuple()):
        """"""
        cmd_list = []
        if kwargs.get('override_channels', False) and 'channel' not in kwargs:
            raise TypeError('conda search: override_channels requires channel')

        if 'env' in kwargs:
            cmd_list.extend(['--name', kwargs.pop('env')])
        if 'prefix' in kwargs:
            cmd_list.extend(['--prefix', kwargs.pop('prefix')])
        if 'channel' in kwargs:
            channel = kwargs.pop('channel')
            if isinstance(channel, str):
                cmd_list.extend(['--channel', channel])
            else:
                cmd_list.append('--channel')
                cmd_list.extend(channel)

        for key in keys:
            if key in kwargs and kwargs[key]:
                cmd_list.append('--' + key.replace('_', '-'))

        return cmd_list