def parse_char(txt):
"""
Parse a c character
:param txt: character to parse
:type txt: string
:return: a character literal
:rtype: string
"""
if not txt: raise PreprocError("attempted to parse a null char")
if txt[0] != '\\':
return ord(txt)
c = txt[1]
if c == 'x':
if len(txt) == 4 and txt[3] in string.hexdigits: return int(txt[2:], 16)
return int(txt[2:], 16)
elif c.isdigit():
if c == '0' and len(txt)==2: return 0
for i in 3, 2, 1:
if len(txt) > i and txt[1:1+i].isdigit():
return (1+i, int(txt[1:1+i], 8))
else:
try: return chr_esc[c]
except KeyError: raise PreprocError("could not parse char literal '%s'" % txt)
python类hexdigits()的实例源码
def parse_char(txt):
"""
Parse a c character
:param txt: character to parse
:type txt: string
:return: a character literal
:rtype: string
"""
if not txt: raise PreprocError("attempted to parse a null char")
if txt[0] != '\\':
return ord(txt)
c = txt[1]
if c == 'x':
if len(txt) == 4 and txt[3] in string.hexdigits: return int(txt[2:], 16)
return int(txt[2:], 16)
elif c.isdigit():
if c == '0' and len(txt)==2: return 0
for i in 3, 2, 1:
if len(txt) > i and txt[1:1+i].isdigit():
return (1+i, int(txt[1:1+i], 8))
else:
try: return chr_esc[c]
except KeyError: raise PreprocError("could not parse char literal '%s'" % txt)
def parse_char(txt):
"""
Parse a c character
:param txt: character to parse
:type txt: string
:return: a character literal
:rtype: string
"""
if not txt: raise PreprocError("attempted to parse a null char")
if txt[0] != '\\':
return ord(txt)
c = txt[1]
if c == 'x':
if len(txt) == 4 and txt[3] in string.hexdigits: return int(txt[2:], 16)
return int(txt[2:], 16)
elif c.isdigit():
if c == '0' and len(txt)==2: return 0
for i in 3, 2, 1:
if len(txt) > i and txt[1:1+i].isdigit():
return (1+i, int(txt[1:1+i], 8))
else:
try: return chr_esc[c]
except KeyError: raise PreprocError("could not parse char literal '%s'" % txt)
def check_id_value_in_json_response(context, id_attribute_name):
"""Check the ID attribute in the JSON response.
Check if ID is stored in a format like: '477e85660c504b698beae2b5f2a28b4e'
ie. it is a string with 32 characters containing 32 hexadecimal digits
"""
response = context.response
assert response is not None
json_data = response.json()
assert json_data is not None
check_attribute_presence(json_data, id_attribute_name)
id_attribute = json_data[id_attribute_name]
assert id_attribute is not None
assert isinstance(id_attribute, str) and len(id_attribute) == 32
assert all(char in string.hexdigits for char in id_attribute)
def get_color_info_html(self, color_string):
"""
return formatted info for *color_string, taken from color xmls (default + themes + core).
"""
color_info = ""
for item in self.get_colors():
if item["name"] == color_string:
color_hex = "#" + item["content"][2:]
cont_color = utils.get_contrast_color(color_hex)
alpha_percent = round(int(item["content"][:2], 16) / (16 * 16) * 100)
color_info += '%s <a href="test" style="background-color:%s;color:%s">%s</a> %d %% alpha<br>' % (os.path.basename(item["file"]), color_hex, cont_color, item["content"], alpha_percent)
if color_info:
return color_info
if all(c in string.hexdigits for c in color_string) and len(color_string) == 8:
color_hex = "#" + color_string[2:]
cont_color = utils.get_contrast_color(color_hex)
alpha_percent = round(int(color_string[:2], 16) / (16 * 16) * 100)
return '<a href="test" style="background-color:%s;color:%s">%d %% alpha</a>' % (color_hex, cont_color, alpha_percent)
def step_size_start(self, char):
if char in string.hexdigits:
return self._add_size_char(char, start=True)
if ' ' == char:
return self.STATUS_AFTER_SIZE
if '\t' == char:
self.setError(self.ERROR_BAD_SPACE, critical=False)
return self.STATUS_AFTER_SIZE
if ';' == char:
return self.STATUS_TRAILER
if '\r' == char:
self.eof += u'[CR]'
return self.STATUS_AFTER_CR
if '\n' == char:
self.setError(self.ERROR_LF_WITHOUT_CR, critical=False)
self.eof += u'[LF]'
return self.STATUS_END
# other chars are bad
self.setError(self.ERROR_BAD_CHUNK_HEADER)
return self.STATUS_END
def step_size(self, char):
if char in string.hexdigits:
return self._add_size_char(char)
if ' ' == char:
return self.STATUS_AFTER_SIZE
if '\t' == char:
self.setError(self.ERROR_BAD_SPACE, critical=False)
return self.STATUS_AFTER_SIZE
if ';' == char:
return self.STATUS_TRAILER
if '\r' == char:
self.eof += u'[CR]'
return self.STATUS_AFTER_CR
if '\n' == char:
self.setError(self.ERROR_LF_WITHOUT_CR, critical=False)
self.eof += u'[LF]'
return self.STATUS_END
# other chars are bad
self.setError(self.ERROR_BAD_CHUNK_HEADER)
return self.STATUS_END
def parseAnswers(self,a,auth,ar,dns):
sect_map = {'a':'add_answer','auth':'add_auth','ar':'add_ar'}
for sect in 'a','auth','ar':
f = getattr(dns,sect_map[sect])
for rr in locals()[sect]:
rname,ttl,rclass,rtype = rr[:4]
rdata = rr[4:]
rd = RDMAP.get(rtype,RD)
try:
if rd == RD and \
any([ x not in string.hexdigits for x in rdata[-1]]):
# Only support hex encoded data for fallback RD
pass
else:
f(RR(rname=rname,
ttl=int(ttl),
rtype=getattr(QTYPE,rtype),
rclass=getattr(CLASS,rclass),
rdata=rd.fromZone(rdata)))
except DNSError as e:
if self.debug:
print("DNSError:",e,rr)
else:
# Skip records we dont understand
pass
def parseAnswers(self,a,auth,ar,dns):
sect_map = {'a':'add_answer','auth':'add_auth','ar':'add_ar'}
for sect in 'a','auth','ar':
f = getattr(dns,sect_map[sect])
for rr in locals()[sect]:
rname,ttl,rclass,rtype = rr[:4]
rdata = rr[4:]
rd = RDMAP.get(rtype,RD)
try:
if rd == RD and \
any([ x not in string.hexdigits for x in rdata[-1]]):
# Only support hex encoded data for fallback RD
pass
else:
f(RR(rname=rname,
ttl=int(ttl),
rtype=getattr(QTYPE,rtype),
rclass=getattr(CLASS,rclass),
rdata=rd.fromZone(rdata)))
except DNSError as e:
if self.debug:
print("DNSError:",e,rr)
else:
# Skip records we dont understand
pass
def parseAnswers(self,a,auth,ar,dns):
sect_map = {'a':'add_answer','auth':'add_auth','ar':'add_ar'}
for sect in 'a','auth','ar':
f = getattr(dns,sect_map[sect])
for rr in locals()[sect]:
rname,ttl,rclass,rtype = rr[:4]
rdata = rr[4:]
rd = RDMAP.get(rtype,RD)
try:
if rd == RD and \
any([ x not in string.hexdigits for x in rdata[-1]]):
# Only support hex encoded data for fallback RD
pass
else:
f(RR(rname=rname,
ttl=int(ttl),
rtype=getattr(QTYPE,rtype),
rclass=getattr(CLASS,rclass),
rdata=rd.fromZone(rdata)))
except DNSError as e:
if self.debug:
print("DNSError:",e,rr)
else:
# Skip records we dont understand
pass
def test_id_to_header_conversion():
# Test passing a standard Integer ID
original_id = instana.util.generate_id()
converted_id = instana.util.id_to_header(original_id)
# Assert that it is a string and there are no non-hex characters
assert isinstance(converted_id, string_types)
assert all(c in string.hexdigits for c in converted_id)
# Test passing a standard Integer ID as a String
original_id = instana.util.generate_id()
converted_id = instana.util.id_to_header(original_id)
# Assert that it is a string and there are no non-hex characters
assert isinstance(converted_id, string_types)
assert all(c in string.hexdigits for c in converted_id)
def test_ctypes(self):
def check(func, expected):
self.assertEqual(func(i), expected)
self.assertEqual(func(c), expected)
for i in range(256):
c = b = chr(i)
check(curses.ascii.isalnum, b.isalnum())
check(curses.ascii.isalpha, b.isalpha())
check(curses.ascii.isdigit, b.isdigit())
check(curses.ascii.islower, b.islower())
check(curses.ascii.isspace, b.isspace())
check(curses.ascii.isupper, b.isupper())
check(curses.ascii.isascii, i < 128)
check(curses.ascii.ismeta, i >= 128)
check(curses.ascii.isctrl, i < 32)
check(curses.ascii.iscntrl, i < 32 or i == 127)
check(curses.ascii.isblank, c in ' \t')
check(curses.ascii.isgraph, 32 < i <= 126)
check(curses.ascii.isprint, 32 <= i <= 126)
check(curses.ascii.ispunct, c in string.punctuation)
check(curses.ascii.isxdigit, c in string.hexdigits)
def test_ctypes(self):
def check(func, expected):
self.assertEqual(func(i), expected)
self.assertEqual(func(c), expected)
for i in range(256):
c = b = chr(i)
check(curses.ascii.isalnum, b.isalnum())
check(curses.ascii.isalpha, b.isalpha())
check(curses.ascii.isdigit, b.isdigit())
check(curses.ascii.islower, b.islower())
check(curses.ascii.isspace, b.isspace())
check(curses.ascii.isupper, b.isupper())
check(curses.ascii.isascii, i < 128)
check(curses.ascii.ismeta, i >= 128)
check(curses.ascii.isctrl, i < 32)
check(curses.ascii.iscntrl, i < 32 or i == 127)
check(curses.ascii.isblank, c in ' \t')
check(curses.ascii.isgraph, 32 < i <= 126)
check(curses.ascii.isprint, 32 <= i <= 126)
check(curses.ascii.ispunct, c in string.punctuation)
check(curses.ascii.isxdigit, c in string.hexdigits)
def assert_success(response: Response) -> None:
"""
Assert that the given response is a success response for adding a
target.
Raises:
AssertionError: The given response is not a valid success response
for adding a target.
"""
assert_vws_response(
response=response,
status_code=codes.CREATED,
result_code=ResultCodes.TARGET_CREATED,
)
expected_keys = {'result_code', 'transaction_id', 'target_id'}
assert response.json().keys() == expected_keys
target_id = response.json()['target_id']
assert len(target_id) == 32
assert all(char in hexdigits for char in target_id)
def encodingChanged(self, idx):
encoding = str(self.mode_combo.currentText())
validator = None
if encoding == 'hex':
# only clear the box if there are non-hex chars
# before setting the validator.
txt = str(self.data_edit.text())
if not all(c in string.hexdigits for c in txt):
self.data_edit.setText('')
regex = QtCore.QRegExp('^[0-9A-Fa-f]+$')
validator = QtWidgets.QRegExpValidator(regex)
self.data_edit.setValidator(validator)
txt = str(self.data_edit.text())
txt_encoded = self.encodeData(txt, encoding)
self.updateHexPreview(txt_encoded)
def encodingChanged(self, idx):
encoding = str(self.mode_combo.currentText())
validator = None
if encoding == 'hex':
# only clear the box if there are non-hex chars
# before setting the validator.
txt = str(self.data_edit.text())
if not all(c in string.hexdigits for c in txt):
self.data_edit.setText('')
regex = QtCore.QRegExp('^[0-9A-Fa-f]+$')
validator = QtWidgets.QRegExpValidator(regex)
self.data_edit.setValidator(validator)
self.renderMemory()
def getCharset(num,addchar):
char = ""
charset = { '1': s.ascii_lowercase,
'2': s.ascii_uppercase,
'3': s.digits,
'4': s.hexdigits,
'5': s.punctuation,
'6': s.printable}
if num is 1:
return charset['1']
else:
num = num.split(',')
for i in num:
if 1 <= int(i) <= 6:
i= '%s' % i
char += charset[i]
else:
print "Number %s out of range." % (i)
return char+''.join(addchar)
def parseAnswers(self,a,auth,ar,dns):
sect_map = {'a':'add_answer','auth':'add_auth','ar':'add_ar'}
for sect in 'a','auth','ar':
f = getattr(dns,sect_map[sect])
for rr in locals()[sect]:
rname,ttl,rclass,rtype = rr[:4]
rdata = rr[4:]
rd = RDMAP.get(rtype,RD)
try:
if rd == RD and \
any([ x not in string.hexdigits for x in rdata[-1]]):
# Only support hex encoded data for fallback RD
pass
else:
f(RR(rname=rname,
ttl=int(ttl),
rtype=getattr(QTYPE,rtype),
rclass=getattr(CLASS,rclass),
rdata=rd.fromZone(rdata)))
except DNSError as e:
if self.debug:
print("DNSError:",e,rr)
else:
# Skip records we dont understand
pass
def callback(self, stream):
data = str(stream).replace(" ", "").strip()
if '0:' in data:
return
if len(data) > 16:
print "Frame length error : ", data
return
if not all(c in string.hexdigits for c in data):
print "Frame hex error : ", data
return
data = data.replace(' ', '').ljust(16, "0")
if self.currentrequest:
values = self.currentrequest.get_values_from_stream(data)
i = 0
for name in self.names:
if name in values:
value = values[name]
if value is not None:
self.table.item(i, 0).setText(value)
i += 1
def is_hex(value):
if not is_string(value):
return False
elif value.lower() in {b'0x', '0x'}:
return True
unprefixed_value = remove_0x_prefix(value)
if len(unprefixed_value) % 2 != 0:
value_to_decode = (b'0' if is_bytes(unprefixed_value) else '0') + unprefixed_value
else:
value_to_decode = unprefixed_value
if any(char not in string.hexdigits for char in force_obj_to_text(value_to_decode)):
return False
try:
value_as_bytes = codecs.decode(value_to_decode, 'hex')
except binascii.Error:
return False
except TypeError:
return False
else:
return bool(value_as_bytes)
def parseAnswers(self,a,auth,ar,dns):
sect_map = {'a':'add_answer','auth':'add_auth','ar':'add_ar'}
for sect in 'a','auth','ar':
f = getattr(dns,sect_map[sect])
for rr in locals()[sect]:
rname,ttl,rclass,rtype = rr[:4]
rdata = rr[4:]
rd = RDMAP.get(rtype,RD)
try:
if rd == RD and \
any([ x not in string.hexdigits for x in rdata[-1]]):
# Only support hex encoded data for fallback RD
pass
else:
f(RR(rname=rname,
ttl=int(ttl),
rtype=getattr(QTYPE,rtype),
rclass=getattr(CLASS,rclass),
rdata=rd.fromZone(rdata)))
except DNSError as e:
if self.debug:
print("DNSError:",e,rr)
else:
# Skip records we dont understand
pass
def test_cache_cleaning(self):
"""Make sure the automatic cache cleaning logic works as expected."""
with TemporaryDirectory() as cache_directory:
context = create_context()
accelerator = NpmAccel(context=context, cache_directory=cache_directory)
just_above_limit = accelerator.cache_limit + 1
for i in range(just_above_limit):
# Create a fake (empty) tar archive.
fingerprint = random_string(length=40, characters=string.hexdigits)
filename = os.path.join(cache_directory, '%s.tar' % fingerprint)
context.write_file(filename, '')
# Create the cache metadata.
accelerator.write_metadata(filename)
# Sanity check the cache entries.
assert len(list(accelerator.find_archives())) == just_above_limit
# Run the cleanup.
accelerator.clean_cache()
# Make sure the number of cache entries decreased.
assert len(list(accelerator.find_archives())) == accelerator.cache_limit
def get_container_name(self, *args):
"""
Given an incomplete container identifier, construct the name
with the project name included. Args can be a string like 'nginx_1'
or an iterable like ('nginx', 2). If the arg is the container ID
then it will be returned unchanged.
"""
if (len(args) == 1 and all(c in string.hexdigits for c in args[0])):
return args[0]
name = '_'.join([str(a) for a in args])
if (name.startswith(self.project_name)
and name.startswith('{0}_{0}_'.format(self.project_name))):
# some projects have services with the same name
return name
return '{}_{}'.format(self.project_name, name)
def isHex(val: str) -> bool:
"""
Return whether the given str represents a hex value or not
:param val: the string to check
:return: whether the given str represents a hex value
"""
if isinstance(val, bytes):
# only decodes utf-8 string
try:
val = val.decode()
except ValueError:
return False
return isinstance(val, str) and all(c in string.hexdigits for c in val)
# decorator
def availchar(charactertype):
import string
if charactertype == 'letters':
return string.ascii_letters
elif charactertype == 'lowercase':
return string.ascii_lowercase
elif charactertype == 'uppercase':
return string.ascii_uppercase
elif charactertype == 'digits':
return string.digits
elif charactertype == 'hexdigits':
return string.hexdigits
elif charactertype == 'punctuation':
return string.punctuation
elif charactertype == 'printable':
return string.printable
elif charactertype == 'whitespace':
return string.whitespace
else:
raise RuntimeError('An Error Has Occured: Invalid Operation Entered (0008)')
# Get The Value Of A Word
def ishex(x):
if x.startswith("0x") or x.startswith("0X"):
x = x[2:]
return all([c in string.hexdigits for c in x])
def __handle_unescape(self, key):
start = 0
while True:
start_js = self.js
offset = self.js.find(key, start)
if offset == -1: break
offset += len(key)
expr = ''
extra = ''
last_c = self.js[offset - 1]
abort = False
for i, c in enumerate(self.js[offset:]):
extra += c
if c == ')':
break
elif (i > 0 and c == '(') or (c == '[' and last_c != '+'):
abort = True
break
elif c == '%' or c in string.hexdigits:
expr += c
last_c = c
if not abort:
self.js = self.js.replace(key + extra, urllib.unquote(expr))
if start_js == self.js:
break
else:
start = offset
def ishex(s):
hex_digits = set(string.hexdigits)
# if s is long, then it is faster to check against a set
return all(c in hex_digits for c in s)
def hexStr(data):
"""Convert binary data to a hex string."""
h = string.hexdigits
r = ''
for c in data:
i = byteord(c)
r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
return r
def hexStr(s):
h = string.hexdigits
r = ''
for c in s:
i = byteord(c)
r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
return r