Convert an RDLFormatCode string to HTML
181049
def rdlfc_to_html(text, node=None, md=None):
    
    if md is None:
        md = markdown.Markdown()

    # --------------------------------------------------------------------------
    # Remove any common indentation
    # --------------------------------------------------------------------------
    linelist = text.splitlines()
    if linelist:
        text = (
            linelist[0].lstrip()
            + "\n"
            + textwrap.dedent("\n".join(linelist[1:]))
        )
    else:
        text = text.strip()

    # --------------------------------------------------------------------------
    # Parse and replace RDLFormatCode Tags
    # --------------------------------------------------------------------------
    token_spec = [
        ('b', r'\[b\]'),
        ('xb', r'\[/b\]'),
        ('i', r'\[i\]'),
        ('xi', r'\[/i\]'),
        ('u', r'\[u\]'),
        ('xu', r'\[/u\]'),
        ('color', r'\[color=[^\]]+\]'),
        ('xcolor', r'\[/color\]'),
        ('size', r'\[size=[^\]]+\]'),
        ('xsize', r'\[/size\]'),
        ('plainurl', r'\[url\].*?\[/url\]'),
        ('url', r'\[url=[^\]]+\]'),
        ('xurl', r'\[/url\]'),
        ('email', r'\[email\].*?\[/email\]'),
        ('img', r'\[img\].*?\[/img\]'),
        ('code', r'\[code\].*?\[/code\]'),
        ('list', r'\[list(?:=[^\]]+)?\]'),
        ('bullet', r'\[\*\]'),
        ('xlist', r'\[/list\]'),
        ('quote', r'\[quote\]'),
        ('xquote', r'\[/quote\]'),
        ('br', r'\[br\]'),
        ('lb', r'\[lb\]'),
        ('rb', r'\[rb\]'),
        ('p', r'\[p\]'),
        ('xp', r'\[/p\]'),
        ('sp', r'\[sp\]'),
        ('index', r'\[index\]'),
        ('index_parent', r'\[index_parent\]'),
        ('name', r'\[name\]'),
        ('instname', r'\[instname\]'),
    ]
    tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_spec)
    pos = 0
    text_segs = []
    is_first_bullet = []
    list_end_tag = []
    for m in re.finditer(tok_regex, text, re.DOTALL):
        start = m.start()
        end = m.end()

        # Emit prior text
        if start != pos:
            text_segs.append(text[pos:start])
        pos = end

        if m.lastgroup == 'b':
            text_segs.append("<b>")
        elif m.lastgroup == 'xb':
            text_segs.append("</b>")
        elif m.lastgroup == 'i':
            text_segs.append("<i>")
        elif m.lastgroup == 'xi':
            text_segs.append("</i>")
        elif m.lastgroup == 'u':
            text_segs.append("<u>")
        elif m.lastgroup == 'xu':
            text_segs.append("</u>")
        elif m.lastgroup == 'color':
            m2 = re.match(r'\[color=([^\]]+)\]', m.group(0))
            text_segs.append('<span style="color:%s">' % m2.group(1))
        elif m.lastgroup == 'xcolor':
            text_segs.append('</span>')
        elif m.lastgroup == 'size':
            m2 = re.match(r'\[size=([^\]]+)\]', m.group(0))
            text_segs.append('<span style="font-size:%s">' % m2.group(1))
        elif m.lastgroup == 'xsize':
            text_segs.append('</span>')
        elif m.lastgroup == 'plainurl':
            m2 = re.match(r'\[url\](.*?)\[/url\]', m.group(0), re.DOTALL)
            text_segs.append('<a href="%s">%s</a>' % (m2.group(1).strip(), m2.group(1).strip()))
        elif m.lastgroup == 'url':
            m2 = re.match(r'\[url=([^\]]+)\]', m.group(0))
            text_segs.append('<a href="%s">' % m2.group(1).strip())
        elif m.lastgroup == 'xurl':
            text_segs.append('</a>')
        elif m.lastgroup == 'email':
            m2 = re.match(r'\[email\](.*?)\[/email\]', m.group(0), re.DOTALL)
            text_segs.append('<a href="mailto:%s">%s</a>' % (m2.group(1).strip(), m2.group(1).strip()))
        elif m.lastgroup == 'img':
            m2 = re.match(r'\[img\](.*?)\[/img\]', m.group(0), re.DOTALL)
            text_segs.append('<img src="%s">' % m2.group(1))
        elif m.lastgroup == 'code':
            m2 = re.match(r'\[code\](.*?)\s*\[/code\]', m.group(0), re.DOTALL)
            text_segs.append('<code>%s</code>' % m2.group(1))

        elif m.lastgroup == 'list':
            # List start tag
            m2 = re.match(r'\[list(?:=([^\]]+))?\]', m.group(0))
            ltype = m2.group(1)
            if ltype is None:
                text_segs.append('<ul>')
                is_first_bullet.append(True)
                list_end_tag.append('</ul>')
            elif ltype.strip() in ("1", "A", "a", "I", "i"):
                text_segs.append('<ol type="%s">' % ltype.strip())
                is_first_bullet.append(True)
                list_end_tag.append('</ol>')
            else:
                # Bad type. re-emit erronous list tag
                text_segs.append(m.group(0))

        elif m.lastgroup == 'bullet':
            if len(is_first_bullet) == 0: #pylint: disable=len-as-condition
                # Not inside a list tag. Re-emit erronous tag
                text_segs.append("\\[\\*\\]")
            else:
                if not is_first_bullet[-1]:
                    text_segs.append("</li>")
                is_first_bullet[-1] = False
                text_segs.append("<li>")

        elif m.lastgroup == 'xlist':
            if len(list_end_tag) == 0: #pylint: disable=len-as-condition
                # Not inside a list tag. Re-emit erronous tag
                text_segs.append(m.group(0))
            else:
                if not is_first_bullet[-1]:
                    text_segs.append("</li>")
                text_segs.append(list_end_tag[-1])
                is_first_bullet.pop()
                list_end_tag.pop()

        elif m.lastgroup == 'quote':
            text_segs.append('"')
        elif m.lastgroup == 'xquote':
            text_segs.append('"')
        elif m.lastgroup == 'br':
            text_segs.append("<br>")
        elif m.lastgroup == 'lb':
            text_segs.append("\\[")
        elif m.lastgroup == 'rb':
            text_segs.append("\\]")
        elif m.lastgroup == 'p':
            text_segs.append("\n\n<p>")
        elif m.lastgroup == 'xp':
            text_segs.append("</p>")
        elif m.lastgroup == 'sp':
            text_segs.append("&nbsp")
        elif m.lastgroup == 'index':
            if (node is not None) and node.inst.is_array:
                subscripts = []
                if node.current_idx is None:
                    # Index is not known. Use range
                    for dim in node.inst.array_dimensions:
                        subscripts.append("[0:%d]" % dim)
                else:
                    # Index is known
                    for idx in node.current_idx:
                        subscripts.append("[%d]" % idx)
                range_str = "".join(subscripts)
                text_segs.append("<span class='rdlfc-index'>%s</span>" % range_str)
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'index_parent':
            if (node is not None) and (node.parent is not None) and node.parent.inst.is_array:
                subscripts = []
                if node.parent.current_idx is None:
                    # Index is not known. Use range
                    for dim in node.parent.inst.array_dimensions:
                        subscripts.append("[0:%d]" % dim)
                else:
                    # Index is known
                    for idx in node.parent.current_idx:
                        subscripts.append("[%d]" % idx)
                range_str = "".join(subscripts)
                text_segs.append("<span class='rdlfc-index_parent'>%s</span>" % range_str)
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'name':
            if node is not None:
                text_segs.append(node.get_property("name"))
            else:
                text_segs.append(m.group(0))
        elif m.lastgroup == 'instname':
            if node is not None:
                text_segs.append(node.inst.inst_name)
            else:
                text_segs.append(m.group(0))

    # Emit trailing text
    text_segs.append(text[pos:])

    text_out = "".join(text_segs)

    #---------------------------------------------------------------------------
    # Pass through markdown processor
    #---------------------------------------------------------------------------
    text_out = md.reset().convert(text_out)

    return text_out
