Parse LINK Chunk Method
321999
def linkChunk(key, chunk):
    
    # Extract link type card
    linkType = chunk[1].strip().split()[0]

    # Cases
    if linkType == 'DX':
        # Cross section link type handler
        result = xSectionLink(chunk)

    elif linkType == 'STRUCTURE':
        # Structure link type handler
        result = structureLink(chunk)

    elif linkType in ('RESERVOIR', 'LAKE'):
        # Reservoir link type handler
        result = reservoirLink(chunk)
    return result
832604
function( url, callback ) {

		// Node quick, not present on browser builds
		if (IS_NODE) {

			// Helper function
			var readChunk = function ( filename ) {
				// Read into buffer
				var file = fs.readFileSync(filename),
					u8 = new Uint8Array(file);
				// Return buffer
				return u8.buffer;
			}

			// Read by chunks
			if (url.substr(-5) === ".jbbp") {

				// Add by buffer
				var base = url.substr(0,url.length-5);
				this.addByBuffer( [
					readChunk(base + '.jbbp'),
					readChunk(base + '_b16.jbbp'),
					readChunk(base + '_b32.jbbp'),
					readChunk(base + '_b64.jbbp'),
				], callback );

			} else {

				// Add by buffer
				this.addByBuffer( readChunk(url), callback );

			}

			// Don't continue on browser builds
			return;

		}

		// Check for base dir
		var prefix = "";
		if (this.baseDir)
			prefix = this.baseDir + "/";

		// Check for sparse bundle
		var parts = url.split("?"), suffix = "", reqURL = [];
		if (parts.length > 1) suffix = "?"+parts[1];
		if (parts[0].substr(parts[0].length - 5).toLowerCase() === ".jbbp") {
			var base = prefix + parts[0].substr(0, parts[0].length - 5);
			reqURL = [
				base + '.jbbp' + suffix,
				base + '_b16.jbbp' + suffix,
				base + '_b32.jbbp' + suffix,
				base + '_b64.jbbp' + suffix
			];
		} else {
			// Assume .jbb if missing (TODO: not a good idea)
			var url = parts[0];
			if (url.substr(url.length-4) != ".jbb") url += ".jbb";
			reqURL = [ prefix + url + suffix ];
		}

		// Load bundle header and keep a callback
		// for the remainging loading operations
		var pendingBundle = {
			'callback': callback,
			'status': PBUND_REQUESTED,
			'buffer': undefined,
			'url': reqURL
		};

		// Keep this pending action
		this.queuedRequests.push( pendingBundle );

	}
956372
function parseRawLines(rawText, extendedSyntax, parsedRawLinesCallback) {
        var entries = rawText.replace(reBlank, '').split(/[\r\n]+/);
        var currentLang = '*';
        var genericLang = lang.split('-', 1)[0];
        var skipLang = false;
        var match = '';

        function nextEntry() {
          // Use infinite loop instead of recursion to avoid reaching the
          // maximum recursion limit for content with many lines.
          while (true) {
            if (!entries.length) {
              parsedRawLinesCallback();
              return;
            }
            var line = entries.shift();

            // comment or blank line?
            if (reComment.test(line))
              continue;

            // the extended syntax supports [lang] sections and @import rules
            if (extendedSyntax) {
              match = reSection.exec(line);
              if (match) { // section start?
                // RFC 4646, section 4.4, "All comparisons MUST be performed
                // in a case-insensitive manner."

                currentLang = match[1].toLowerCase();
                skipLang = (currentLang !== '*') &&
                    (currentLang !== lang) && (currentLang !== genericLang);
                continue;
              } else if (skipLang) {
                continue;
              }
              match = reImport.exec(line);
              if (match) { // @import rule?
                loadImport(baseURL + match[1], nextEntry);
                return;
              }
            }

            // key-value pair
            var tmp = line.match(reSplit);
            if (tmp && tmp.length == 3) {
              dictionary[tmp[1]] = evalString(tmp[2]);
            }
          }
        }
        nextEntry();
      }
277988
function parseChunks(selector, selectors) {
          var parts = [], extra, matches, i;

          do {
            chunker.exec("");
            matches = chunker.exec(selector);

            if (matches) {
              selector = matches[3];
              parts.push(matches[1]);

              if (matches[2]) {
                extra = matches[3];
                break;
              }
            }
          } while (matches);

          if (extra) {
            parseChunks(extra, selectors);
          }

          selector = [];
          for (i = 0; i < parts.length; i++) {
            if (parts[i] != '>') {
              selector.push(compile(parts[i], [], parts[i - 1] === '>'));
            }
          }

          selectors.push(selector);

          return selectors;
        }
