Parse an external link at the head of the wikicode string.
169759
def _parse_external_link(self, brackets):
        """"""
        if self._context & contexts.NO_EXT_LINKS or not self._can_recurse():
            if not brackets and self._context & contexts.DL_TERM:
                self._handle_dl_term()
            else:
                self._emit_text(self._read())
            return

        reset = self._head
        self._head += 1
        try:
            link, extra, delta = self._really_parse_external_link(brackets)
        except BadRoute:
            self._head = reset
            if not brackets and self._context & contexts.DL_TERM:
                self._handle_dl_term()
            else:
                self._emit_text(self._read())
        else:
            if not brackets:
                scheme = link[0].text.split(":", 1)[0]
                self._remove_uri_scheme_from_textbuffer(scheme)
            self._emit(tokens.ExternalLinkOpen(brackets=brackets))
            self._emit_all(link)
            self._emit(tokens.ExternalLinkClose())
            self._head += delta
            if extra:
                self._emit_text(extra)
485415
def parse_link(value):
    

    links = []

    replace_chars = ' \'"'

    value = value.strip(replace_chars)
    if not value:
        return links

    for val in re.split(', *<', value):
        try:
            url, params = val.split(';', 1)
        except ValueError:
            url, params = val, ''

        link = {'url': url.strip('<> \'"')}

        for param in params.split(';'):
            try:
                key, value = param.split('=')
            except ValueError:
                break

            link[key.strip(replace_chars)] = value.strip(replace_chars)

        links.append(link)

    return links
1175508
public InputStream fetchExternalContent() {

        final URI uri = link.getUri();
        final String scheme = uri.getScheme();
        LOGGER.debug("scheme is {}", scheme);
        if (scheme != null) {
            try {
                if (scheme.equals("file")) {
                    return new FileInputStream(uri.getPath());
                } else if (scheme.equals("http") || scheme.equals("https")) {
                    return uri.toURL().openStream();
                }
            } catch (final IOException e) {
                throw new ExternalContentAccessException("Failed to read external content from " + uri, e);
            }
        }
        return null;
    }
509924
def _parse_reference(self, el):
        """"""
        if '#' in el.get('href', ''):
            return [el.get('href').split('#', 1)[1]]
        elif 'rid' in el.attrib:
            return [el.attrib['rid']]
        elif 'idref' in el.attrib:
            return [el.attrib['idref']]
        else:
            return [''.join(el.itertext()).strip()]
290795
function parseLinkHeader(header) {
    if (!header) {
        return {};
    }

    // Split parts by comma
    const parts = header.split(',');
    const links = {};

    // Parse each part into a named link
    parts.forEach((p) => {
        const section = p.split(';');
        if (section.length != 2) {
            throw new Error('section could not be split on ";"');
        }
        const url = section[0].replace(/<(.*)>/, '$1').trim();
        const name = section[1].replace(/rel="(.*)"/, '$1').trim();
        links[name] = url;
    });

    return links;
}
39410
def parse_string(code)
		code = code.encode(@internal_encoding)
		artifact = StringArtifact.new(code)
		parse_artifact(artifact)
	end
1115136
def parse_link_descriptor(self, descriptor):
        ''''''
        optional_attributes = {}
        link_components = descriptor.split(":{", 1)
        device = link_components[0]
        if (len(link_components) == 2 and link_components[1].endswith("}")):
            # assume json
            some_json = "{" + link_components[1]
            optional_attributes = self.parse_link_attributes(some_json)
        return (device, optional_attributes)
582139
def parse_root(raw):
    ""
    if sys.version < '3':
        fp = StringIO(raw)
    else:
        fp = BytesIO(raw.encode('UTF-8'))
    for event, element in etree.iterparse(fp, events=('start',)):
        return (element.tag, element.attrib)
974797
void parseNextResponse() throws IOException {
    contentId++;

    // Extract the outer headers.
    String line;
    while ((line = readLine()) != null && !line.equals("")) {
      // Do nothing.
    }

    // Extract the status code.
    String statusLine = readLine();
    String[] statusParts = statusLine.split(" ");
    int statusCode = Integer.parseInt(statusParts[1]);

    // Extract and store the inner headers.
    // TODO(rmistry): Handle inner headers that span multiple lines. More details here:
    // http://tools.ietf.org/html/rfc2616#section-2.2
    List<String> headerNames = new ArrayList<String>();
    List<String> headerValues = new ArrayList<String>();
    long contentLength = -1L;
    while ((line = readLine()) != null && !line.equals("")) {
      String[] headerParts = line.split(": ", 2);
      String headerName = headerParts[0];
      String headerValue = headerParts[1];
      headerNames.add(headerName);
      headerValues.add(headerValue);
      if ("Content-Length".equalsIgnoreCase(headerName.trim())) {
          contentLength = Long.parseLong(headerValue);
      }
    }

    InputStream body;
    if (contentLength == -1) {
      // This isn't very efficient, but most respectable servers should set the Content-Length
      ByteArrayOutputStream buffer = new ByteArrayOutputStream();
      while ((line = readRawLine()) != null && !line.startsWith(boundary)) {
        // Convert characters back to bytes:
        buffer.write(line.getBytes("ISO-8859-1"));
      }

      // Remove CRLF that separates body from boundary token
      body = trimCrlf(buffer.toByteArray());

      // Remove CRLF from the boundary token (to match readLine)
      line = trimCrlf(line);
    } else {
      body = new FilterInputStream(ByteStreams.limit(inputStream, contentLength)) {
        @Override
        public void close() {
          // Don't allow the parser to close the underlying stream
        }
      };
    }

    HttpResponse response =
        getFakeResponse(statusCode, body, headerNames, headerValues);

    parseAndCallback(requestInfos.get(contentId - 1), statusCode, response);

    // Consume any bytes that were not consumed by the parser
    while (body.skip(contentLength) > 0 || body.read() != -1) {
    }

    if (contentLength != -1) {
      line = readLine();
    } else {
      // The line was already read
    }
    // Consume any blank lines that follow the response (not included in Content-Length)
    while ((line != null) && (line.length() == 0)) {
      line = readLine();
    }

    checkForFinalBoundary(line);
  }
