Use the `pygments` library to create a highlighted HTML
        representation of the code snippet.
970677
def save(self, *args, **kwargs):
        
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(style=self.style, linenos=linenos,
                                  full=True, **options)
        self.highlighted = highlight(self.code, lexer, formatter)
        super(Snippet, self).save(*args, **kwargs)

        # limit the number of instances retained
        snippets = Snippet.objects.all()
        if len(snippets) > 100:
            snippets[0].delete()
1016369
function highlight(code) {
  return new Promise((resolve, reject) => {
    pygmentize({ lang: 'html', format: 'html' }, code, function (err, result) {
      if (err) {
        console.log(err);
        reject(err);
      } else {
        resolve(result.toString());
      };
    });
  });
}
491300
def wrap_traceback(traceback):
    
    if email().format == 'html':
        try:
            from pygments import highlight
            from pygments.lexers import PythonTracebackLexer
            from pygments.formatters import HtmlFormatter
            with_pygments = True
        except ImportError:
            with_pygments = False

        if with_pygments:
            formatter = HtmlFormatter(noclasses=True)
            wrapped = highlight(traceback, PythonTracebackLexer(), formatter)
        else:
            wrapped = '<pre>%s</pre>' % traceback
    else:
        wrapped = traceback

    return wrapped
408243
def colored_pygments_excepthook(type_, value, tb):
    
    tbtext = ''.join(traceback.format_exception(type_, value, tb))
    try:
        from utool import util_str
        formatted_text = util_str.highlight_text(tbtext, lexer_name='pytb',
                                                 stripall=True)
    except Exception:
        # FIXME silent errro
        formatted_text = tbtext
        return sys.__excepthook__(type_, value, tb)
        #import utool as ut
        #if ut.SUPER_STRICT:
        #    raise
    sys.stderr.write(formatted_text)
96015
def stylify_code(code):
    """"""
    try:
        output = check_output(
            ['astyle', '--max-code-length=69', '--indent=spaces=2'],
            universal_newlines=True, input=code
        )
    except (OSError, CalledProcessError, TypeError):
        logging.debug(_('failed to stylify code'))
        return code
    return output
598659
function buildHTMLForSegment(segment) {
		var html = '';
		var isRTL = opt('isRTL');
		var event = segment.event;
		var url = event.url;

		// generate the list of CSS classNames
		var classNames = [ 'fc-event', 'fc-event-hori' ];
		if (isEventDraggable(event)) {
			classNames.push('fc-event-draggable');
		}
		if (segment.isStart) {
			classNames.push('fc-event-start');
		}
		if (segment.isEnd) {
			classNames.push('fc-event-end');
		}
		// use the event's configured classNames
		// guaranteed to be an array via `normalizeEvent`
		classNames = classNames.concat(event.className);
		if (event.source) {
			// use the event's source's classNames, if specified
			classNames = classNames.concat(event.source.className || []);
		}

		// generate a semicolon delimited CSS string for any of the "skin" properties
		// of the event object (`backgroundColor`, `borderColor` and such)
		var skinCss = getSkinCss(event, opt);

		if (url) {
			html += "<a href='" + htmlEscape(url) + "'";
		}else{
			html += "<div";
		}
		html +=
			" class='" + classNames.join(' ') + "'" +
			" style=" +
				"'" +
				"position:absolute;" +
				"left:" + segment.left + "px;" +
				skinCss +
				"'" +
			">" +
			"<div class='fc-event-inner'>";
		if (!event.allDay && segment.isStart) {
			html +=
				"<span class='fc-event-time'>" +
				htmlEscape(
					formatDates(event.start, event.end, opt('timeFormat'))
				) +
				"</span>";
		}
		html +=
			"<span class='fc-event-title'>" +
			htmlEscape(event.title || '') +
			"</span>" +
			"</div>";
		if (segment.isEnd && isEventResizable(event)) {
			html +=
				"<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" +
				"&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7
				"</div>";
		}
		html += "</" + (url ? "a" : "div") + ">";

		// TODO:
		// When these elements are initially rendered, they will be briefly visibile on the screen,
		// even though their widths/heights are not set.
		// SOLUTION: initially set them as visibility:hidden ?

		return html;
	}