1275251
function parseElementBlock(stream, state) {
        if(stream.eat("<")) {
            if(stream.match("?")) {
                pushContext(state, TAG_INSTRUCTION);
                state.tokenize = parseProcessingInstructionStartTag;
                return STYLE_INSTRUCTION;
            } else if(stream.match("!--")) {
                // new context: comment
                pushContext(state, TAG_COMMENT);
                return chain(stream, state, inBlock(STYLE_COMMENT, "-->",
                    state.context == null ? parseDocument : parseElementBlock));
            } else if(stream.match("![CDATA[")) {
                // new context: CDATA section
                pushContext(state, TAG_CDATA);
                return chain(stream, state, inBlock(STYLE_TEXT, "]]>",
                    state.context == null ? parseDocument : parseElementBlock));
            } else if(stream.eatSpace() || stream.eol() ) {
                stream.skipToEnd();
                return STYLE_ERROR;
            } else {
                // element
                state.tokenize = parseElementTagName;
                return STYLE_ELEMENT_NAME;
            }
        } else if(stream.eat("&")) {
            stream.eatWhile(/[^;]/);
            stream.eat(";");
            return STYLE_ENTITIES;
        } else {
            // new context: text
            pushContext(state, TAG_TEXT);
            state.tokenize = parseText;
            return null;
        }
        
        state.tokenize = state.context == null ? parseDocument : parseElementBlock;
        stream.skipToEnd();
        return null;
    }
268457
function ChunkedStream_getBytes(length) {
      var bytes = this.bytes;
      var pos = this.pos;
      var strEnd = this.end;

      if (!length) {
        this.ensureRange(pos, strEnd);
        return bytes.subarray(pos, strEnd);
      }

      var end = pos + length;
      if (end > strEnd) {
        end = strEnd;
      }
      this.ensureRange(pos, end);

      this.pos = end;
      return bytes.subarray(pos, end);
    }
187774
def _parse_description(html_chunk):
    
    description_tag = html_chunk.match(
        ["div", {"class": "kniha_detail_text"}],
        "p"
    )

    if not description_tag:
        return None

    description = get_first_content(description_tag)
    description = description.replace("<br />", "\n")
    description = description.replace("<br/>", "\n")

    return dhtmlparser.removeTags(description).strip()
336228
def _cellChunk(self, lines):
        
        KEYWORDS = ('CELLIJ',
                    'NUMPIPES',
                    'SPIPE')

        result = {'i': None,
                  'j': None,
                  'numPipes': None,
                  'spipes': []}

        chunks = pt.chunk(KEYWORDS, lines)

        # Parse chunks associated with each key
        for card, chunkList in iteritems(chunks):
            # Parse each chunk in the chunk list
            for chunk in chunkList:
                schunk = chunk[0].strip().split()

                # Cases
                if card == 'CELLIJ':
                    # CELLIJ handler
                    result['i'] = schunk[1]
                    result['j'] = schunk[2]

                elif card == 'NUMPIPES':
                    # NUMPIPES handler
                    result['numPipes'] = schunk[1]

                elif card == 'SPIPE':
                    # SPIPE handler
                    pipe = {'linkNumber': schunk[1],
                            'nodeNumber': schunk[2],
                            'fraction': schunk[3]}

                    result['spipes'].append(pipe)

        return result
867932
private String parseLink(final String link) {
		String[] tokens = link.substring(7, link.length() - 1).split("\\s");
		if (tokens.length == 1) {
			return tokens[0];
		}
		StringBuilder result = new StringBuilder();

		boolean parametersSeen = false;
		boolean inParameters = false;

		for (int index = 0; index < tokens.length; index++) {
			result.append(" ").append(tokens[index]);
			if (tokens[index].indexOf('(') != -1 && !parametersSeen) {
				inParameters = true;
			}
			if (index == 1 && !inParameters) {
				result = new StringBuilder(tokens[index]);
			}
			if (tokens[index].indexOf(')') != -1 && !parametersSeen) {
				parametersSeen = true;
				if (index != tokens.length - 1) {
					result = new StringBuilder();
				}

			}

		}

		return result.toString().trim();
	}
1331002
def _url_chunk_join(self, *args):
        """"""
        # Strip slashes from either side of each path piece.
        pathlets = map(lambda s: s.strip('/'), args)
        # Remove empty pieces.
        pathlets = filter(None, pathlets)
        url = '/'.join(pathlets)
        # If this is a directory, add a trailing slash.
        if args[-1].endswith('/'):
            url = '%s/' % url
        return url
504609
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE):
    """"""
    while True:
        chunk = file.read(size)
        if not chunk:
            break
        yield chunk
1365984
public function parseFromArray()
    {
        $this->chunk = '';
        // read the length byte
        $length = $this->reader->next();
        // just take the splice from this array
        $this->childParseFromArray($length);
    }