365491
public static void encodeHTML4DHTMLAttrs(ResponseWriter rw, Map<String, Object> attrs, String[] alist)
			throws IOException {
		// Encode attributes (HTML 4 + DHTML)

		for (String a : alist) {
			if (attrs.get(a) != null) {
				String val = A.asString(attrs.get(a));
				if (val != null && val.length() > 0) {
					rw.writeAttribute(a, val, a);
				}
			}
		}
	}
621565
private String getHtmlCode()
	{
		StringBuffer _body = new StringBuffer();
		for (Option _option : getOptions())
		{
			_body.append(_option.getHtmlCode());
		}
		Object[] _params =
		{
				getHtmlCodeForNameAttribute(),
				getHtmlCodeForIdAttribute(),
				_body.toString(),
				isMultiple() ? HtmlUtils.SpecialAttribute.ALLOW_MULTIPLE_SELECTION : HtmlUtils.SpecialAttribute.NONE,
				isDisabled() ? HtmlUtils.SpecialAttribute.DISABLED : HtmlUtils.SpecialAttribute.NONE
		};
		return FORMAT__SELECT.format(_params);
	}
196917
function HTML(strings, ...values) {
  var dummy = document.createElement('div');
  var fragment = document.createDocumentFragment();
  dummy.innerHTML = compose(strings, ...values);
  forEach.call(dummy.childNodes, appendChild, fragment);
  return fragment;
}
216376
function DataURIScheme_StringToDataURI(str,        // @arg String
                                       mimeType,   // @arg MimeTypeString
                                       callback) { // @arg Function - callback(err:Error|null, String:DataURISchemeString):void
                                                   // @ret void
//{@dev
    $args(DataURIScheme_StringToDataURI, arguments);
//}@dev
    var reader = new FileReader();
    reader.addEventListener("loadend", function() {
        var dataURI = reader.result.replace(";base64,", ";charset=utf-8;base64,");
        // example: data:text/plain;charset=utf-8;base64,YfCgrp9i8J+SqQ==
        //{@dev
        console.info(dataURI);
        //}@dev
        callback(null, dataURI);
    });
    reader.addEventListener("error", function(ev) {
        var err = new Error(ev.target.error.name+": "+ev.target.error.message);
        console.info(err);
        callback(err, "");
    });
    reader.readAsDataURL(new Blob([str], {type: mimeType}));
}
1374556
public static String decodeHtml(String s) {
    int firstAmp = s.indexOf('&');
    int safeLimit = longestPrefixOfGoodCodeunits(s);
    if ((firstAmp & safeLimit) < 0) { return s; }

    StringBuilder sb;
    {
      int n = s.length();
      sb = new StringBuilder(n);
      int pos = 0;
      int amp = firstAmp;
      while (amp >= 0) {
        long endAndCodepoint = HtmlEntities.decodeEntityAt(s, amp, n);
        int end = (int) (endAndCodepoint >>> 32);
        int codepoint = (int) endAndCodepoint;
        sb.append(s, pos, amp).appendCodePoint(codepoint);
        pos = end;
        amp = s.indexOf('&', end);
      }
      sb.append(s, pos, n);
    }

    stripBannedCodeunits(
        sb,
        firstAmp < 0
          ? safeLimit : safeLimit < 0
          ? firstAmp : Math.min(firstAmp, safeLimit));

    return sb.toString();
  }
