How to use escape method in wpt

Best JavaScript code snippet using wpt

sre_parse.py

Source:sre_parse.py Github

copy

Full Screen

...271 self.index = index272 self.__next()273 def error(self, msg, offset=0):274 return error(msg, self.string, self.tell() - offset)275def _class_escape(source, escape):276 # handle escape code inside character class277 code = ESCAPES.get(escape)278 if code:279 return code280 code = CATEGORIES.get(escape)281 if code and code[0] is IN:282 return code283 try:284 c = escape[1:2]285 if c == "x":286 # hexadecimal escape (exactly two digits)287 escape += source.getwhile(2, HEXDIGITS)288 if len(escape) != 4:289 raise source.error("incomplete escape %s" % escape, len(escape))290 return LITERAL, int(escape[2:], 16)291 elif c == "u" and source.istext:292 # unicode escape (exactly four digits)293 escape += source.getwhile(4, HEXDIGITS)294 if len(escape) != 6:295 raise source.error("incomplete escape %s" % escape, len(escape))296 return LITERAL, int(escape[2:], 16)297 elif c == "U" and source.istext:298 # unicode escape (exactly eight digits)299 escape += source.getwhile(8, HEXDIGITS)300 if len(escape) != 10:301 raise source.error("incomplete escape %s" % escape, len(escape))302 c = int(escape[2:], 16)303 chr(c) # raise ValueError for invalid code304 return LITERAL, c305 elif c in OCTDIGITS:306 # octal escape (up to three digits)307 escape += source.getwhile(2, OCTDIGITS)308 c = int(escape[1:], 8)309 if c > 0o377:310 raise source.error('octal escape value %s outside of '311 'range 0-0o377' % escape, len(escape))312 return LITERAL, c313 elif c in DIGITS:314 raise ValueError315 if len(escape) == 2:316 if c in ASCIILETTERS:317 raise source.error('bad escape %s' % escape, len(escape))318 return LITERAL, ord(escape[1])319 except ValueError:320 pass321 raise source.error("bad escape %s" % escape, len(escape))322def _escape(source, escape, state):323 # handle escape code in expression324 code = CATEGORIES.get(escape)325 if code:326 return code327 code = ESCAPES.get(escape)328 if code:329 return code330 try:331 c = escape[1:2]332 if c == "x":333 # hexadecimal escape334 escape += source.getwhile(2, HEXDIGITS)335 if len(escape) != 4:336 raise source.error("incomplete escape %s" % escape, len(escape))337 return LITERAL, int(escape[2:], 16)338 elif c == "u" and source.istext:339 # unicode escape (exactly four digits)340 escape += source.getwhile(4, HEXDIGITS)341 if len(escape) != 6:342 raise source.error("incomplete escape %s" % escape, len(escape))343 return LITERAL, int(escape[2:], 16)344 elif c == "U" and source.istext:345 # unicode escape (exactly eight digits)346 escape += source.getwhile(8, HEXDIGITS)347 if len(escape) != 10:348 raise source.error("incomplete escape %s" % escape, len(escape))349 c = int(escape[2:], 16)350 chr(c) # raise ValueError for invalid code351 return LITERAL, c352 elif c == "0":353 # octal escape354 escape += source.getwhile(2, OCTDIGITS)355 return LITERAL, int(escape[1:], 8)356 elif c in DIGITS:357 # octal escape *or* decimal group reference (sigh)358 if source.next in DIGITS:359 escape += source.get()360 if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and361 source.next in OCTDIGITS):362 # got three octal digits; this is an octal escape363 escape += source.get()364 c = int(escape[1:], 8)365 if c > 0o377:366 raise source.error('octal escape value %s outside of '367 'range 0-0o377' % escape,368 len(escape))369 return LITERAL, c370 # not an octal escape, so this is a group reference371 group = int(escape[1:])372 if group < state.groups:373 if not state.checkgroup(group):374 raise source.error("cannot refer to an open group",375 len(escape))376 state.checklookbehindgroup(group, source)377 return GROUPREF, group378 raise source.error("invalid group reference %d" % group, len(escape) - 1)379 if len(escape) == 2:380 if c in ASCIILETTERS:381 raise source.error("bad escape %s" % escape, len(escape))382 return LITERAL, ord(escape[1])383 except ValueError:384 pass385 raise source.error("bad escape %s" % escape, len(escape))386def _parse_sub(source, state, verbose, nested):387 # parse an alternation: a|b|c388 items = []389 itemsappend = items.append390 sourcematch = source.match391 start = source.tell()392 while True:393 itemsappend(_parse(source, state, verbose, nested + 1,394 not nested and not items))395 if not sourcematch("|"):396 break397 if len(items) == 1:398 return items[0]399 subpattern = SubPattern(state)400 subpatternappend = subpattern.append401 # check if all items share a common prefix402 while True:403 prefix = None404 for item in items:405 if not item:406 break407 if prefix is None:408 prefix = item[0]409 elif item[0] != prefix:410 break411 else:412 # all subitems start with a common "prefix".413 # move it out of the branch414 for item in items:415 del item[0]416 subpatternappend(prefix)417 continue # check next one418 break419 # check if the branch can be replaced by a character set420 for item in items:421 if len(item) != 1 or item[0][0] is not LITERAL:422 break423 else:424 # we can store this as a character set instead of a425 # branch (the compiler may optimize this even more)426 subpatternappend((IN, [item[0] for item in items]))427 return subpattern428 subpattern.append((BRANCH, (None, items)))429 return subpattern430def _parse_sub_cond(source, state, condgroup, verbose, nested):431 item_yes = _parse(source, state, verbose, nested + 1)432 if source.match("|"):433 item_no = _parse(source, state, verbose, nested + 1)434 if source.next == "|":435 raise source.error("conditional backref with more than two branches")436 else:437 item_no = None438 subpattern = SubPattern(state)439 subpattern.append((GROUPREF_EXISTS, (condgroup, item_yes, item_no)))440 return subpattern441def _parse(source, state, verbose, nested, first=False):442 # parse a simple pattern443 subpattern = SubPattern(state)444 # precompute constants into local variables445 subpatternappend = subpattern.append446 sourceget = source.get447 sourcematch = source.match448 _len = len449 _ord = ord450 while True:451 this = source.next452 if this is None:453 break # end of pattern454 if this in "|)":455 break # end of subpattern456 sourceget()457 if verbose:458 # skip whitespace and comments459 if this in WHITESPACE:460 continue461 if this == "#":462 while True:463 this = sourceget()464 if this is None or this == "\n":465 break466 continue467 if this[0] == "\\":468 code = _escape(source, this, state)469 subpatternappend(code)470 elif this not in SPECIAL_CHARS:471 subpatternappend((LITERAL, _ord(this)))472 elif this == "[":473 here = source.tell() - 1474 # character set475 set = []476 setappend = set.append477## if sourcematch(":"):478## pass # handle character classes479 if sourcematch("^"):480 setappend((NEGATE, None))481 # check remaining characters482 start = set[:]483 while True:484 this = sourceget()485 if this is None:486 raise source.error("unterminated character set",487 source.tell() - here)488 if this == "]" and set != start:489 break490 elif this[0] == "\\":491 code1 = _class_escape(source, this)492 else:493 code1 = LITERAL, _ord(this)494 if sourcematch("-"):495 # potential range496 that = sourceget()497 if that is None:498 raise source.error("unterminated character set",499 source.tell() - here)500 if that == "]":501 if code1[0] is IN:502 code1 = code1[1][0]503 setappend(code1)504 setappend((LITERAL, _ord("-")))505 break506 if that[0] == "\\":507 code2 = _class_escape(source, that)508 else:509 code2 = LITERAL, _ord(that)510 if code1[0] != LITERAL or code2[0] != LITERAL:511 msg = "bad character range %s-%s" % (this, that)512 raise source.error(msg, len(this) + 1 + len(that))513 lo = code1[1]514 hi = code2[1]515 if hi < lo:516 msg = "bad character range %s-%s" % (this, that)517 raise source.error(msg, len(this) + 1 + len(that))518 setappend((RANGE, (lo, hi)))519 else:520 if code1[0] is IN:521 code1 = code1[1][0]...

