query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
html encode string
|
python
|
def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the HTML and
:class:`HTMLResponse <HTMLResponse>` headers.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._html:
self._encoding = html_to_unicode(self.default_encoding, self._html)[0]
# Fall back to requests' detected encoding if decode fails.
try:
self.raw_html.decode(self.encoding, errors='replace')
except UnicodeDecodeError:
self._encoding = self.default_encoding
return self._encoding if self._encoding else self.default_encoding
|
https://github.com/kennethreitz/requests-html/blob/b59a9f2fb9333d7d467154a0fd82978efdb9d23b/requests_html.py#L119-L136
|
html encode string
|
python
|
def encode(self, string):
"""Encode a_string as per the canonicalisation encoding rules.
See the AWS dev reference page 186 (2009-11-30 version).
@return: a_string encoded.
"""
if isinstance(string, unicode):
string = string.encode("utf-8")
return quote(string, safe="~")
|
https://github.com/twisted/txaws/blob/5c3317376cd47e536625027e38c3b37840175ce0/txaws/ec2/client.py#L1122-L1130
|
html encode string
|
python
|
def encoding(self) -> _Encoding:
"""The encoding string to be used, extracted from the XML and
:class:`XMLResponse <XMLResponse>` header.
"""
if self._encoding:
return self._encoding
# Scan meta tags for charset.
if self._xml:
self._encoding = html_to_unicode(self.default_encoding, self._xml)[0]
return self._encoding if self._encoding else self.default_encoding
|
https://github.com/erinxocon/requests-xml/blob/923571ceae4ddd4f2f57a2fc8780d89b50f3e7a1/requests_xml.py#L157-L168
|
html encode string
|
python
|
def encode(self, s):
"""
Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str
"""
if isinstance(s, basestring) and self.needsEncoding(s):
for x in self.encodings:
s = s.replace(x[0], x[1])
return s
|
https://github.com/heroku/sf-suds/blob/44b6743a45ff4447157605d6fecc9bf5922ce68a/suds/sax/enc.py#L55-L66
|
html encode string
|
python
|
def encode(self, s):
"""
Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str
"""
if isinstance(s, basestring) and self.__needs_encoding(s):
for x in self.encodings:
s = re.sub(x[0], x[1], s)
return s
|
https://github.com/suds-community/suds/blob/6fb0a829337b5037a66c20aae6f89b41acd77e40/suds/sax/enc.py#L51-L64
|
html encode string
|
python
|
def encode(self, s):
"""
Encode special characters found in string I{s}.
@param s: A string to encode.
@type s: str
@return: The encoded string.
@rtype: str
"""
if isinstance(s, str) and self.needsEncoding(s):
for x in self.encodings:
s = re.sub(x[0], x[1], s)
return s
|
https://github.com/cackharot/suds-py3/blob/7387ec7806e9be29aad0a711bea5cb3c9396469c/suds/sax/enc.py#L65-L76
|
html encode string
|
python
|
def encode_for_xml(text, wash=False, xml_version='1.0', quote=False):
"""Encode special characters in a text so that it would be XML-compliant.
:param text: text to encode
:return: an encoded text
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
if quote:
text = text.replace('"', '"')
if wash:
text = wash_for_xml(text, xml_version=xml_version)
return text
|
https://github.com/inveniosoftware-attic/invenio-utils/blob/9a1c6db4e3f1370901f329f510480dd8df188296/invenio_utils/text.py#L368-L380
|
html encode string
|
python
|
def encode_string(data, encoding='hex'):
'''
Encode string
:param data: string to encode
:param encoding: encoding to use (default: 'hex')
:return: encoded string
'''
if six.PY2:
return data.encode(encoding)
else:
if isinstance(data, str):
data = bytes(data, 'utf-8')
return codecs.encode(data, encoding).decode('ascii')
|
https://github.com/cisco-sas/kitty/blob/cb0760989dcdfe079e43ac574d872d0b18953a32/kitty/remote/rpc.py#L39-L52
|
html encode string
|
python
|
def text(self):
"""Content as string
If :attr:`encoding` is None, the encoding is guessed with :meth:`guess_encoding`
"""
if not self.content:
return
if self.encoding:
return self.content.decode(self.encoding, errors='replace')
return self.content.decode(self.guess_encoding(), errors='replace')
|
https://github.com/Diaoul/subliminal/blob/a952dfb2032eb0fd6eb1eb89f04080923c11c4cf/subliminal/subtitle.py#L64-L76
|
html encode string
|
python
|
def encode(self, delimiter=';'):
"""Encode a command string from message."""
try:
return delimiter.join([str(f) for f in [
self.node_id,
self.child_id,
int(self.type),
self.ack,
int(self.sub_type),
self.payload,
]]) + '\n'
except ValueError:
_LOGGER.error('Error encoding message to gateway')
|
https://github.com/theolind/pymysensors/blob/a139ab6e2f6b71ebaf37282f69bfd0f7fe6193b6/mysensors/message.py#L62-L74
|
html encode string
|
python
|
def encode(self, text, encoding, defaultchar='?'):
""" Encode text under the given encoding
:param text: Text to encode
:param encoding: Encoding name to use (must be defined in capabilities)
:param defaultchar: Fallback for non-encodable characters
"""
codepage_char_map = self._get_codepage_char_map(encoding)
output_bytes = bytes([self._encode_char(char, codepage_char_map, defaultchar) for char in text])
return output_bytes
|
https://github.com/python-escpos/python-escpos/blob/52719c0b7de8948fabdffd180a2d71c22cf4c02b/src/escpos/magicencode.py#L141-L150
|
html encode string
|
python
|
def html_with_encoding(self, url, timeout=None, encoding="utf-8"):
"""Manually get html with user encoding setting.
"""
response = self.get_response(url, timeout=timeout)
if response:
return self.decoder.decode(response.content, encoding)[0]
else:
return None
|
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/crawler/simplecrawler.py#L185-L192
|
html encode string
|
python
|
def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS):
"""
Converts a `html` containing an HTML page into Unicode.
Tries to guess character encoding from meta tag.
"""
if isinstance(html, unicode):
return html
if encoding:
return html.decode(encoding, errors)
match = CHARSET_META_TAG_PATTERN.search(html)
if match:
declared_encoding = match.group(1).decode("ASCII")
# proceed unknown encoding as if it wasn't found at all
with ignored(LookupError):
return html.decode(declared_encoding, errors)
# unknown encoding
try:
# try UTF-8 first
return html.decode("utf8")
except UnicodeDecodeError:
# try lucky with default encoding
try:
return html.decode(default_encoding, errors)
except UnicodeDecodeError as e:
raise JustextError("Unable to decode the HTML to Unicode: " + unicode(e))
|
https://github.com/miso-belica/jusText/blob/ad05130df2ca883f291693353f9d86e20fe94a4e/justext/core.py#L71-L98
|
html encode string
|
python
|
def _to_encoded_string(o):
"""
Build an encoded string suitable for use as a URL component. This includes double-escaping the string to
avoid issues with escaped backslash characters being automatically converted by WSGI or, in some cases
such as default Apache servers, blocked entirely.
:param o: an object of any kind, if it has an as_dict() method this will be used, otherwise uses __dict__
:return: an encoded string suitable for use as a URL component
:internal:
"""
_dict = o.__dict__
if o.as_dict:
_dict = o.as_dict()
return urllib.quote_plus(urllib.quote_plus(json.dumps(obj=_dict, separators=(',', ':'))))
|
https://github.com/camsci/meteor-pi/blob/7b01527650bd1b2b76d6f364e8122e25b8812c8d/src/pythonModules/meteorpi_client/meteorpi_client/__init__.py#L37-L50
|
html encode string
|
python
|
def encode(self):
"""
Encodes the current state of the object into a string.
:return: The encoded string
"""
opt_dict = {}
for k, v in self.options.items():
opt_dict[k] = v[0]
ss = '{0}://{1}'.format(self.scheme, ','.join(self.hosts))
if self.bucket:
ss += '/' + self.bucket
# URL encode options then decoded forward slash /
ss += '?' + urlencode(opt_dict).replace('%2F', '/')
return ss
|
https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/connstr.py#L126-L143
|
html encode string
|
python
|
def encode (self, s):
"""Encode string with output encoding."""
assert isinstance(s, unicode)
return s.encode(self.output_encoding, self.codec_errors)
|
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/__init__.py#L208-L211
|
html encode string
|
python
|
def encode(text, orig_coding):
"""
Function to encode a text.
@param text text to encode (string)
@param orig_coding type of the original coding (string)
@return encoded text and encoding
"""
if orig_coding == 'utf-8-bom':
return BOM_UTF8 + text.encode("utf-8"), 'utf-8-bom'
# Try declared coding spec
coding = get_coding(text)
if coding:
try:
return text.encode(coding), coding
except (UnicodeError, LookupError):
raise RuntimeError("Incorrect encoding (%s)" % coding)
if (orig_coding and orig_coding.endswith('-default') or
orig_coding.endswith('-guessed')):
coding = orig_coding.replace("-default", "")
coding = orig_coding.replace("-guessed", "")
try:
return text.encode(coding), coding
except (UnicodeError, LookupError):
pass
# Try saving as ASCII
try:
return text.encode('ascii'), 'ascii'
except UnicodeError:
pass
# Save as UTF-8 without BOM
return text.encode('utf-8'), 'utf-8'
|
https://github.com/spyder-ide/conda-manager/blob/89a2126cbecefc92185cf979347ccac1c5ee5d9d/conda_manager/utils/encoding.py#L151-L184
|
html encode string
|
python
|
def decode_html(html):
"""
Converts bytes stream containing an HTML page into Unicode.
Tries to guess character encoding from meta tag of by "chardet" library.
"""
if isinstance(html, unicode):
return html
match = CHARSET_META_TAG_PATTERN.search(html)
if match:
declared_encoding = match.group(1).decode("ASCII")
# proceed unknown encoding as if it wasn't found at all
with ignored(LookupError):
return html.decode(declared_encoding, "ignore")
# try to enforce UTF-8 firstly
with ignored(UnicodeDecodeError):
return html.decode("utf8")
text = TAG_MARK_PATTERN.sub(to_bytes(" "), html)
diff = text.decode("utf8", "ignore").encode("utf8")
sizes = len(diff), len(text)
# 99% of text is UTF-8
if abs(len(text) - len(diff)) < max(sizes) * 0.01:
return html.decode("utf8", "ignore")
# try detect encoding
encoding = "utf8"
encoding_detector = chardet.detect(text)
if encoding_detector["encoding"]:
encoding = encoding_detector["encoding"]
return html.decode(encoding, "ignore")
|
https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/document.py#L28-L61
|
html encode string
|
python
|
def encode(char_data, encoding='utf-8'):
"""
Encode the parameter as a byte string.
:param char_data: the data to encode
:rtype: bytes
"""
if type(char_data) is str:
return char_data.encode(encoding, errors='replace')
elif type(char_data) is bytes:
return char_data
else:
raise TypeError('message should be a string or bytes, found %s' % type(char_data))
|
https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/backward3.py#L32-L45
|
html encode string
|
python
|
def encode_non_ascii_string(string):
"""
:param string:
The string to be encoded
:type string:
unicode or str
:return:
The encoded string
:rtype:
str
"""
encoded_string = string.encode('utf-8', 'replace')
if six.PY3:
encoded_string = encoded_string.decode()
return encoded_string
|
https://github.com/box/genty/blob/85f7c960a2b67cf9e58e0d9e677e4a0bc4f05081/genty/private/__init__.py#L35-L50
|
html encode string
|
python
|
def encode(self, text):
""" 对需要加密的明文进行填充补位
@param text: 需要进行填充补位操作的明文
@return: 补齐明文字符串
"""
text_length = len(text)
# 计算需要填充的位数
amount_to_pad = self.block_size - (text_length % self.block_size)
if amount_to_pad == 0:
amount_to_pad = self.block_size
# 获得补位所用的字符
pad = chr(amount_to_pad)
return text + pad * amount_to_pad
|
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L113-L125
|
html encode string
|
python
|
def html_encode(text):
"""
Encode characters with a special meaning as HTML.
:param text: The plain text (a string).
:returns: The text converted to HTML (a string).
"""
text = text.replace('&', '&')
text = text.replace('<', '<')
text = text.replace('>', '>')
text = text.replace('"', '"')
return text
|
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/converter/__init__.py#L289-L300
|
html encode string
|
python
|
def _EncodeString(self, string):
"""Encodes the string.
Args:
string (str): string to encode.
Returns:
bytes: encoded string.
"""
try:
# Note that encode() will first convert string into a Unicode string
# if necessary.
encoded_string = string.encode(self._encoding, errors=self._errors)
except UnicodeEncodeError:
if self._errors == 'strict':
logging.error(
'Unable to properly write output due to encoding error. '
'Switching to error tolerant encoding which can result in '
'non Basic Latin (C0) characters to be replaced with "?" or '
'"\\ufffd".')
self._errors = 'replace'
encoded_string = string.encode(self._encoding, errors=self._errors)
return encoded_string
|
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/recursive_hasher.py#L160-L184
|
html encode string
|
python
|
def encode(self, text: str) -> str:
"""Encode @username into <@id> or <!alias>."""
def callback(match: Match) -> str:
name = match.group("name").lower()
if name in ["here", "everyone", "channel"]:
return f"<!{name}>"
else:
for user in self.users.values():
if user.name == name:
return f"<@{user.id}>"
return match.group(0)
return self.encode_re.sub(callback, text)
|
https://github.com/jreese/aioslack/blob/5e705f557dde9e81903d84ffb2896ec0a074ad5c/aioslack/core.py#L120-L133
|
html encode string
|
python
|
def encode(cls, s):
"""converts a plain text string to base64 encoding
:param s: unicode str|bytes, the base64 encoded string
:returns: unicode str
"""
b = ByteString(s)
be = base64.b64encode(b).strip()
return String(be)
|
https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/utils.py#L119-L127
|
html encode string
|
python
|
def encode(self, text):
r"""Perform encoding of run-length-encoding (RLE).
Parameters
----------
text : str
A text string to encode
Returns
-------
str
Word decoded by RLE
Examples
--------
>>> rle = RLE()
>>> bwt = BWT()
>>> rle.encode(bwt.encode('align'))
'n\x00ilag'
>>> rle.encode('align')
'align'
>>> rle.encode(bwt.encode('banana'))
'annb\x00aa'
>>> rle.encode('banana')
'banana'
>>> rle.encode(bwt.encode('aaabaabababa'))
'ab\x00abbab5a'
>>> rle.encode('aaabaabababa')
'3abaabababa'
"""
if text:
text = ((len(list(g)), k) for k, g in groupby(text))
text = (
(str(n) + k if n > 2 else (k if n == 1 else 2 * k))
for n, k in text
)
return ''.join(text)
|
https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/compression/_rle.py#L50-L89
|
html encode string
|
python
|
def encode_string(self, value):
"""Convert ASCII, Latin-1 or UTF-8 to pure Unicode"""
if not isinstance(value, str): return value
try:
return unicode(value, 'utf-8')
except: # really, this should throw an exception.
# in the interest of not breaking current
# systems, however:
arr = []
for ch in value:
arr.append(unichr(ord(ch)))
return u"".join(arr)
|
https://github.com/yyuu/botornado/blob/fffb056f5ff2324d1d5c1304014cfb1d899f602e/boto/sdb/db/manager/sdbmanager.py#L356-L367
|
html encode string
|
python
|
def encode(cls, value):
"""
take a valid unicode string and turn it into utf-8 bytes
:param value: unicode, str
:return: bytes
"""
coerced = unicode(value)
if coerced == value:
return coerced.encode(cls._encoding)
raise InvalidValue('not text')
|
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L139-L150
|
html encode string
|
python
|
def encode(self, splitchars=';, \t', maxlinelen=None, linesep='\n'):
r"""Encode a message header into an RFC-compliant format.
There are many issues involved in converting a given string for use in
an email header. Only certain character sets are readable in most
email clients, and as header strings can only contain a subset of
7-bit ASCII, care must be taken to properly convert and encode (with
Base64 or quoted-printable) header strings. In addition, there is a
75-character length limit on any given encoded header field, so
line-wrapping must be performed, even with double-byte character sets.
Optional maxlinelen specifies the maximum length of each generated
line, exclusive of the linesep string. Individual lines may be longer
than maxlinelen if a folding point cannot be found. The first line
will be shorter by the length of the header name plus ": " if a header
name was specified at Header construction time. The default value for
maxlinelen is determined at header construction time.
Optional splitchars is a string containing characters which should be
given extra weight by the splitting algorithm during normal header
wrapping. This is in very rough support of RFC 2822's `higher level
syntactic breaks': split points preceded by a splitchar are preferred
during line splitting, with the characters preferred in the order in
which they appear in the string. Space and tab may be included in the
string to indicate whether preference should be given to one over the
other as a split point when other split chars do not appear in the line
being split. Splitchars does not affect RFC 2047 encoded lines.
Optional linesep is a string to be used to separate the lines of
the value. The default value is the most useful for typical
Python applications, but it can be set to \r\n to produce RFC-compliant
line separators when needed.
"""
self._normalize()
if maxlinelen is None:
maxlinelen = self._maxlinelen
# A maxlinelen of 0 means don't wrap. For all practical purposes,
# choosing a huge number here accomplishes that and makes the
# _ValueFormatter algorithm much simpler.
if maxlinelen == 0:
maxlinelen = 1000000
formatter = _ValueFormatter(self._headerlen, maxlinelen,
self._continuation_ws, splitchars)
lastcs = None
hasspace = lastspace = None
for string, charset in self._chunks:
if hasspace is not None:
hasspace = string and self._nonctext(string[0])
import sys
if lastcs not in (None, 'us-ascii'):
if not hasspace or charset not in (None, 'us-ascii'):
formatter.add_transition()
elif charset not in (None, 'us-ascii') and not lastspace:
formatter.add_transition()
lastspace = string and self._nonctext(string[-1])
lastcs = charset
hasspace = False
lines = string.splitlines()
if lines:
formatter.feed('', lines[0], charset)
else:
formatter.feed('', '', charset)
for line in lines[1:]:
formatter.newline()
if charset.header_encoding is not None:
formatter.feed(self._continuation_ws, ' ' + line.lstrip(),
charset)
else:
sline = line.lstrip()
fws = line[:len(line)-len(sline)]
formatter.feed(fws, sline, charset)
if len(lines) > 1:
formatter.newline()
if self._chunks:
formatter.add_transition()
value = formatter._str(linesep)
if _embeded_header.search(value):
raise HeaderParseError("header value appears to contain "
"an embedded header: {!r}".format(value))
return value
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/header.py#L316-L395
|
html encode string
|
python
|
def encode(cls, d):
"""
Internal: encode a string for url representation
"""
warnings.warn(
'The `encode` class method of APIRequestor is deprecated and '
'will be removed in version 2.0.'
'If you need public access to this function, please email us '
'at support@stripe.com.',
DeprecationWarning)
return urllib.urlencode(list(_api_encode(d)))
|
https://github.com/lextoumbourou/txstripe/blob/a69e67f524258026fd1840655a0578311bba3b89/stripe/api_requestor.py#L115-L125
|
html encode string
|
python
|
def encode(self, txt):
'''Encode a text string by replacing characters with alphabet index.
Parameters
----------
txt : str
A string to encode.
Returns
-------
classes : list of int
A sequence of alphabet index values corresponding to the given text.
'''
return list(self._fwd_index.get(c, 0) for c in txt)
|
https://github.com/lmjohns3/theanets/blob/79db9f878ef2071f2f576a1cf5d43a752a55894a/theanets/recurrent.py#L97-L110
|
html encode string
|
python
|
def encode(cls, command):
"""Encode a command as an unambiguous string.
Args:
command (Command): The command to encode.
Returns:
str: The encoded command
"""
args = []
for arg in command.args:
if not isinstance(arg, str):
arg = str(arg)
if "," in arg or arg.startswith(" ") or arg.endswith(" ") or arg.startswith("hex:"):
arg = "hex:{}".format(hexlify(arg.encode('utf-8')).decode('utf-8'))
args.append(arg)
argstr = ""
if len(args) > 0:
argstr = " {" + ",".join(args) + "}"
return command.name + argstr
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilecore/iotile/core/utilities/command_file.py#L128-L153
|
html encode string
|
python
|
def encode_character(char):
"""Returns URL encoding for a single character
:param char (str) Single character to encode
:returns (str) URL-encoded character
"""
if char == '!': return '%21'
elif char == '"': return '%22'
elif char == '#': return '%23'
elif char == '$': return '%24'
elif char == '%': return '%25'
elif char == '&': return '%26'
elif char == '\'': return '%27'
elif char == '(': return '%28'
elif char == ')': return '%29'
elif char == '*': return '%2A'
elif char == '+': return '%2B'
elif char == ',': return '%2C'
elif char == '-': return '%2D'
elif char == '.': return '%2E'
elif char == '/': return '%2F'
elif char == ':': return '%3A'
elif char == ';': return '%3B'
elif char == '<': return '%3C'
elif char == '=': return '%3D'
elif char == '>': return '%3E'
elif char == '?': return '%3F'
elif char == '@': return '%40'
elif char == '[': return '%5B'
elif char == '\\': return '%5C'
elif char == ']': return '%5D'
elif char == '^': return '%5E'
elif char == '_': return '%5F'
elif char == '`': return '%60'
elif char == '{': return '%7B'
elif char == '|': return '%7C'
elif char == '}': return '%7D'
elif char == '~': return '%7E'
elif char == ' ': return '%7F'
else: return char
|
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L152-L191
|
html encode string
|
python
|
def encode_password(password):
"""Performs URL encoding for passwords
:param password: (str) password to encode
:return: (str) encoded password
"""
log = logging.getLogger(mod_logger + '.password_encoder')
log.debug('Encoding password: {p}'.format(p=password))
encoded_password = ''
for c in password:
encoded_password += encode_character(char=c)
log.debug('Encoded password: {p}'.format(p=encoded_password))
return encoded_password
|
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/pygit.py#L137-L149
|
html encode string
|
python
|
def encode(in_bytes):
"""Encode a string using Consistent Overhead Byte Stuffing/Reduced (COBS/R).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string may be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01'"""
out_bytes = []
idx = 0
search_start_idx = 0
for in_char in in_bytes:
if idx - search_start_idx == 0xFE:
out_bytes.append('\xFF')
out_bytes.append(in_bytes[search_start_idx:idx])
search_start_idx = idx
if in_char == '\x00':
out_bytes.append(chr(idx - search_start_idx + 1))
out_bytes.append(in_bytes[search_start_idx:idx])
search_start_idx = idx + 1
idx += 1
try:
final_byte = in_bytes[-1]
except IndexError:
final_byte = '\x00'
length_value = idx - search_start_idx + 1
if ord(final_byte) < length_value:
# Encoding same as plain COBS
out_bytes.append(chr(length_value))
out_bytes.append(in_bytes[search_start_idx:idx])
else:
# Special COBS/R encoding: length code is final byte,
# and final byte is removed from data sequence.
out_bytes.append(final_byte)
out_bytes.append(in_bytes[search_start_idx:idx - 1])
return ''.join(out_bytes)
|
https://github.com/cmcqueen/cobs-python/blob/ec4ce301e5574c9b6e72bfb485c116bdbffe0769/python2/cobs/cobsr/_cobsr_py.py#L12-L48
|
html encode string
|
python
|
def encode_string(v, encoding="utf-8"):
"""Returns the given value as a Python byte string (if possible)."""
if isinstance(encoding, basestring):
encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore"))
if isinstance(v, unicode):
for e in encoding:
try:
return v.encode(*e)
except:
pass
return v
return str(v)
|
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/compat.py#L126-L137
|
html encode string
|
python
|
def encode(cls, text):
"""
对需要加密的明文进行填充补位
@param text: 需要进行填充补位操作的明文
@return: 补齐明文字符串
"""
text_length = len(text)
# 计算需要填充的位数
amount_to_pad = cls.block_size - (text_length % cls.block_size)
if amount_to_pad == 0:
amount_to_pad = cls.block_size
# 获得补位所用的字符
pad = to_binary(chr(amount_to_pad))
return text + pad * amount_to_pad
|
https://github.com/doraemonext/wechat-python-sdk/blob/bf6f6f3d4a5440feb73a51937059d7feddc335a0/wechat_sdk/lib/crypto/pkcs7.py#L11-L24
|
html encode string
|
python
|
def encode(char_data, encoding='utf-8'):
"""
Encode the parameter as a byte string.
:param char_data:
:rtype: bytes
"""
if type(char_data) is unicode:
return char_data.encode(encoding, 'replace')
else:
return char_data
|
https://github.com/jasonrbriggs/stomp.py/blob/643843c5fbf25fd24339dd0e69a9411c3d8b94c7/stomp/backward2.py#L28-L39
|
html encode string
|
python
|
def encode(string, encoding=None, errors=None):
"""Encode to specified encoding.
``encoding`` defaults to the preferred encoding.
``errors`` defaults to the preferred error handler.
"""
if encoding is None:
encoding = getpreferredencoding()
if errors is None:
errors = getpreferrederrors()
return string.encode(encoding, errors)
|
https://github.com/Jarn/jarn.mkrelease/blob/844377f37a3cdc0a154148790a926f991019ec4a/jarn/mkrelease/utils.py#L73-L83
|
html encode string
|
python
|
def encode(string, charset='utf-8', encoding=None, lang=''):
"""Encode string using the CTE encoding that produces the shorter result.
Produces an RFC 2047/2243 encoded word of the form:
=?charset*lang?cte?encoded_string?=
where '*lang' is omitted unless the 'lang' parameter is given a value.
Optional argument charset (defaults to utf-8) specifies the charset to use
to encode the string to binary before CTE encoding it. Optional argument
'encoding' is the cte specifier for the encoding that should be used ('q'
or 'b'); if it is None (the default) the encoding which produces the
shortest encoded sequence is used, except that 'q' is preferred if it is up
to five characters longer. Optional argument 'lang' (default '') gives the
RFC 2243 language string to specify in the encoded word.
"""
string = str(string)
if charset == 'unknown-8bit':
bstring = string.encode('ascii', 'surrogateescape')
else:
bstring = string.encode(charset)
if encoding is None:
qlen = _cte_encode_length['q'](bstring)
blen = _cte_encode_length['b'](bstring)
# Bias toward q. 5 is arbitrary.
encoding = 'q' if qlen - blen < 5 else 'b'
encoded = _cte_encoders[encoding](bstring)
if lang:
lang = '*' + lang
return "=?{0}{1}?{2}?{3}?=".format(charset, lang, encoding, encoded)
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_encoded_words.py#L202-L232
|
html encode string
|
python
|
def encode(cls, value):
"""
take a list of strings and turn it into utf-8 byte-string
:param value:
:return:
"""
coerced = unicode(value)
if coerced == value and cls.PATTERN.match(coerced):
return coerced.encode(cls._encoding)
raise InvalidValue('not ascii')
|
https://github.com/72squared/redpipe/blob/e6ee518bc9f3e2fee323c8c53d08997799bd9b1b/redpipe/fields.py#L170-L181
|
html encode string
|
python
|
def encode(encoding, data):
"""
Encodes the given data using the encoding that is specified
:param str encoding: encoding to use, should be one of the supported encoding
:param data: data to encode
:type data: str or bytes
:return: multibase encoded data
:rtype: bytes
:raises ValueError: if the encoding is not supported
"""
data = ensure_bytes(data, 'utf8')
try:
return ENCODINGS_LOOKUP[encoding].code + ENCODINGS_LOOKUP[encoding].converter.encode(data)
except KeyError:
raise ValueError('Encoding {} not supported.'.format(encoding))
|
https://github.com/multiformats/py-multibase/blob/8f435762b50a17f921c13b59eb0c7b9c52afc879/multibase/multibase.py#L32-L47
|
html encode string
|
python
|
def encode(cls, string, errors='strict'):
"""Return the encoded version of a string.
:param string:
The input string to encode.
:type string:
`basestring`
:param errors:
The error handling scheme. Only 'strict' is supported.
:type errors:
`basestring`
:return:
Tuple of encoded string and number of input bytes consumed.
:rtype:
`tuple` (`unicode`, `int`)
"""
if errors != 'strict':
raise UnicodeError('Unsupported error handling {0}'.format(errors))
unicode_string = cls._ensure_unicode_string(string)
encoded = unicode_string.translate(cls._encoding_table)
return encoded, len(string)
|
https://github.com/box/rotunicode/blob/6149b6bb5bb50d322db248acfdb910dc3cb1bcc2/rotunicode/rotunicode.py#L50-L73
|
html encode string
|
python
|
def handle_encodnig(html):
"""
Look for encoding in given `html`. Try to convert `html` to utf-8.
Args:
html (str): HTML code as string.
Returns:
str: HTML code encoded in UTF.
"""
encoding = _get_encoding(
dhtmlparser.parseString(
html.split("</head>")[0]
)
)
if encoding == "utf-8":
return html
return html.decode(encoding).encode("utf-8")
|
https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/scrappers/zonerpress_cz/zonerpress_api.py#L66-L85
|
html encode string
|
python
|
def encode(val):
"""
Encode a string assuming the encoding is UTF-8.
:param: a unicode or bytes object
:returns: bytes
"""
if isinstance(val, (list, tuple)): # encode a list or tuple of strings
return [encode(v) for v in val]
elif isinstance(val, str):
return val.encode('utf-8')
else:
# assume it was an already encoded object
return val
|
https://github.com/gem/oq-engine/blob/8294553a0b8aba33fd96437a35065d03547d0040/openquake/baselib/python3compat.py#L28-L41
|
html encode string
|
python
|
def tostring(doc, pretty_print=False, include_meta_content_type=False,
encoding=None, method="html", with_tail=True, doctype=None):
"""Return an HTML string representation of the document.
Note: if include_meta_content_type is true this will create a
``<meta http-equiv="Content-Type" ...>`` tag in the head;
regardless of the value of include_meta_content_type any existing
``<meta http-equiv="Content-Type" ...>`` tag will be removed
The ``encoding`` argument controls the output encoding (defauts to
ASCII, with &#...; character references for any characters outside
of ASCII). Note that you can pass the name ``'unicode'`` as
``encoding`` argument to serialise to a Unicode string.
The ``method`` argument defines the output method. It defaults to
'html', but can also be 'xml' for xhtml output, or 'text' to
serialise to plain text without markup.
To leave out the tail text of the top-level element that is being
serialised, pass ``with_tail=False``.
The ``doctype`` option allows passing in a plain string that will
be serialised before the XML tree. Note that passing in non
well-formed content here will make the XML output non well-formed.
Also, an existing doctype in the document tree will not be removed
when serialising an ElementTree instance.
Example::
>>> from lxml import html
>>> root = html.fragment_fromstring('<p>Hello<br>world!</p>')
>>> html.tostring(root)
b'<p>Hello<br>world!</p>'
>>> html.tostring(root, method='html')
b'<p>Hello<br>world!</p>'
>>> html.tostring(root, method='xml')
b'<p>Hello<br/>world!</p>'
>>> html.tostring(root, method='text')
b'Helloworld!'
>>> html.tostring(root, method='text', encoding='unicode')
u'Helloworld!'
>>> root = html.fragment_fromstring('<div><p>Hello<br>world!</p>TAIL</div>')
>>> html.tostring(root[0], method='text', encoding='unicode')
u'Helloworld!TAIL'
>>> html.tostring(root[0], method='text', encoding='unicode', with_tail=False)
u'Helloworld!'
>>> doc = html.document_fromstring('<p>Hello<br>world!</p>')
>>> html.tostring(doc, method='html', encoding='unicode')
u'<html><body><p>Hello<br>world!</p></body></html>'
>>> print(html.tostring(doc, method='html', encoding='unicode',
... doctype='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'
... ' "http://www.w3.org/TR/html4/strict.dtd">'))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html><body><p>Hello<br>world!</p></body></html>
"""
html = etree.tostring(doc, method=method, pretty_print=pretty_print,
encoding=encoding, with_tail=with_tail,
doctype=doctype)
if method == 'html' and not include_meta_content_type:
if isinstance(html, str):
html = __str_replace_meta_content_type('', html)
else:
html = __bytes_replace_meta_content_type(bytes(), html)
return html
|
https://github.com/AkihikoITOH/capybara/blob/e86c2173ea386654f4ae061148e8fbe3f25e715c/capybara/virtualenv/lib/python2.7/site-packages/lxml/html/__init__.py#L1578-L1649
|
html encode string
|
python
|
def enc(x, codec='ascii'):
"""Encodes a string for SGML/XML/HTML"""
x = x.replace('&', '&').replace('>', '>').replace('<', '<').replace('"', '"')
return x.encode(codec, 'xmlcharrefreplace')
|
https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L232-L235
|
html encode string
|
python
|
def encode (text):
"""Encode text with default encoding if its Unicode."""
if isinstance(text, unicode):
return text.encode(i18n.default_encoding, 'ignore')
return text
|
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/director/console.py#L31-L35
|
html encode string
|
python
|
def json(a):
"""
Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filter.
"""
json_str = json_dumps(a)
# Escape all the XML/HTML special characters.
escapes = ['<', '>', '&']
for c in escapes:
json_str = json_str.replace(c, r'\u%04x' % ord(c))
# now it's safe to use mark_safe
return mark_safe(json_str)
|
https://github.com/fusionbox/django-argonauts/blob/0f64f9700199e8c70a1cb9a055b8e31f6843933d/argonauts/templatetags/argonauts.py#L12-L31
|
html encode string
|
python
|
def decode_text(s):
"""Decodes a PDFDocEncoding string to Unicode."""
if s.startswith(b'\xfe\xff'):
return unicode(s[2:], 'utf-16be', 'ignore')
else:
return ''.join(PDFDocEncoding[ord(c)] for c in s)
|
https://github.com/euske/pdfminer/blob/8150458718e9024c80b00e74965510b20206e588/pdfminer/utils.py#L223-L228
|
html encode string
|
python
|
def encode(data, mime_type='', charset='utf-8', base64=True):
"""
Encode data to DataURL
"""
if isinstance(data, six.text_type):
data = data.encode(charset)
else:
charset = None
if base64:
data = utils.text(b64encode(data))
else:
data = utils.text(quote(data))
result = ['data:', ]
if mime_type:
result.append(mime_type)
if charset:
result.append(';charset=')
result.append(charset)
if base64:
result.append(';base64')
result.append(',')
result.append(data)
return ''.join(result)
|
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/dataurl.py#L14-L38
|
html encode string
|
python
|
def xml_decode(string):
""" Returns the string with special characters decoded.
"""
string = string.replace("&", "&")
string = string.replace("<", "<")
string = string.replace(">", ">")
string = string.replace(""","\"")
string = string.replace("/", SLASH)
return string
|
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/tree.py#L1263-L1271
|
html encode string
|
python
|
def text(self):
"""Decode content as a string.
"""
data = self.content
return data.decode(self.encoding or 'utf-8') if data else ''
|
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L565-L569
|
html encode string
|
python
|
def encode(self, boundary):
"""Returns the string encoding of this parameter"""
if self.value is None:
value = self.fileobj.read()
else:
value = self.value
if re.search("^--%s$" % re.escape(boundary), value, re.M):
raise ValueError("boundary found in encoded string")
return "%s%s\r\n" % (self.encode_hdr(boundary), value)
|
https://github.com/podio/podio-py/blob/5ce956034a06c98b0ef18fcd940b36da0908ad6c/pypodio2/encode.py#L221-L231
|
html encode string
|
python
|
def encode_7or8bit(msg):
"""Set the Content-Transfer-Encoding header to 7bit or 8bit."""
orig = msg.get_payload()
if orig is None:
# There's no payload. For backwards compatibility we use 7bit
msg['Content-Transfer-Encoding'] = '7bit'
return
# We play a trick to make this go fast. If encoding/decode to ASCII
# succeeds, we know the data must be 7bit, otherwise treat it as 8bit.
try:
if isinstance(orig, str):
orig.encode('ascii')
else:
orig.decode('ascii')
except UnicodeError:
charset = msg.get_charset()
output_cset = charset and charset.output_charset
# iso-2022-* is non-ASCII but encodes to a 7-bit representation
if output_cset and output_cset.lower().startswith('iso-2022-'):
msg['Content-Transfer-Encoding'] = '7bit'
else:
msg['Content-Transfer-Encoding'] = '8bit'
else:
msg['Content-Transfer-Encoding'] = '7bit'
if not isinstance(orig, str):
msg.set_payload(orig.decode('ascii', 'surrogateescape'))
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/encoders.py#L55-L80
|
html encode string
|
python
|
def decode(self, binary, url, encoding=None, errors="strict"):
"""
Decode binary to string.
:param binary: binary content of a http request.
:param url: endpoint of the request.
:param encoding: manually specify the encoding.
:param errors: errors handle method.
:return: str
"""
if encoding is None:
domain = util.get_domain(url)
if domain in self.domain_encoding_table:
encoding = self.domain_encoding_table[domain]
html = binary.decode(encoding, errors=errors)
else:
html, encoding, confidence = smart_decode(
binary, errors=errors)
# cache domain name and encoding
self.domain_encoding_table[domain] = encoding
else:
html = binary.decode(encoding, errors=errors)
return html
|
https://github.com/MacHu-GWU/crawlib-project/blob/241516f2a7a0a32c692f7af35a1f44064e8ce1ab/crawlib/decode.py#L49-L73
|
html encode string
|
python
|
def encoding(self):
"""
encoding of Response.content.
if Response.encoding is None, encoding will be guessed
by header or content or chardet if available.
"""
if hasattr(self, '_encoding'):
return self._encoding
# content is unicode
if isinstance(self.content, six.text_type):
return 'unicode'
# Try charset from content-type or content
encoding = get_encoding(self.headers, self.content)
# Fallback to auto-detected encoding.
if not encoding and chardet is not None:
encoding = chardet.detect(self.content[:600])['encoding']
if encoding and encoding.lower() == 'gb2312':
encoding = 'gb18030'
self._encoding = encoding or 'utf-8'
return self._encoding
|
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/response.py#L61-L86
|
html encode string
|
python
|
def encode(self, data, content_encoding="aes128gcm"):
"""Encrypt the data.
:param data: A serialized block of byte data (String, JSON, bit array,
etc.) Make sure that whatever you send, your client knows how
to understand it.
:type data: str
:param content_encoding: The content_encoding type to use to encrypt
the data. Defaults to RFC8188 "aes128gcm". The previous draft-01 is
"aesgcm", however this format is now deprecated.
:type content_encoding: enum("aesgcm", "aes128gcm")
"""
# Salt is a random 16 byte array.
if not data:
return
if not self.auth_key or not self.receiver_key:
raise WebPushException("No keys specified in subscription info")
salt = None
if content_encoding not in self.valid_encodings:
raise WebPushException("Invalid content encoding specified. "
"Select from " +
json.dumps(self.valid_encodings))
if content_encoding == "aesgcm":
salt = os.urandom(16)
# The server key is an ephemeral ECDH key used only for this
# transaction
server_key = ec.generate_private_key(ec.SECP256R1, default_backend())
crypto_key = server_key.public_key().public_bytes(
encoding=serialization.Encoding.X962,
format=serialization.PublicFormat.UncompressedPoint
)
if isinstance(data, six.string_types):
data = bytes(data.encode('utf8'))
if content_encoding == "aes128gcm":
encrypted = http_ece.encrypt(
data,
salt=salt,
private_key=server_key,
dh=self.receiver_key,
auth_secret=self.auth_key,
version=content_encoding)
reply = CaseInsensitiveDict({
'body': encrypted
})
else:
crypto_key = base64.urlsafe_b64encode(crypto_key).strip(b'=')
encrypted = http_ece.encrypt(
data,
salt=salt,
private_key=server_key,
keyid=crypto_key.decode(),
dh=self.receiver_key,
auth_secret=self.auth_key,
version=content_encoding)
reply = CaseInsensitiveDict({
'crypto_key': crypto_key,
'body': encrypted,
})
if salt:
reply['salt'] = base64.urlsafe_b64encode(salt).strip(b'=')
return reply
|
https://github.com/web-push-libs/pywebpush/blob/2a23f45b7819e31bd030de9fe1357a1cf7dcfdc4/pywebpush/__init__.py#L162-L224
|
html encode string
|
python
|
def unicode_from_html(content):
"""Attempts to decode an HTML string into unicode.
If unsuccessful, the original content is returned.
"""
encodings = get_encodings_from_content(content)
for encoding in encodings:
try:
return unicode(content, encoding)
except (UnicodeError, TypeError):
pass
return content
|
https://github.com/bububa/pyTOP/blob/1e48009bcfe886be392628244b370e6374e1f2b2/pyTOP/packages/requests/utils.py#L279-L293
|
html encode string
|
python
|
def encode(self, tags, encoding, values_to_sub):
"""
reads the encoding type from the event-mapping.json
and determines whether a value needs encoding
Parameters
----------
tags: dict
the values of a particular event that can be substituted
within the event json
encoding: string
string that helps navigate to the encoding field of the json
values_to_sub: dict
key/value pairs that will be substituted into the json
Returns
-------
values_to_sub: dict
the encoded (if need be) values to substitute into the json.
"""
for tag in tags:
if tags[tag].get(encoding) != "None":
if tags[tag].get(encoding) == "url":
values_to_sub[tag] = self.url_encode(values_to_sub[tag])
if tags[tag].get(encoding) == "base64":
values_to_sub[tag] = self.base64_utf_encode(values_to_sub[tag])
return values_to_sub
|
https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/generated_sample_events/events.py#L36-L62
|
html encode string
|
python
|
def encode_str(data: str, encoding: str = DEFAULT_CODING, errors: str = 'strict') -> bytes:
"""
集中调用 encode
"""
return data.encode(encoding, errors)
|
https://github.com/zeromake/aiko/blob/53b246fa88652466a9e38ac3d1a99a6198195b0f/aiko/utils.py#L38-L42
|
html encode string
|
python
|
def encode(input, encoding=UTF8, errors='strict'):
"""
Encode a single string.
:param input: An Unicode string.
:param encoding: An :class:`Encoding` object or a label string.
:param errors: Type of error handling. See :func:`codecs.register`.
:raises: :exc:`~exceptions.LookupError` for an unknown encoding label.
:return: A byte string.
"""
return _get_encoding(encoding).codec_info.encode(input, errors)[0]
|
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/webencodings/__init__.py#L172-L183
|
html encode string
|
python
|
def encode(strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ''
for string in strs.split():
res += str(len(string)) + ":" + string
return res
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/encode_decode.py#L8-L16
|
html encode string
|
python
|
def encode(in_bytes):
"""Encode a string using Consistent Overhead Byte Stuffing/Reduced (COBS/R).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string may be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01'"""
if isinstance(in_bytes, str):
raise TypeError('Unicode-objects must be encoded as bytes first')
in_bytes_mv = _get_buffer_view(in_bytes)
out_bytes = bytearray()
idx = 0
search_start_idx = 0
for in_char in in_bytes_mv:
if idx - search_start_idx == 0xFE:
out_bytes.append(0xFF)
out_bytes += in_bytes_mv[search_start_idx:idx]
search_start_idx = idx
if in_char == b'\x00':
out_bytes.append(idx - search_start_idx + 1)
out_bytes += in_bytes_mv[search_start_idx:idx]
search_start_idx = idx + 1
idx += 1
try:
final_byte_value = ord(in_bytes_mv[-1])
except IndexError:
final_byte_value = 0
length_value = idx - search_start_idx + 1
if final_byte_value < length_value:
# Encoding same as plain COBS
out_bytes.append(length_value)
out_bytes += in_bytes_mv[search_start_idx:idx]
else:
# Special COBS/R encoding: length code is final byte,
# and final byte is removed from data sequence.
out_bytes.append(final_byte_value)
out_bytes += in_bytes_mv[search_start_idx:idx - 1]
return bytes(out_bytes)
|
https://github.com/cmcqueen/cobs-python/blob/ec4ce301e5574c9b6e72bfb485c116bdbffe0769/python3/cobs/cobsr/_cobsr_py.py#L22-L61
|
html encode string
|
python
|
def set_encoding (parsobj, attrs):
"""
Set document encoding for the HTML parser according to the <meta>
tag attribute information.
@param attrs: attributes of a <meta> HTML tag
@type attrs: dict
@return: None
"""
charset = attrs.get_true('charset', u'')
if charset:
# <meta charset="utf-8">
# eg. in http://cn.dolphin-browser.com/activity/Dolphinjump
charset = charset.encode('ascii', 'ignore').lower()
elif attrs.get_true('http-equiv', u'').lower() == u"content-type":
# <meta http-equiv="content-type" content="text/html;charset="utf-8">
charset = attrs.get_true('content', u'')
charset = charset.encode('ascii', 'ignore').lower()
charset = get_ctype_charset(charset)
if charset and charset in SUPPORTED_CHARSETS:
parsobj.encoding = charset
|
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/HtmlParser/__init__.py#L218-L238
|
html encode string
|
python
|
def encode_str(s, mutable=False):
"""Encodes a SemaphoreStr"""
rv = ffi.new("SemaphoreStr *")
if isinstance(s, text_type):
s = s.encode("utf-8")
if mutable:
s = bytearray(s)
rv.data = ffi.from_buffer(s)
rv.len = len(s)
# we have to hold a weak reference here to ensure our string does not
# get collected before the string is used.
attached_refs[rv] = s
return rv
|
https://github.com/getsentry/semaphore/blob/6f260b4092261e893b4debd9a3a7a78232f46c5e/py/semaphore/utils.py#L80-L92
|
html encode string
|
python
|
def _EncodeString(self, string):
"""Encodes a string in the preferred encoding.
Returns:
bytes: encoded string.
"""
try:
# Note that encode() will first convert string into a Unicode string
# if necessary.
encoded_string = string.encode(
self.preferred_encoding, errors=self._encode_errors)
except UnicodeEncodeError:
if self._encode_errors == 'strict':
logger.error(
'Unable to properly write output due to encoding error. '
'Switching to error tolerant encoding which can result in '
'non Basic Latin (C0) characters to be replaced with "?" or '
'"\\ufffd".')
self._encode_errors = 'replace'
encoded_string = string.encode(
self.preferred_encoding, errors=self._encode_errors)
return encoded_string
|
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/cli/tools.py#L86-L109
|
html encode string
|
python
|
def encode(self, text):
"""Encode a text using arithmetic coding.
Text and the 0-order probability statistics -> longval, nbits
The encoded number is Fraction(longval, 2**nbits)
Parameters
----------
text : str
A string to encode
Returns
-------
tuple
The arithmetically coded text
Example
-------
>>> ac = Arithmetic('the quick brown fox jumped over the lazy dog')
>>> ac.encode('align')
(16720586181, 34)
"""
text = text_type(text)
if '\x00' in text:
text = text.replace('\x00', ' ')
minval = Fraction(0)
maxval = Fraction(1)
for char in text + '\x00':
prob_range = self._probs[char]
delta = maxval - minval
maxval = minval + prob_range[1] * delta
minval = minval + prob_range[0] * delta
# I tried without the /2 just to check. Doesn't work.
# Keep scaling up until the error range is >= 1. That
# gives me the minimum number of bits needed to resolve
# down to the end-of-data character.
delta = (maxval - minval) / 2
nbits = long(0)
while delta < 1:
nbits += 1
delta *= 2
# The below condition shouldn't ever be false
if nbits == 0: # pragma: no cover
return 0, 0
# using -1 instead of /2
avg = (maxval + minval) * 2 ** (nbits - 1)
# Could return a rational instead ...
# the division truncation is deliberate
return avg.numerator // avg.denominator, nbits
|
https://github.com/chrislit/abydos/blob/165466b3ff6afd8024a4c8660421b0c4e7773db9/abydos/compression/_arithmetic.py#L150-L202
|
html encode string
|
python
|
def encode(self) -> str:
"""Encode credentials."""
creds = ('%s:%s' % (self.login, self.password)).encode(self.encoding)
return 'Basic %s' % base64.b64encode(creds).decode(self.encoding)
|
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/helpers.py#L172-L175
|
html encode string
|
python
|
def encodeGsm7(plaintext, discardInvalid=False):
""" GSM-7 text encoding algorithm
Encodes the specified text string into GSM-7 octets (characters). This method does not pack
the characters into septets.
:param text: the text string to encode
:param discardInvalid: if True, characters that cannot be encoded will be silently discarded
:raise ValueError: if the text string cannot be encoded using GSM-7 encoding (unless discardInvalid == True)
:return: A bytearray containing the string encoded in GSM-7 encoding
:rtype: bytearray
"""
result = bytearray()
if PYTHON_VERSION >= 3:
plaintext = str(plaintext)
for char in plaintext:
idx = GSM7_BASIC.find(char)
if idx != -1:
result.append(idx)
elif char in GSM7_EXTENDED:
result.append(0x1B) # ESC - switch to extended table
result.append(ord(GSM7_EXTENDED[char]))
elif not discardInvalid:
raise ValueError('Cannot encode char "{0}" using GSM-7 encoding'.format(char))
return result
|
https://github.com/faucamp/python-gsmmodem/blob/834c68b1387ca2c91e2210faa8f75526b39723b5/gsmmodem/pdu.py#L660-L686
|
html encode string
|
python
|
def decode(text):
"""
Function to decode a text.
@param text text to decode (string)
@return decoded text and encoding
"""
try:
if text.startswith(BOM_UTF8):
# UTF-8 with BOM
return to_text_string(text[len(BOM_UTF8):], 'utf-8'), 'utf-8-bom'
elif text.startswith(BOM_UTF16):
# UTF-16 with BOM
return to_text_string(text[len(BOM_UTF16):], 'utf-16'), 'utf-16'
elif text.startswith(BOM_UTF32):
# UTF-32 with BOM
return to_text_string(text[len(BOM_UTF32):], 'utf-32'), 'utf-32'
coding = get_coding(text)
if coding:
return to_text_string(text, coding), coding
except (UnicodeError, LookupError):
pass
# Assume UTF-8
try:
return to_text_string(text, 'utf-8'), 'utf-8-guessed'
except (UnicodeError, LookupError):
pass
# Assume Latin-1 (behaviour before 3.7.1)
return to_text_string(text, "latin-1"), 'latin-1-guessed'
|
https://github.com/spyder-ide/spyder/blob/f76836ce1b924bcc4efd3f74f2960d26a4e528e0/spyder/utils/encoding.py#L142-L169
|
html encode string
|
python
|
def _EncodeString(self, string):
"""Encodes a string in the preferred encoding.
Returns:
bytes: encoded string.
"""
try:
# Note that encode() will first convert string into a Unicode string
# if necessary.
encoded_string = string.encode(
self._preferred_encoding, errors=self._encode_errors)
except UnicodeEncodeError:
if self._encode_errors == 'strict':
logging.error(
'Unable to properly write output due to encoding error. '
'Switching to error tolerant encoding which can result in '
'non Basic Latin (C0) characters to be replaced with "?" or '
'"\\ufffd".')
self._encode_errors = 'replace'
encoded_string = string.encode(
self._preferred_encoding, errors=self._encode_errors)
return encoded_string
|
https://github.com/log2timeline/dfvfs/blob/2b3ccd115f9901d89f383397d4a1376a873c83c4/examples/source_analyzer.py#L39-L62
|
html encode string
|
python
|
def encode(self):
"""The bytes representation of this :class:`HttpRequest`.
Called by :class:`HttpResponse` when it needs to encode this
:class:`HttpRequest` before sending it to the HTTP resource.
"""
# Call body before fist_line in case the query is changes.
first_line = self.first_line()
if self.body and self.wait_continue:
self.headers['expect'] = '100-continue'
headers = self.headers
if self.unredirected_headers:
headers = self.unredirected_headers.copy()
headers.update(self.headers)
buffer = [first_line.encode('ascii'), b'\r\n']
buffer.extend((('%s: %s\r\n' % (name, value)).encode(CHARSET)
for name, value in headers.items()))
buffer.append(b'\r\n')
return b''.join(buffer)
|
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/client.py#L296-L314
|
html encode string
|
python
|
def xhtml_escape(value: Union[str, bytes]) -> str:
"""Escapes a string so it is valid within HTML or XML.
Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``.
When used in attribute values the escaped strings must be enclosed
in quotes.
.. versionchanged:: 3.2
Added the single quote to the list of escaped characters.
"""
return _XHTML_ESCAPE_RE.sub(
lambda match: _XHTML_ESCAPE_DICT[match.group(0)], to_basestring(value)
)
|
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/escape.py#L43-L56
|
html encode string
|
python
|
def encode(request, data):
""" Add request content data to request body, set Content-type header.
Should be overridden by subclasses if not using JSON encoding.
Args:
request (HTTPRequest): The request object.
data (dict, None): Data to be encoded.
Returns:
HTTPRequest: The request object.
"""
if data is None:
return request
request.add_header('Content-Type', 'application/json')
request.data = json.dumps(data)
return request
|
https://github.com/hirmeos/entity-fishing-client-python/blob/cd5c6e10c6c4e653669e11d735d5773766986bda/nerd/client.py#L45-L63
|
html encode string
|
python
|
def ASCII_encoding(self):
"""Returns the ASCII encoding of a string"""
w = unicodedata.normalize('NFKD', self.word).encode('ASCII',
'ignore') # Encode into ASCII, returns a bytestring
w = w.decode('utf-8') # Convert back to string
return w
|
https://github.com/cltk/cltk/blob/ed9c025b7ec43c949481173251b70e05e4dffd27/cltk/phonology/middle_high_german/transcription.py#L272-L279
|
html encode string
|
python
|
def decode_string(v, encoding="utf-8"):
"""Returns the given value as a Unicode string (if possible)."""
if isinstance(encoding, basestring):
encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore"))
if isinstance(v, binary_type):
for e in encoding:
try:
return v.decode(*e)
except:
pass
return v
return unicode(v)
|
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/compat.py#L112-L123
|
html encode string
|
python
|
def encodeQueryElement(element):
"""Encode a URL query element according to RFC3986."""
return urllib.parse.quote(
(
element.encode('utf-8')
if isinstance(element, str)
else str(element)
if isinstance(element, int)
else element
),
safe=d1_common.const.URL_QUERYELEMENT_SAFE_CHARS,
)
|
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/lib_common/src/d1_common/url.py#L78-L89
|
html encode string
|
python
|
async def text(self,
encoding: Optional[str]=None, errors: str='strict') -> str:
"""Read response payload and decode."""
if self._body is None:
await self.read()
if encoding is None:
encoding = self.get_encoding()
return self._body.decode(encoding, errors=errors)
|
https://github.com/aio-libs/aiohttp/blob/9504fe2affaaff673fa4f3754c1c44221f8ba47d/aiohttp/client_reqrep.py#L956-L965
|
html encode string
|
python
|
def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
"""
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
encoded = self.encode_numeric()
elif self.mode == tables.modes['binary']:
encoded = self.encode_bytes()
elif self.mode == tables.modes['kanji']:
encoded = self.encode_kanji()
return encoded
|
https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L146-L158
|
html encode string
|
python
|
def encode_filename(filename, from_encoding='utf-8', to_encoding=None):
"""
>>> print encode_filename('\xe4\xb8\xad\xe5\x9b\xbd.doc')
\xd6\xd0\xb9\xfa.doc
>>> f = unicode('\xe4\xb8\xad\xe5\x9b\xbd.doc', 'utf-8')
>>> print encode_filename(f)
\xd6\xd0\xb9\xfa.doc
>>> print encode_filename(f.encode('gbk'), 'gbk')
\xd6\xd0\xb9\xfa.doc
>>> print encode_filename(f, 'gbk', 'utf-8')
\xe4\xb8\xad\xe5\x9b\xbd.doc
>>> print encode_filename('\xe4\xb8\xad\xe5\x9b\xbd.doc', 'utf-8', 'gbk')
\xd6\xd0\xb9\xfa.doc
"""
import sys
to_encoding = to_encoding or sys.getfilesystemencoding()
from_encoding = from_encoding or sys.getfilesystemencoding()
if not isinstance(filename, unicode):
try:
f = unicode(filename, from_encoding)
except UnicodeDecodeError:
try:
f = unicode(filename, 'utf-8')
except UnicodeDecodeError:
raise Exception, "Unknown encoding of the filename %s" % filename
filename = f
if to_encoding:
return filename.encode(to_encoding)
else:
return filename
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/files.py#L42-L72
|
html encode string
|
python
|
def encode(in_bytes):
"""Encode a string using Consistent Overhead Byte Stuffing (COBS).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string will be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01'"""
final_zero = True
out_bytes = []
idx = 0
search_start_idx = 0
for in_char in in_bytes:
if in_char == '\x00':
final_zero = True
out_bytes.append(chr(idx - search_start_idx + 1))
out_bytes.append(in_bytes[search_start_idx:idx])
search_start_idx = idx + 1
else:
if idx - search_start_idx == 0xFD:
final_zero = False
out_bytes.append('\xFF')
out_bytes.append(in_bytes[search_start_idx:idx+1])
search_start_idx = idx + 1
idx += 1
if idx != search_start_idx or final_zero:
out_bytes.append(chr(idx - search_start_idx + 1))
out_bytes.append(in_bytes[search_start_idx:idx])
return ''.join(out_bytes)
|
https://github.com/cmcqueen/cobs-python/blob/ec4ce301e5574c9b6e72bfb485c116bdbffe0769/python2/cobs/cobs/_cobs_py.py#L12-L41
|
html encode string
|
python
|
def escape(s):
"""Convert the characters &, <, >, ' and " in string s to HTML-safe
sequences. Use this if you need to display text that might contain
such characters in HTML. Marks return value as markup string.
"""
if hasattr(s, '__html__'):
return s.__html__()
if isinstance(s, six.binary_type):
s = six.text_type(str(s), 'utf8')
elif isinstance(s, six.text_type):
s = s
else:
s = str(s)
return (s
.replace('&', '&')
.replace('>', '>')
.replace('<', '<')
.replace("'", ''')
.replace('"', '"')
)
|
https://github.com/syrusakbary/pyjade/blob/d8cf1d9404c759c6a2430c9a900874ab0e970cd8/pyjade/runtime.py#L28-L48
|
html encode string
|
python
|
def encoding(self):
"""the character encoding of the request, usually only set in POST type requests"""
encoding = None
ct = self.get_header('content-type')
if ct:
ah = AcceptHeader(ct)
if ah.media_types:
encoding = ah.media_types[0][2].get("charset", None)
return encoding
|
https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L828-L837
|
html encode string
|
python
|
def encodeString(string):
'''
Encode an UTF-8 string into MQTT format.
Returns a bytearray
'''
encoded = bytearray(2)
encoded.extend(bytearray(string, encoding='utf-8'))
l = len(encoded)-2
if(l > 65535):
raise StringValueError(l)
encoded[0] = l >> 8
encoded[1] = l & 0xFF
return encoded
|
https://github.com/astrorafael/twisted-mqtt/blob/5b322f7c2b82a502b1e1b70703ae45f1f668d07d/mqtt/pdu.py#L51-L63
|
html encode string
|
python
|
def _encode_string(s):
"""Encodes a unicode instance to utf-8. If a str is passed it will
simply be returned
:param s: str or unicode to encode
:returns: encoded output as str
"""
if six.PY2 and isinstance(s, unicode):
return s.encode('utf-8')
return s
|
https://github.com/owncloud/pyocclient/blob/b9e1f04cdbde74588e86f1bebb6144571d82966c/owncloud/owncloud.py#L1644-L1653
|
html encode string
|
python
|
def encode(msg):
"""encode(msg) -> SLIP-encoded message.
Encodes a message (a byte sequence) into a
SLIP-encoded packet.
:param bytes msg: The message that must be encoded
:return: The SLIP-encoded message
:rtype: bytes
"""
msg = bytes(msg)
return END + msg.replace(ESC, ESC + ESC_ESC).replace(END, ESC + ESC_END) + END
|
https://github.com/rhjdjong/SlipLib/blob/8300dba3e512bca282380f234be34d75f4a73ce1/sliplib/slip.py#L29-L40
|
html encode string
|
python
|
def encode(self, s):
"""Encodes text into a list of integers."""
s = tf.compat.as_text(s)
tokens = self._tokenizer.tokenize(s)
tokens = _prepare_tokens_for_encode(tokens)
ids = []
for token in tokens:
ids.extend(self._token_to_ids(token))
return text_encoder.pad_incr(ids)
|
https://github.com/tensorflow/datasets/blob/46ceb0cf7b4690f38ecbbc689e4d659a903d08dc/tensorflow_datasets/core/features/text/subword_text_encoder.py#L80-L88
|
html encode string
|
python
|
def xml_encode(string):
""" Returns the string with XML-safe special characters.
"""
string = string.replace("&", "&")
string = string.replace("<", "<")
string = string.replace(">", ">")
string = string.replace("\"",""")
string = string.replace(SLASH, "/")
return string
|
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/tree.py#L1253-L1261
|
html encode string
|
python
|
def encode(self):
"""
Encodes the object to a xml.etree.ElementTree.Element
:return: the encoded element
:rtype: xml.etree.ElementTree.Element
"""
root_element = ElementTree.Element(self.TAG_NAME)
for value in [value for value in self.__dict__.values() if isinstance(value, fields.Field)]:
if value.required or value.value:
root_element.append(value.encode())
return root_element
|
https://github.com/seibert-media/Highton/blob/1519e4fb105f62882c2e7bc81065d994649558d8/highton/parsing/xml_encoder.py#L34-L45
|
html encode string
|
python
|
def force_encoding(value, encoding='utf-8'):
"""
Return a string encoded in the provided encoding
"""
if not isinstance(value, (str, unicode)):
value = str(value)
if isinstance(value, unicode):
value = value.encode(encoding)
elif encoding != 'utf-8':
value = value.decode('utf-8').encode(encoding)
return value
|
https://github.com/majerteam/sqla_inspect/blob/67edb5541e6a56b0a657d3774d1e19c1110cd402/sqla_inspect/ascii.py#L35-L45
|
html encode string
|
python
|
def encode_utf8(mk):
"""
(Double-)encodes the given string (masterkey) with utf-8
Tries to behave like the Java implementation
"""
utf8mk = mk.decode('raw_unicode_escape')
utf8mk = list(utf8mk)
to_char = chr
if sys.version_info[0] < 3:
to_char = unichr
for i in range(len(utf8mk)):
c = ord(utf8mk[i])
# fix java encoding (add 0xFF00 to non ascii chars)
if 0x7f < c < 0x100:
c += 0xff00
utf8mk[i] = to_char(c)
return ''.join(utf8mk).encode('utf-8')
|
https://github.com/bluec0re/android-backup-tools/blob/e2e0d95e56624c1a99a176df9e307398e837d908/android_backup/android_backup.py#L239-L256
|
html encode string
|
python
|
def encode(self, obj, qualifier: str):
"""Encodes a dictionary-like object to a Lua string
:param qualifier:
:param obj: object to encode
:return: valid Lua string
"""
LOGGER.debug('encoding dictionary to text')
if not obj:
if qualifier.replace('=', '').rstrip() == 'mapResource':
# Accept empty mapResource
return '{}\n{{\n}} -- end of {}\n'.format(qualifier, qualifier.replace('=', '').rstrip())
else:
LOGGER.error('{}\n{{\n}} -- end of {}\n'.format(qualifier, qualifier.replace('=', '').rstrip()))
raise SLTPEmptyObjectError(qualifier)
self.depth = 0
out = []
s = self.__encode(obj)
lines = s.split(self.newline)
for line in lines:
m = self.line_end.match(line)
if m:
out.append('{},{}'.format(m.group('intro'), m.group('comment')))
else:
out.append(line)
return '{}{} -- end of {}\n'.format(qualifier, self.newline.join(out), qualifier.replace('=', '').rstrip())
|
https://github.com/etcher-be/elib_miz/blob/f28db58fadb2cd9341e0ae4d65101c0cc7d8f3d7/elib_miz/sltp.py#L94-L118
|
html encode string
|
python
|
def encodeSentence(self, *words):
"""
Encode given sentence in API format.
:param words: Words to endoce.
:returns: Encoded sentence.
"""
encoded = map(self.encodeWord, words)
encoded = b''.join(encoded)
# append EOS (end of sentence) byte
encoded += b'\x00'
return encoded
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L14-L25
|
html encode string
|
python
|
def url_quote(s, charset='utf-8', safe='/:'):
"""URL encode a single string with a given encoding.
:param s: the string to quote.
:param charset: the charset to be used.
:param safe: an optional sequence of safe characters.
"""
if isinstance(s, unicode):
s = s.encode(charset)
elif not isinstance(s, str):
s = str(s)
return _quote(s, safe=safe)
|
https://github.com/core/uricore/blob/dc5ef4be7bd93da4c39e5c1cbd1ae4f3ad3f1f2a/uricore/wkz_urls.py#L383-L394
|
html encode string
|
python
|
def urldecode(query):
"""Decode a query string in x-www-form-urlencoded format into a sequence
of two-element tuples.
Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce
correct formatting of the query string by validation. If validation fails
a ValueError will be raised. urllib.parse_qsl will only raise errors if
any of name-value pairs omits the equals sign.
"""
# Check if query contains invalid characters
if query and not set(query) <= urlencoded:
error = ("Error trying to decode a non urlencoded string. "
"Found invalid characters: %s "
"in the string: '%s'. "
"Please ensure the request/response body is "
"x-www-form-urlencoded.")
raise ValueError(error % (set(query) - urlencoded, query))
# Check for correctly hex encoded values using a regular expression
# All encoded values begin with % followed by two hex characters
# correct = %00, %A0, %0A, %FF
# invalid = %G0, %5H, %PO
if INVALID_HEX_PATTERN.search(query):
raise ValueError('Invalid hex encoding in query string.')
# We encode to utf-8 prior to parsing because parse_qsl behaves
# differently on unicode input in python 2 and 3.
# Python 2.7
# >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6')
# u'\xe5\x95\xa6\xe5\x95\xa6'
# Python 2.7, non unicode input gives the same
# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6')
# '\xe5\x95\xa6\xe5\x95\xa6'
# but now we can decode it to unicode
# >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8')
# u'\u5566\u5566'
# Python 3.3 however
# >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6')
# u'\u5566\u5566'
query = query.encode(
'utf-8') if not PY3 and isinstance(query, unicode_type) else query
# We want to allow queries such as "c2" whereas urlparse.parse_qsl
# with the strict_parsing flag will not.
params = urlparse.parse_qsl(query, keep_blank_values=True)
# unicode all the things
return decode_params_utf8(params)
|
https://github.com/oauthlib/oauthlib/blob/30321dd3c0ca784d3508a1970cf90d9f76835c79/oauthlib/common.py#L119-L165
|
html encode string
|
python
|
def encode(self, input, errors='strict'):
"""
Encodes a byte string into trytes.
"""
if isinstance(input, memoryview):
input = input.tobytes()
if not isinstance(input, (binary_type, bytearray)):
raise with_context(
exc=TypeError(
"Can't encode {type}; byte string expected.".format(
type=type(input).__name__,
)),
context={
'input': input,
},
)
# :bc: In Python 2, iterating over a byte string yields
# characters instead of integers.
if not isinstance(input, bytearray):
input = bytearray(input)
trytes = bytearray()
for c in input:
second, first = divmod(c, len(self.alphabet))
trytes.append(self.alphabet[first])
trytes.append(self.alphabet[second])
return binary_type(trytes), len(input)
|
https://github.com/iotaledger/iota.lib.py/blob/97cdd1e241498446b46157b79b2a1ea2ec6d387a/iota/codecs.py#L81-L113
|
html encode string
|
python
|
def encode(in_bytes):
"""Encode a string using Consistent Overhead Byte Stuffing (COBS).
Input is any byte string. Output is also a byte string.
Encoding guarantees no zero bytes in the output. The output
string will be expanded slightly, by a predictable amount.
An empty string is encoded to '\\x01'"""
if isinstance(in_bytes, str):
raise TypeError('Unicode-objects must be encoded as bytes first')
in_bytes_mv = _get_buffer_view(in_bytes)
final_zero = True
out_bytes = bytearray()
idx = 0
search_start_idx = 0
for in_char in in_bytes_mv:
if in_char == b'\x00':
final_zero = True
out_bytes.append(idx - search_start_idx + 1)
out_bytes += in_bytes_mv[search_start_idx:idx]
search_start_idx = idx + 1
else:
if idx - search_start_idx == 0xFD:
final_zero = False
out_bytes.append(0xFF)
out_bytes += in_bytes_mv[search_start_idx:idx+1]
search_start_idx = idx + 1
idx += 1
if idx != search_start_idx or final_zero:
out_bytes.append(idx - search_start_idx + 1)
out_bytes += in_bytes_mv[search_start_idx:idx]
return bytes(out_bytes)
|
https://github.com/cmcqueen/cobs-python/blob/ec4ce301e5574c9b6e72bfb485c116bdbffe0769/python3/cobs/cobs/_cobs_py.py#L22-L54
|
html encode string
|
python
|
def _DecodeURL(self, url):
"""Decodes the URL, replaces %XX to their corresponding characters.
Args:
url (str): encoded URL.
Returns:
str: decoded URL.
"""
if not url:
return ''
decoded_url = urlparse.unquote(url)
if isinstance(decoded_url, py2to3.BYTES_TYPE):
try:
decoded_url = decoded_url.decode('utf-8')
except UnicodeDecodeError as exception:
decoded_url = decoded_url.decode('utf-8', errors='replace')
logger.warning(
'Unable to decode URL: {0:s} with error: {1!s}'.format(
url, exception))
return decoded_url
|
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/analysis/browser_search.py#L77-L99
|
html encode string
|
python
|
def xhtml_escape(value):
"""Escapes a string so it is valid within HTML or XML.
Escapes the characters ``<``, ``>``, ``"``, ``'``, and ``&``.
When used in attribute values the escaped strings must be enclosed
in quotes.
.. versionchanged:: 3.2
Added the single quote to the list of escaped characters.
"""
return _XHTML_ESCAPE_RE.sub(lambda match: _XHTML_ESCAPE_DICT[match.group(0)],
to_basestring(value))
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/escape.py#L103-L115
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.