本文整理汇总了Python中random.getrandbits方法的典型用法代码示例。如果您正苦于以下问题:Python random.getrandbits方法的具体用法?Python random.getrandbits怎么用?Python random.getrandbits使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类random
的用法示例。
在下文中一共展示了random.getrandbits方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _py_func_with_gradient
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def _py_func_with_gradient(func, inp, Tout, stateful=True, name=None,
grad_func=None):
"""
PyFunc defined as given by Tensorflow
:param func: Custom Function
:param inp: Function Inputs
:param Tout: Ouput Type of out Custom Function
:param stateful: Calculate Gradients when stateful is True
:param name: Name of the PyFunction
:param grad: Custom Gradient Function
:return:
"""
# Generate random name in order to avoid conflicts with inbuilt names
rnd_name = 'PyFuncGrad-' + '%0x' % getrandbits(30 * 4)
# Register Tensorflow Gradient
tf.RegisterGradient(rnd_name)(grad_func)
# Get current graph
g = tf.get_default_graph()
# Add gradient override map
with g.gradient_override_map(
{"PyFunc": rnd_name, "PyFuncStateless": rnd_name}):
return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
示例2: exact_single_frame
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def exact_single_frame(self, length):
"""
Simplest test possible. Create a packet, then parse a buffer containing this packet. Size of buffer is exactly
one packet (no excess).
:param length: Number of bytes in payload.
"""
import random
import pyvesc.protocol.packet.codec as vesc_packet
correct_payload_index = None
if length < 256:
correct_payload_index = 2
else:
correct_payload_index = 3
test_payload = bytes(random.getrandbits(8) for i in range(length))
# test framing
packet = vesc_packet.frame(test_payload)
self.assertEqual(len(packet), correct_payload_index + length + 3, "size of packet")
buffer = bytearray(packet)
# test Parser
parsed, consumed = vesc_packet.unframe(buffer)
buffer = buffer[consumed:]
self.assertEqual(parsed, test_payload)
self.assertEqual(len(buffer), 0)
示例3: _symlinks_supported
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def _symlinks_supported(self) -> bool:
log.debug("Checking if is filesystem supports symbolic links...")
dst = "test_dst_%s" % random.getrandbits(32)
src = "test_src_%s" % random.getrandbits(32)
dst_file = self.root_path / dst
src_file = self.root_path / src
src_file.touch()
try:
log.debug("attempting to symlink %s to %s", src_file, dst_file)
dst_file.symlink_to(src_file)
dst_file.unlink()
src_file.unlink()
except BaseException:
if src_file.exists():
src_file.unlink()
log.error("Symbolic links not supported")
log.error("Albums are not going to be synced - requires symlinks")
return False
return True
示例4: filter_input
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def filter_input(text: str):
if text is None:
return None
filtered = text
urls = re.findall(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
text)
# Replace all URLS with a unique token
url_token = 'URL%s' % random.getrandbits(64)
for url in urls:
filtered = filtered.replace(url, url_token)
filtered = re.sub(r'(&)', '', filtered)
filtered = re.sub(r'[,:;\'`\-_“^"<>(){}/\\*]', '', filtered)
# Swamp URLs back for token
for url in urls:
filtered = filtered.replace(url_token, url)
return filtered
示例5: __init__
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def __init__(self, graph, rep_size=128, batch_size=1000, negative_ratio=5, order=3):
self.cur_epoch = 0
self.order = order
self.g = graph
self.node_size = graph.G.number_of_nodes()
self.rep_size = rep_size
self.batch_size = batch_size
self.negative_ratio = negative_ratio
self.gen_sampling_table()
self.sess = tf.Session()
cur_seed = random.getrandbits(32)
initializer = tf.contrib.layers.xavier_initializer(
uniform=False, seed=cur_seed)
with tf.variable_scope("model", reuse=None, initializer=initializer):
self.build_graph()
self.sess.run(tf.global_variables_initializer())
示例6: _get_descending_key
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def _get_descending_key(gettime=time.time):
"""Returns a key name lexically ordered by time descending.
This lets us have a key name for use with Datastore entities which returns
rows in time descending order when it is scanned in lexically ascending order,
allowing us to bypass index building for descending indexes.
Args:
gettime: Used for testing.
Returns:
A string with a time descending key.
"""
now_descending = int((_FUTURE_TIME - gettime()) * 100)
request_id_hash = os.environ.get("REQUEST_ID_HASH")
if not request_id_hash:
request_id_hash = str(random.getrandbits(32))
return "%d%s" % (now_descending, request_id_hash)
示例7: __init__
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def __init__(self, *args, **kwds):
## Create shared memory for rendered image
#pg.dbg(namespace={'r': self})
if sys.platform.startswith('win'):
self.shmtag = "pyqtgraph_shmem_" + ''.join([chr((random.getrandbits(20)%25) + 97) for i in range(20)])
self.shm = mmap.mmap(-1, mmap.PAGESIZE, self.shmtag) # use anonymous mmap on windows
else:
self.shmFile = tempfile.NamedTemporaryFile(prefix='pyqtgraph_shmem_')
self.shmFile.write(b'\x00' * (mmap.PAGESIZE+1))
fd = self.shmFile.fileno()
self.shm = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE)
atexit.register(self.close)
GraphicsView.__init__(self, *args, **kwds)
self.scene().changed.connect(self.update)
self.img = None
self.renderTimer = QtCore.QTimer()
self.renderTimer.timeout.connect(self.renderView)
self.renderTimer.start(16)
示例8: _random_bytes
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def _random_bytes(length):
if random.choice((0, 1)):
b = bytes(random.getrandbits(8)
for _ in range(int(length)))
else:
# We use b'\x00' as a placeholder for padding when faking missing files
# during verification, so we increase the probability of b'\x00' at the
# beginning and/or end
if random.choice((0, 1)):
beg = b'\x00' * random.randint(0, int(length / 2))
else:
beg = b''
if random.choice((0, 1)):
end = b'\x00' * random.randint(0, int(length / 2))
else:
end = b''
b = beg + bytes(random.getrandbits(8)
for _ in range(int(length - len(beg) - len(end)))) + end
assert len(b) == length
return b
示例9: make_msgid
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def make_msgid(idstring=None):
"""Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
<142480216486.20800.16526388040877946887@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id.
"""
timeval = int(time.time()*100)
pid = os.getpid()
randint = random.getrandbits(64)
if idstring is None:
idstring = ''
else:
idstring = '.' + idstring
idhost = socket.getfqdn()
msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, idhost)
return msgid
# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions. We use this to worm
# around broken older Pythons.
示例10: __init__
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def __init__(self):
self.board = [int(7 * random.getrandbits(1)) for _ in xrange(size)]
self.color = [[154, 154, 174], [0, 0, 255], [0, 0, 200], [0, 0, 160], [0, 0, 140], [0, 0, 90], [0, 0, 60], [0, 0, 0]]
示例11: __init__
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def __init__(self, args):
if "-r" in args:
self.synth_mode = self.SYNTH_MODE_RANDOM
elif "-b" in args:
self.synth_mode = self.SYNTH_MODE_BRUTE
elif "-t" in args:
self.synth_mode = self.SYNTH_MODE_TUNNEL
self.args = args
self.root = (os.geteuid() == 0)
self.seed = random.getrandbits(32)
示例12: gen_random_bits
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def gen_random_bits(self, width):
'''
You can generate a bitvector with random bits with the bits
spanning a specified width. For example, if you wanted a random
bit vector to fully span 32 bits, you would say
bv = BitVector(intVal = 0)
bv = bv.gen_random_bits(32)
print(bv) # 11011010001111011010011111000101
As you would expect, gen_random_bits() returns a bitvector object.
The bulk of the work here is done by calling random.getrandbits(
width) which returns an integer whose binary code representation
will NOT BE LARGER than the argument 'width'. When random numbers
are generated as candidates for primes, you often want to make sure
that the random number thus created spans the full width specified
by 'width' and that the number is odd. This we do by setting the
two most significant bits and the least significant bit.
'''
import random
candidate = random.getrandbits( width )
candidate |= 1
candidate |= (1 << width-1)
candidate |= (2 << width-3)
return BitVector( intVal = candidate )
# For backward compatibility:
示例13: generateToken
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def generateToken(bits=128):
return "{:x}".format(random.getrandbits(bits))
示例14: exact_two_frames
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def exact_two_frames(self, length1, length2):
"""
Check that if there is more than one packet in a buffer, that the unpacker will properly unpack the packets.
Size of buffer for this test is exactly two packets.
:param length1: Length of first payload
:param length2: Length of second payload
"""
import random
import pyvesc.protocol.packet.codec as vesc_packet
correct_payload_index1 = None
correct_payload_index2 = None
if length1 < 256:
correct_payload_index1 = 2
else:
correct_payload_index1 = 3
if length2 < 256:
correct_payload_index2 = 2
else:
correct_payload_index2 = 3
test_payload1 = bytes(random.getrandbits(8) for i in range(length1))
test_payload2 = bytes(random.getrandbits(8) for i in range(length2))
# test framing
packet1 = vesc_packet.frame(test_payload1)
packet2 = vesc_packet.frame(test_payload2)
self.assertEqual(len(packet1), correct_payload_index1 + length1 + 3, "size of packet")
self.assertEqual(len(packet2), correct_payload_index2 + length2 + 3, "size of packet")
buffer = bytearray(packet1 + packet2)
# test Parser
parsed, consumed = vesc_packet.unframe(buffer)
buffer = buffer[consumed:]
self.assertEqual(parsed, test_payload1)
self.assertEqual(len(buffer), len(packet2))
parsed, consumed = vesc_packet.unframe(buffer)
buffer = buffer[consumed:]
self.assertEqual(parsed, test_payload2)
self.assertEqual(len(buffer), 0)
示例15: parse_buffer
# 需要导入模块: import random [as 别名]
# 或者: from random import getrandbits [as 别名]
def parse_buffer(self, length):
import random
import pyvesc.protocol.packet.codec as vesc_packet
correct_payload_index = None
if length < 256:
correct_payload_index = 2
else:
correct_payload_index = 3
test_payload = bytes(random.getrandbits(8) for i in range(length))
packet = vesc_packet.frame(test_payload)
# test on small buffers
for n in range(0, 5):
in_buffer = bytearray(packet[:n])
parsed, consumed = vesc_packet.unframe(in_buffer)
out_buffer = in_buffer[consumed:]
self.assertEqual(parsed, None)
self.assertEqual(in_buffer, out_buffer)
# test on buffer almost big enough
for n in range(len(packet) - 4, len(packet)):
in_buffer = bytearray(packet[:n])
parsed, consumed = vesc_packet.unframe(in_buffer)
out_buffer = in_buffer[consumed:]
self.assertEqual(parsed, None)
self.assertEqual(in_buffer, out_buffer)
# test on buffer slightly too big
extension = b'\x02\x04\x07'
extended_packet = packet + b'\x02\x04\x07'
for n in range(len(packet) + 1, len(packet) + 4):
in_buffer = bytearray(extended_packet[:n])
parsed, consumed = vesc_packet.unframe(in_buffer)
out_buffer = in_buffer[consumed:]
self.assertEqual(parsed, test_payload)
self.assertEqual(out_buffer, extension[:n - len(packet)])