Renders HTML from an RST fragment.

  :param string in_rst: An rst formatted string.
  :param stderr: An open stream to use for docutils stderr output.
  :returns: A tuple of (html rendered rst, return code)
329310
def rst_to_html(in_rst, stderr):
  
  if not in_rst:
    return '', 0

  # Unfortunately, docutils is really setup for command line use.
  # We're forced to patch the bits of sys its hardcoded to use so that we can call it in-process
  # and still reliably determine errors.
  # TODO(John Sirois): Move to a subprocess execution model utilizing a docutil chroot/pex.
  orig_sys_exit = sys.exit
  orig_sys_stderr = sys.stderr
  returncodes = []
  try:
    sys.exit = returncodes.append
    sys.stderr = stderr
    pp = publish_parts(in_rst,
                       writer_name='html',
                       # Report and exit at level 2 (warnings) or higher.
                       settings_overrides=dict(exit_status_level=2, report_level=2),
                       enable_exit_status=True)
  finally:
    sys.exit = orig_sys_exit
    sys.stderr = orig_sys_stderr

  return_value = ''
  if 'title' in pp and pp['title']:
    return_value += '<title>{0}</title>\n<p style="font: 200% bold">{0}</p>\n'.format(pp['title'])
  return_value += pp['body'].strip()
  return return_value, returncodes.pop() if returncodes else 0
517552
def rst(filename):
    '''
    
    '''
    content = open(filename).read()
    return re.sub(r'\.\.\s? code-block::\s*(\w|\+)+', '::', content)
710320
def _render(self, text):
        ''''''
        parser = commonmark.Parser()
        ast = parser.parse(text)
        renderer = HtmlRenderer(self)
        html = renderer.render(ast)
        return html
821481
def _repr_html_(self):
        """"""
        out="<table class='taqltable'>\n"

        # Print column name (not if it is auto-generated)
        if not(self.name()[:4]=="Col_"):
            out+="<tr>"
            out+="<th><b>"+self.name()+"</b></th>"
            out+="</tr>"

        cropped=False
        rowcount=0
        colkeywords=self.getkeywords()
        for row in self:
            out +="\n<tr>"
            out += "<td>" + _format_cell(row, colkeywords) + "</td>\n"
            out += "</tr>\n"
            rowcount+=1
            out+="\n"
            if rowcount>=20:
                cropped=True
                break

        if out[-2:]=="\n\n":
            out=out[:-1]

        out+="</table>"

        if cropped:
            out+="<p style='text-align:center'>("+str(self.nrows()-20)+" more rows)</p>\n"

        return out
1280557
def html(dom: str):
    
    r = _get_report()
    r.append_body(render.html(dom))
    r.stdout_interceptor.write_source('[ADDED] HTML\n')
