Parse the WMI packages output.
559786
def ParseMultiple(self, result_dicts):
    """"""
    for result_dict in result_dicts:
      args = {"ifname": result_dict["Description"]}
      args["mac_address"] = binascii.unhexlify(
          result_dict["MACAddress"].replace(":", ""))

      self._ConvertIPs([("IPAddress", "addresses"),
                        ("DefaultIPGateway", "ip_gateway_list"),
                        ("DHCPServer", "dhcp_server_list")], result_dict, args)

      if "DHCPLeaseExpires" in result_dict:
        args["dhcp_lease_expires"] = self.WMITimeStrToRDFDatetime(
            result_dict["DHCPLeaseExpires"])

      if "DHCPLeaseObtained" in result_dict:
        args["dhcp_lease_obtained"] = self.WMITimeStrToRDFDatetime(
            result_dict["DHCPLeaseObtained"])

      yield rdf_client_network.Interface(**args)

      yield rdf_client_network.DNSClientConfiguration(
          dns_server=result_dict["DNSServerSearchOrder"],
          dns_suffix=result_dict["DNSDomainSuffixSearchOrder"])
883183
def _parse_reported_packages_from_remove_output(output):
    '''
    
    '''
    reported_pkgs = {}
    remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
    for line in salt.utils.itertools.split(output, '\n'):
        match = remove_pattern.match(line)
        if match:
            reported_pkgs[match.group('package')] = ''

    return reported_pkgs
213350
def parse_setup() -> Tuple[PackagesType, PackagesType, Set[str], Set[str]]:
    """"""
    essential_packages: PackagesType = {}
    test_packages: PackagesType = {}
    essential_duplicates: Set[str] = set()
    test_duplicates: Set[str] = set()

    with open('setup.py') as setup_file:
        contents = setup_file.read()

    # Parse out essential packages.
    package_string = re.search(r"""install_requires=\[[\s\n]*['"](.*?)['"],?[\s\n]*\]""",
                               contents, re.DOTALL).groups()[0].strip()
    for package in re.split(r"""['"],[\s\n]+['"]""", package_string):
        module, version = parse_package(package)
        if module in essential_packages:
            essential_duplicates.add(module)
        else:
            essential_packages[module] = version

    # Parse packages only needed for testing.
    package_string = re.search(r"""tests_require=\[[\s\n]*['"](.*?)['"],?[\s\n]*\]""",
                               contents, re.DOTALL).groups()[0].strip()
    for package in re.split(r"""['"],[\s\n]+['"]""", package_string):
        module, version = parse_package(package)
        if module in test_packages:
            test_duplicates.add(module)
        else:
            test_packages[module] = version

    return essential_packages, test_packages, essential_duplicates, test_duplicates
466527
def parse_sysctl(text):
    '''  '''
    lines = text.splitlines()
    results = {}
    for line in lines:
        key, _, value = line.decode('ascii').partition(': ')

        if key == 'hw.memsize':
            value = int(value)

        elif key == 'vm.swapusage':
            values = value.split()[2::3]            # every third token
            su_unit = values[0][-1].lower()         # get unit, 'M'
            PAGESIZE = 1024
            if su_unit == 'm':
                PAGESIZE = 1024 * 1024

            value = [ (float(val[:-1]) * PAGESIZE) for val in values ]

        results[key] = value
    return results
821188
def parse(binary, **params):
    """"""
    binary = io.BytesIO(binary)
    collection = list()
    with tarfile.TarFile(fileobj=binary, mode='r') as tar:
        for tar_info in tar.getmembers():
            content_type, encoding = mimetypes.guess_type(tar_info.name)
            content = tar.extractfile(tar_info)
            content = content_encodings.get(encoding).decode(content)
            content = content_types.get(content_type).parse(content, **params)
            collection.apppend((tar_info.name, content))
    return collection