1066880
function htmlPath(dir) {
  var parts = dir.split('/');
  var crumb = new Array(parts.length);

  for (var i = 0; i < parts.length; i++) {
    var part = parts[i];

    if (part) {
      parts[i] = encodeURIComponent(part);
      crumb[i] = '<a href="' + escapeHtml(parts.slice(0, i + 1).join('/')) + '">' + escapeHtml(part) + '</a>';
    }
  }

  return crumb.join(' / ');
}
117466
private static String linkToHtml( Link l ){
		if( l == null ) {
			return "null";
		}

		StringBuilder result = new StringBuilder();

		result.append("<div class=\"Link\"><b class=\"Link\">Link:</b>" +
				l.getType() + ": \"" +
				convertTags( l.getText() )+ "\" -> \"" + convertTags( l.getTarget() ) +"\"");

		if( l.getParameters().size() != 0 ){
			for( String parameter: l.getParameters() ) {
				result.append("<br>\nPARAMETER: \""+convertTags( parameter )+"\"");
			}
		}

		result.append("</div>\n");

		return result.toString();
	}
1201474
public void encodeHTML(FacesContext context, Button button)
	throws IOException {
		boolean idHasBeenRendered=false;
		if (button.getHref()!=null&&button.getOutcome()!=null) 
			throw new FacesException("Please define the href attribute or the outcome attribute, but not both");
		ResponseWriter rw = context.getResponseWriter();
		String clientId = button.getClientId();
		
		// add responsive style
		String clazz = Responsive.getResponsiveStyleClass(button, false).trim();
		boolean isResponsive = clazz.length() > 0;
		if (isResponsive) {
			rw.startElement("div", button);
			rw.writeAttribute("class", clazz, null);
			rw.writeAttribute("id", clientId, "id");
			idHasBeenRendered = true;
		}


		Object value = (button.getValue() != null ? button.getValue() : "");
		String style = button.getStyle();

		String tag = "button";
		if ((button.getHref() != null) || (button.getTarget() != null)) {
			tag="a";
		}
		rw.startElement(tag, button);
		if (!idHasBeenRendered) {
			rw.writeAttribute("id", clientId, "id");
		}
		rw.writeAttribute("name", clientId, "name");
		if ("button".equals(tag)) {
			rw.writeAttribute("type", "button", null);
		}
		if(BsfUtils.isStringValued(button.getDir())) {
			rw.writeAttribute("dir", button.getDir(), "dir");
		}
		if (style != null) {
			rw.writeAttribute("style", style, "style");
		}
		if (button.getHref() != null)
			rw.writeAttribute("href", button.getHref(), "href");
		if (button.getTarget() != null)
			rw.writeAttribute("target", button.getTarget(), "target");
		rw.writeAttribute("class", getStyleClasses(button, isResponsive), "class");

		Tooltip.generateTooltip(context, button, rw);

		final String clickHandler = encodeClick(context, button);
		if (null != clickHandler && clickHandler.length() > 0) {
			rw.writeAttribute("onclick", clickHandler, null);
		}
		if (BsfUtils.isStringValued(button.getDismiss())) {
			rw.writeAttribute("data-dismiss", button.getDismiss(), null);
		}
		if (button.isDisabled()) {
			rw.writeAttribute("disabled", "disabled", null);
		}

		// Encode attributes (HTML 4 pass-through + DHTML)
		renderPassThruAttributes(context, button, new String[] { "accesskey", "dir", "lang", "style", "tabindex", "title" });
		
		writeAttribute(rw, "onblur", button.getOnblur());
		writeAttribute(rw, "onchange", button.getOnchange());
		writeAttribute(rw, "onclick", button.getOnclick());
		writeAttribute(rw, "ondblclick", button.getOndblclick());
		writeAttribute(rw, "onfocus", button.getOnfocus());
		writeAttribute(rw, "onkeydown", button.getOnkeydown());
		writeAttribute(rw, "onkeypress", button.getOnkeypress());
		writeAttribute(rw, "onkeyup", button.getOnkeyup());
		writeAttribute(rw, "onmousedown", button.getOnmousedown());
		writeAttribute(rw, "onmousemove", button.getOnmousemove());
		writeAttribute(rw, "onmouseout", button.getOnmouseout());
		writeAttribute(rw, "onmouseover", button.getOnmouseover());
		writeAttribute(rw, "onmouseup", button.getOnmouseup());
		
		renderPassThruAttributes(context, button, button.getEventNames().toArray(new String[0]));


		String icon = button.getIcon();
		String faicon = button.getIconAwesome();
		boolean fa = false; // flag to indicate whether the selected icon set is
							// Font Awesome or not.
		if (faicon != null) {
			icon = faicon;
			fa = true;
		}
		if (icon != null) {
			Object ialign = button.getIconAlign(); // Default Left
			if (ialign != null && ialign.equals("right")) {
				rw.writeText(value + " ", null);
				IconRenderer.encodeIcon(rw, button, icon, fa, button.getIconSize(), button.getIconRotate(), button.getIconFlip(), button.isIconSpin(), null, null, false, false, false, false,
						button.isIconBrand(), button.isIconInverse(), button.isIconLight(), button.isIconPulse(), button.isIconRegular(), button.isIconRegular());
			} else {
				IconRenderer.encodeIcon(rw, button, icon, fa, button.getIconSize(), button.getIconRotate(), button.getIconFlip(), button.isIconSpin(), null, null, false, false, false, false,
						button.isIconBrand(), button.isIconInverse(), button.isIconLight(), button.isIconPulse(), button.isIconRegular(), button.isIconRegular());
				rw.writeText(" " + value, null);
			}

		} else {
			rw.writeText(value, null);
		}

		Tooltip.activateTooltips(context, button);
		rw.endElement(tag);
		if (isResponsive) {
			rw.endElement("div");
		}
	}