185668
def parse_headers_link(headers):
    """"""

    header = CaseInsensitiveDict(headers).get('link')

    l = {}

    if header:
        links = parse_link(header)

        for link in links:
            key = link.get('rel') or link.get('url')
            l[key] = link

    return l
468469
public static Link parse(String origin, String link, boolean allowModuleName) {
        String originMod = origin;
        int index = link.indexOf('#');
        if (index == -1) {
            if (allowModuleName) {
                index = link.lastIndexOf('/');
                if (index == -1) {
                    return new Link(null, null, link);
                }

                return new Link(null, link.substring(0, index), link.substring(index + 1));
            }

            return new Link(null, null, link);
        }

        String name = link.substring(index + 1);
        String uri = link.substring(0, index);
        if (originMod == null) {
            originMod = "";
        } else {
            index = originMod.lastIndexOf('/');
            originMod = index == -1 ? "" : originMod.substring(0, index);
        }

        if (uri.startsWith("../")) {
            uri = uri.substring(3);
        }

        while (uri.startsWith("../")) {
            index = originMod.lastIndexOf('/');
            if (index == -1) {
                originMod = "";
            } else {
                originMod = originMod.substring(0, index);
            }
            uri = uri.substring(3);
        }

        return new Link(originMod.isEmpty() ? uri : originMod + '/' + uri, null, name);
    }
1214536
def _handle_wikilink_separator(self):
        """"""
        self._context ^= contexts.WIKILINK_TITLE
        self._context |= contexts.WIKILINK_TEXT
        self._emit(tokens.WikilinkSeparator())
385581
def parse_link(link_str):
    
    atts = {}
    help_str = "--link option '%s' (format rel,href,att1=val1...)" % (link_str)
    try:
        segs = link_str.split(',')
        # First segments are relation and subject
        atts['rel'] = segs.pop(0)
        atts['href'] = segs.pop(0)
        if (atts['href'] == ''):
            raise ClientFatalError("Missing uri in " + help_str)
        # Remaining segments are attributes
        for term in segs:
            (k, v) = term.split('=')
            if (k == '' or v == ''):
                raise ClientFatalError(
                    "Bad attribute (%s) in " %
                    (term) + help_str)
            atts[k] = v
    except ValueError as e:
        raise ClientFatalError("Bad component of " + help_str)
    except IndexError as e:
        raise ClientFatalError("Incomplete component of " + help_str)

    return(atts)
132858
def find_external_urls(self, entry):
        
        soup = BeautifulSoup(entry.html_content, 'html.parser')
        external_urls = [a['href'] for a in soup.find_all('a')
                         if self.is_external_url(
                             a['href'], self.ressources.site_url)]
        return external_urls
471980
def _get_link(element: Element) -> Optional[str]:
    
    link = get_text(element, 'link')
    if link is not None:
        return link

    guid = get_child(element, 'guid')
    if guid is not None and guid.attrib.get('isPermaLink') == 'true':
        return get_text(element, 'guid')

    return None
919321
def parse_header(cls, value='*/*'):
        """"""
        yield from sorted((
            cls.from_string(token.strip())
            for token in value.split(',')
            if token.strip()
        ), reverse=True)
456682
def _parse_and_clean_wikicode(raw_content):
  """"""
  wikicode = tfds.core.lazy_imports.mwparserfromhell.parse(raw_content)

  # Filters for references, tables, and file/image links.
  re_rm_wikilink = re.compile(
      "^(?:File|Image|Media):", flags=re.IGNORECASE | re.UNICODE)
  def rm_wikilink(obj):
    return bool(re_rm_wikilink.match(six.text_type(obj.title)))
  def rm_tag(obj):
    return six.text_type(obj.tag) in {"ref", "table"}
  def rm_template(obj):
    return obj.name.lower() in {
        "reflist", "notelist", "notelist-ua", "notelist-lr", "notelist-ur",
        "notelist-lg"}

  def try_remove_obj(obj, section):
    try:
      section.remove(obj)
    except ValueError:
      # For unknown reasons, objects are sometimes not found.
      pass

  section_text = []
  # Filter individual sections to clean.
  for section in wikicode.get_sections(
      flat=True, include_lead=True, include_headings=True):
    for obj in section.ifilter_wikilinks(matches=rm_wikilink, recursive=True):
      try_remove_obj(obj, section)
    for obj in section.ifilter_templates(matches=rm_template, recursive=True):
      try_remove_obj(obj, section)
    for obj in section.ifilter_tags(matches=rm_tag, recursive=True):
      try_remove_obj(obj, section)

    section_text.append(section.strip_code().strip())
  return "\n\n".join(section_text)