Ejemplo n.º 1
0
    def get_html(self):
        """
        Return the contents of this tag, rendered to html, as an etree element.
        """
        # xss-lint: disable=python-wrap-html
        html = '<section class="targeted-feedback-span"><span>{}</span></section>'.format(
            etree.tostring(self.xml))
        try:
            xhtml = etree.XML(html)

        except Exception as err:  # pylint: disable=broad-except
            if self.system.DEBUG:
                # xss-lint: disable=python-wrap-html
                msg = """
                    <html>
                      <div class="inline-error">
                        <p>Error {err}</p>
                        <p>Failed to construct targeted feedback from <pre>{html}</pre></p>
                      </div>
                    </html>
                """.format(err=cgi_escape(err), html=cgi_escape(html))
                log.error(msg)
                return etree.XML(msg)
            else:
                raise
        return xhtml
 def _clickable_text(self):
     """
     The "clickability" is provided by the enclosing <a> element
     """
     hint = _('Open a new window to start the animation')
     title = _('Sorry, no preview image (yet)!')
     return (u'<span title="' + cgi_escape(title, True) + u'">' +
             cgi_escape(hint) + u'</span>')
Ejemplo n.º 3
0
 def get_html(self):
     """
     Return the contents of this tag, rendered to html, as an etree element.
     """
     html = '<section class="targeted-feedback-span"><span>{}</span></section>'.format(etree.tostring(self.xml))
     try:
         xhtml = etree.XML(html)
     except Exception as err:  # pylint: disable=broad-except
         if self.system.DEBUG:
             msg = """
                 <html>
                   <div class="inline-error">
                     <p>Error {err}</p>
                     <p>Failed to construct targeted feedback from <pre>{html}</pre></p>
                   </div>
                 </html>
             """.format(err=cgi_escape(err), html=cgi_escape(html))
             log.error(msg)
             return etree.XML(msg)
         else:
             raise
     return xhtml
Ejemplo n.º 4
0
def serialize_obsel_table(graph, resource, bindings=None, highlight=None):

    yield '<html><head><style>'
    yield CSS
    yield '</style><script>'
    yield SCRIPT
    yield '</script></head></body>'
    trace_uri = resource.uri.rsplit('/', 1)[0]
    trace_id = trace_uri.rsplit('/', 1)[1]
    yield u'<p><a href="{0}/">Trace {1}</a> (<a href="{0}/@obsels.csv" target="_top" download>download as CSV</a>)</p>' \
        .format(trace_uri, trace_id).encode('utf8')

    rows = iter_csv_rows(resource.trace.uri, graph)
    yield '<pre><table><tr>'
    column_headers = next(rows)
    for col_name in column_headers:
        yield u'<th>{}</th>'.format(col_name).encode('utf8')
    for row in rows:
        row_id = row[0].rsplit('/', 1)[1]
        classes = "highlight" if row[0] == highlight else ""
        yield u'</tr><tr id="{}" class="{}">'.format(row_id,
                                                     classes).encode('utf8')

        for cell in row:
            values = cell.split(' | ')
            htmlvalues = []
            for val in values:
                if HTTP_URI.match(val):
                    short = LAST_PART.search(val).group(1)
                    htmlvalues.append(u'<a href="{0}">{1}</a>'.format(
                        val, short))
                else:
                    htmlvalues.append(cgi_escape(val))

            yield '<td>{}</td>'.format('&nbsp;|&nbsp;'.join(
                i.encode('utf8') for i in htmlvalues))
    yield '</tr></table></pre>'
    yield '</body></html>'
Ejemplo n.º 5
0
def serialize_obsel_table(graph, resource, bindings=None, highlight=None):

    yield '<html><head><style>'
    yield CSS
    yield '</style><script>'
    yield SCRIPT
    yield '</script></head></body>'
    trace_uri = resource.uri.rsplit('/',1)[0]
    trace_id = trace_uri.rsplit('/',1)[1]
    yield u'<p><a href="{0}/">Trace {1}</a> (<a href="{0}/@obsels.csv" target="_top" download>download as CSV</a>)</p>' \
        .format(trace_uri, trace_id).encode('utf8')

    rows = iter_csv_rows(resource.trace.uri, graph)
    yield '<pre><table><tr>'
    column_headers = next(rows)
    for col_name in column_headers:
        yield u'<th>{}</th>'.format(col_name).encode('utf8')
    for row in rows:
        row_id = row[0].rsplit('/', 1)[1]
        classes = "highlight" if row[0] == highlight else ""
        yield u'</tr><tr id="{}" class="{}">'.format(row_id, classes).encode('utf8')

        for cell in row:
            values = cell.split(' | ')
            htmlvalues = []
            for val in values:
                if HTTP_URI.match(val):
                    short = LAST_PART.search(val).group(1)
                    htmlvalues.append(u'<a href="{0}">{1}</a>'.format(val, short))
                else:
                    htmlvalues.append(cgi_escape(val))

            yield '<td>{}</td>'.format(
              '&nbsp;|&nbsp;'.join(i.encode('utf8') for i in htmlvalues)
            )
    yield '</tr></table></pre>'
    yield '</body></html>'
