URL Encode and truncate tag to match limit (128 characters) of ThreatConnect API.

        Args:
           tag (string): The tag to be truncated

        Returns:
            (string): The truncated tag
329119
def safe_tag(self, tag, errors='strict'):
        
        if tag is not None:
            try:
                # handle unicode characters and url encode tag value
                tag = quote(self.s(tag, errors=errors), safe='~')[:128]
            except KeyError as e:
                warn = 'Failed converting tag to safetag ({})'.format(e)
                self.log.warning(warn)
        return tag
948802
function getOpenTagParams(tag, tmplRule) {
  var pattern = tmplRule.openTagParams,
      matchArr,
      ret;

  while (matchArr = pattern.exec(tag)) {
    var key = matchArr[1];

    if (key === '/') {
      //If match to the last of "/", then continue the loop.
      continue;
    }

    if (!ret) {
      ret = [];
    }

    var value = matchArr[8],
        onlyBrace = matchArr[4] != null ? matchArr[4] : matchArr[6],
        onlyKey = false;

    if (value != null) {
      value = clearQuot(value); //Remove quotation marks
    } else {
      value = key; //Match to Similar to "checked" or "disabled" attribute.

      if (!onlyBrace) {
        onlyKey = true;
      }
    } //Removed at the end of "/>", ">" or "/".


    if (!matchArr[9] && !matchArr[10]) {
      if (/\/>$/.test(value)) {
        value = value.substr(0, value.length - 2);
      } else if (/>$/.test(value) || /\/$/.test(value)) {
        value = value.substr(0, value.length - 1);
      }
    } //Transform special key


    var hasColon = void 0;

    if (key[0] === ':') {
      key = key.substr(1);
      hasColon = true;
    }

    ret.push({
      key: key,
      value: value,
      onlyBrace: onlyBrace,
      hasColon: hasColon,
      onlyKey: onlyKey
    });
  }

  return ret;
}
662551
def remove_tag(self, *tag: str):
        
        LOGGER.info('removing tag(s) from repo: %s', tag)

        self.repo.delete_tag(*tag)
1028227
def nrefs(self, tag):
        

        n = _C.Vnrefs(self._id, tag)
        _checkErr('nrefs', n, "bad arguments")
        return n
1175396
def delete(self, tag, **kwds):
        
        return self._client.post("/tag/%s/delete.json" %
                                 self._quote_url(self._extract_id(tag)),
                                 **kwds)["result"]
603642
def handle_endtag(self, tagName):
        '''
            
        '''
        inTag = self._inTag
        try:
            # Handle closing tags which should have been closed but weren't
            foundIt = False
            for i in range(len(inTag)):
                if inTag[i].tagName == tagName:
                    foundIt = True
                    break

            if not foundIt:
                sys.stderr.write('WARNING: found close tag with no matching start.\n')
                return

            while inTag[-1].tagName != tagName:
                oldTag = inTag.pop()
                if oldTag.tagName in PREFORMATTED_TAGS:
                    self.inPreformatted -= 1

                self.currentIndentLevel -= 1

            inTag.pop()
            if tagName != INVISIBLE_ROOT_TAG:
                self.currentIndentLevel -= 1
            if tagName in PREFORMATTED_TAGS:
                self.inPreformatted -= 1
        except:
            pass
703464
def itemFromTag( self, tag ):
        
        for row in range(self.count() - 1):
            item = self.item(row)
            if ( item and item.text() == tag ):
                return item
        return None
186602
def _var_uint64_byte_size_no_tag(uint64):
    
    if uint64 > UINT64_MAX:
        raise errors.EncodeError('Value out of range: %d' % uint64)
    bytes = 1
    while uint64 > 0x7f:
        bytes += 1
        uint64 >>= 7
    return bytes
839106
def get_tag(self, tag):
        
        headers = {'Accept': 'text/plain'}
        j, _ = self.datacenter.request('GET', self.path + '/tags/' + tag)
        return j
546988
function parseTag(buf) {
  var index = 0;
  var tag = buf[index++];
  var constructed = (tag & 0x20) == 0x20;
  
  if ((tag & 0x1F) == 0x1F) {
    do {
      tag = tag << 8;
      tag = tag | buf[index++];  
    } while((tag & 0x80) == 0x80);
    
    if (index > 4) {
      throw new RangeError("The length of the tag cannot be more than 4 bytes in this implementation");
    }
  }
  return { tag: tag, length: index, constructed: constructed };
}
489962
function truncate(str, maxLength) {
	maxLength = maxLength || 300;

	if (str.length > maxLength) {
		var index = str.indexOf('>');
		str = str.substring(0, index + 1);
	}

	return str;
}
1347348
public static function truncateHTML($html, $maxLength, $trailing='...') {
		$html = trim($html);
		$printedLength = 0;
		$position = 0;
		$tags = [];

		$res = '';

		while ($printedLength < $maxLength && preg_match('{</?([a-z]+)[^>]*>|&#?[a-zA-Z0-9]+;}', $html, $match, PREG_OFFSET_CAPTURE, $position)) {
			list($tag, $tagPosition) = $match[0];

			$str = substr($html, $position, $tagPosition - $position);
			if($printedLength + strlen($str) > $maxLength) {
				$res .= (substr($str, 0, $maxLength - $printedLength));
				$printedLength = $maxLength;
				break;
			}

			$res .= ($str);
			$printedLength += strlen($str);

			if($tag[0] == '&') {
				$res .= ($tag);
				$printedLength++;
			}
			else {
				$tagName = $match[1][0];
				if($tag[1] == '/')
					$res .= ($tag);
				elseif($tag[strlen($tag) - 2] == '/' || $tagName == 'br' || $tagName == 'hr')
					$res .= ($tag);
				else {
					$res .= ($tag);
					$tags[] = $tagName;
				}
			}

			$position = $tagPosition + strlen($tag);
		}

		if($printedLength < $maxLength && $position < strlen($html))
			$res .= (substr($html, $position, $maxLength - $printedLength));

		if($position < strlen($html))
			$res .= $trailing;

		while(!empty($tags))
			$res .= sprintf('</%s>', array_pop($tags));

		return $res;
	}
251407
def del_tag(
            self,
            tag):
        

        if tag.replace("@", "") not in self.tags:
            return

        self.refresh
        oldContent = self.to_string(indentLevel=1)
        newTags = []
        newTags[:] = [n for n in newTags if tag not in n]
        self.tags = newTags
        newContent = self.to_string(indentLevel=1)

        # ADD DIRECTLY TO CONTENT IF THE PROJECT IS BEING ADDED SPECIFICALLY TO
        # THIS OBJECT
        self.parent._update_document_tree(
            oldContent=oldContent,
            newContent=newContent
        )

        self.refresh
        return None
1064166
def encr_tags(self) -> dict:
        

        return {t: self._tags[t] for t in self.tags or {} if not t.startswith('~')} or None
1369127
def delete_tag(self, tag):
        
        j, r = self.datacenter.request('DELETE', self.path + '/tags/' + tag)
        r.raise_for_status()
828630
def SplitTag(self, tag):
      
      idx = tag.find(NS_SEP)
      if idx >= 0:
         return tag[:idx], tag[idx + 1:]
      else:
         return "", tag
1053553
def _get_tag(self, response, tag_name="html", encoding="utf-8"):
        
        def find_tag(tag_name):
            tag_start = tag_end = None
            found = lambda: \
                tag_start is not None and tag_end is not None
            html = self._html.lower()
            start = html.find("<%s" % tag_name)
            if start >= 0:
                tag_start = start
            else:
                return None # no tag
            end = html.find("</%s>" % tag_name)
            if end > tag_start:
                tag_end = end+len(tag_name)+3
            elif consumed:
                tag_end = -1 # till the end
            if found():
                return self._html[tag_start:tag_end]
            return None
        consumed = getattr(response, 'consumed', False)
        if not consumed:
            stream = getattr(response, 'stream', None)
            if stream is None:
                stream = response.iter_content(config.CHUNK_SIZE) # , decode_unicode=True
                response.stream = stream
            while True:
                try:
                    chunk = next(stream)
                    self._html += chunk
                    tag = find_tag(tag_name)
                    if tag:
                        return tag
                    if len(self._html) > config.HTML_MAX_BYTESIZE:
                        raise HTMLParseError('Maximum response size reached.')
                except StopIteration:
                    response.consumed = True
        tag = find_tag(tag_name)
        return decode(tag, encoding)