Tries a variety of methods to get a MAC address.

    Format of method lists:
    Tuple:  (regex, regex index, command, command args)
            Command args is a list of strings to attempt to use as arguments
    lambda: Function to call
554962
def _hunt_for_mac(to_find, type_of_thing, net_ok=True):
    # type: (Optional[str], int, bool) -> Optional[str]
    
    if to_find is None:
        log.warning("_hunt_for_mac() failed: to_find is None")
        return None
    if not PY2 and isinstance(to_find, bytes):
        to_find = str(to_find, 'utf-8')

    if WINDOWS and type_of_thing == INTERFACE:
        methods = [
            # getmac - Connection Name
            (r'\r\n' + to_find + r'.*' + MAC_RE_DASH + r'.*\r\n',
             0, 'getmac.exe', ['/NH /V']),

            # ipconfig
            (to_find + r'(?:\n?[^\n]*){1,8}Physical Address[ .:]+' + MAC_RE_DASH + r'\r\n',
             0, 'ipconfig.exe', ['/all']),

            # getmac - Network Adapter (the human-readable name)
            (r'\r\n.*' + to_find + r'.*' + MAC_RE_DASH + r'.*\r\n',
             0, 'getmac.exe', ['/NH /V']),

            # wmic - WMI command line utility
            lambda x: _popen('wmic.exe', 'nic where "NetConnectionID = \'%s\'" get '
                                         'MACAddress /value' % x).strip().partition('=')[2],
        ]
    elif (WINDOWS or WSL) and type_of_thing in [IP4, IP6, HOSTNAME]:
        methods = [
            # arp -a - Parsing result with a regex
            (MAC_RE_DASH, 0, 'arp.exe', ['-a %s' % to_find]),
        ]

        # Add methods that make network requests
        # Insert it *after* arp.exe since that's probably faster.
        if net_ok and type_of_thing != IP6 and not WSL:
            methods.insert(1, _windows_ctypes_host)
    elif (DARWIN or FREEBSD) and type_of_thing == INTERFACE:
        methods = [
            (r'ether ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),

            # Alternative match for ifconfig if it fails
            (to_find + r'.*ether ' + MAC_RE_COLON,
             0, 'ifconfig', ['']),

            (MAC_RE_COLON,
             0, 'networksetup', ['-getmacaddress %s' % to_find]),
        ]
    elif FREEBSD and type_of_thing in [IP4, IP6, HOSTNAME]:
        methods = [
            (r'\(' + re.escape(to_find) + r'\)\s+at\s+' + MAC_RE_COLON,
             0, 'arp', [to_find])
        ]
    elif OPENBSD and type_of_thing == INTERFACE:
        methods = [
            (r'lladdr ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),
        ]
    elif OPENBSD and type_of_thing in [IP4, IP6, HOSTNAME]:
        methods = [
            (re.escape(to_find) + r'[ ]+' + MAC_RE_COLON,
             0, 'arp', ['-an']),
        ]
    elif type_of_thing == INTERFACE:
        methods = [
            _read_sys_iface_file,
            _fcntl_iface,

            # Fast modern Ubuntu ifconfig
            (r'ether ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),

            # Fast ifconfig
            (r'HWaddr ' + MAC_RE_COLON,
             0, 'ifconfig', [to_find]),

            # ip link (Don't use 'list' due to SELinux [Android 24+])
            (to_find + r'.*\n.*link/ether ' + MAC_RE_COLON,
             0, 'ip', ['link %s' % to_find, 'link']),

            # netstat
            (to_find + r'.*HWaddr ' + MAC_RE_COLON,
             0, 'netstat', ['-iae']),

            # More variations of ifconfig
            (to_find + r'.*ether ' + MAC_RE_COLON,
             0, 'ifconfig', ['']),
            (to_find + r'.*HWaddr ' + MAC_RE_COLON,
             0, 'ifconfig', ['', '-a', '-v']),

            # Tru64 ('-av')
            (to_find + r'.*Ether ' + MAC_RE_COLON,
             0, 'ifconfig', ['-av']),
            _uuid_lanscan_iface,
        ]
    elif type_of_thing in [IP4, IP6, HOSTNAME]:
        esc = re.escape(to_find)
        methods = [
            _read_arp_file,
            lambda x: _popen('ip', 'neighbor show %s' % x)
            .partition(x)[2].partition('lladdr')[2].strip().split()[0],

            (r'\(' + esc + r'\)\s+at\s+' + MAC_RE_COLON,
             0, 'arp', [to_find, '-an', '-an %s' % to_find]),

            # Darwin oddness
            (r'\(' + esc + r'\)\s+at\s+' + MAC_RE_DARWIN,
             0, 'arp', [to_find, '-a', '-a %s' % to_find]),
            _uuid_ip,
        ]
    else:
        log.critical("Reached end of _hunt_for_mac() if-else chain!")
        return None
    return _try_methods(methods, to_find)
110102
function Command(args) {
  if (false === (this instanceof Command)) throw new Error('new operator required');
  if (typeof args == 'function') { // shorthand for function command
    args = {type: 'Function', contents: args};
  }
  if (args instanceof Procedure) { // shorthand for Procedure command
    args = {type: 'Procedure', contents: args};
  }
  args = args || {};
  var i;
  var unusedProperties = getInvalidProperties(args,
    ['name', 'description', 'type', 'contents', 'scope', 'timeout', 'theme', 'icon', 'bucket', 'presentationMode','location','images']);
  var errorList = [];
  for (i = 0; i < unusedProperties.length; i++) errorList.push('invalid property: ' + unusedProperties[i]);
  if (errorList.length > 1) throw new Error('error creating Command: multiple errors');
  if (errorList.length) throw new Error('error creating Command: ' + errorList[0]);
  for (i in args) this[i] = args[i];
  this.name = this.name || "a command"; // name is optional
  if ('string' != typeof this.name) throw new Error('name must be string');
  if ('undefined' == typeof this.description) this.description = this.name + ' Command';
  if ('undefined' == typeof this.type) this.type = 'Stub';
  if (!contains(Command.getTypes(), this.type)) throw new Error('Invalid command type: ' + this.type);
  switch (this.type) {
    case 'Stub':
      break;
    case 'Menu':
      if (!(this.contents instanceof Array)) throw new Error('contents must be array of menu items');
      if (!this.contents.length) throw new Error('contents must be array of menu items');
      for (i in this.contents) {
        if (this.contents.hasOwnProperty(i))
          if (typeof this.contents[i] != 'string' && !(this.contents[i] instanceof Command))
            throw new Error('contents must be array of menu items');
      }
      break;
    case 'Presentation':
      if (!(this.contents instanceof Presentation)) throw new Error('contents must be a Presentation');
      this.presentationMode = this.presentationMode || 'View';
      if (!contains(Command.getPresentationModes(), this.presentationMode)) throw new Error('Invalid presentationMode: ' + this.presentationMode);
      //['View', 'Edit', 'List']
      break;
    case 'Function':
      if (typeof this.contents != 'function') throw new Error('contents must be a Function');
      break;
    case 'Procedure':
      if (!(this.contents instanceof Procedure)) throw new Error('contents must be a Procedure');
      break;
    default:
      throw new TypeError();
  }
  if ('undefined' != typeof this.scope)
    if (!((this.scope instanceof Model) || (this.scope instanceof List)))
      throw new Error('optional scope property must be Model or List');
  if ('undefined' != typeof this.timeout)
    if (typeof this.timeout != 'number') throw new Error('timeout must be a Number');
  if ('undefined' != typeof this.timeout)
    if (typeof this.timeout != 'number') throw new Error('timeout must be a Number');
  if ('undefined' != typeof this.theme) {
    if ('string' != typeof this.theme) throw new Error('invalid theme');
    if (!contains(['default', 'primary', 'success', 'info', 'warning', 'danger', 'link'], this.theme))
      throw new Error('invalid theme');
  }
  if ('undefined' != typeof this.icon) {
    if ('string' != typeof this.icon) throw new Error('invalid icon');
    if (!contains(['fa', 'glyphicon'], this.icon.split('-')[0]) || !this.icon.split('-')[1])
      throw new Error('invalid icon');
  }

  // Validations done
  this._eventListeners = [];
}
947900
def parse_cmd(cmd, flags)
      if cmd.flags?
        args = Raw.arguments_to(cmd.flags.short, flags)
        if args.nil? || args.empty?
          args = Raw.arguments_to(cmd.flags.long, flags)
        end
      else
        args = Raw.arguments_to(cmd.index.to_s, flags)
      end
      unless cmd.type.to_s =~ /stdin/
        return nil if args.nil?
      end
      case cmd.type
      when :stdin
        args = STDIN.gets.strip
      when :stdin_stream
        args = STDIN
      when :stdin_string
        args = STDIN.gets.strip
      when :stdin_strings
        args = []
        while arg = STDIN.gets
          next if arg.nil?
          arg = arg.strip
          args << arg
        end
        args
      when :stdin_integer
        args = STDIN.gets.strip.to_i
      when :stdin_integers
        args = []
        while arg = STDIN.gets
          next if arg.nil?
          arg = arg.strip
          parse = arg.to_i
          if parse.to_s == arg
            args << parse
          end
        end
        args
      when :stdin_bool
        args = STDIN.gets.strip.downcase == "true"
      when :single, :string
        args = args.first
      when :strings, :multi
        if cmd.delimiter?
          if args.count > 1
            args = args.first.split(cmd.delimiter)
          else
            args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
          end
        end
        args
      when :integer
        args = args.first.to_i
      when :integers
        if cmd.delimiter?
          if args.count > 1
            args = args.join
            args = args.select { |arg| arg if arg.include?(cmd.delimiter) }
            args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
          else
            args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
          end
        end
        args = args.map(&:to_i)
      when :bool, :bools
        if cmd.delimiter?
          if args.count > 1
            args = args.join
            args = args.select { |arg| arg if arg.include?(cmd.delimiter) }
            args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
          else
            args = args.map { |arg| arg.split(cmd.delimiter) }.flatten
          end
        end
        args = args.map { |arg| arg == "true" }
      end
    rescue => e# this is dangerous
      puts e
      nil
    end
925223
def args_str(self):
        
        matched = [str(m) for m in self._used_matchers]
        unmatched = [str(m) for m in self._unused_matchers]
        return 'matched=[{}], unmatched=[{}]'.format(
            ', '.join(matched), ', '.join(unmatched))
409693
private String getMethodArgs(Method m)
    {
        StringBuffer sb = new StringBuffer();
        Class [] argTypes = m.getParameterTypes();
        for (int i = 0; i < argTypes.length; i++)
        {
            if (i != 0) sb.append(",");
            sb.append(argTypes[i].toString());
        }
        return sb.toString();
    }
914203
def get_args(args, kwargs, arg_names):
    '''
    '''
    n_args = len(arg_names)
    if len(args) + len(kwargs) > n_args:
        raise MoultScannerError('Too many arguments supplied. Expected: {}'.format(n_args))

    out_args = {}
    for i, a in enumerate(args):
        out_args[arg_names[i]] = a

    for a in arg_names:
        if a not in out_args:
            out_args[a] = None

    out_args.update(kwargs)
    return out_args
24240
def match_mac_list
      str = config_get('route_map', 'match_mac_list', @get_args)
      return if str.nil?
      str.empty? ? default_match_mac_list : str.split
    end
1084641
def dispatch(cls, arguments, **kwargs):
        
        # first match wins
        # spec: all '-' elements must match, all others are False;
        #       '<sth>' elements are converted to call args on order of
        #       appearance
        #
        # kwargs are provided to dispatch call and used in func call
        for spec, func in cls._specs:
            # if command and arguments.get(command) and match(args):
            args = []  # specified args in order of appearance
            options = list(filter(lambda k: k.startswith('-') and
                                       (arguments[k] or k in spec),
                             arguments.keys()))
            cmds = list(filter(lambda k: not (k.startswith('-') or
                                         k.startswith('<')) and arguments[k],
                          arguments.keys()))
            args_spec = list(filter(lambda k: k.startswith('<'), spec))
            cmd_spec = list(filter(lambda k: not (k.startswith('-') or
                                             k.startswith('<')), spec))
            for element in spec:
                if element.startswith('-'):
                    # element is an option
                    if element in options:
                        args.append(arguments.get(element, False))
                        options.remove(element)
                elif element.startswith('<') and \
                        not arguments.get(element) is False:
                    # element is an argument
                    args.append(arguments.get(element))
                    if element in args_spec:
                        args_spec.remove(element)
                else:
                    # element is a command
                    if element in cmds and element in cmd_spec:
                        cmds.remove(element)
                        cmd_spec.remove(element)

            if options:
                continue  # not all options have been matched
            if cmds:
                continue  # not all cmds from command line have been matched
            if args_spec:
                continue  # not all args from spec have been provided
            if cmd_spec:
                continue  # not all cmds from spec have been provided
            # all options and cmds matched : call the cmd
            # TODO leave out all args to deal with "empty" signature
            exit_code = func(*args, **kwargs)
            return exit_code
        # no matching spec found
        raise Exception('No implementation for spec: %s' % arguments)
50837
def get_args_names(method)
      args = method.args
      args_names = ' '
      args.each_with_index { |a, i|args_names << "${#{i + 1}:#{a}}, " }
      args_names.chop!.chop! unless args.empty?
    end
742393
def valid_mitemp_mac(mac, pat=re.compile(r"4C:65:A8:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}")):
    """"""
    if not pat.match(mac.upper()):
        raise argparse.ArgumentTypeError('The MAC address "{}" seems to be in the wrong format'.format(mac))
    return mac
475897
def _parse_args(args, cls):
    
    
    d = _create_djset(args, cls)
    
    key_value_pair = args.get('<key>=<value>')
    key = args.get('<key>')
    func = None
    if args.get('add') and key_value_pair:
        fargs = tuple(args.get('<key>=<value>').split('='))
        if fargs[1]:
            func = d.set
    elif args.get('remove') and key:
        func = d.remove
        fargs = (args.get('<key>'),)
    kwargs = {'glob': args.get('--global')}
    if func:
        return func, fargs, kwargs
    else:
        return None, None, None
1369508
def normalize_getitem_args(args):
    '''
    '''
    if not isinstance(args, tuple):
        args = (args,)
    return_val = []
    for arg in args:
        if isinstance(arg, six.string_types + (int, )):
            return_val.append(arg)
        elif isinstance(arg, slice):
            return_val.append((arg.start, arg.stop))
        else:
            raise TypeError(
                'Brackets cannot contain objects of type {0.__name__}'
                .format(type(arg)))
    return return_val
243665
def get_args
      bin_path = get_binpath
      target   = get_target
      center   = get_center
      jd       = get_jd
      km       = get_km
      check_bin_path(bin_path)
      check_target_center(target, center)
      return [bin_path, target, center, jd, km]
    rescue => e
      raise
    end
1372970
def cmd2list(cmd):
   ''' 
   '''
   p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
   stdout, stderr = p.communicate()
   if p.returncode != 0 and stderr != '':
      return "ERROR: %s\n"%(stderr)
   else:
      return stdout.split('\n')
518110
def joinArgs(args):
    
    if not args:
        return ''
    arglist = []
    for key in sorted(args, key=lambda x: x.lower()):
        value = compat.ustr(args[key])
        arglist.append('%s=%s' % (key, compat.quote(value)))
    return '?%s' % '&'.join(arglist)
674821
def main(argv=None):  # suppress(unused-function)
    
    argv = argv or sys.argv

    if "--" not in argv:
        sys.stderr.write("""Must specify command after '--'.\n""")
        return 1

    cmd_index = argv.index("--")
    args, cmd = (argv[1:cmd_index], argv[cmd_index + 1:])

    parser = argparse.ArgumentParser(description="""Cache results from jobs""")
    parser.add_argument("--dependencies",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of paths which, if more recent than the last time this job was invoked, will cause the job to be re-invoked.""")
    parser.add_argument("--output-files",
                        metavar="PATH",
                        nargs="*",
                        help="""A list of expected output paths form this command, which, if they do not exist, will cause the job to be re-invoked.""")
    parser.add_argument("--stamp-directory",
                        metavar="DIRECTORY",
                        type=str,
                        help="""A directory to store cached results from this command. If a matching invocation is used and the files specified in --dependencies and --output-files are up-to-date, then the cached stdout, stderr and return code is used and the command is not run again.""")
    parser.add_argument("--use-hashes",
                        action="store_true",
                        help="""Use hash comparison in order to determine if dependencies have changed since the last invocation of the job. This method is slower, but can withstand files being copied or moved.""")
    namespace = parser.parse_args(args)
    stamp_directory = namespace.stamp_directory
    if namespace.use_hashes:
        method = jobstamp.HashMethod
    else:
        method = jobstamp.MTimeMethod

    result = jobstamp.run(_run_cmd,
                          cmd,
                          jobstamps_dependencies=namespace.dependencies,
                          jobstamps_output_files=namespace.output_files,
                          jobstamps_cache_output_directory=stamp_directory,
                          jobstamps_method=method)

    sys.stdout.write(result["stdout"].decode())
    sys.stderr.write(result["stderr"].decode())
    return result["code"]
43675
def _try_methods(methods, to_find=None):
    # type: (list, Optional[str]) -> Optional[str]
    
    found = None
    for m in methods:
        try:
            if isinstance(m, tuple):
                for arg in m[3]:  # list(str)
                    if DEBUG:
                        log.debug("Trying: '%s %s'", m[2], arg)
                    # Arguments: (regex, _popen(command, arg), regex index)
                    found = _search(m[0], _popen(m[2], arg), m[1])
                    if DEBUG:
                        log.debug("Result: %s\n", found)
                    if found:  # Skip remaining args AND remaining methods
                        break
            elif callable(m):
                if DEBUG:
                    log.debug("Trying: '%s' (to_find: '%s')", m.__name__, str(to_find))
                if to_find is not None:
                    found = m(to_find)
                else:
                    found = m()
                if DEBUG:
                    log.debug("Result: %s\n", found)
            else:
                log.critical("Invalid type '%s' for method '%s'", type(m), str(m))
        except Exception as ex:
            if DEBUG:
                log.debug("Exception: %s", str(ex))
            if DEBUG >= 2:
                log.debug(traceback.format_exc())
            continue
        if found:  # Skip remaining methods
            break
    return found