809190
static String getStatsHTML(Database db, long requiredHeap, ArrayList<Feedback> warnings) {
        StringBuilder sb = new StringBuilder();
        sb.append("<table class='table table-condensed'>\n");

        // count things
        int indexes = 0, views = 0, statements = 0;
        int partitionedTables = 0, replicatedTables = 0;
        int partitionedProcs = 0, replicatedProcs = 0;
        int readProcs = 0, writeProcs = 0;
        for (Table t : db.getTables()) {
            if (t.getMaterializer() != null) {
                views++;
            }
            else {
                if (t.getIsreplicated()) {
                    replicatedTables++;
                }
                else {
                    partitionedTables++;
                }
            }

            indexes += t.getIndexes().size();
        }
        for (Procedure p : db.getProcedures()) {
            // skip auto-generated crud procs
            if (p.getDefaultproc()) {
                continue;
            }

            if (p.getSinglepartition()) {
                partitionedProcs++;
            }
            else {
                replicatedProcs++;
            }

            if (p.getReadonly()) {
                readProcs++;
            }
            else {
                writeProcs++;
            }

            statements += p.getStatements().size();
        }

        // version
        sb.append("<tr><td>Generated by VoltDB Version</td><td>");
        sb.append(VoltDB.instance().getVersionString()).append("</td></tr>\n");

        // timestamp
        sb.append("<tr><td>Last Schema Update on</td><td>");
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
        sb.append(sdf.format(m_timestamp)).append("</td></tr>\n");

        // tables
        sb.append("<tr><td>Table Count</td><td>");
        sb.append(String.format("%d (%d partitioned / %d replicated)",
                partitionedTables + replicatedTables, partitionedTables, replicatedTables));
        sb.append("</td></tr>\n");

        // views
        sb.append("<tr><td>Materialized View Count</td><td>").append(views).append("</td></tr>\n");

        // indexes
        sb.append("<tr><td>Index Count</td><td>").append(indexes).append("</td></tr>\n");

        // procedures
        sb.append("<tr><td>Procedure Count</td><td>");
        sb.append(String.format("%d (%d partitioned / %d replicated) (%d read-only / %d read-write)",
                partitionedProcs + replicatedProcs, partitionedProcs, replicatedProcs,
                readProcs, writeProcs));
        sb.append("</td></tr>\n");

        // statements
        sb.append("<tr><td>SQL Statement Count</td><td>").append(statements).append("</td></tr>\n");

        //heap
        sb.append("<tr><td>Required Java Heap</td><td>").append(requiredHeap).append(" Megabytes").append("</td></tr>\n");

        long megabytes = 1024 * 1024;
        long configuredHeap = Runtime.getRuntime().maxMemory() / megabytes;
        if (configuredHeap > requiredHeap) {
            sb.append("<tr><td>Configured Java Heap</td><td>").append(configuredHeap).append(" Megabytes").append("</td></tr>\n");
        } else {
            sb.append("<tr><td>Configured Java Heap</td><td><font color=\"red\">").append(configuredHeap).append("<font color=\"black\">").append(" Megabytes").append("</td></tr>\n");
        }

        sb.append("</table>\n\n");

        // warnings, add warning section if any
        if (warnings.size() > 0){
            sb.append("<h4>Warnings</h4>");
            sb.append("<table class='table table-condensed'>\n");
            for (Feedback warning : warnings) {
                String procName = warning.getFileName().replace(".class", "");
                String nameLink = "";
                // not a warning during compiling procedures, must from the schema
                if (procName.compareToIgnoreCase("null") == 0) {
                    String schemaName = "";
                    String warningMsg = warning.getMessage().toLowerCase();
                    if (warningMsg.contains("table ")) {
                        int begin = warningMsg.indexOf("table ") + 6;
                        int end = (warningMsg.substring(begin)).indexOf(" ");
                        schemaName = warningMsg.substring(begin, begin + end);
                    }
                    nameLink = "<a href='#s-" + schemaName + "'>" + schemaName.toUpperCase() + "</a>";
                } else {
                    nameLink = "<a href='#p-" + procName.toLowerCase() + "'>" + procName + "</a>";
                }
                sb.append("<tr><td>").append(nameLink).append("</td><td>").append(escapeHtml4(warning.getMessage())).append("</td></tr>\n");
            }
            sb.append("</table>\n").append("</td></tr>\n");
        }

        return sb.toString();
    }
