Wrap `url` in angle brackets when needed, or when forced. In links, images, and definitions, the URL part needs to be enclosed when it:  - has a length of `0` - contains white-space - has more or less opening than closing parentheses
502072
function enclose(uri, always) {
  if (
    always ||
    uri.length === 0 ||
    expression.test(uri) ||
    count(uri, leftParenthesis) !== count(uri, rightParenthesis)
  ) {
    return lessThan + uri + greaterThan
  }

  return uri
}
523155
def shorten_url(url, length=32, strip_www=True, strip_path=True, ellipsis=False):
    
    if '://' not in url:
        # Ensure we have a protocol
        url = 'http://%s' % url

    parsed_url = urlparse(url)
    ext = tldextract.extract(parsed_url.netloc)
    if ext.subdomain and (not strip_www or (strip_www and ext.subdomain != 'www')):
        shortened = u'%s.%s' % (ext.subdomain, ext.domain)
    else:
        shortened = u'%s' % ext.domain

    if ext.tld:
        shortened = u'%s.%s' % (shortened, ext.tld)

    if not strip_path:
        if parsed_url.path:
            shortened += parsed_url.path

    if len(shortened) <= length:
        return shortened
    else:
        domain = shortened
        i = length + 1 - 3
        left = right = int(i/2)
        if not i % 2:
            right -= 1
        if ellipsis:
            shortened = u"%s\u2026%s" % (domain[:left], domain[-right:])
        else:
            shortened = '%s...%s' % (domain[:left], domain[-right:])

        return shortened
304338
function urlJoin() {
    var args = Array.prototype.slice.call(arguments),
        prefixDoubleSlash = false,
        url;

    // Remove empty item at the beginning
    if (args[0] === '') {
        args.shift();
    }

    // Handle schemeless protocols
    if (args[0].indexOf('//') === 0) {
        prefixDoubleSlash = true;
    }

    // join the elements using a slash
    url = args.join('/');

    // Fix multiple slashes
    url = url.replace(/(^|[^:])\/\/+/g, '$1/');

    // Put the double slash back at the beginning if this was a schemeless protocol
    if (prefixDoubleSlash) {
        url = url.replace(/^\//, '//');
    }

    url = deduplicateSubDir(url);
    return url;
}
79335
private int getURLIndex(String url, List<String> urlList) {
        int urlIndex = 0;
        int numURLs = urlList.size();

        // get URL index
        if (url != null)
            for (int i = 0; i < numURLs; i++)
                if ((urlList.get(i)).equalsIgnoreCase(url)) {
                    urlIndex = i;
                    break;
                }

        return urlIndex;
    }
201582
def _check_inline_links(self, url_data, content):
        
        MAX_LINK_TEXT_SENTINEL = 3000
        curr_pos = 0
        content_length = len(content)
        while True:  # Handle the next link.
            # The next '[' is the start of:
            # - an inline anchor:   [text](url "title")
            # - an inline img:      ![text](url "title")
            # - not markup:         [...anything else...
            try:
                start_idx = content.index('[', curr_pos)
            except ValueError:
                break

            # Find the matching closing ']'.
            bracket_depth = 0
            for p in range(start_idx+1, min(start_idx+MAX_LINK_TEXT_SENTINEL, content_length)):
                if content[p] == ']':
                    bracket_depth -= 1
                    if bracket_depth < 0:
                        break
                elif content[p] == '[':
                    bracket_depth += 1
            else:
                # Closing bracket not found within sentinel length. This isn't markup.
                curr_pos = start_idx + 1
                continue

            # Now determine what this is by the remainder.
            p += 1
            if p >= content_length:
                return

            if content[p] == '(':
                url, url_end_idx = self._extract_url_and_title(content, p)
                if url is not None:
                    self._save_url(url_data, content, url, p)
                    start_idx = url_end_idx

            # Otherwise, it isn't markup.
            curr_pos = start_idx + 1
218996
def expand_brackets(s):
    """"""
    s = ''.join(s.split())
    while True:
        start = s.find('(')
        if start == -1:
            break
        count = 1 # Number of hanging open brackets
        p = start + 1
        while p < len(s):
            if s[p] == '(':
                count += 1
            if s[p] == ')':
                count -= 1
            if not count:
                break
            p += 1
        if count:
            raise ValueError("Unbalanced parenthesis in '{0}'.".format(s))
        if start == 0 or s[start - 1] != '*':
            s = s[0:start] + s[start + 1:p] + s[p + 1:]
        else:
            m = BRACKET_RE.search(s)
            if m:
                factor = int(m.group('factor'))
                matchstart = m.start('factor')
                s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] + ',') + s[start + 1:p] + s[p + 1:]
            else:
                raise ValueError("Failed to parse '{0}'.".format(s))
    return s
