Parse the inventory text and return udi dict.
508815
def parse_inventory(inventory_output=None):
    """"""
    udi = {
        "name": "",
        "description": "",
        "pid": "",
        "vid": "",
        "sn": ""
    }
    if inventory_output is None:
        return udi

    # find the record with chassis text in name or descr
    capture_next = False
    chassis_udi_text = None
    for line in inventory_output.split('\n'):
        lc_line = line.lower()
        if ('chassis' in lc_line or 'switch system' in lc_line or 'rack' in lc_line) and 'name' in lc_line and 'descr':
            capture_next = True
            chassis_udi_text = line
            continue
        if capture_next:
            inventory_output = chassis_udi_text + "\n" + line
            break
    match = re.search(r"(?i)NAME: (?P<name>.*?),? (?i)DESCR", inventory_output, re.MULTILINE)
    if match:
        udi['name'] = match.group('name').strip('" ,')

    match = re.search(r"(?i)DESCR: (?P<description>.*)", inventory_output, re.MULTILINE)
    if match:
        udi['description'] = match.group('description').strip('" ')

    match = re.search(r"(?i)PID: (?P<pid>.*?),? ", inventory_output, re.MULTILINE)
    if match:
        udi['pid'] = match.group('pid')

    match = re.search(r"(?i)VID: (?P<vid>.*?),? ", inventory_output, re.MULTILINE)
    if match:
        udi['vid'] = match.group('vid')

    match = re.search(r"(?i)SN: (?P<sn>.*)", inventory_output, re.MULTILINE)
    if match:
        udi['sn'] = match.group('sn').strip()
    return udi
295914
def _parse_docline(self, line, container):
        """"""
        match = self.RE_DECOR.match(line)
        if match is not None:
            return "{}.{}".format(container.name, match.group("name"))
        else:
            return container.name
301112
def _parse_output_records(self, item: IterationRecord) -> Dict[str, Any]:
        """"""
        output_records = {}
        for key, sub_item in item.output_records.items():
            if isinstance(sub_item, dict) or isinstance(sub_item, list):
                output_records[key] = sub_item
            else:
                output_records[key] = sub_item.__dict__

        return output_records
955316
def parse(self, text, encoding='utf8', raise_exception=False):
        """"""

        return self.helper.string.serialization.json.parse(
            text=text,
            encoding=encoding,
            raise_exception=raise_exception)
954626
def decode(self, text):
        
        LOGGER.debug('decoding text to dictionary')

        if not text or type(text) is not str:
            raise SLTPParsingError(ERRORS['unexp_type_str'])

        LOGGER.debug('extracting qualifier')
        qual = re.compile(r'^(?P<value>(dictionary|mission|mapResource|warehouses) = ?)\n')
        match = qual.match(text)

        if match is None:
            raise ValueError('qualifier not found; first line: {}'.format(text.split('\n')[0]))

        self.qual = match.group('value')
        text = qual.sub('', text)

        reg = re.compile(r' -- .*[^(\\|",)]$', re.M)
        text = reg.sub('', text)

        self.text = text
        self.at, self.ch, self.depth = 0, '', 0
        self.len = len(text)
        self.next_chr()
        result = self.value()
        return result, self.qual
751152
def get_defaults_dict(self) -> Dict:
        
        return deserializer.inventory.Defaults.serialize(self.defaults).dict()
1091426
def item_parser(item):
    
    if __is_deleted(item):
        return deleted_parser(item)
    return Item(
        __check_key('id', item),
        __check_key('deleted', item),
        __check_key('type', item),
        __check_key('by', item),
        __check_key('time', item),
        __check_key('text', item),
        __check_key('dead', item),
        __check_key('parent', item),
        __check_key('kids', item),
        __check_key('url', item),
        __check_key('score', item),
        __check_key('title', item),
        __check_key('parts', item),
    )
974740
def getMetadata(self, objectId=None, **filters):
        
        if objectId is None:
            return self.inventory
        elif objectId in self.inventory.children.keys():
            return self.inventory[objectId]
        texts, _, _ = self.__getTextMetadata__(urn=objectId)

        # We store inventory names and if there is only one we recreate the inventory
        inv_names = [text.parent.parent.parent.id for text in texts]
        if len(set(inv_names)) == 1:
            inventory = self.classes["inventory"](name=inv_names[0])
        else:
            inventory = self.classes["inventory"]()

        # For each text we found using the filter
        for text in texts:
            tg_urn = str(text.parent.parent.urn)
            wk_urn = str(text.parent.urn)
            txt_urn = str(text.urn)
            # If we need to generate a textgroup object
            if tg_urn not in inventory.textgroups:
                self.classes["textgroup"](urn=tg_urn, parent=inventory)
            # If we need to generate a work object
            if wk_urn not in inventory.textgroups[tg_urn].works:
                self.classes["work"](urn=wk_urn, parent=inventory.textgroups[tg_urn])

            if isinstance(text, CtsEditionMetadata):
                x = self.classes["edition"](urn=txt_urn, parent=inventory.textgroups[tg_urn].works[wk_urn])
                x.citation = text.citation
            elif isinstance(text, CtsTranslationMetadata):
                x = self.classes["translation"](urn=txt_urn, parent=inventory.textgroups[tg_urn].works[wk_urn], lang=text.lang)
                x.citation = text.citation
            elif isinstance(text, CtsCommentaryMetadata):
                x = self.classes["commentary"](urn=txt_urn, parent=inventory.textgroups[tg_urn].works[wk_urn], lang=text.lang)
                x.citation = text.citation

        return inventory[objectId]
537850
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self,
                   'text_normalized') and self.text_normalized is not None:
            _dict['text_normalized'] = self.text_normalized
        return _dict