992920
def reservoirLink(lines):
    
    # Constants
    KEYWORDS = ('LINK',
                'RESERVOIR',
                'RES_MINWSE',
                'RES_INITWSE',
                'RES_MAXWSE',
                'RES_NUMPTS',
                'LAKE',
                'MINWSE',
                'INITWSE',
                'MAXWSE',
                'NUMPTS')

    result  =  {'header': {'link': None,
                           'res_minwse': None,
                           'res_initwse': None,
                           'res_maxwse': None,
                           'res_numpts': None,
                           'minwse': None,
                           'initwse': None,
                           'maxwse': None,
                           'numpts': None},
                'type': None,
                'points': []}

    pair = {'i': None,
            'j': None}

    # Rechunk the chunk
    chunks = pt.chunk(KEYWORDS, lines)

    # Parse chunks associated with each key
    for key, chunkList in iteritems(chunks):
        # Parse each chunk in the chunk list
        for chunk in chunkList:
            schunk = chunk[0].strip().split()


            # Cases
            if key in ('NUMPTS', 'RES_NUMPTS'):
                # Points handler
                result['header'][key.lower()] = schunk[1]

                # Parse points
                for idx in range(1, len(chunk)):
                    schunk = chunk[idx].strip().split()

                    for count, ordinate in enumerate(schunk):
                        # Divide ordinates into ij pairs
                        if (count % 2) == 0:
                            pair['i'] = ordinate
                        else:
                            pair['j'] = ordinate
                            result['points'].append(pair)
                            pair = {'i': None,
                                    'j': None}

            elif key in ('LAKE', 'RESERVOIR'):
                # Type handler
                result['type'] = schunk[0]
            else:
                # Header variables handler
                result['header'][key.lower()] = schunk[1]
    return result
1215473
public void parse() {
        ChunkHeader firstChunkHeader = readChunkHeader();
        if (firstChunkHeader == null) {
            return;
        }

        switch (firstChunkHeader.getChunkType()) {
            case ChunkType.XML:
            case ChunkType.NULL:
                break;
            case ChunkType.STRING_POOL:
            default:
                // strange chunk header type, just skip this chunk header?
        }

        // read string pool chunk
        ChunkHeader stringPoolChunkHeader = readChunkHeader();
        if (stringPoolChunkHeader == null) {
            return;
        }

        ParseUtils.checkChunkType(ChunkType.STRING_POOL, stringPoolChunkHeader.getChunkType());
        stringPool = ParseUtils.readStringPool(buffer, (StringPoolHeader) stringPoolChunkHeader);

        // read on chunk, check if it was an optional XMLResourceMap chunk
        ChunkHeader chunkHeader = readChunkHeader();
        if (chunkHeader == null) {
            return;
        }

        if (chunkHeader.getChunkType() == ChunkType.XML_RESOURCE_MAP) {
            long[] resourceIds = readXmlResourceMap((XmlResourceMapHeader) chunkHeader);
            resourceMap = new String[resourceIds.length];
            for (int i = 0; i < resourceIds.length; i++) {
                resourceMap[i] = Attribute.AttrIds.getString(resourceIds[i]);
            }
            chunkHeader = readChunkHeader();
        }

        while (chunkHeader != null) {
                /*if (chunkHeader.chunkType == ChunkType.XML_END_NAMESPACE) {
                    break;
                }*/
            long beginPos = buffer.position();
            switch (chunkHeader.getChunkType()) {
                case ChunkType.XML_END_NAMESPACE:
                    XmlNamespaceEndTag xmlNamespaceEndTag = readXmlNamespaceEndTag();
                    xmlStreamer.onNamespaceEnd(xmlNamespaceEndTag);
                    break;
                case ChunkType.XML_START_NAMESPACE:
                    XmlNamespaceStartTag namespaceStartTag = readXmlNamespaceStartTag();
                    xmlStreamer.onNamespaceStart(namespaceStartTag);
                    break;
                case ChunkType.XML_START_ELEMENT:
                    XmlNodeStartTag xmlNodeStartTag = readXmlNodeStartTag();
                    break;
                case ChunkType.XML_END_ELEMENT:
                    XmlNodeEndTag xmlNodeEndTag = readXmlNodeEndTag();
                    break;
                case ChunkType.XML_CDATA:
                    XmlCData xmlCData = readXmlCData();
                    break;
                default:
                    if (chunkHeader.getChunkType() >= ChunkType.XML_FIRST_CHUNK &&
                            chunkHeader.getChunkType() <= ChunkType.XML_LAST_CHUNK) {
                        Buffers.skip(buffer, chunkHeader.getBodySize());
                    } else {
                        throw new ParserException("Unexpected chunk type:" + chunkHeader.getChunkType());
                    }
            }
            Buffers.position(buffer, beginPos + chunkHeader.getBodySize());
            chunkHeader = readChunkHeader();
        }
    }