Full Screen

Full Screen

converters.py

Source:converters.py Github

copy

Full Screen

1from ._compat import PY2, text_type, long_type, JYTHON, IRONPYTHON, unichr2import datetime3from decimal import Decimal4import re5import time6from .constants import FIELD_TYPE, FLAG7from .charset import charset_by_id, charset_to_encoding8def escape_item(val, charset, mapping=None):9 if mapping is None:10 mapping = encoders11 encoder = mapping.get(type(val))12 # Fallback to default when no encoder found13 if not encoder:14 try:15 encoder = mapping[text_type]16 except KeyError:17 raise TypeError("no default type converter defined")18 if encoder in (escape_dict, escape_sequence):19 val = encoder(val, charset, mapping)20 else:21 val = encoder(val, mapping)22 return val23def escape_dict(val, charset, mapping=None):24 n = {}25 for k, v in val.items():26 quoted = escape_item(v, charset, mapping)27 n[k] = quoted28 return n29def escape_sequence(val, charset, mapping=None):30 n = []31 for item in val:32 quoted = escape_item(item, charset, mapping)33 n.append(quoted)34 return "(" + ",".join(n) + ")"35def escape_set(val, charset, mapping=None):36 return ','.join([escape_item(x, charset, mapping) for x in val])37def escape_bool(value, mapping=None):38 return str(int(value))39def escape_object(value, mapping=None):40 return str(value)41def escape_int(value, mapping=None):42 return str(value)43def escape_float(value, mapping=None):44 return ('%.15g' % value)45_escape_table = [unichr(x) for x in range(128)]46_escape_table[0] = u'\\0'47_escape_table[ord('\\')] = u'\\\\'48_escape_table[ord('\n')] = u'\\n'49_escape_table[ord('\r')] = u'\\r'50_escape_table[ord('\032')] = u'\\Z'51_escape_table[ord('"')] = u'\\"'52_escape_table[ord("'")] = u"\\'"53def _escape_unicode(value, mapping=None):54 """escapes *value* without adding quote.55 Value should be unicode56 """57 return value.translate(_escape_table)58if PY2:59 def escape_string(value, mapping=None):60 """escape_string escapes *value* but not surround it with quotes.61 Value should be bytes or unicode.62 """63 if isinstance(value, unicode):64 return _escape_unicode(value)65 assert isinstance(value, (bytes, bytearray))66 value = value.replace('\\', '\\\\')67 value = value.replace('\0', '\\0')68 value = value.replace('\n', '\\n')69 value = value.replace('\r', '\\r')70 value = value.replace('\032', '\\Z')71 value = value.replace("'", "\\'")72 value = value.replace('"', '\\"')73 return value74 def escape_bytes(value, mapping=None):75 assert isinstance(value, (bytes, bytearray))76 return b"_binary'%s'" % escape_string(value)77else:78 escape_string = _escape_unicode79 # On Python ~3.5, str.decode('ascii', 'surrogateescape') is slow.80 # (fixed in Python 3.6, http://bugs.python.org/issue24870)81 # Workaround is str.decode('latin1') then translate 0x80-0xff into 0udc80-0udcff.82 # We can escape special chars and surrogateescape at once.83 _escape_bytes_table = _escape_table + [chr(i) for i in range(0xdc80, 0xdd00)]84 def escape_bytes(value, mapping=None):85 return "_binary'%s'" % value.decode('latin1').translate(_escape_bytes_table)86def escape_unicode(value, mapping=None):87 return u"'%s'" % _escape_unicode(value)88def escape_str(value, mapping=None):89 return "'%s'" % escape_string(str(value), mapping)90def escape_None(value, mapping=None):91 return 'NULL'92def escape_timedelta(obj, mapping=None):93 seconds = int(obj.seconds) % 6094 minutes = int(obj.seconds // 60) % 6095 hours = int(obj.seconds // 3600) % 24 + int(obj.days) * 2496 if obj.microseconds:97 fmt = "'{0:02d}:{1:02d}:{2:02d}.{3:06d}'"98 else:99 fmt = "'{0:02d}:{1:02d}:{2:02d}'"100 return fmt.format(hours, minutes, seconds, obj.microseconds)101def escape_time(obj, mapping=None):102 if obj.microsecond:103 fmt = "'{0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}'"104 else:105 fmt = "'{0.hour:02}:{0.minute:02}:{0.second:02}'"106 return fmt.format(obj)107def escape_datetime(obj, mapping=None):108 if obj.microsecond:109 fmt = "'{0.year:04}-{0.month:02}-{0.day:02} {0.hour:02}:{0.minute:02}:{0.second:02}.{0.microsecond:06}'"110 else:111 fmt = "'{0.year:04}-{0.month:02}-{0.day:02} {0.hour:02}:{0.minute:02}:{0.second:02}'"112 return fmt.format(obj)113def escape_date(obj, mapping=None):114 fmt = "'{0.year:04}-{0.month:02}-{0.day:02}'"115 return fmt.format(obj)116def escape_struct_time(obj, mapping=None):117 return escape_datetime(datetime.datetime(*obj[:6]))118def _convert_second_fraction(s):119 if not s:120 return 0121 # Pad zeros to ensure the fraction length in microseconds122 s = s.ljust(6, '0')123 return int(s[:6])124DATETIME_RE = re.compile(r"(\d{1,4})-(\d{1,2})-(\d{1,2})[T ](\d{1,2}):(\d{1,2}):(\d{1,2})(?:.(\d{1,6}))?")125def convert_datetime(obj):126 """Returns a DATETIME or TIMESTAMP column value as a datetime object:127 >>> datetime_or_None('2007-02-25 23:06:20')128 datetime.datetime(2007, 2, 25, 23, 6, 20)129 >>> datetime_or_None('2007-02-25T23:06:20')130 datetime.datetime(2007, 2, 25, 23, 6, 20)131 Illegal values are returned as None:132 >>> datetime_or_None('2007-02-31T23:06:20') is None133 True134 >>> datetime_or_None('0000-00-00 00:00:00') is None135 True136 """137 if not PY2 and isinstance(obj, (bytes, bytearray)):138 obj = obj.decode('ascii')139 m = DATETIME_RE.match(obj)140 if not m:141 return convert_date(obj)142 try:143 groups = list(m.groups())144 groups[-1] = _convert_second_fraction(groups[-1])145 return datetime.datetime(*[ int(x) for x in groups ])146 except ValueError:147 return convert_date(obj)148TIMEDELTA_RE = re.compile(r"(-)?(\d{1,3}):(\d{1,2}):(\d{1,2})(?:.(\d{1,6}))?")149def convert_timedelta(obj):150 """Returns a TIME column as a timedelta object:151 >>> timedelta_or_None('25:06:17')152 datetime.timedelta(1, 3977)153 >>> timedelta_or_None('-25:06:17')154 datetime.timedelta(-2, 83177)155 Illegal values are returned as None:156 >>> timedelta_or_None('random crap') is None157 True158 Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but159 can accept values as (+|-)DD HH:MM:SS. The latter format will not160 be parsed correctly by this function.161 """162 if not PY2 and isinstance(obj, (bytes, bytearray)):163 obj = obj.decode('ascii')164 m = TIMEDELTA_RE.match(obj)165 if not m:166 return None167 try:168 groups = list(m.groups())169 groups[-1] = _convert_second_fraction(groups[-1])170 negate = -1 if groups[0] else 1171 hours, minutes, seconds, microseconds = groups[1:]172 tdelta = datetime.timedelta(173 hours = int(hours),174 minutes = int(minutes),175 seconds = int(seconds),176 microseconds = int(microseconds)177 ) * negate178 return tdelta179 except ValueError:180 return None181TIME_RE = re.compile(r"(\d{1,2}):(\d{1,2}):(\d{1,2})(?:.(\d{1,6}))?")182def convert_time(obj):183 """Returns a TIME column as a time object:184 >>> time_or_None('15:06:17')185 datetime.time(15, 6, 17)186 Illegal values are returned as None:187 >>> time_or_None('-25:06:17') is None188 True189 >>> time_or_None('random crap') is None190 True191 Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but192 can accept values as (+|-)DD HH:MM:SS. The latter format will not193 be parsed correctly by this function.194 Also note that MySQL's TIME column corresponds more closely to195 Python's timedelta and not time. However if you want TIME columns196 to be treated as time-of-day and not a time offset, then you can197 use set this function as the converter for FIELD_TYPE.TIME.198 """199 if not PY2 and isinstance(obj, (bytes, bytearray)):200 obj = obj.decode('ascii')201 m = TIME_RE.match(obj)202 if not m:203 return None204 try:205 groups = list(m.groups())206 groups[-1] = _convert_second_fraction(groups[-1])207 hours, minutes, seconds, microseconds = groups208 return datetime.time(hour=int(hours), minute=int(minutes),209 second=int(seconds), microsecond=int(microseconds))210 except ValueError:211 return None212def convert_date(obj):213 """Returns a DATE column as a date object:214 >>> date_or_None('2007-02-26')215 datetime.date(2007, 2, 26)216 Illegal values are returned as None:217 >>> date_or_None('2007-02-31') is None218 True219 >>> date_or_None('0000-00-00') is None220 True221 """222 if not PY2 and isinstance(obj, (bytes, bytearray)):223 obj = obj.decode('ascii')224 try:225 return datetime.date(*[ int(x) for x in obj.split('-', 2) ])226 except ValueError:227 return None228def convert_mysql_timestamp(timestamp):229 """Convert a MySQL TIMESTAMP to a Timestamp object.230 MySQL >= 4.1 returns TIMESTAMP in the same format as DATETIME:231 >>> mysql_timestamp_converter('2007-02-25 22:32:17')232 datetime.datetime(2007, 2, 25, 22, 32, 17)233 MySQL < 4.1 uses a big string of numbers:234 >>> mysql_timestamp_converter('20070225223217')235 datetime.datetime(2007, 2, 25, 22, 32, 17)236 Illegal values are returned as None:237 >>> mysql_timestamp_converter('2007-02-31 22:32:17') is None238 True239 >>> mysql_timestamp_converter('00000000000000') is None240 True241 """242 if not PY2 and isinstance(timestamp, (bytes, bytearray)):243 timestamp = timestamp.decode('ascii')244 if timestamp[4] == '-':245 return convert_datetime(timestamp)246 timestamp += "0"*(14-len(timestamp)) # padding247 year, month, day, hour, minute, second = \248 int(timestamp[:4]), int(timestamp[4:6]), int(timestamp[6:8]), \249 int(timestamp[8:10]), int(timestamp[10:12]), int(timestamp[12:14])250 try:251 return datetime.datetime(year, month, day, hour, minute, second)252 except ValueError:253 return None254def convert_set(s):255 if isinstance(s, (bytes, bytearray)):256 return set(s.split(b","))257 return set(s.split(","))258def through(x):259 return x260#def convert_bit(b):261# b = "\x00" * (8 - len(b)) + b # pad w/ zeroes262# return struct.unpack(">Q", b)[0]263#264# the snippet above is right, but MySQLdb doesn't process bits,265# so we shouldn't either266convert_bit = through267def convert_characters(connection, field, data):268 field_charset = charset_by_id(field.charsetnr).name269 encoding = charset_to_encoding(field_charset)270 if field.flags & FLAG.SET:271 return convert_set(data.decode(encoding))272 if field.flags & FLAG.BINARY:273 return data274 if connection.use_unicode:275 data = data.decode(encoding)276 elif connection.charset != field_charset:277 data = data.decode(encoding)278 data = data.encode(connection.encoding)279 return data280encoders = {281 bool: escape_bool,282 int: escape_int,283 long_type: escape_int,284 float: escape_float,285 str: escape_str,286 text_type: escape_unicode,287 tuple: escape_sequence,288 list: escape_sequence,289 set: escape_sequence,290 frozenset: escape_sequence,291 dict: escape_dict,292 bytearray: escape_bytes,293 type(None): escape_None,294 datetime.date: escape_date,295 datetime.datetime: escape_datetime,296 datetime.timedelta: escape_timedelta,297 datetime.time: escape_time,298 time.struct_time: escape_struct_time,299 Decimal: escape_object,300}301if not PY2 or JYTHON or IRONPYTHON:302 encoders[bytes] = escape_bytes303decoders = {304 FIELD_TYPE.BIT: convert_bit,305 FIELD_TYPE.TINY: int,306 FIELD_TYPE.SHORT: int,307 FIELD_TYPE.LONG: int,308 FIELD_TYPE.FLOAT: float,309 FIELD_TYPE.DOUBLE: float,310 FIELD_TYPE.LONGLONG: int,311 FIELD_TYPE.INT24: int,312 FIELD_TYPE.YEAR: int,313 FIELD_TYPE.TIMESTAMP: convert_mysql_timestamp,314 FIELD_TYPE.DATETIME: convert_datetime,315 FIELD_TYPE.TIME: convert_timedelta,316 FIELD_TYPE.DATE: convert_date,317 FIELD_TYPE.SET: convert_set,318 FIELD_TYPE.BLOB: through,319 FIELD_TYPE.TINY_BLOB: through,320 FIELD_TYPE.MEDIUM_BLOB: through,321 FIELD_TYPE.LONG_BLOB: through,322 FIELD_TYPE.STRING: through,323 FIELD_TYPE.VAR_STRING: through,324 FIELD_TYPE.VARCHAR: through,325 FIELD_TYPE.DECIMAL: Decimal,326 FIELD_TYPE.NEWDECIMAL: Decimal,327}328# for MySQLdb compatibility329conversions = encoders.copy()330conversions.update(decoders)...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...36 >>> Markup(Foo())37 Markup(u'<a href="#">foo</a>')38 If you want object passed being always treated as unsafe you can use the39 :meth:`escape` classmethod to create a :class:`Markup` object:40 >>> Markup.escape("Hello <em>World</em>!")41 Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')42 Operations on a markup string are markup aware which means that all43 arguments are passed through the :func:`escape` function:44 >>> em = Markup("<em>%s</em>")45 >>> em % "foo & bar"46 Markup(u'<em>foo &amp; bar</em>')47 >>> strong = Markup("<strong>%(text)s</strong>")48 >>> strong % {'text': '<blink>hacker here</blink>'}49 Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')50 >>> Markup("<em>Hello</em> ") + "<foo>"51 Markup(u'<em>Hello</em> &lt;foo&gt;')52 """53 __slots__ = ()54 def __new__(cls, base=u'', encoding=None, errors='strict'):55 if hasattr(base, '__html__'):56 base = base.__html__()57 if encoding is None:58 return text_type.__new__(cls, base)59 return text_type.__new__(cls, base, encoding, errors)60 def __html__(self):61 return self62 def __add__(self, other):63 if isinstance(other, string_types) or hasattr(other, '__html__'):64 return self.__class__(super(Markup, self).__add__(self.escape(other)))65 return NotImplemented66 def __radd__(self, other):67 if hasattr(other, '__html__') or isinstance(other, string_types):68 return self.escape(other).__add__(self)69 return NotImplemented70 def __mul__(self, num):71 if isinstance(num, int_types):72 return self.__class__(text_type.__mul__(self, num))73 return NotImplemented74 __rmul__ = __mul__75 def __mod__(self, arg):76 if isinstance(arg, tuple):77 arg = tuple(_MarkupEscapeHelper(x, self.escape) for x in arg)78 else:79 arg = _MarkupEscapeHelper(arg, self.escape)80 return self.__class__(text_type.__mod__(self, arg))81 def __repr__(self):82 return '%s(%s)' % (83 self.__class__.__name__,84 text_type.__repr__(self)85 )86 def join(self, seq):87 return self.__class__(text_type.join(self, map(self.escape, seq)))88 join.__doc__ = text_type.join.__doc__89 def split(self, *args, **kwargs):90 return list(map(self.__class__, text_type.split(self, *args, **kwargs)))91 split.__doc__ = text_type.split.__doc__92 def rsplit(self, *args, **kwargs):93 return list(map(self.__class__, text_type.rsplit(self, *args, **kwargs)))94 rsplit.__doc__ = text_type.rsplit.__doc__95 def splitlines(self, *args, **kwargs):96 return list(map(self.__class__, text_type.splitlines(97 self, *args, **kwargs)))98 splitlines.__doc__ = text_type.splitlines.__doc__99 def unescape(self):100 r"""Unescape markup again into an text_type string. This also resolves101 known HTML4 and XHTML entities:102 >>> Markup("Main &raquo; <em>About</em>").unescape()103 u'Main \xbb <em>About</em>'104 """105 from markupsafe._constants import HTML_ENTITIES106 def handle_match(m):107 name = m.group(1)108 if name in HTML_ENTITIES:109 return unichr(HTML_ENTITIES[name])110 try:111 if name[:2] in ('#x', '#X'):112 return unichr(int(name[2:], 16))113 elif name.startswith('#'):114 return unichr(int(name[1:]))115 except ValueError:116 pass117 return u''118 return _entity_re.sub(handle_match, text_type(self))119 def striptags(self):120 r"""Unescape markup into an text_type string and strip all tags. This121 also resolves known HTML4 and XHTML entities. Whitespace is122 normalized to one:123 >>> Markup("Main &raquo; <em>About</em>").striptags()124 u'Main \xbb About'125 """126 stripped = u' '.join(_striptags_re.sub('', self).split())127 return Markup(stripped).unescape()128 @classmethod129 def escape(cls, s):130 """Escape the string. Works like :func:`escape` with the difference131 that for subclasses of :class:`Markup` this function would return the132 correct subclass.133 """134 rv = escape(s)135 if rv.__class__ is not cls:136 return cls(rv)137 return rv138 def make_simple_escaping_wrapper(name):139 orig = getattr(text_type, name)140 def func(self, *args, **kwargs):141 args = _escape_argspec(list(args), enumerate(args), self.escape)142 _escape_argspec(kwargs, iteritems(kwargs), self.escape)143 return self.__class__(orig(self, *args, **kwargs))144 func.__name__ = orig.__name__145 func.__doc__ = orig.__doc__146 return func147 for method in '__getitem__', 'capitalize', \148 'title', 'lower', 'upper', 'replace', 'ljust', \149 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \150 'translate', 'expandtabs', 'swapcase', 'zfill':151 locals()[method] = make_simple_escaping_wrapper(method)152 # new in python 2.5153 if hasattr(text_type, 'partition'):154 def partition(self, sep):155 return tuple(map(self.__class__,156 text_type.partition(self, self.escape(sep))))157 def rpartition(self, sep):158 return tuple(map(self.__class__,159 text_type.rpartition(self, self.escape(sep))))160 # new in python 2.6161 if hasattr(text_type, 'format'):162 def format(*args, **kwargs):163 self, args = args[0], args[1:]164 formatter = EscapeFormatter(self.escape)165 kwargs = _MagicFormatMapping(args, kwargs)166 return self.__class__(formatter.vformat(self, args, kwargs))167 def __html_format__(self, format_spec):168 if format_spec:169 raise ValueError('Unsupported format specification '170 'for Markup.')171 return self172 # not in python 3173 if hasattr(text_type, '__getslice__'):174 __getslice__ = make_simple_escaping_wrapper('__getslice__')175 del method, make_simple_escaping_wrapper176class _MagicFormatMapping(Mapping):177 """This class implements a dummy wrapper to fix a bug in the Python178 standard library for string formatting.179 See http://bugs.python.org/issue13598 for information about why180 this is necessary.181 """182 def __init__(self, args, kwargs):183 self._args = args184 self._kwargs = kwargs185 self._last_index = 0186 def __getitem__(self, key):187 if key == '':188 idx = self._last_index189 self._last_index += 1190 try:191 return self._args[idx]192 except LookupError:193 pass194 key = str(idx)195 return self._kwargs[key]196 def __iter__(self):197 return iter(self._kwargs)198 def __len__(self):199 return len(self._kwargs)200if hasattr(text_type, 'format'):201 class EscapeFormatter(string.Formatter):202 def __init__(self, escape):203 self.escape = escape204 def format_field(self, value, format_spec):205 if hasattr(value, '__html_format__'):206 rv = value.__html_format__(format_spec)207 elif hasattr(value, '__html__'):208 if format_spec:209 raise ValueError('No format specification allowed '210 'when formatting an object with '211 'its __html__ method.')212 rv = value.__html__()213 else:214 rv = string.Formatter.format_field(self, value, format_spec)215 return text_type(self.escape(rv))216def _escape_argspec(obj, iterable, escape):217 """Helper for various string-wrapped functions."""218 for key, value in iterable:219 if hasattr(value, '__html__') or isinstance(value, string_types):220 obj[key] = escape(value)221 return obj222class _MarkupEscapeHelper(object):223 """Helper for Markup.__mod__"""224 def __init__(self, obj, escape):225 self.obj = obj226 self.escape = escape227 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x], s.escape)228 __unicode__ = __str__ = lambda s: text_type(s.escape(s.obj))229 __repr__ = lambda s: str(s.escape(repr(s.obj)))230 __int__ = lambda s: int(s.obj)231 __float__ = lambda s: float(s.obj)232# we have to import it down here as the speedups and native233# modules imports the markup type which is define above.234try:235 from markupsafe._speedups import escape, escape_silent, soft_unicode236except ImportError:237 from markupsafe._native import escape, escape_silent, soft_unicode238if not PY2:239 soft_str = soft_unicode...