667227
def get_edu_text(text_subtree):
    """"""
    assert text_subtree.label() == 'text', "text_subtree: {}".format(text_subtree)
    edu_str = u' '.join(word for word in text_subtree.leaves())
    return re.sub('_!(.*?)_!', '\g<1>', edu_str)
549671
def parse(self):
        """"""
        data = utils.ruby_lines(self.readlines())
        data = [tuple(j.strip() for j in line.split(None, 1))
                for line in data]
        depends = {}
        for line in data:
            if not len(line) == 2:
                continue
            key, value = line
            if key == 'depends':
                value = value.split(',')
                lib = utils.ruby_strip(value[0])
                detail = [utils.ruby_strip(j) for j in value[1:]]
                depends[lib] = detail
        datamap = {key: utils.ruby_strip(val) for key, val in data}
        if depends:
            datamap['depends'] = depends
        self.seek(0)
        return datamap
586755
def parse_text_to_dict(self, txt):
        
        op = {}
        print('TODO - import NLP, split into verbs / nouns')
        op['nouns'] = txt
        op['verbs'] = txt
        
        return op
445284
def _parse_description(self, description_text):
        """"""
        text = description_text
        text = text.strip()
        lines = text.split('\n')

        data = {}
        for line in lines:
            if ":" in line:
                idx = line.index(":")
                key = line[:idx]
                value = line[idx+1:].lstrip().rstrip()
                data[key] = value
            else:
                if isinstance(value, list) is False:
                    value = [value]
                value.append(line.lstrip().rstrip())
                data[key] = value
        return data
421662
def iterjson(text):
    """"""
    decoder = json.JSONDecoder()
    while text:
        obj, ndx = decoder.raw_decode(text)

        if not isinstance(obj, dict):
            raise ValueError()

        text = text[ndx:].lstrip('\r\n')
        yield obj
290747
def display_inventory(my_devices):
    """"""
    inventory_groups = ["all"]
    inventory_devices = []
    for k, v in my_devices.items():
        if isinstance(v, list):
            inventory_groups.append(k)
        elif isinstance(v, dict):
            inventory_devices.append((k, v["device_type"]))

    inventory_groups.sort()
    inventory_devices.sort(key=lambda x: x[0])
    print("\nDevices:")
    print("-" * 40)
    for a_device, device_type in inventory_devices:
        device_type = "  ({})".format(device_type)
        print("{:<25}{:>15}".format(a_device, device_type))
    print("\n\nGroups:")
    print("-" * 40)
    for a_group in inventory_groups:
        print(a_group)
    print()
1324007
def parse_info(response):
    ""
    info = {}
    response = nativestr(response)

    def get_value(value):
        if ',' not in value or '=' not in value:
            try:
                if '.' in value:
                    return float(value)
                else:
                    return int(value)
            except ValueError:
                return value
        else:
            sub_dict = {}
            for item in value.split(','):
                k, v = item.rsplit('=', 1)
                sub_dict[k] = get_value(v)
            return sub_dict

    for line in response.splitlines():
        if line and not line.startswith('#'):
            if line.find(':') != -1:
                key, value = line.split(':', 1)
                info[key] = get_value(value)
            else:
                # if the line isn't splittable, append it to the "__raw__" key
                info.setdefault('__raw__', []).append(line)

    return info
468829
def _parse_content(fh):
    """"""
    content = iter(fh)
    deps = {}

    for line in content:
        # quickly discard most of the lines
        if 'fades' not in line:
            continue

        # discard other string with 'fades' that isn't a comment
        if '#' not in line:
            continue

        # assure that it's a well commented line and no other stuff
        line = line.strip()
        index_of_last_fades = line.rfind('fades')
        index_of_first_hash = line.index('#')

        # discard when fades does not appear after #
        if index_of_first_hash > index_of_last_fades:
            continue

        import_part, fades_part = line.rsplit("#", 1)

        # discard other comments in the same line that aren't for fades
        if "fades" not in fades_part:
            import_part, fades_part = import_part.rsplit("#", 1)

        fades_part = fades_part.strip()
        if not fades_part.startswith("fades"):
            continue

        if not import_part:
            # the fades comment was done at the beginning of the line,
            # which means that the import info is in the next one
            import_part = next(content).strip()

        if import_part.startswith('#'):
            continue

        # get module
        import_tokens = import_part.split()
        if import_tokens[0] == 'import':
            module_path = import_tokens[1]
        elif import_tokens[0] == 'from' and import_tokens[2] == 'import':
            module_path = import_tokens[1]
        else:
            logger.debug("Not understood import info: %s", import_tokens)
            continue
        module = module_path.split(".")[0]
        # If fades know the real name of the pkg. Replace it!
        if module in PKG_NAMES_DB:
            module = PKG_NAMES_DB[module]
        # To match the "safe" name that pkg_resources creates:
        module = module.replace('_', '-')

        # get the fades info after 'fades' mark, if any
        if len(fades_part) == 5 or fades_part[5:].strip()[0] in "<>=!":
            # just the 'fades' mark, and maybe a version specification, the requirement is what
            # was imported (maybe with that version comparison)
            requirement = module + fades_part[5:]
        elif fades_part[5] != " ":
            # starts with fades but it's part of a longer weird word
            logger.warning("Not understood fades info: %r", fades_part)
            continue
        else:
            # more complex stuff, to be parsed as a normal requirement
            requirement = fades_part[5:]

        # parse and convert the requirement
        parsed_req = parse_fade_requirement(requirement)
        if parsed_req is None:
            continue
        repo, dependency = parsed_req
        deps.setdefault(repo, []).append(dependency)

    return deps