Encode entity for HTML or XML output.
438964
public static String entityEncode(String text) {
		String result = text;

		if (result == null) {
			return result;
		}

		// The escapeXml function doesn't cope with some 'special' chrs

		return StringEscapeUtils.escapeXml10(XMLStringUtil.escapeControlChrs(result));
	}
756068
def _has_xml_encode(self, content):
        """"""

        encode = None

        m = RE_XML_START.match(content)
        if m:
            if m.group(1):
                m2 = RE_XML_ENCODE.match(m.group(1))

                if m2:
                    enc = m2.group(2).decode('ascii')

                    try:
                        codecs.getencoder(enc)
                        encode = enc
                    except LookupError:
                        pass
            else:
                if m.group(2):
                    enc = 'utf-32-be'
                    text = m.group(2)
                elif m.group(3):
                    enc = 'utf-32-le'
                    text = m.group(3)
                elif m.group(4):
                    enc = 'utf-16-be'
                    text = m.group(4)
                elif m.group(5):
                    enc = 'utf-16-le'
                    text = m.group(5)
                try:
                    m2 = RE_XML_ENCODE_U.match(text.decode(enc))
                except Exception:  # pragma: no cover
                    m2 = None

                if m2:
                    enc = m2.group(2)

                    try:
                        codecs.getencoder(enc)
                        encode = enc
                    except Exception:
                        pass

        return encode
654640
private void encodeHTML(FacesContext fc) throws IOException {
		boolean idHasBeenRendered = false;
		Map<String, Object> attrs = getAttributes();
		String clientId = getClientId(fc);
		ResponseWriter rw = fc.getResponseWriter();
		int numberOfDivs = 0;
		String responsiveStyleClass = Responsive.getResponsiveStyleClass(this, false).trim();
		if (responsiveStyleClass.length() > 0 && (!CoreRenderer.isHorizontalForm(this))) {
			rw.startElement("div", this);
			rw.writeAttribute("class", responsiveStyleClass, "class");
			rw.writeAttribute("id", clientId, "id");
			Tooltip.generateTooltip(fc, this, rw);
			idHasBeenRendered = true;
			numberOfDivs++;
		}
		rw.startElement("div", this);
		numberOfDivs++;
		String errorSeverityClass = BsfUtils.isLegacyFeedbackClassesEnabled() ? ""
				: FacesMessages.getErrorSeverityClass(clientId);

		String formGroupClass = "";
		if (!(getParent() instanceof FormGroup)) {
			formGroupClass = "form-group";
		}
		rw.writeAttribute("class", formGroupClass + errorSeverityClass, "class");
		if (!idHasBeenRendered) {
			rw.writeAttribute("id", clientId, "id");
			Tooltip.generateTooltip(fc, this, rw);
			idHasBeenRendered = true;
		}
		addLabel(rw, clientId + "_input", clientId);

		if (responsiveStyleClass.length() > 0 && (CoreRenderer.isHorizontalForm(this))) {
			rw.startElement("div", this);
			numberOfDivs++;
			rw.writeAttribute("class", responsiveStyleClass, "class");
		}

		// stz = selectTimeZone(attrs.get(A.TZ));

		sloc = selectLocale(fc.getViewRoot().getLocale(), A.asString(attrs.get(JQ.LOCALE)));
		sdf = selectDateFormat(sloc, A.asString(attrs.get(JQ.DTFORMAT)));

		// Debugging Locale and dateformat
		// rw.write("<span>DEBUG sloc='"+sloc+"', sdf='"+sdf+"' </span>");

		String dpId;

		Object v = getSubmittedValue();
		if (v == null) {
			v = this.getValue();
		}

		/*
		 * 6 modes: 1) inline 2) popup (no icons) 3) popup-icon 4) icon-popup 5)
		 * toggle-icon (Default) 6) icon-toggle
		 */
		boolean isDisabled = A.toBool(attrs.get("disabled"));
		mode = A.asString(attrs.get("mode"), "toggle-icon");
		boolean inline = mode.equals("inline");

		if (inline) { // inline => div with ID
			dpId = clientId + "_" + "div";
			rw.startElement("div", this);
			rw.writeAttribute("id", dpId, null);
			if (getStyleClass() != null) {
				rw.writeAttribute("class", getStyleClass(), "styleClass");
			}
			if (getStyle() != null) {
				rw.writeAttribute("style", getStyle(), "style");
			}
			rw.endElement("div");
		} else { // popup
			dpId = clientId + "_input";

			if (!mode.equals("popup")) { // with icon => div with prepend/append
											// style
				rw.startElement("div", this);
				numberOfDivs++;
				String clazz = "input-group ";
				if (null != getStyleClass()) {
					clazz += getStyleClass() + " ";
				}
				rw.writeAttribute("class", clazz, "class");
				if (getStyle() != null) {
					rw.writeAttribute("style", getStyle(), "style");
				}

				if (mode.equals("icon-popup") || mode.equals("icon-toggle")) {
					rw.startElement("span", this);
					rw.writeAttribute("id", clientId + "_" + ADDON, "id");
					rw.writeAttribute("class", ADDON, "class");
					IconRenderer.encodeIcon(rw, this, "calendar", false, null, null, null, false, null, null,
							isDisabled, true, true, true, isIconBrand(), isIconInverse(), isIconLight(), isIconPulse(),
							isIconRegular(), isIconRegular());

					rw.endElement("span");
				}
			}
		}
		String type = inline ? "hidden" : "text";

		rw.startElement("input", null);
		rw.writeAttribute("id", clientId + "_input", null);
		if (getTabindex() != null) {
			rw.writeAttribute("tabindex", getTabindex(), null);
		}

		// if (getStyle() != null) {
		// rw.writeAttribute("style", getStyle(), "style");
		// }
		rw.writeAttribute("name", clientId, null);
		rw.writeAttribute("type", type, null);
		String styleClass = new CoreRenderer().getErrorAndRequiredClass(this, clientId);
		rw.writeAttribute("class", "form-control " + styleClass, "class");
		if (v != null) {
			rw.writeAttribute("value", getConvertedDateAsString(v, sdf, sloc), null);
		}

		String ph = A.asString(attrs.get("placeholder"));
		if (ph != null) {
			rw.writeAttribute("placeholder", ph, null);
		}

		if (isDisabled) {
			rw.writeAttribute("disabled", "disabled", null);
		}
		if (A.toBool(attrs.get("readonly"))) {
			rw.writeAttribute("readonly", "readonly", null);
		}
		rw.endElement("input");

		encodeJS(fc, rw, clientId + "_input", dpId);
		if (mode.equals("popup-icon") || mode.equals("toggle-icon")) {
			rw.startElement("span", this);
			rw.writeAttribute("id", clientId + "_" + ADDON, "id");
			rw.writeAttribute("class", ADDON, "class");

			IconRenderer.encodeIcon(rw, this, "calendar", false, null, null, null, false, null, null, isDisabled, true,
					true, true, isIconBrand(), isIconInverse(), isIconLight(), isIconPulse(), isIconRegular(),
					isIconRegular());

			rw.endElement("span");
		}

		if (!inline && !mode.equals("popup")) {
			rw.endElement("div");
			numberOfDivs--;
			JQ.datePickerToggler(rw, clientId + "_input", clientId + "_" + ADDON);

		} // Closes the popup prepend/append style div

		while (numberOfDivs > 0) {
			rw.endElement("div");
			numberOfDivs--;
		}
	}
396681
def _EncodeDateField(field, value):
    """"""
    if field.repeated:
        result = [d.isoformat() for d in value]
    else:
        result = value.isoformat()
    return encoding.CodecResult(value=result, complete=True)
165909
public static String entityToString(HttpEntity entity) throws IOException {
        if (entity != null) {
            InputStream is = entity.getContent();
            return IOUtils.toString(is, "UTF-8");
        }
        return "";
    }
546096
public static String encodeXMLEntity(final String tagName) {
		StringBuffer encoded = new StringBuffer(tagName);
		//replaceAll(encoded,";","&semi;");
		replaceAll(encoded,"&","&amp;");
		replaceAll(encoded,"\"","&quot;");
		replaceAll(encoded,"'","&apos;");
		replaceAll(encoded,"<","&lt;");
		replaceAll(encoded,">","&gt;");
		return encoded.toString();
	}
790433
def ConvertToWireFormat(self, value):
    """"""
    data = value.SerializeToString()
    return (self.encoded_tag, VarintEncode(len(data)), data)
681097
function formatAttrs(attributes, opts, keyOnlyAttribs = []) {
  if (!attributes) return;

  var output = '',
    value;

  // Loop through the attributes
  for (var key in attributes) {
    value = attributes[key];
    if (output) {
      output += ' ';
    }

    if (!value && booleanAttributes[key] || isExpr(key) || isKeyOnlyAttr(key, keyOnlyAttribs)) {
      output += key;
    } else {
      output += key + `=${isExpr(value) ? '' : '"'}` + (opts.decodeEntities ? entities.encodeXML(value) : value) + (isExpr(value) ? '' : '"');
    }
  }

  return output;
}
343757
public static String encodeXMLEntityQuote(final String content) {
		StringBuffer encoded = new StringBuffer(content);
		replaceAll(encoded,"amp","&#38;#38;");
		replaceAll(encoded,"apos","&#39;");
		replaceAll(encoded,"<","&#38;#60;");
		replaceAll(encoded,"gt","&#62;");
		replaceAll(encoded,"quot","&#34;");
		return encoded.toString();
	}
869058
protected static function htmlentitiesApply($str, $encodeTags, $isXml, $charsets)
    {
        self::getCfg(); // sets htmlentitiesmore
        $return = '';
        if (!$encodeTags) {
            // $debug->log('don\'t encode tags');
            $return = self::htmlentitiesSansTags($str, $charsets);
        }
        // now entityfy final (or only) segment
        if (!in_array(trim($str), array('', '0'), true)) {
            foreach ($charsets as $charset) {
                // change: was call_user_func_array
                $strEntityfied = @htmlentities($str, ENT_COMPAT, $charset);
                if (!empty($strEntityfied)) {
                    #$debug->log('success with '.$charset);
                    break;
                }
            }
            if (empty($strEntityfied)) {
                // $debug->warn('unable to convert');
                $strEntityfied = $str;
            }
            $str = preg_replace('/&amp;(#\d+;|[a-zA-Z]+;)/', '&\\1', $strEntityfied);
            $str = str_replace(
                array_keys(self::$htmlentitiesMore),
                array_values(self::$htmlentitiesMore),
                $str
            );
            $return .= $str;
        }
        if ($isXml) {
            if (empty(self::$xmlentitiesHtml)) {
                self::buildEntities();
            }
            $return = str_replace(self::$xmlentitiesHtml, self::$xmlentitiesUtf8, $return);
        }
        return $return;
    }
527553
def encode_document(document):
    """"""
    tree = etree.Element('document')
    etree.SubElement(tree, 'id').text = document.id
    encode_infons(tree, document.infons)
    for passage in document.passages:
        tree.append(encode_passage(passage))
    for ann in document.annotations:
        tree.append(encode_annotation(ann))
    for rel in document.relations:
        tree.append(encode_relation(rel))
    return tree
570775
def serialize(self, value, entity=None, request=None):
    

    ret = self.from_python(value)
    self.validate(ret)
    self.run_validators(value)
    return ret
87341
def replace_entities(self, html):
        
        def fixup(text):
            """replace the htmlentities in some text"""
            text = text.group(0)
            if text[:2] == "&#":
                # character reference
                try:
                    if text[:3] == "&#x":
                        return chr(int(text[3:-1], 16))
                    else:
                        return chr(int(text[2:-1]))
                except ValueError:
                    pass
            else:
                # named entity
                try:
                    text = chr(htmlentitydefs.name2codepoint[text[1:-1]])
                except KeyError:
                    pass
            return text  # leave as is
        return re.sub(r"&#?\w+;", fixup, html)
1252442
def xml_encode(string):
    
    string = string.replace("&", "&amp;")
    string = string.replace("<", "&lt;")
    string = string.replace(">", "&gt;")
    string = string.replace("\"","&quot;")
    string = string.replace(SLASH, "/")
    return string
67857
function htmlEncode($html, $in = null, $out = null, $mode = 'auto')
    {
        $valid = array(
            'auto',
            'iconv',
            'mb_convert_encoding'
        );
        if (! isset($out)) {
            $out = 'UTF-8';
        }
        if (! in_array($mode, $valid)) {
            user_error('invalid mode, mode=' . $mode, E_USER_ERROR);
        }
        $if = function_exists('mb_convert_encoding');
        $if = $if && ($mode == 'auto' || $mode == 'mb_convert_encoding');
        $func = null;
        if (function_exists('iconv') && ($mode == 'auto' || $mode == 'iconv')) {
            $func = 'iconv';
        } elseif ($if) {
            $func = 'mb_convert_encoding';
        } else {
            user_error('encode failed, php extension not found', E_USER_ERROR);
        }
        $pattern = '/(<meta[^>]*?charset=(["\']?))([a-z\d_\-]*)(\2[^>]*?>)/is';
        if (! isset($in)) {
            $n = preg_match($pattern, $html, $in);
            if ($n > 0) {
                $in = $in[3];
            } else {
                if (function_exists('mb_detect_encoding')) {
                    $in = mb_detect_encoding($html);
                } else {
                    $in = null;
                }
            }
        }
        if (isset($in)) {
            $old = error_reporting(error_reporting() & ~ E_NOTICE);
            $html = call_user_func($func, $in, $out . '//IGNORE', $html);
            error_reporting($old);
            $html = preg_replace($pattern, "\\1$out\\4", $html, 1);
        } else {
            user_error('source encoding is unknown', E_USER_ERROR);
        }
        return $html;
    }
160345
def to_xml(ele, encoding="UTF-8", pretty_print=False):
    ""
    xml = etree.tostring(ele, encoding=encoding, pretty_print=pretty_print)
    if sys.version < '3':
        return xml if xml.startswith('<?xml') else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml)
    else:
        return xml.decode('UTF-8') if xml.startswith(b'<?xml') \
            else '<?xml version="1.0" encoding="%s"?>%s' % (encoding, xml.decode('UTF-8'))
425450
def htmlDocContentDumpOutput(self, buf, encoding):
        
        if buf is None: buf__o = None
        else: buf__o = buf._o
        libxml2mod.htmlDocContentDumpOutput(buf__o, self._o, encoding)