Full Screen

Full Screen

middlewares.py

Source:middlewares.py Github

copy

Full Screen

...59 use_type = self.__filter_param(path, _get_key)60 else:61 use_type = escape_type62 if use_type == 'url':63 new_value = url_escape(_get_value)64 elif use_type == 'texteditor':65 new_value = texteditor_escape(_get_value)66 else:67 new_value = html_escape(_get_value)68 else:69 new_value = html_escape(_get_value, True)70 new_value_list.append(new_value)71 data_copy.setlist(_get_key, new_value_list)72 return data_copy73 def __filter_param(self, path, param):74 """75 特殊path处理76 @param path: 路径77 @param param: 参数78 @return: 'url/texteditor'79 """80 use_url_paths, use_texteditor_paths = self.__filter_path_list()81 result = self.__check_escape_type(path, param, use_url_paths, 'url')82 # 富文本内容过滤83 if result == 'html':...

Full Screen

Full Screen

resource.py

Source:resource.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2"""3 pygments.lexers.resource4 ~~~~~~~~~~~~~~~~~~~~~~~~5 Lexer for resource definition files.6 :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.7 :license: BSD, see LICENSE for details.8"""9import re10from pygments.lexer import RegexLexer, bygroups, words11from pygments.token import Comment, String, Number, Operator, Text, \12 Keyword, Name13__all__ = ['ResourceLexer']14class ResourceLexer(RegexLexer):15 """Lexer for `ICU Resource bundles16 <http://userguide.icu-project.org/locale/resources>`_.17 .. versionadded:: 2.018 """19 name = 'ResourceBundle'20 aliases = ['resource', 'resourcebundle']21 filenames = ['*.txt']22 _types = (':table', ':array', ':string', ':bin', ':import', ':intvector',23 ':int', ':alias')24 flags = re.MULTILINE | re.IGNORECASE25 tokens = {26 'root': [27 (r'//.*?$', Comment),28 (r'"', String, 'string'),29 (r'-?\d+', Number.Integer),30 (r'[,{}]', Operator),31 (r'([^\s{:]+)(\s*)(%s?)' % '|'.join(_types),32 bygroups(Name, Text, Keyword)),33 (r'\s+', Text),34 (words(_types), Keyword),35 ],36 'string': [37 (r'(\\x[0-9a-f]{2}|\\u[0-9a-f]{4}|\\U00[0-9a-f]{6}|'38 r'\\[0-7]{1,3}|\\c.|\\[abtnvfre\'"?\\]|\\\{|[^"{\\])+', String),39 (r'\{', String.Escape, 'msgname'),40 (r'"', String, '#pop')41 ],42 'msgname': [43 (r'([^{},]+)(\s*)', bygroups(Name, String.Escape), ('#pop', 'message'))44 ],45 'message': [46 (r'\{', String.Escape, 'msgname'),47 (r'\}', String.Escape, '#pop'),48 (r'(,)(\s*)([a-z]+)(\s*\})',49 bygroups(Operator, String.Escape, Keyword, String.Escape), '#pop'),50 (r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)(offset)(\s*)(:)(\s*)(-?\d+)(\s*)',51 bygroups(Operator, String.Escape, Keyword, String.Escape, Operator,52 String.Escape, Operator.Word, String.Escape, Operator,53 String.Escape, Number.Integer, String.Escape), 'choice'),54 (r'(,)(\s*)([a-z]+)(\s*)(,)(\s*)',55 bygroups(Operator, String.Escape, Keyword, String.Escape, Operator,56 String.Escape), 'choice'),57 (r'\s+', String.Escape)58 ],59 'choice': [60 (r'(=|<|>|<=|>=|!=)(-?\d+)(\s*\{)',61 bygroups(Operator, Number.Integer, String.Escape), 'message'),62 (r'([a-z]+)(\s*\{)', bygroups(Keyword.Type, String.Escape), 'str'),63 (r'\}', String.Escape, ('#pop', '#pop')),64 (r'\s+', String.Escape)65 ],66 'str': [67 (r'\}', String.Escape, '#pop'),68 (r'\{', String.Escape, 'msgname'),69 (r'[^{}]+', String)70 ]71 }72 def analyse_text(text):73 if text.startswith('root:table'):...

Full Screen

Full Screen

test_force_escape.py

Source:test_force_escape.py Github

copy

Full Screen

...41 def test_force_escape08(self):42 output = self.engine.render_to_string('force-escape08', {"a": "x&y"})43 self.assertEqual(output, "x&amp;amp;y")44class FunctionTests(SimpleTestCase):45 def test_escape(self):46 escaped = force_escape('<some html & special characters > here')47 self.assertEqual(escaped, '&lt;some html &amp; special characters &gt; here')48 self.assertIsInstance(escaped, SafeData)49 def test_unicode(self):50 self.assertEqual(51 force_escape('<some html & special characters > here ĐÅ€£'),52 '&lt;some html &amp; special characters &gt; here \u0110\xc5\u20ac\xa3',...

Full Screen

Full Screen

test_misc.py

Source:test_misc.py Github

copy

Full Screen

...31 terms = ['',32 'word',33 'two words']34 for term, expected_term in zip(terms, terms):35 assert_equal(_sql_escape(term), expected_term)36 def test_escape_chararacter_is_escaped(self):37 """Asserts that the escape character is escaped"""38 term = r'backslash \ character'39 assert_equal (_sql_escape(term, escape='\\'),40 r'backslash \\ character')41 term = 'surprise!'42 assert_equal (_sql_escape(term, escape='!'),43 r'surprise!!')44 def test_default_escape_character_is_a_backslash(self):45 """Asserts that the default escape character is the backslash"""46 term = r'backslash \ character'47 assert_equal (_sql_escape(term),48 r'backslash \\ character')49 def test_sql_like_special_characters_are_escaped(self):50 """Asserts that '%' and '_' are escaped correctly"""51 terms = [52 (r'percents %', r'percents \%'),53 (r'underscores _', r'underscores \_'),54 (r'backslash \ ', r'backslash \\ '),55 (r'all three \ _%', r'all three \\ \_\%'),56 ]57 for term, expected_result in terms:...

Full Screen

Full Screen

char_escape.py

Source:char_escape.py Github

copy

Full Screen

...2627ESCAPED_CHARSET_MAP_DICT = EscapeCharsetMapClass()282930def char_escape(s: str, escape_charset, escape_char_type: str):31 """32 :param s:33 :param escape_charset: None means all char will be escaped34 :param escape_char_type:35 :return:36 """37 if escape_charset is not None:38 new_s = s39 for each_escape_char in escape_charset:40 new_s = new_s.replace(each_escape_char,41 getattr(ESCAPED_CHARSET_MAP_DICT[each_escape_char], escape_char_type))42 else:43 new_s = []44 for each_char in s:45 new_s.append(getattr(ESCAPED_CHARSET_MAP_DICT[each_char], escape_char_type))4647 new_s = ''.join(new_s)48 s = new_s4950 return s515253def htmltitle2path(htmltitle, escape_char_type='url'):54 path = char_escape(htmltitle, INVALID_FILE_CHAR_SET, escape_char_type)55 path = ''.join(re.split('\s+', path)) # in case other blank char ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3 if (err) return console.error(err);4 console.log('Test status check: ' + data.statusText);5});6var wpt = require('webpagetest');7var wpt = new WebPageTest('www.webpagetest.org');8 if (err) return console.error(err);9 console.log('Test status check: ' + data.statusText);10});11var wpt = require('webpagetest');12var wpt = new WebPageTest('www.webpagetest.org');13 if (err) return console.error(err);14 console.log('Test status check: ' + data.statusText);15});16var wpt = require('webpagetest');17var wpt = new WebPageTest('www.webpagetest.org');18 if (err) return console.error(err);19 console.log('Test status check: ' + data.statusText);20});21var wpt = require('webpagetest');22var wpt = new WebPageTest('www.webpagetest.org');23 if (err) return console.error(err);24 console.log('Test status check: ' + data.statusText);25});26var wpt = require('webpagetest');27var wpt = new WebPageTest('www.webpagetest.org');28 if (err) return console.error(err);29 console.log('Test status check: ' + data.statusText);30});31var wpt = require('webpagetest');32var wpt = new WebPageTest('www.webpagetest.org');

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var api = new wpt('www.webpagetest.org');3 if (err) {4 console.error(err);5 } else {6 api.getTestResults(data.data.testId, function(err, data) {7 if (err) {8 console.error(err);9 } else {10 console.log(data);11 }12 });13 }14});15{ statusCode: 400,16 { statusCode: 400,17 responseText: 'Missing URL' } }18{ statusCode: 400,19 { statusCode: 400,20 responseText: 'Missing URL' } }21{ [Error: Cannot find module 'webpagetest']22 code: 'MODULE_NOT_FOUND' }23{ statusCode: 400,24 { statusCode: 400,25 responseText: 'Missing URL' } }26{ statusCode: 400,27 { statusCode: 400,28 responseText: 'Missing URL' } }

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var instance = wpt('www.webpagetest.org');3 console.log(data);4 instance.getTestResults(data.data.testId, function(err, data) {5 console.log(data);6 });7});8var wpt = require('webpagetest');9var instance = wpt('www.webpagetest.org');10 console.log(data);11 instance.getTestResults(data.data.testId, function(err, data) {12 console.log(data);13 });14});15var wpt = require('webpagetest');16var instance = wpt('www.webpagetest.org');17 console.log(data);18 instance.getTestResults(data.data.testId, function(err, data) {19 console.log(data);20 });21});22var wpt = require('webpagetest');23var instance = wpt('www.webpagetest.org');24 console.log(data);25 instance.getTestResults(data.data.testId, function(err, data) {26 console.log(data);27 });28});29var wpt = require('webpagetest');30var instance = wpt('www.webpagetest.org');31 console.log(data);32 instance.getTestResults(data.data.testId, function(err, data) {33 console.log(data);34 });35});36var wpt = require('webpagetest');37var instance = wpt('www.webpagetest.org');38 console.log(data);39 instance.getTestResults(data.data.testId, function(err, data) {40 console.log(data);41 });42});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var testOptions = {4};5wpt.runTest(testURL, testOptions, function(err, data) {6 if (err) {7 console.log('Error: ' + err);8 } else {9 console.log('Test submitted successfully. View your test at: ' + data.data.userUrl);10 }11});12var wpt = require('webpagetest');13var wpt = new WebPageTest('www.webpagetest.org');14var testOptions = {15};16wpt.runTest(testURL, testOptions, function(err, data) {17 if (err) {18 console.log('Error: ' + err);19 } else {20 console.log('Test submitted successfully. View your test at: ' + data.data.userUrl);21 }22});23var wpt = require('webpagetest');24var wpt = new WebPageTest('www.webpagetest.org');25var testOptions = {26};27wpt.runTest(testURL, testOptions, function(err, data) {28 if (err) {29 console.log('Error: ' + err);30 } else {31 console.log('Test submitted successfully. View your test at: ' + data.data.userUrl);32 }33});34var wpt = require('webpagetest');35var wpt = new WebPageTest('www.webpagetest.org');36var testOptions = {

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org');3wpt.runTest(url, { runs: 1, location: 'Dulles:Chrome' }, function(err, data) {4 if (err) return console.log(err);5 console.log('Test status: ' + data.statusText);6 console.log('Test ID: ' + data.data.testId);7 console.log('Test URL: ' + data.data.userUrl);8 console.log('Test results URL: ' + data.data.summaryCSV);9});10var wpt = require('wpt');11var wpt = new WebPageTest('www.webpagetest.org');12wpt.runTest(url, { runs: 1, location: 'Dulles:Chrome' }, function(err, data) {13 if (err) return console.log(err);14 console.log('Test status: ' + data.statusText);15 console.log('Test ID: ' + data.data.testId);16 console.log('Test URL: ' + data.data.userUrl);17 console.log('Test results URL: ' + data.data.summaryCSV);18});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org','A.2b4c5d6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7');3var options = {4};5wpt.runTest(url, options, function(err, data) {6 if (err) return console.error(err);7 console.log(data);8});9wpt.getTestResults(data.data.testId, function(err, data) {10 if (err) return console.error(err);11 console.log(data);12});13wpt.getTestResults(data.data.testId, function(err, data) {14 if (err) return console.error(err);15 console.log(data);16});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wptexturize = require('wptexturize');2var text = 'Some text to escape';3var escaped = wptexturize.escape(text);4console.log(escaped);5var wptexturize = require('wptexturize');6var text = 'Some&#160;text&#160;to&#160;escape';7var unescaped = wptexturize.unescape(text);8console.log(unescaped);9var wptexturize = require('wptexturize');10var text = 'Some text to escape';11var texturized = wptexturize.texturize(text);12console.log(texturized);13var wptexturize = require('wptexturize');14var text = 'Some&#160;text&#160;to&#160;escape';15var untexturized = wptexturize.untexturize(text);16console.log(untexturized);17var wptexturize = require('wptexturize');18var text = 'Some text to escape';19var texturized = wptexturize.texturize(text, false);20console.log(texturized);21var wptexturize = require('wptexturize');22var text = 'Some text to escape';23var untexturized = wptexturize.untexturize(text, false);24console.log(untexturized);