421670
function wrap (rule) {
  return ($) => {
    let value = rule($)
    if (typeof value !== 'string') return
    if (isUrl(value)) return
    if (value.indexOf('www.') === 0) return
    if (value.includes('|')) return

    // trim extra whitespace
    value = value.replace(/\s+/g, ' ')
    value = value.trim()

    // remove any extra "by" in the start of the string
    value = value.replace(/^[\s\n]*by[\s\n]*/im, '')

    // make it title case, since some sites have it in weird casing
    value = toTitleCase(value)

    return value
  }
}
407441
def wrap(cls, url):
    
    if isinstance(url, cls):
      return url
    elif isinstance(url, compatible_string):
      return cls(url)
    else:
      raise ValueError('url must be either a string or Link.')
179674
function split(url) {
  assert.equal(typeof url, 'string', 'url-querystring: url should be a string');

  var res = {};
  var nw = url.split('?');

  res.url = nw[0];
  res.qs = nw.length == 2
    ? qs.parse(nw[1])
    : {};

  return res;
}
1245268
function correctQuestionMarkAndAnd(url) {
	var baseURL = url;

	// Remove && mistake
	baseURL = baseURL.replace(new RegExp('&&', 'g'), '&');

	// Ends width ?
	if (new RegExp('[\?]$').test(baseURL)) {
		// Do nothing
	} else {
		// Does not end on ?
		// Contains ?
		if (baseURL.includes('?')) {
			// Ends width &
			if (new RegExp('[\&]$').test(baseURL)) {
				// Do nothing
			} else {
				// Does not end on &
				// Add &
				baseURL += '&';
			}

		} else {
			// Does not contain on ?

			// Count of &
			var countOfAnd = baseURL.split('&').length - 1;

			// Ends with &
			if (new RegExp('[\&]$').test(baseURL)) {

				if (countOfAnd === 1) {
					// Remove &
					baseURL = baseURL.slice(0, -1);
					// Add ?
					baseURL += '?';
				} else {
					// Replace first & with ?
					baseURL = baseURL.replace('&', '?');
				}

			} else {
				// Does not contain on ? ends not on &

				// Contains one or more &
				if (countOfAnd > 1) {

					// Replace first & with ?
					baseURL = baseURL.replace('&', '?');

					// Add &
					baseURL += '&';
				} else {
					// Does not contain &
					// Add ?
					baseURL += '?';
				}

			}

		}
	}

	return baseURL;
}
675713
function formatUrl (url, query) {
  let protocol
  let index = url.indexOf('://')
  if (index !== -1) {
    protocol = url.substring(0, index)
    url = url.substring(index + 3)
  } else if (url.indexOf('//') === 0) {
    url = url.substring(2)
  }

  let parts = url.split('/')
  let result = (protocol ? protocol + '://' : '//') + parts.shift()

  let path = parts.filter(Boolean).join('/')
  let hash
  parts = path.split('#')
  if (parts.length === 2) {
    path = parts[0]
    hash = parts[1]
  }

  result += path ? '/' + path : ''

  if (query && JSON.stringify(query) !== '{}') {
    result += (url.split('?').length === 2 ? '&' : '?') + formatQuery(query)
  }
  result += hash ? '#' + hash : ''

  return result
}
882791
function parseUrl (url) {
  const regex = /(https?).*\/(.+)\/thread\/(\d+)/g
  let protocol
  let board
  let threadNo

  try {
    [, protocol, board, threadNo] = regex.exec(url)
  } catch (err) {
    throw new Error('Invalid 4chan URL!')
  }

  return {
    protocol,
    board,
    threadNo: Number.parseInt(threadNo)
  }
}
1281553
function urldata(value){
  if(!value){
    return;
  }
  var result = [];
  var urlCursor = value.indexOf("url");
  var start = 0;
  var end = 0;
  while(urlCursor >= 0){
    start = urlCursor + 3;

    while(value[start] === " "){ start++; }

    if(value[start] === "("){
      start ++;
    } else {
      return result;
    }

    while(value[start] === " "){ start++; }

    var openQuote = value[start];
    if(openQuote === "\'" || openQuote === "\""){
      start++;
    } else {
      openQuote = "";
    }

    if(!openQuote){
      while(value[start] === " "){ start++; }
    }

    if (!openQuote) {
        end = value.indexOf(")", start);
    } else {
        end = start;
        while(value[end] !== openQuote && end < value.length) { end++; }
        while(value[end] !== ")" && end < value.length){ end++; }
    }
    
    if(end < 0){
      return result;
    } else if (end === value.length) {
      return result;
    }
    end--;
    while(value[end]===" "){
      end--;
    }
    if(!!openQuote){
      if(value[end] === openQuote){
        end--;
      } else {
        start--;
      }
    }
    result[result.length] = value.slice(start, end + 1);
    urlCursor = value.indexOf("url", end);
  }
  return result;
}
54201
def url_norm (url, encoding=None):
    
    if isinstance(url, unicode):
        # try to decode the URL to ascii since urllib.unquote()
        # handles non-unicode strings differently
        try:
            url = url.encode('ascii')
        except UnicodeEncodeError:
            pass
        encode_unicode = True
    else:
        encode_unicode = False
    urlparts = list(urlparse.urlsplit(url))
    # scheme
    urlparts[0] = urllib.unquote(urlparts[0]).lower()
    # mailto: urlsplit is broken
    if urlparts[0] == 'mailto':
        url_fix_mailto_urlsplit(urlparts)
    # host (with path or query side effects)
    is_idn = url_fix_host(urlparts)
    # query
    urlparts[3] = url_parse_query(urlparts[3], encoding=encoding)
    if urlparts[0] in urlparse.uses_relative:
        # URL has a hierarchical path we should norm
        if not urlparts[2]:
            # Empty path is allowed if both query and fragment are also empty.
            # Note that in relative links, urlparts[0] might be empty.
            # In this case, do not make any assumptions.
            if urlparts[0] and (urlparts[3] or urlparts[4]):
                urlparts[2] = '/'
        else:
            # fix redundant path parts
            urlparts[2] = collapse_segments(urlparts[2])
    # anchor
    urlparts[4] = urllib.unquote(urlparts[4])
    # quote parts again
    urlparts[0] = url_quote_part(urlparts[0], encoding=encoding) # scheme
    urlparts[1] = url_quote_part(urlparts[1], safechars='@:', encoding=encoding) # host
    urlparts[2] = url_quote_part(urlparts[2], safechars=_nopathquote_chars, encoding=encoding) # path
    urlparts[4] = url_quote_part(urlparts[4], encoding=encoding) # anchor
    res = urlunsplit(urlparts)
    if url.endswith('#') and not urlparts[4]:
        # re-append trailing empty fragment
        res += '#'
    if encode_unicode:
        res = unicode(res)
    return (res, is_idn)
237399
def prepend_http(url):
    
    url = url.lstrip()
    if not urlparse(url).scheme:
        return 'http://' + url
    return url
875989
def url_normolize(url: str):
    
    u = parse.urljoin('///{}/'.format(url), '.')
    u = re.sub(r'/+', '/', u)
    return u if url.endswith('/') else u[:-1]
660575
def make_link(title, url, blank=False):
	
	attrs = 'href="%s"' % url
	if blank:
		attrs += ' target="_blank" rel="noopener noreferrer"'
	return '<a %s>%s</a>' % (attrs, title)