607278
def create_highlights(data, tfidf):
    '''

    '''
    try:
        fc = etl.create_fc_from_html(
            data['content-location'], data['body'], tfidf=tfidf, encoding=None)
    except Exception, exc:
        logger.critical('failed to build FC', exc_info=True)
        return {
            'state': ERROR,
            'error': {'code': 7,
                      'message': 'internal error: %s' % traceback.format_exc(exc),
                      }
        }
    if fc is None:
        logger.critical('failed to get FC using %d bytes from %r',
                        len(body), data['content-location'])
        response.status = 500
        return {
            'state': ERROR,
            'error': {
                'code': 7,
                'message': 'internal error: FC not generated for that content',
            },
        }
    try:
        highlights = dict()
        for feature_name, pretty_name in feature_pretty_names:
            # Each type of string is
            if feature_name not in fc:
                continue
            total = sum(fc[feature_name].values())
            bow = sorted(fc[feature_name].items(), key=itemgetter(1), reverse=True)
            highlights[pretty_name] = [(phrase, count / total)
                                       for phrase, count in bow]
            logger.info('%r and %d keys',
                        feature_name, len(highlights[pretty_name]))

        highlight_objs = build_highlight_objects(data['body'], highlights)
    except Exception, exc:
        logger.critical('failed to build highlights', exc_info=True)
        return {
            'state': ERROR,
            'error': {'code': 7,
                      'message': 'internal error: %s' % traceback.format_exc(exc),
                      }
        }

    payload = {
        'highlights': highlight_objs,
        'state': COMPLETED,
    }
    return payload
90946
def markdown(text)
      renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: false, with_toc_data: false)
      options = {
        autolink: true,
        no_intra_emphasis: true,
        fenced_code_blocks: true,
        lax_html_blocks: true,
        tables: true,
        strikethrough: true,
        superscript: true,
        xhtml: true
      }
      Redcarpet::Markdown.new(renderer, options).render(text).html_safe
    end
435069
def _highlight(string, color):
	''''''
	if CONFIG['color']:
		if color < 8:
			return '\033[{color}m{string}\033[0m'.format(string = string, color = color+30)
		else:
			return '\033[{color}m{string}\033[0m'.format(string = string, color = color+82)
	else:
		return string
138992
def load_snippets_html(cls, src_path, violation_lines):
        
        snippet_list = cls.load_snippets(src_path, violation_lines)
        return [snippet.html() for snippet in snippet_list]
1042483
function _createHighLighter() {
			var highLighter = document.createElement("div");

			highLighter.style.cssText = "box-sizing: border-box;border:1px solid blue;background: rgba(20, 20, 200, 0.4);position: absolute";

			var highLighterWrapper = document.createElement("div");

			highLighterWrapper.id = "ui5-highlighter";
			highLighterWrapper.style.cssText = "position: fixed;top:0;right:0;bottom:0;left:0;z-index: 1000;overflow: hidden;";
			highLighterWrapper.appendChild(highLighter);

			document.body.appendChild(highLighterWrapper);

			// Save reference for later usage
			_highLighter = document.getElementById("ui5-highlighter");

			// Add event handler
			_highLighter.onmouseover = _hideHighLighter;
		}
988159
def latexsnippet(code, kvs, staffsize=17, initiallines=1):
    """"""
    snippet = ''
    staffsize = int(kvs['staffsize']) if 'staffsize' in kvs \
        else staffsize
    initiallines = int(kvs['initiallines']) if 'initiallines' in kvs \
        else initiallines
    annotationsize = .5 * staffsize
    if 'mode' in kvs:
        snippet = (
            "\\greannotation{{\\fontsize{%s}{%s}\\selectfont{}%s}}\n" %
            (annotationsize, annotationsize, kvs['mode'])
        ) + snippet
    if 'annotation' in kvs:
        snippet = (
            "\\grechangedim{annotationseparation}{%s mm}{fixed}\n"
            "\\greannotation{{\\fontsize{%s}{%s}\\selectfont{}%s}}\n" %
            (staffsize / 60, annotationsize, annotationsize, kvs['annotation'])
        ) + snippet
    snippet = (
        "\\gresetinitiallines{%s}\n" % initiallines +
        "\\grechangestaffsize{%s}\n" % staffsize +
        "\\grechangestyle{initial}{\\fontsize{%s}{%s}\\selectfont{}}" %
        (2.5 * staffsize, 2.5 * staffsize)
    ) + snippet
    snippet = "\\setlength{\\parskip}{0pt}\n" + snippet + code
    return snippet
350361
function(lineIndex, lineNumber, lineHtml)
  {
    var classes = [
      'line',
      'number' + lineNumber,
      'index' + lineIndex,
      'alt' + (lineNumber % 2 == 0 ? 1 : 2).toString()
    ];

    if (this.linesToHighlight[lineNumber])
      classes.push('highlighted');

    if (lineNumber == 0)
      classes.push('break');

    return '<div class="' + classes.join(' ') + '">' + lineHtml + '</div>';
  }
255186
def _highlight_line_difflib(self, line, next):
        

        if line['action'] == 'del':
            old, new = line, next
        else:
            old, new = next, line

        oldwords = re.split(r'(\W)', old['line'])
        newwords = re.split(r'(\W)', new['line'])

        sequence = difflib.SequenceMatcher(None, oldwords, newwords)

        oldfragments, newfragments = [], []
        for tag, i1, i2, j1, j2 in sequence.get_opcodes():
            oldfrag = ''.join(oldwords[i1:i2])
            newfrag = ''.join(newwords[j1:j2])
            if tag != 'equal':
                if oldfrag:
                    oldfrag = '<del>%s</del>' % oldfrag
                if newfrag:
                    newfrag = '<ins>%s</ins>' % newfrag
            oldfragments.append(oldfrag)
            newfragments.append(newfrag)

        old['line'] = "".join(oldfragments)
        new['line'] = "".join(newfragments)
528745
function highlightPostSyntax( post ) {

	var codeTags = [],
			i = 0,
			len = 0;

	doc = doc || createDom( post.content );
	
	codeTags = doc.querySelectorAll('pre code');

	len = codeTags.length;

	for ( ; i < len; i++ ) {

		// Replace class names beginning with "lang-" with "language-" for Highlight.js
		codeTags[i].className = codeTags[i].className.replace('lang-', 'language-');

		hljs.highlightBlock( codeTags[i] );
	}

	post.content = doc.body.innerHTML;
}
765772
def highlight_text(text, lexer_name='python', **kwargs):
    
    """
    # Resolve extensions to languages
    lexer_name = {
        'py': 'python',
        'h': 'cpp',
        'cpp': 'cpp',
        'c': 'cpp',
    }.get(lexer_name.replace('.', ''), lexer_name)
    if lexer_name in ['red', 'yellow', 'blue', 'green']:
        # hack for coloring
        return color_text(text, lexer_name)
    import utool as ut
    if ENABLE_COLORS:
        try:
            import pygments
            import pygments.lexers
            import pygments.formatters
            #from pygments import highlight
            #from pygments.lexers import get_lexer_by_name
            #from pygments.formatters import TerminalFormatter
            #if ut.WIN32:
            #    assert False
            #    #formater = pygments.formatters.terminal256.Terminal256Formatter()
            #    import pygments.formatters.terminal256
            #    formater = pygments.formatters.terminal256.Terminal256Formatter()
            #else:
            import pygments.formatters.terminal
            formater = pygments.formatters.terminal.TerminalFormatter(bg='dark')
            lexer = pygments.lexers.get_lexer_by_name(lexer_name, **kwargs)
            return pygments.highlight(text, lexer, formater)
        except Exception:
            if ut.SUPER_STRICT:
                raise
            return text
    return text
176389
def pygments_required(func):
    """"""
    def wrapper(*args, **kwargs):
        if not HAS_PYGMENTS:  # pragma: no cover
            raise ImportError(
                "Please install 'pygments' library to use syntax_color.")
        rv = func(*args, **kwargs)
        return rv
    return wrapper