Python random.getrandbits() Examples
The following are 30
code examples of random.getrandbits().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
random
, or try the search function
.

Example #1
Source File: utils_pytorch.py From neural-fingerprinting with BSD 3-Clause "New" or "Revised" License | 7 votes |
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)
Example #2
Source File: test.py From PyVESC with Creative Commons Attribution 4.0 International | 6 votes |
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)
Example #3
Source File: Checks.py From gphotos-sync with MIT License | 6 votes |
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
Example #4
Source File: markov_engine.py From armchair-expert with MIT License | 6 votes |
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
Example #5
Source File: line.py From OpenNE with MIT License | 6 votes |
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())
Example #6
Source File: model.py From browserscope with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: RemoteGraphicsView.py From tf-pose with Apache License 2.0 | 6 votes |
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)
Example #8
Source File: conftest.py From torf with GNU General Public License v3.0 | 6 votes |
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
Example #9
Source File: utils.py From ironpython2 with Apache License 2.0 | 6 votes |
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.
Example #10
Source File: util.py From locality-sensitive-hashing with MIT License | 6 votes |
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)
Example #11
Source File: game-of-life.py From unicorn-hat-hd with MIT License | 5 votes |
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]]
Example #12
Source File: sifter.py From sandsifter with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #13
Source File: BitVector.py From knob with MIT License | 5 votes |
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:
Example #14
Source File: dockerconfig.py From Paradrop with Apache License 2.0 | 5 votes |
def generateToken(bits=128): return "{:x}".format(random.getrandbits(bits))
Example #15
Source File: test.py From PyVESC with Creative Commons Attribution 4.0 International | 5 votes |
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)
Example #16
Source File: test.py From PyVESC with Creative Commons Attribution 4.0 International | 5 votes |
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)])
Example #17
Source File: rules.py From pydfs-lineup-optimizer with MIT License | 5 votes |
def apply_for_iteration(self, solver, players_dict, result): variables = [] coefficients = [] optimizer_min_deviation, optimizer_max_deviation = self.optimizer.get_deviation() for player, variable in players_dict.items(): variables.append(variable) multiplier = uniform( player.min_deviation if player.min_deviation is not None else optimizer_min_deviation, player.max_deviation if player.max_deviation is not None else optimizer_max_deviation ) coefficients.append(player.fppg * (1 + (-1 if bool(getrandbits(1)) else 1) * multiplier)) solver.set_objective(variables, coefficients)
Example #18
Source File: line.py From OpenNE with MIT License | 5 votes |
def build_graph(self): self.h = tf.placeholder(tf.int32, [None]) self.t = tf.placeholder(tf.int32, [None]) self.sign = tf.placeholder(tf.float32, [None]) cur_seed = random.getrandbits(32) self.embeddings = tf.get_variable(name="embeddings"+str(self.order), shape=[ self.node_size, self.rep_size], initializer=tf.contrib.layers.xavier_initializer(uniform=False, seed=cur_seed)) self.context_embeddings = tf.get_variable(name="context_embeddings"+str(self.order), shape=[ self.node_size, self.rep_size], initializer=tf.contrib.layers.xavier_initializer(uniform=False, seed=cur_seed)) # self.h_e = tf.nn.l2_normalize(tf.nn.embedding_lookup(self.embeddings, self.h), 1) # self.t_e = tf.nn.l2_normalize(tf.nn.embedding_lookup(self.embeddings, self.t), 1) # self.t_e_context = tf.nn.l2_normalize(tf.nn.embedding_lookup(self.context_embeddings, self.t), 1) self.h_e = tf.nn.embedding_lookup(self.embeddings, self.h) self.t_e = tf.nn.embedding_lookup(self.embeddings, self.t) self.t_e_context = tf.nn.embedding_lookup( self.context_embeddings, self.t) self.second_loss = -tf.reduce_mean(tf.log_sigmoid( self.sign*tf.reduce_sum(tf.multiply(self.h_e, self.t_e_context), axis=1))) self.first_loss = -tf.reduce_mean(tf.log_sigmoid( self.sign*tf.reduce_sum(tf.multiply(self.h_e, self.t_e), axis=1))) if self.order == 1: self.loss = self.first_loss else: self.loss = self.second_loss optimizer = tf.train.AdamOptimizer(0.001) self.train_op = optimizer.minimize(self.loss)
Example #19
Source File: test_unit_arrow_chunk_iterator.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
def test_iterate_over_bool_chunk(): random.seed(datetime.datetime.now()) column_meta = {"logicalType": "BOOLEAN"} def bool_generator(): return bool(random.getrandbits(1)) iterate_over_test_chunk([pyarrow.bool_(), pyarrow.bool_()], [column_meta, column_meta], bool_generator)
Example #20
Source File: test_dataintegrity.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
def test_BINARY(conn_cnx): def generator(row, col): return bytes(random.getrandbits(8) for _ in range(50)) check_data_integrity(conn_cnx, ('col1 BINARY',), 'BINARY', generator)
Example #21
Source File: test_dataintegrity.py From snowflake-connector-python with Apache License 2.0 | 5 votes |
def test_BINARY(conn_cnx): def generator(row, col): return bytes(random.getrandbits(8) for _ in range(50)) check_data_integrity(conn_cnx, ('col1 BINARY',), 'BINARY', generator)
Example #22
Source File: zwift_offline.py From zwift-offline with GNU General Public License v3.0 | 5 votes |
def get_id(table_name): cur = g.db.cursor() while True: # I think activity id is actually only uint32. On the off chance it's # int32, stick with 31 bits. ident = int(random.getrandbits(31)) cur.execute("SELECT id FROM %s WHERE id = ?" % table_name, (str(ident),)) if not cur.fetchall(): break return ident
Example #23
Source File: zwift_offline.py From zwift-offline with GNU General Public License v3.0 | 5 votes |
def api_zfiles(): # Don't care about zfiles, but shuts up some errors in Zwift log. zfile = zfiles_pb2.ZFile() zfile.id = int(random.getrandbits(31)) zfile.folder = "logfiles" zfile.filename = "yep_took_good_care_of_that_file.txt" zfile.timestamp = int(time.time()) return zfile.SerializeToString(), 200 # Probably don't need, haven't investigated
Example #24
Source File: zwift_offline.py From zwift-offline with GNU General Public License v3.0 | 5 votes |
def relay_worlds_hash_seeds(): seeds = hash_seeds_pb2.HashSeeds() for x in range(4): seed = seeds.seeds.add() seed.seed1 = int(random.getrandbits(31)) seed.seed2 = int(random.getrandbits(31)) seed.expiryDate = world_time()+(10800+x*1200)*1000 return seeds.SerializeToString(), 200 # XXX: attributes have not been thoroughly investigated
Example #25
Source File: models.py From coursys with GNU General Public License v3.0 | 5 votes |
def new_feed_token(): """ Generate a random token for the feed URL """ random.seed() n = random.getrandbits(128) return "%032x" % (n)
Example #26
Source File: comment_tests.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def setUp(self): super(TestCommentOBS, self).setUp() self.wf = OBSLocal.StagingWorkflow() self.wf.create_user('factory-auto') self.wf.create_user('repo-checker') self.wf.create_user('staging-bot') self.wf.create_group('factory-staging', ['staging-bot']) self.wf.create_project(PROJECT, maintainer={'groups': ['factory-staging']}) self.api = CommentAPI(self.apiurl) # Ensure different test runs operate in unique namespace. self.bot = '::'.join([type(self).__name__, str(random.getrandbits(8))])
Example #27
Source File: ReviewBot_tests.py From openSUSE-release-tools with GNU General Public License v2.0 | 5 votes |
def setUp(self): super(TestReviewBotComment, self).setUp() self.api = CommentAPI(self.apiurl) self.wf = OBSLocal.StagingWorkflow() self.wf.create_user('factory-auto') self.project = self.wf.create_project(PROJECT) # Ensure different test runs operate in unique namespace. self.bot = '::'.join([type(self).__name__, str(random.getrandbits(8))]) self.review_bot = ReviewBot(self.apiurl, logger=logging.getLogger(self.bot)) self.review_bot.bot_name = self.bot self.osc_user('factory-auto')
Example #28
Source File: cifar10.py From ResNeXt-Tensorflow with MIT License | 5 votes |
def _random_flip_leftright(batch): for i in range(len(batch)): if bool(random.getrandbits(1)): batch[i] = np.fliplr(batch[i]) return batch
Example #29
Source File: test_utils.py From APIFuzzer with GNU General Public License v3.0 | 5 votes |
def generate_random_auth_headers(self): if bool(random.getrandbits(1)): self.auth_headers = [{self.random_string(): self.random_string()}] else: self.auth_headers = {self.random_string(): self.random_string()}
Example #30
Source File: messages.py From checklocktimeverify-demos with GNU General Public License v3.0 | 5 votes |
def __init__(self, protover=PROTO_VERSION): super(msg_version, self).__init__(protover) self.nVersion = protover self.nServices = 1 self.nTime = int(time.time()) self.addrTo = CAddress(PROTO_VERSION) self.addrFrom = CAddress(PROTO_VERSION) self.nNonce = random.getrandbits(64) self.strSubVer = (b'/python-bitcoinlib:' + bitcoin.__version__.encode('ascii') + b'/') self.nStartingHeight = -1