Ejemplo n.º 6
0
 def _escape(text):
     """
     cgi escape tool
     """
     return cgi_escape(text, quote=True)
Ejemplo n.º 7
0
def escape(data):
    return cgi_escape(unicode(data))
Ejemplo n.º 8
0
def content_preview(eval_ctx, story, char_limit=400, text_only=False, escape=True):
    """
    Public: a filter that generates a content preview for a Story. Uses the
            description of the Story, if it has one, or the text content.

    story         - the Story to preview
    char_limit    - (optional:400) the int number of characters to show
    text_only     - (optional:False) a Boolean flag indicating that the result
                    should not be wrapped in spans
    escape        - (optional:True) escape HTML entities in the text_only
                    content output

    Examples

        {{ story|content_preview }}

        {{ story|content_preview(char_limit=200) }}

        {{ story|content_preview(text_only=True) }}

    Returns a str of HTML up to `char_limit` content characters long (count
    doesn't include markup).
    """
    # Default to an empty string since this is for a template.
    content_preview = u''
    generate_preview = True

    if hasattr(story, 'description'):
        if story.description == '' or story.description is None:
            generate_preview = True
        else:
            generate_preview = False
            content_preview = story.description[:char_limit]
            if len(story.description) > char_limit:
                if text_only:
                    content_preview += u'…'
                else:
                    content_preview += '&hellip;'

    if generate_preview:
        content_preview_text_length = 0

        for block in story.content:

            # Only include Text blocks that aren't pre-formatted.
            if block and block.type == Text.type and block.role != 'pre':
                content = block.content.lstrip().rstrip()
                if content:

                    # If this iteration of content will put the total over the
                    # limit, truncate it.
                    if content_preview_text_length + len(content) > char_limit:
                        content = content[:char_limit - content_preview_text_length]

                    # Keep track of the preview length.
                    content_preview_text_length += len(content)

                    if escape:
                        # Escape after, so character count doesn't include markup.
                        content = cgi_escape(content, quote=True)

                    # Wrap the iteration's snippet in a tag that indicates the
                    # role, to allow for styling.
                    if text_only:
                        content_preview += u"{0} ".format(content)
                    else:
                        content_preview += u" <span data-role='{0}'>{1}</span>".format(block.role, content)

                    # Add an ellipsis to the content to append if over the limit.
                    if content_preview_text_length >= char_limit:
                        if text_only and not escape:
                            content_preview += u'…'
                        else:
                            content_preview += '&hellip;'

                    if content_preview_text_length >= char_limit:
                        break

    if eval_ctx.autoescape:
        content_preview = Markup(content_preview)

    return content_preview
Ejemplo n.º 9
0
 def sanitize(self, str):
     return cgi_escape(str)
Ejemplo n.º 10
0
def _escape(s):
  return cgi_escape(urlquote(smart_str(s)), True)
Ejemplo n.º 11
0
At the moment this only activates the improved progress bar.

Use ``%load_ext nengo.ipynb`` in a Jupyter notebook to load the extension.

Note
----

This IPython extension cannot be unloaded.
"""

try:
    from html import escape
except ImportError:
    from cgi import escape as cgi_escape
    escape = lambda s, quote=True: cgi_escape(s, quote=quote)
import warnings

import IPython

from nengo.rc import rc
from nengo.utils.ipython import has_ipynb_widgets
from nengo.utils.progress import ProgressBar, timestamp2timedelta

if has_ipynb_widgets():
    if IPython.version_info[0] <= 3:
        from IPython.html.widgets import DOMWidget
        import IPython.utils.traitlets as traitlets
    else:
        import ipywidgets
        from ipywidgets import DOMWidget
Ejemplo n.º 12
0
def escape(s):
    from cgi import escape as cgi_escape
    return cgi_escape(s).replace('"', '&quot;');
Ejemplo n.º 13
0
 def html_escape(*args,**kwargs):
     # make the defaults match the py3 defaults
     kwargs['quote'] = kwargs.get('quote', True)
     return cgi_escape(*args,**kwargs)
Ejemplo n.º 14
0
#!/usr/bin/env python
from __future__ import print_function
import sys
import time
import calendar
import json
import fnmatch

if sys.version_info[0] > 2:
    from urllib.parse import urlencode
    from urllib.request import urlopen
    from html import escape
else:
    from urllib import urlencode, urlopen
    from cgi import escape as cgi_escape
    escape = lambda string: cgi_escape(string, quote=True)

from .messages import MESSAGES

#import logging
#logger = logging.getLogger(__name__)
    

def to_trello_date(timestamp):
    """
    Take a timestamp (number of seconds since the epoch) and turn it into a
    string in Trello's date format.
    """
    return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(timestamp))

Ejemplo n.º 15
0
def content_preview(eval_ctx,
                    story,
                    char_limit=400,
                    text_only=False,
                    escape=True):
    """
    Public: a filter that generates a content preview for a Story. Uses the
            description of the Story, if it has one, or the text content.

    story         - the Story to preview
    char_limit    - (optional:400) the int number of characters to show
    text_only     - (optional:False) a Boolean flag indicating that the result
                    should not be wrapped in spans
    escape        - (optional:True) escape HTML entities in the text_only
                    content output

    Examples

        {{ story|content_preview }}

        {{ story|content_preview(char_limit=200) }}

        {{ story|content_preview(text_only=True) }}

    Returns a str of HTML up to `char_limit` content characters long (count
    doesn't include markup).
    """
    # Default to an empty string since this is for a template.
    content_preview = u''
    generate_preview = True

    if hasattr(story, 'description'):
        if story.description == '' or story.description is None:
            generate_preview = True
        else:
            generate_preview = False
            content_preview = story.description[:char_limit]
            if len(story.description) > char_limit:
                if text_only:
                    content_preview += u'…'
                else:
                    content_preview += '&hellip;'

    if generate_preview:
        content_preview_text_length = 0

        for block in story.content:

            # Only include Text blocks that aren't pre-formatted.
            if block and block.type == Text.type and block.role != 'pre':
                content = block.content.lstrip().rstrip()
                if content:

                    # If this iteration of content will put the total over the
                    # limit, truncate it.
                    if content_preview_text_length + len(content) > char_limit:
                        content = content[:char_limit -
                                          content_preview_text_length]

                    # Keep track of the preview length.
                    content_preview_text_length += len(content)

                    if escape:
                        # Escape after, so character count doesn't include markup.
                        content = cgi_escape(content, quote=True)

                    # Wrap the iteration's snippet in a tag that indicates the
                    # role, to allow for styling.
                    if text_only:
                        content_preview += u"{0} ".format(content)
                    else:
                        content_preview += u" <span data-role='{0}'>{1}</span>".format(
                            block.role, content)

                    # Add an ellipsis to the content to append if over the limit.
                    if content_preview_text_length >= char_limit:
                        if text_only and not escape:
                            content_preview += u'…'
                        else:
                            content_preview += '&hellip;'

                    if content_preview_text_length >= char_limit:
                        break

    if eval_ctx.autoescape:
        content_preview = Markup(content_preview)

    return content_preview
Ejemplo n.º 16
0
 def _strip_irc_codes(self, message):
     return cgi_escape(re.sub(IRC_CODES_RE, '', message))
Ejemplo n.º 17
0
def escape(x, encoding=api_encoding):
    """Escape string for HTML."""

    return cgi_escape(unicode(x)).encode(encoding, "xmlcharrefreplace")
Ejemplo n.º 18
0
def html_quote(s):
    """HTML quotes the string"""
    s = str(s)
    return cgi_escape(s, True)
Ejemplo n.º 19
0
At the moment this only activates the improved progress bar.

Use ``%load_ext nengo.ipynb`` in an IPython notebook to load the extension.

Note
----

This IPython extension cannot be unloaded.
"""

try:
    from html import escape
except ImportError:
    from cgi import escape as cgi_escape
    escape = lambda s, quote=True: cgi_escape(s, quote=quote)
import warnings

import IPython

from nengo.rc import rc
from nengo.utils.ipython import has_ipynb_widgets
from nengo.utils.progress import ProgressBar, timestamp2timedelta

if has_ipynb_widgets():
    if IPython.version_info[0] <= 3:
        from IPython.html.widgets import DOMWidget
        import IPython.utils.traitlets as traitlets
    else:
        import ipywidgets
        from ipywidgets import DOMWidget
Ejemplo n.º 20
0
def escape(data):
    return cgi_escape(unicode(data))
Ejemplo n.º 21
0
def escape(s):
    from cgi import escape as cgi_escape
    return cgi_escape(s).replace('"', '&quot;');
Ejemplo n.º 22
0
def html_quote(s):
    """HTML quotes the string"""
    s = unicode(s)
    return cgi_escape(s, True)