Full Screen

Using AI Code Generation

copy

Full Screen

1var textpattern = CKEDITOR.plugins.get('wptextpattern');2var escaped = textpattern.escape( 'test' );3console.log( 'escaped: ' + escaped );4var textpattern = CKEDITOR.plugins.get('wptextpattern');5var unescaped = textpattern.unescape( 'test' );6console.log( 'unescaped: ' + unescaped );7var textpattern = CKEDITOR.plugins.get('wptextpattern');8var trigger = textpattern.getTriggerRegex( 'test' );9console.log( 'trigger: ' + trigger );10var textpattern = CKEDITOR.plugins.get('wptextpattern');11var config = textpattern.getTextPatternConfig( 'test' );12console.log( 'config: ' + config );13var textpattern = CKEDITOR.plugins.get('wptextpattern');14var pattern = textpattern.getTextPattern( 'test' );15console.log( 'pattern: ' + pattern );16var textpattern = CKEDITOR.plugins.get('wptextpattern');17var regex = textpattern.getTextPatternRegex( 'test' );18console.log( 'regex: ' + regex );19var textpattern = CKEDITOR.plugins.get('wptextpattern');20var replacement = textpattern.getTextPatternReplacement( 'test' );21console.log( 'replacement: ' + replacement );22var textpattern = CKEDITOR.plugins.get('wptextpattern');23var offset = textpattern.getTextPatternCursorOffset( 'test' );24console.log( 'offset: ' + offset );

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('wpt');2var wpt = new WebPageTest('www.webpagetest.org', 'A.1d8d6e9d9b9f9b8b2b2b2b2b2b2b2b2b');3 if (err) return console.error(err);4 console.log(data);5});6var wpt = require('wpt');7var wpt = new WebPageTest('www.webpagetest.org', 'A.1d8d6e9d9b9f9b8b2b2b2b2b2b2b2b');8 if (err) return console.error(err);9 console.log(data);10});11var wpt = require('wpt');12var wpt = new WebPageTest('www.webpagetest.org', 'A.1d8d6e9d9b9f9b8b2b2b2b2b2b2b2b');13 if (err) return console.error(err);14 console.log(data);15});16var wpt = require('wpt');17var wpt = new WebPageTest('www.webpagetest.org', 'A.1d8d6e9d9b9f9b8b2b2b2b2b2b2b2b');18 if (err) return console.error(err);19 console.log(data);20});21var wpt = require('wpt');22var wpt = new WebPageTest('www.webpagetest.org', 'A.1d8d6e9d9b9f9b8b2b2b

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful