Best JavaScript code snippet using chai
sre_parse.py
Source:sre_parse.py
...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]...
converters.py
Source:converters.py
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)...
__init__.py
Source:__init__.py
...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 <em>World</em>!')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 & bar</em>')47 >>> strong = Markup("<strong>%(text)s</strong>")48 >>> strong % {'text': '<blink>hacker here</blink>'}49 Markup(u'<strong><blink>hacker here</blink></strong>')50 >>> Markup("<em>Hello</em> ") + "<foo>"51 Markup(u'<em>Hello</em> <foo>')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 » <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 » <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...
middlewares.py
Source:middlewares.py
...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':...
resource.py
Source:resource.py
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'):...
test_force_escape.py
Source:test_force_escape.py
...41 def test_force_escape08(self):42 output = self.engine.render_to_string('force-escape08', {"a": "x&y"})43 self.assertEqual(output, "x&amp;y")44class FunctionTests(SimpleTestCase):45 def test_escape(self):46 escaped = force_escape('<some html & special characters > here')47 self.assertEqual(escaped, '<some html & special characters > here')48 self.assertIsInstance(escaped, SafeData)49 def test_unicode(self):50 self.assertEqual(51 force_escape('<some html & special characters > here ÄÃ
â¬Â£'),52 '<some html & special characters > here \u0110\xc5\u20ac\xa3',...
test_misc.py
Source:test_misc.py
...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:...
char_escape.py
Source:char_escape.py
...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
...
Using AI Code Generation
1var chai = require('chai');2var request = require('request');3describe('Test for login page', function() {4 describe('GET /', function() {5 it('should return status code 200', function(done) {6 expect(response.statusCode).to.equal(200);7 done();8 });9 });10 });11});12describe('Test for login page', function() {13 describe('GET /', function() {14 it('should return status code 200', function(done) {15 expect(response.statusCode).to.equal(200);16 done();17 });18 });19 });20});21describe('Test for login page', function() {22 describe('GET /', function() {23 it('should return status code 200', function(done) {24 expect(response.statusCode).to.equal(200);25 done();26 });27 });28 });29});30describe('Test for login page', function() {31 describe('GET /', function() {32 it('should return status code 200', function(done) {33 expect(response.statusCode).to.equal(200);34 done();35 });36 });37 });38});39describe('Test for login page', function() {40 describe('GET /', function() {41 it('should return status code 200', function(done) {42 expect(response.statusCode).to.equal(200);43 done();44 });45 });46 });47});48describe('Test for login page', function() {49 describe('GET /', function() {50 it('should return status code 200', function(done) {51 expect(response.statusCode).to.equal
Using AI Code Generation
1const chai = require('chai');2const expect = chai.expect;3const escape = require('../escape');4describe('escape', () => {5 it('returns a string', () => {6 const str = 'Lighthouse Labs';7 const result = escape(str);8 expect(result).to.be.a('string');9 });10 it('returns an empty string when passed an empty string', () => {11 const str = '';12 const result = escape(str);13 expect(result).to.equal('');14 });15 it('returns a string with escaped characters', () => {16 const str = 'Lighthouse Labs <script>alert("xss");</script>';17 const result = escape(str);18 expect(result).to.equal('Lighthouse Labs <script>alert(\"xss\");</script>');19 });20 it('returns a string with escaped characters', () => {21 const str = 'Lighthouse Labs <script>alert("xss");</script> & <script>alert("xss");</script>';22 const result = escape(str);23 expect(result).to.equal('Lighthouse Labs <script>alert(\"xss\");</script> & <script>alert(\"xss\");</script>');24 });25 it('returns a string with escaped characters', () => {26 const str = 'Lighthouse Labs <script>alert("xss");</script> & <script>alert("xss");</script>';27 const result = escape(str);28 expect(result).to.equal('Lighthouse Labs <script>alert(\"xss\");</script> & <script>alert(\"xss\");</script>');29 });30 it('returns a string with escaped characters', () => {31 const str = 'Lighthouse Labs <script>alert("xss");</script> & <script>alert("xss");</script>';32 const result = escape(str);33 expect(result).to.equal('Lighthouse Labs <script>alert(\"xss\");</script> & <script>alert(\"xss\");</script>');34 });35});
Using AI Code Generation
1var expect = require('chai').expect;2describe('escape', function() {3 it('escapes the string', function() {4 expect('Moe, Larry & Curly'.escape()).to.equal('Moe, Larry & Curly');5 });6});7var expect = require('chai').expect;8describe('unescape', function() {9 it('unescapes the string', function() {10 expect('<div>Moe, Larry & Curly</div>'.unescape()).to.equal('<div>Moe, Larry & Curly</div>');11 });12});13var expect = require('chai').expect;14describe('capitalize', function() {15 it('capitalizes the first letter of the string', function() {16 expect('moe'.capitalize()).to.equal('Moe');17 });18});19var expect = require('chai').expect;20describe('decapitalize', function() {21 it('decapitalizes the first letter of the string', function() {22 expect('Moe'.decapitalize()).to.equal('moe');23 });24});25var expect = require('chai').expect;26describe('swapCase', function() {27 it('swaps the case of the string', function() {28 expect('aBcD'.swapCase()).to.equal('AbCd');29 });30});31var expect = require('chai').expect;32describe('include', function() {33 it('checks if the string contains the given string', function() {34 expect('foobar'.include('bar')).to.be.true;35 });36});37var expect = require('chai').expect;38describe('startsWith', function() {39 it('checks if the string starts with the given string', function() {40 expect('foobar'.startsWith('foo')).to.be.true;41 });42});43var expect = require('chai').expect;44describe('
Using AI Code Generation
1const expect = require('chai').expect;2const escape = require('../escape');3describe('#escape()', () => {4 it('should return a string', () => {5 const input = 'Lighthouse Labs';6 const output = escape(input);7 expect(output).to.be.a('string');8 });9 it('should return the string with escaped characters', () => {10 const input = 'Lighthouse Labs';11 const output = escape(input);12 expect(output).to.equal('Lighthouse Labs');13 });14 it('should return the string with escaped characters', () => {15 const input = 'Lighthouse Labs';16 const output = escape(input);17 expect(output).to.equal('Lighthouse Labs');18 });19 it('should return the string with escaped characters', () => {20 const input = 'Lighthouse Labs';21 const output = escape(input);22 expect(output).to.equal('Lighthouse Labs');23 });24});
Using AI Code Generation
1const chai = require('chai');2const expect = chai.expect;3const escape = require('../escape');4describe('escape', () => {5 it('should escape "&", "<", ">", \'"\', and "\'", in a string', () => {6 const str = 'Curly, Larry & Moe';7 const escaped = escape(str);8 expect(escaped).to.equal('Curly, Larry & Moe');9 });10});11const _ = require('lodash');12module.exports = (str) => {13 return _.escape(str);14};15const chai = require('chai');16const expect = chai.expect;17const escape = require('../escape');18describe('escape', () => {19 it('should escape "&", "<", ">", \'"\', and "\'", in a string', () => {20 const str = 'Curly, Larry & Moe';21 const escaped = escape(str);22 expect(escaped).to.equal('Curly, Larry & Moe');23 });24});25const _ = require('lodash');26module.exports = (str) => {27 return _.escape(str);28};29const chai = require('chai');30const expect = chai.expect;31const escape = require('../escape');32describe('escape', () => {33 it('should escape "&", "<", ">", \'"\', and "\'", in a string', () => {34 const str = 'Curly, Larry & Moe';35 const escaped = escape(str);36 expect(escaped).to.equal('Curly, Larry & Moe');37 });38});39const _ = require('lodash');40module.exports = (str) => {41 return _.escape(str);42};43const chai = require('chai');44const expect = chai.expect;45const escape = require('../escape');46describe('escape', () => {47 it('should escape "&", "<", ">", \'"\', and "\'", in a string', () => {48 const str = 'Curly, Larry & Moe';
Using AI Code Generation
1var assert = require('chai').assert;2var expect = require('chai').expect;3var should = require('chai').should();4var request = require('supertest');5var app = require('../app');6describe('Test', function() {7 describe('GET /', function() {8 it('respond with json', function(done) {9 request(app)10 .get('/')11 .expect('Content-Type', /json/)12 .expect(200, done);13 });14 });15});
Using AI Code Generation
1const chai = require('chai');2const expect = chai.expect;3const escape = require('../escape');4describe('escape', () => {5 it('should return a string', () => {6 const str1 = "Lighthouse Labs";7 const str2 = "Bootcamp";8 const str3 = "Toronto";9 expect(escape(str1)).to.be.a('string');10 expect(escape(str2)).to.be.a('string');11 expect(escape(str3)).to.be.a('string');12 });13 it('should return a string with escaped characters', () => {14 const str1 = "Lighthouse Labs";15 const str2 = "Bootcamp";16 const str3 = "Toronto";17 expect(escape(str1)).to.equal("Lighthouse Labs");18 expect(escape(str2)).to.equal("Bootcamp");19 expect(escape(str3)).to.equal("Toronto");20 });21});
Using AI Code Generation
1const chai = require('chai');2const expect = chai.expect;3const escape = require('../escape');4describe('escape', () => {5 it('should escape HTML characters', () => {6 const input = '<script>alert("hi");</script>';7 const output = '<script>alert("hi");</script>';8 expect(escape(input)).to.equal(output);9 });10});11const chai = require('chai');12const expect = chai.expect;13const escape = require('../escape');14describe('escape', () => {15 it('should escape HTML characters', () => {16 const input = '<script>alert("hi");</script>';17 const output = '<script>alert("hi");</script>';18 expect(escape(input)).to.equal(output);19 });20});21const chai = require('chai');22const expect = chai.expect;23const escape = require('../escape');24describe('escape', () => {25 it('should escape HTML characters', () => {26 const input = '<script>alert("hi");</script>';27 const output = '<script>alert("hi");</script>';28 expect(escape(input)).to.equal(output);29 });30});31const chai = require('chai');32const expect = chai.expect;33const escape = require('../escape');34describe('escape', () => {35 it('should escape HTML characters', () => {36 const input = '<script>alert("hi");</script>';37 const output = '<script>alert("hi");</script>';38 expect(escape(input)).to.equal(output);39 });40});41const chai = require('chai');42const expect = chai.expect;43const escape = require('../escape');44describe('escape', () => {45 it('should escape HTML characters', () => {46 const input = '<script>alert("hi");</script>';47 const output = '<script>alert
Using AI Code Generation
1var chai = require("chai");2var expect = chai.expect;3describe("String#escape", function() {4 it("should escape special characters in a string", function() {5 expect("<script>alert('hello');</script>".escape()).to.equal(6 "<script>alert('hello');</script>"7 );8 });9});10var chai = require("chai");11var expect = chai.expect;12describe("String#escape", function() {13 it("should escape special characters in a string", function() {14 expect("<script>alert('hello');</script>".escape()).to.equal(15 "<script>alert('hello');</script>"16 );17 });18});19var chai = require("chai");20var expect = chai.expect;21describe("String#escape", function() {22 it("should escape special characters in a string", function() {23 expect("<script>alert('hello');</script>".escape()).to.equal(24 "<script>alert('hello');</script>"25 );26 });27});28var chai = require("chai");29var expect = chai.expect;30describe("String#escape", function() {31 it("should escape special characters in a string", function() {32 expect("<script>alert('hello');</script>".escape()).to.equal(33 "<script>alert('hello');</script>"34 );35 });36});37var chai = require("chai");38var expect = chai.expect;39describe("String#escape", function() {40 it("should escape special characters in a string", function() {41 expect("<script>alert('hello');</script>".escape()).to.equal(42 "<script>alert('hello');</script>"43 );44 });45});
Using AI Code Generation
1var expect = require('chai').expect;2var escape = require('escape-html');3describe('escape', function(){4 it('should escape the html', function(){5 expect(escape('<script>')).to.equal('<script>');6 });7});8var expect = require('chai').expect;9var escape = require('escape-html');10describe('escape', function(){11 it('should escape the html', function(){12 expect(escape('<script>')).to.equal('<script>');13 });14});15var expect = require('chai').expect;16var escape = require('escape-html');17describe('escape', function(){18 it('should escape the html', function(){19 expect(escape('<script>')).to.equal('<script>');20 });21});22var expect = require('chai').expect;23var escape = require('escape-html');24describe('escape', function(){25 it('should escape the html', function(){26 expect(escape('<script>')).to.equal('<script>');27 });28});29var expect = require('chai').expect;30var escape = require('escape-html');31describe('escape', function(){32 it('should escape the html', function(){33 expect(escape('<script>')).to.equal('<script>');34 });35});36var expect = require('chai').expect;37var escape = require('escape-html');38describe('escape', function(){39 it('should escape the html', function(){40 expect(escape('<script>')).to.equal('<script>');41 });42});43var expect = require('chai').expect;44var escape = require('escape-html');45describe('escape', function(){46 it('should escape the html', function(){47 expect(escape('<script>
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!