144643
def _from_docstring_rst(doc):
    

    def format_fn(line, status):
        """ format function """

        if re_from_data.match(line):
            line = re_from_data.sub(r"**\1** ", line)
            status["add_line"] = True
        line = re_from_defaults.sub(r"*\1*", line)
        if status["listing"]:
            # parameters
            if re_from_param.match(line):
                m = re_from_param.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - ``{}`` {}".format(m.group(1), m.group(3))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", line)
            # is continuation line
            else:
                line = " " * 4 + line.lstrip()
        # in .rst format code samples use double backticks vs single ones for
        # .md This converts them.
        line = re_lone_backtick.sub("``", line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
1192142
def htmlCtxtReadDoc(self, cur, URL, encoding, options):
        
        ret = libxml2mod.htmlCtxtReadDoc(self._o, cur, URL, encoding, options)
        if ret is None:raise treeError('htmlCtxtReadDoc() failed')
        __tmp = xmlDoc(_obj=ret)
        return __tmp
305331
def _repr_html_(self, **kwargs):
        """"""
        from jinja2 import Template
        from markdown import markdown as convert_markdown

        extensions = [
            'markdown.extensions.extra',
            'markdown.extensions.admonition'
        ]

        return convert_markdown(self.markdown, extensions)
1362579
def html_to_rst(html):
    
    doc = ReSTDocument()
    doc.include_doc_string(html)
    raw_doc = doc.getvalue()
    return raw_doc.decode('utf-8')
516133
function(str){
    return str.replace(URL_LTR_RTL_RE, function(){
      if(arguments[1]) return arguments[0];
      return arguments[0].substr(0, arguments[0].length - 4)
               + (arguments[2] == 'ltr' ? 'rtl' : 'ltr')
               + arguments[0].slice(-1);
    });
  }
547881
def rst_to_html(input_string: str) -> str:
    

    overrides = dict(input_encoding='unicode', doctitle_xform=True,
                     initial_header_level=1)
    parts = publish_parts(
        writer_name='html',
        source=input_string,
        settings_overrides=overrides
    )
    return parts['html_body']
980810
def _on_process_stderr_ready(self):
        
        try:
            o = self.readAllStandardError()
        except (TypeError, RuntimeError):
            # widget already deleted
            return
        try:
            output = bytes(o).decode(self._encoding)
        except TypeError:
            output = bytes(o.data()).decode(self._encoding)
        for line in output.splitlines():
            self._srv_logger.error(line)
142336
def to_rst(cls) -> str:
        """"""
        sep_line = '+' + 6 * '-' + '+' + '-' * 71 + '+\n'
        blank_line = '|' + 78 * ' ' + '|\n'
        table = ''
        for group in cls.groups:
            table += sep_line
            table += blank_line
            table += '|' + '**{}**'.format(group.name).center(78) + '|\n'
            table += blank_line
            for error in group.errors:
                table += sep_line
                table += ('|' + error.code.center(6) + '| ' +
                          error.short_desc.ljust(70) + '|\n')
        table += sep_line
        return table
960401
def _render_rst(self):  # pragma: no cover
        
        # Create a mapping of headers to annotations.  We want to group
        # all annotations by a header, but they could be in multiple handlers
        # so we create a map of them here with the heading as the key and
        # the list of associated annotations as a list.  This is so we can
        # sort them alphabetically to make reading the api docs easier.
        heading_to_annotations_map = defaultdict(list)
        for heading, route, handler, annotations in (
                self.harness.iter_annotations()):
            # Set the route and handler as attributes so we can retrieve them
            # when we loop through them all below.
            for annotation in annotations:
                annotation.route = route
                annotation.handler = handler
                heading_to_annotations_map[heading].append(annotation)

        headings = list(heading_to_annotations_map.keys())
        headings.sort()
        previous_heading = None
        for heading in headings:
            annotations = heading_to_annotations_map.get(heading)
            # Sort all the annotations by title.
            annotations.sort(key=lambda a: a.title)
            # Only emit a new heading if the resource has changed.  This
            # esnures that documented endpoints for the same resource all
            # end up under a single heading.
            if previous_heading != heading:
                previous_heading = heading
                yield HEADING_TOKEN + heading
            for annotation in annotations:
                route = annotation.route
                normalized_route = normalize_route(route)
                handler = annotation.handler
                # Adds a title for the endpoint.
                if annotation.title is not None:
                    yield annotation.title
                    yield '#' * len(annotation.title)
                docstring = get_description_lines(getattr(annotation.logic,
                                                          '__doc__', None))

                # Documents the logic function associated with the annotation.
                docstring.append(':Logic Func: :func:`~{}.{}`'.format(
                    annotation.logic.__module__, annotation.logic.__name__))

                field = '<json'
                if annotation.http_method in ('DELETE', 'GET'):
                    field = 'query'
                docstring.extend(get_json_lines(
                    annotation, field=field, route=normalized_route,
                    request=True)
                )

                # Document any request headers.
                defined_headers = list(self.harness._get_headers(
                    str(route), annotation).keys())
                defined_headers.sort()
                for header in defined_headers:
                    definition = self.harness.header_definitions.get(
                        header, '').strip()
                    docstring.append(':reqheader {}: {}'.format(
                        header, definition))

                # Document response if a type was defined.
                if annotation.return_annotation != Parameter.empty:
                    docstring.extend(get_json_lines(
                        annotation, field='>json', route=normalized_route))

                docstring.extend(self._make_example(route, handler, annotation))
                for line in http_directive(annotation.http_method,
                                           normalized_route, docstring):
                    yield line

        # Document resource objects.
        for line in get_resource_object_doc_lines():
            yield line
611679
def _repr_html_(self):
        """"""
        fmt = ""
        if self.n_scalars > 0:
            fmt += "<table>"
            fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>"
            fmt += "<tr><td>"
        # Get the header info
        fmt += self.head(display=False, html=True)
        # Fill out scalar arrays
        if self.n_scalars > 0:
            fmt += "</td><td>"
            fmt += "\n"
            fmt += "<table>\n"
            row = "<tr><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th></tr>\n"
            fmt += row.format("Name", "Field", "Type", "Min", "Max")
            row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.3e}</td><td>{:.3e}</td></tr>\n"

            def format_array(key, field):
                """internal helper to foramt array information for printing"""
                arr = get_scalar(self, key)
                dl, dh = self.get_data_range(key)
                if key == self.active_scalar_info[1]:
                    key = '<b>{}</b>'.format(key)
                return row.format(key, field, arr.dtype, dl, dh)

            for i in range(self.GetPointData().GetNumberOfArrays()):
                key = self.GetPointData().GetArrayName(i)
                fmt += format_array(key, field='Points')
            for i in range(self.GetCellData().GetNumberOfArrays()):
                key = self.GetCellData().GetArrayName(i)
                fmt += format_array(key, field='Cells')
            fmt += "</table>\n"
            fmt += "\n"
            fmt += "</td></tr> </table>"
        return fmt