527139
function (chunks) {
	var groupedChunks = [];
	var inCommentBlock = false;
	chunks.forEach(function (chunk) {
		var isComment = helpers.isComment(chunk);
		var isNewline = helpers.isNewline(chunk);
		if (isComment) {
			inCommentBlock = true;
		} else if (inCommentBlock && !isNewline) {
			inCommentBlock = false;
		}

		var previous = groupedChunks[groupedChunks.length - 1];
		var previousIsComment = helpers.isComment(previous);
		var previousIsArray = Array.isArray(previous);
		if (groupedChunks.length > 0 && inCommentBlock && (previousIsComment || previousIsArray)) {
			if (previousIsArray) {
				previous.push(chunk);
			} else if (previousIsComment) {
				groupedChunks[groupedChunks.length - 1] = [].concat(previous, chunk);
			}
		} else {
			groupedChunks.push(chunk);
		}
	});
	return groupedChunks;
}
1164935
private void parseMatch(I_CmsXmlContentLocation linkFormatterLoc, boolean strict) throws ParseException {

        Set<String> containerTypes = new HashSet<String>();
        I_CmsXmlContentValueLocation typesLoc = linkFormatterLoc.getSubValue(path(N_MATCH, N_TYPES));
        I_CmsXmlContentValueLocation widthLoc = linkFormatterLoc.getSubValue(path(N_MATCH, N_WIDTH));
        if (typesLoc != null) {
            List<I_CmsXmlContentValueLocation> singleTypeLocs = typesLoc.getSubValues(N_CONTAINER_TYPE);
            for (I_CmsXmlContentValueLocation singleTypeLoc : singleTypeLocs) {
                String containerType = singleTypeLoc.getValue().getStringValue(m_cms).trim();
                containerTypes.add(containerType);
            }
            m_containerTypes = containerTypes;
        } else if (widthLoc != null) {
            String widthStr = getString(widthLoc, N_WIDTH, null);
            String maxWidthStr = getString(widthLoc, N_MAX_WIDTH, null);
            try {
                m_width = Integer.parseInt(widthStr);
            } catch (Exception e) {
                throw new ParseException("Invalid container width: [" + widthStr + "]", e);
            }
            try {
                m_maxWidth = Integer.parseInt(maxWidthStr);
            } catch (Exception e) {
                m_maxWidth = Integer.MAX_VALUE;
                LOG.debug(maxWidthStr, e);
            }
        } else {
            if (strict) {
                throw new ParseException("Neither container types nor container widths defined!");
            } else {
                m_width = -1;
                m_maxWidth = Integer.MAX_VALUE;
            }
        }
    }
337265
def _really_parse_external_link(self, brackets):
        """"""
        if brackets:
            self._parse_bracketed_uri_scheme()
            invalid = ("\n", " ", "]")
        else:
            self._parse_free_uri_scheme()
            invalid = ("\n", " ", "[", "]")
            punct = tuple(",;\\.:!?)")
        if self._read() is self.END or self._read()[0] in invalid:
            self._fail_route()
        tail = ""
        while True:
            this, next = self._read(), self._read(1)
            if this == "&":
                if tail:
                    self._emit_text(tail)
                    tail = ""
                self._parse_entity()
            elif (this == "<" and next == "!" and self._read(2) ==
                  self._read(3) == "-"):
                if tail:
                    self._emit_text(tail)
                    tail = ""
                self._parse_comment()
            elif not brackets and self._is_free_link_end(this, next):
                return self._pop(), tail, -1
            elif this is self.END or this == "\n":
                self._fail_route()
            elif this == next == "{" and self._can_recurse():
                if tail:
                    self._emit_text(tail)
                    tail = ""
                self._parse_template_or_argument()
            elif this == "]":
                return self._pop(), tail, 0
            elif " " in this:
                before, after = this.split(" ", 1)
                if brackets:
                    self._emit_text(before)
                    self._emit(tokens.ExternalLinkSeparator())
                    if after:
                        self._emit_text(after)
                    self._context ^= contexts.EXT_LINK_URI
                    self._context |= contexts.EXT_LINK_TITLE
                    self._head += 1
                    return self._parse(push=False), None, 0
                punct, tail = self._handle_free_link_text(punct, tail, before)
                return self._pop(), tail + " " + after, 0
            elif not brackets:
                punct, tail = self._handle_free_link_text(punct, tail, this)
            else:
                self._emit_text(this)
            self._head += 1