1254890
def ParseMultiple(self, result_dicts):
    """"""
    for result_dict in result_dicts:
      result = result_dict.ToDict()
      winvolume = rdf_client_fs.WindowsVolume(
          drive_letter=result.get("DeviceID"),
          drive_type=result.get("DriveType"))

      try:
        size = int(result.get("Size"))
      except (ValueError, TypeError):
        size = None

      try:
        free_space = int(result.get("FreeSpace"))
      except (ValueError, TypeError):
        free_space = None

      # Since we don't get the sector sizes from WMI, we just set them at 1 byte
      yield rdf_client_fs.Volume(
          windowsvolume=winvolume,
          name=result.get("VolumeName"),
          file_system_type=result.get("FileSystem"),
          serial_number=result.get("VolumeSerialNumber"),
          sectors_per_allocation_unit=1,
          bytes_per_sector=1,
          total_allocation_units=size,
          actual_available_allocation_units=free_space)
1102208
def _windows_wwns():
    '''
    
    '''
    ps_cmd = r'Get-WmiObject -ErrorAction Stop ' \
             r'-class MSFC_FibrePortHBAAttributes ' \
             r'-namespace "root\WMI" | ' \
             r'Select -Expandproperty Attributes | ' \
             r'%{($_.PortWWN | % {"{0:x2}" -f $_}) -join ""}'
    ret = []
    cmd_ret = salt.modules.cmdmod.powershell(ps_cmd)
    for line in cmd_ret:
        ret.append(line.rstrip())
    return ret
838661
def get_package_data():
    """"""
    BITSIZE, LINKAGE = platform.architecture()
    files = [
        "py.typed",
        "lib/LIBTCOD-CREDITS.txt",
        "lib/LIBTCOD-LICENSE.txt",
        "lib/README-SDL.txt",
    ]
    if "win32" in sys.platform:
        if BITSIZE == "32bit":
            files += ["x86/SDL2.dll"]
        else:
            files += ["x64/SDL2.dll"]
    if sys.platform == "darwin":
        files += ["SDL2.framework/Versions/A/SDL2"]
    return files
290867
def installed_packages(self):
        
        packages = []
        CMDLINE = [sys.executable, "-mpip", "freeze"]
        try:
            for package in subprocess.check_output(CMDLINE) \
                    .decode('utf-8'). \
                    splitlines():
                for comparator in ["==", ">=", "<=", "<", ">"]:
                    if comparator in package:
                        # installed package names usually look like Pillow==2.8.1
                        # ignore others, like external packages that pip show
                        # won't understand
                        name = package.partition(comparator)[0]
                        packages.append(name)
        except RuntimeError as e:
            if logger.isEnabledFor(logging.DEBUG):
                logger.debug("Exception checking existing packages.")
                logger.debug("cmdline: %s", CMDLINE)
                ex_type, ex, tb = sys.exc_info()
                traceback.print_tb(tb)
                logger.debug()
        return packages
622986
def __parse_drac(output):
    '''
    
    '''
    drac = {}
    section = ''

    for i in output.splitlines():
        if i.strip().endswith(':') and '=' not in i:
            section = i[0:-1]
            drac[section] = {}
        if i.rstrip() and '=' in i:
            if section in drac:
                drac[section].update(dict(
                    [[prop.strip() for prop in i.split('=')]]
                ))
            else:
                section = i.strip()
                if section not in drac and section:
                    drac[section] = {}

    return drac
765307
def parse(self):
        """"""

        if os.path.exists(self.pklname):        # check for pkl with binary info
            logger.info('Found bdf pkl file %s. Loading...' % (self.pklname))
            try:
                with open(self.pklname,'rb') as pkl:
                    (self.mimemsg, self.headxml, self.sizeinfo, self.binarychunks, self.n_integrations, self.n_antennas, self.n_baselines, self.n_basebands, self.n_spws, self.n_channels, self.crosspols) = pickle.load(pkl)
            except:
                logger.warning('Something went wrong. Parsing bdf directly...')
                self._parse()
        else:
            if self.pklname:
                logger.info('Could not find bdf pkl file %s.' % (self.pklname))
            self._parse()

        self.headsize, self.intsize = self.calc_intsize()

        return self
465995
def parse_output(self, line):
        """"""

        try:
            key, value = line.split(":")
            self.update_value(key.strip(), value.strip())
        except ValueError:
            pass
269737
static String[] parsePackages(String packages) {

    if (packages == null || packages.trim().length() == 0) {
      return new String[0];
    }
    String[] commaSplit = packages.split(",");
    String[] processPackages = new String[commaSplit.length];
    for (int i = 0; i < commaSplit.length; i++) {
      processPackages[i] = convert(commaSplit[i]);
    }
    return processPackages;
  }
439566
def ParseMultiple(self, result_dicts):
    """"""
    for result_dict in result_dicts:
      wmi_dict = result_dict.ToDict()

      try:
        creator_sid_bytes = bytes(wmi_dict["CreatorSID"])
        wmi_dict["CreatorSID"] = BinarySIDtoStringSID(creator_sid_bytes)
      except ValueError:
        # We recover from corrupt SIDs by outputting it raw as a string
        wmi_dict["CreatorSID"] = compatibility.Repr(wmi_dict["CreatorSID"])
      except KeyError:
        pass

      for output_type in self.output_types:
        anomalies = []

        output = rdfvalue.RDFValue.classes[output_type]()
        for k, v in iteritems(wmi_dict):
          try:
            output.Set(k, v)
          except AttributeError as e:
            # Skip any attribute we don't know about
            anomalies.append("Unknown field %s, with value %s" % (k, v))
          except ValueError as e:
            anomalies.append("Invalid value %s for field %s: %s" % (v, k, e))

        # Yield anomalies first to help with debugging
        if anomalies:
          yield rdf_anomaly.Anomaly(
              type="PARSER_ANOMALY",
              generated_by=self.__class__.__name__,
              finding=anomalies)

        # Raise if the parser generated no output but there were fields.
        if wmi_dict and not output:
          raise ValueError("Non-empty dict %s returned empty output." %
                           wmi_dict)

        yield output
567055
def Parse(self, cmd, args, stdout, stderr, return_val, time_taken,
            knowledge_base):
    """"""
    _ = time_taken, args, knowledge_base  # Unused.
    rpm_re = re.compile(r"^(\w[-\w\+]+?)-(\d.*)$")
    self.CheckReturn(cmd, return_val)
    packages = []
    for line in stdout.splitlines():
      pkg_match = rpm_re.match(line.strip())
      if pkg_match:
        name, version = pkg_match.groups()
        status = rdf_client.SoftwarePackage.InstallState.INSTALLED
        packages.append(
            rdf_client.SoftwarePackage(
                name=name, version=version, install_state=status))
    if packages:
      yield rdf_client.SoftwarePackages(packages=packages)

    for line in stderr.splitlines():
      if "error: rpmdbNextIterator: skipping h#" in line:
        yield rdf_anomaly.Anomaly(
            type="PARSER_ANOMALY", symptom="Broken rpm database.")
        break
1093206
def parse_command_plugins_output(out):
    
    out = out.split('--- end of plugins list ---')[0]
    out = out.partition('plugins ***')[2]
    out = out.splitlines()

    current_slot = 0

    plugins = EmbeddedPlugins([], [])

    for line in out:
        line = line.strip()

        if not line:
            continue

        if line.startswith('***'):
            current_slot += 1
            continue

        if current_slot is not None:
            plugins[current_slot].append(line)

    plugins = plugins._replace(request=[plugin.partition(' ')[2] for plugin in plugins.request])

    return plugins
79343
def _parse_programs(self, string, parent, filepath=None):
        """"""
        #First, get hold of the docstrings  for all the modules so that we can
        #attach them as we parse them.
        moddocs = self.docparser.parse_docs(string)
        #Now look for modules in the file and then match them to their decorators.
        matches = self.RE_PROGRAM.finditer(string)
        result = []
        for rmodule in matches:
            name = rmodule.group("name").lower()
            contents = re.sub("&[ ]*\n", "", rmodule.group("contents"))
            module = self._process_module(name, contents, parent, rmodule, filepath)
            #Check whether the docparser found docstrings for the module.
            if name in moddocs:                
                module.docstring = self.docparser.to_doc(moddocs[name][0], name)
                module.docstart, module.docend = module.absolute_charindex(string, moddocs[name][1],
                                                                           moddocs[name][2])
            result.append(module)
        return result