909731
def render(template=None, ostr=None, **kwargs):
    
    jinja_environment.filters['texscape'] = tex_escape
    template = template or DEFAULT_TEMPLATE
    ostr = ostr or sys.stdout
    jinja_template = jinja_environment.get_template(template)
    jinja_template.stream(**kwargs).dump(ostr)
1058172
def gen_rst(results):
    

    # make sure the destination directory exists
    try:
        os.mkdir(DOCPATH)
    except OSError as e:
        if e.args[0] != errno.EEXIST and e.args[0] != errno.EISDIR:
            raise

    toctree = []
    class_ = []
    for output in results:
        section = output.class_.split(',')
        for i in range(len(section)):
            section[i] = section[i].rstrip()
            if section[i] in CLASSMAP:
                section[i] = CLASSMAP[section[i]]
            if i >= len(class_) or section[i] != class_[i]:
                if i == 0:
                    filename = section[i].replace(' ', '_').lower()
                    rst = open(DOCPATH + filename + '.rst', 'w')
                    rst.write(HEADER)
                    rst.write(section[i] + '\n')
                    rst.write(RSTCHARS[0] * len(section[i]))
                    rst.write(time.strftime("\nGenerated %a %d %b %Y %X UTC\n\n", time.gmtime()))
                    toctree.append(filename)
                else:
                    rst.write(section[i] + '\n')
                    rst.write(RSTCHARS[min(i, len(RSTCHARS)-1)] * len(section[i]))
                    rst.write('\n\n')
        class_ = section
        rst.write('.. _cpydiff_%s:\n\n' % output.name.rsplit('.', 1)[0])
        rst.write(output.desc + '\n')
        rst.write('~' * len(output.desc) + '\n\n')
        if output.cause != 'Unknown':
            rst.write('**Cause:** ' + output.cause + '\n\n')
        if output.workaround != 'Unknown':
            rst.write('**Workaround:** ' + output.workaround + '\n\n')

        rst.write('Sample code::\n\n' + indent(output.code, TAB) + '\n')
        output_cpy = indent(''.join(output.output_cpy[0:2]), TAB).rstrip()
        output_cpy = ('::\n\n' if output_cpy != '' else '') + output_cpy
        output_upy = indent(''.join(output.output_upy[0:2]), TAB).rstrip()
        output_upy = ('::\n\n' if output_upy != '' else '') + output_upy
        table = gen_table([['CPy output:', output_cpy], ['uPy output:', output_upy]])
        rst.write(table)

    template = open(INDEXTEMPLATE, 'r')
    index = open(DOCPATH + INDEX, 'w')
    index.write(HEADER)
    index.write(template.read())
    for section in INDEXPRIORITY:
        if section in toctree:
            index.write(indent(section + '.rst', TAB))
            toctree.remove(section)
    for section in toctree:
        index.write(indent(section + '.rst', TAB))