1064561
function convertHTML(editor, node, pos) {
	if (!containsPoint(node.open, pos)) {
		return Promise.reject('Unsupported HTML context for data:URL convertion');
	}

	const srcAttr = getHTMLAttribute(node, 'src');
	if (!srcAttr) {
		return Promise.reject(`No "src" attribute in <${node.name}> tag`);
	}

	const src = srcAttr.value.value;
	const replacementRange = getRange(srcAttr.value);
	const m = src.match(reIsDataURL);

	return m
		? saveAsFile(editor, src.slice(m[0].length), replacementRange)
		: convertToDataUrl(editor, src, replacementRange);
}
1015670
function (str) {
            return str.replace(getUnEscapeReg(), function (m, n) {
                return htmlEntities[m] || String.fromCharCode(+n);
            });
        }
1085149
public String markdownToHtml(String markdownSource, LinkRenderer linkRenderer) {
        return markdownToHtml(markdownSource.toCharArray(), linkRenderer);
    }
767556
function(html) {
       return html.toString()
         .replace(/&/gmi, '&amp;')
         .replace(/"/gmi, '&quot;')
         .replace(/>/gmi, '&gt;')
         .replace(/</gmi, '&lt;')
     }
115608
def to_xml_string(str = '')
      # macro attribute should be optional!
      str << '<xdr:graphicFrame>'
      str << '<xdr:nvGraphicFramePr>'
      str << ('<xdr:cNvPr id="' << @anchor.drawing.index.to_s << '" name="' << 'item_' << @anchor.drawing.index.to_s << '"/>')
      str << '<xdr:cNvGraphicFramePr/>'
      str << '</xdr:nvGraphicFramePr>'
      str << '<xdr:xfrm>'
      str << '<a:off x="0" y="0"/>'
      str << '<a:ext cx="0" cy="0"/>'
      str << '</xdr:xfrm>'
      str << '<a:graphic>'
      str << ('<a:graphicData uri="' << XML_NS_C << '">')
      str << ('<c:chart xmlns:c="' << XML_NS_C << '" xmlns:r="' << XML_NS_R << '" r:id="' << rId << '"/>')
      str << '</a:graphicData>'
      str << '</a:graphic>'
      str << '</xdr:graphicFrame>'
    end
825624
public static StringBuilder encodeHtml(StringBuilder buffer, CharSequence chars) {
		chars.chars().forEach(c -> {
			switch (c) {
			case '<':
				buffer.append("&lt;");
				break;
			case '>':
				buffer.append("&gt;");
				break;
			case '&':
				buffer.append("&amp;");
				break;
			case '"':
				buffer.append("&quot;");
				break;
			case '\'':
				buffer.append("&#39;");
				break;
			default:
				if (Character.isAlphabetic(c)) {
					buffer.append((char) c);
				} else {
					buffer.append("&#").append(c).append(';');
				}
			}
		});
		return buffer;
	}
1261989
private static String toHtmlString(final OptionWithMetaInfo optionWithMetaInfo) {
		ConfigOption<?> option = optionWithMetaInfo.option;
		String defaultValue = stringifyDefault(optionWithMetaInfo);

		return "" +
			"        <tr>\n" +
			"            <td><h5>" + escapeCharacters(option.key()) + "</h5></td>\n" +
			"            <td style=\"word-wrap: break-word;\">" + escapeCharacters(addWordBreakOpportunities(defaultValue)) + "</td>\n" +
			"            <td>" + formatter.format(option.description()) + "</td>\n" +
			"        </tr>\n";
	}