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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: test_event_images_v1.py From linkedevents with MIT License | 5 votes |
def test__upload_a_non_valid_image(api_client, list_url, user, organization): organization.admin_users.add(user) api_client.force_authenticate(user) non_image_file = BytesIO(bytes(random.getrandbits(8) for _ in range(100))) response = api_client.post(list_url, {'image': non_image_file}) assert response.status_code == 400 assert 'image' in response.data
Example #12
Source File: test_zipfile.py From ironpython2 with Apache License 2.0 | 5 votes |
def getrandbytes(size): return bytes(bytearray.fromhex('%0*x' % (2 * size, getrandbits(8 * size))))
Example #13
Source File: models.py From backend with GNU General Public License v2.0 | 5 votes |
def create(session, user, label, permission_list, ip_white_list, revocable): api_key = base64.b64encode(hashlib.sha256( str(random.getrandbits(256)) ).digest(), random.choice(['rA','aZ','gQ','hH','hG','aR','DD'])).rstrip('==') api_secret = base64.b64encode(hashlib.sha256( str(random.getrandbits(256)) ).digest(), random.choice(['rA','aZ','gQ','hH','hG','aR','DD'])).rstrip('==') password_salt = get_hexdigest('sha1', str(random.random()), str(random.random()))[:5] raw_password = base64.b64encode(hashlib.sha256( str(random.getrandbits(256)) ).digest(), random.choice(['rA','aZ','gQ','hH','hG','aR','DD'])).rstrip('==')[:15] password = get_hexdigest('sha1', password_salt, raw_password ) api_access = ApiAccess( api_key = api_key, user_id = user.id, username = user.username, broker_id = user.broker_id, broker_username = user.broker_username, label = label, api_secret = api_secret, api_password_salt = password_salt, api_password = password, revocable = revocable, ip_white_list = json.dumps(ip_white_list), permission_list = json.dumps(permission_list)) session.add(api_access) session.flush() return api_access, raw_password
Example #14
Source File: accounts.py From pyethapp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def mk_random_privkey(): k = hex(random.getrandbits(256))[2:-1].zfill(64) assert len(k) == 64 return k.decode('hex')
Example #15
Source File: psign.py From fcatalog_server with GNU General Public License v3.0 | 5 votes |
def rand_bytes(n): """ Get n random bytes. """ return bytes(random.getrandbits(8) for i in range(n))
Example #16
Source File: proc_avoid_deadlock.py From pyplus_course with Apache License 2.0 | 5 votes |
def my_func(name, output_q): output_dict = {} output_dict[name] = [] for i in range(0, 50000): # print(i) # print(output_q.full()) output_dict[name].append(random.getrandbits(128)) output_q.put(output_dict) return
Example #17
Source File: test_zlib.py From BinderFilter with MIT License | 5 votes |
def check_big_compress_buffer(self, size, compress_func): _1M = 1024 * 1024 fmt = "%%0%dx" % (2 * _1M) # Generate 10MB worth of random, and expand it by repeating it. # The assumption is that zlib's memory is not big enough to exploit # such spread out redundancy. data = ''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M)) for i in range(10)]) data = data * (size // len(data) + 1) try: compress_func(data) finally: # Release memory data = None
Example #18
Source File: random_number_generator.py From locality-sensitive-hashing with MIT License | 5 votes |
def generate_random_numbers(n=1, bits=32): """ Generates n random numbers. :param n: number of random numbers to generate :param bits: number of bits each random number should contain. :return: list of long integer random numbers. """ return [random.getrandbits(bits) for _ in range(0, n)]
Example #19
Source File: blobs.py From locality-sensitive-hashing with MIT License | 5 votes |
def run(self, filename, blobkey, ds_key): params = "filename %s \tblobkey %s\tds_key %s" % (filename, blobkey, ds_key) logging.info(params) dataset = ndb.Key(urlsafe=ds_key).get() rows = dataset.rows hashes = rows * dataset.bands if len(dataset.random_seeds) != hashes: dataset.random_seeds = [random.getrandbits(max_bits) for _ in xrange(hashes)] logging.warning('Recalculated %d random seeds', hashes) dataset.put() dataset.buckets = [] dataset.put() output = yield mapreduce_pipeline.MapreducePipeline( "locality_sensitive_hashing", "blobs.lsh_map", "blobs.lsh_bucket", 'mapreduce.input_readers.BlobstoreZipLineInputReader', "mapreduce.output_writers.BlobstoreOutputWriter", mapper_params={ "blob_keys": blobkey, }, reducer_params={ "mime_type": "text/plain", }, shards=16) yield StoreLshResults('OpenLSH', blobkey, ds_key, output)
Example #20
Source File: Generator.py From ID2T with MIT License | 5 votes |
def _random_mac(self) -> str: mac_bytes = bytearray(getrandbits(8) for i in range(6)) if not self.broadcast: mac_bytes[0] &= ~1 # clear the first bytes' first bit if not self.virtual: mac_bytes[0] &= ~2 # clear the first bytes' second bit return ":".join("%02X" % b for b in mac_bytes) ################################################# ######## UDP/TCP Packet generation ######## #################################################
Example #21
Source File: lsh_matrix.py From locality-sensitive-hashing with MIT License | 5 votes |
def create(cls, source, filename, file_key = '', rows = settings.rows, bands = settings.bands, shingle_type = settings.shingle_type, minhash_modulo = settings.minhash_modulo): # logging.debug('Matrix.create cls = %s, vars = %s', cls, vars(cls)) Matrix._initialize() # logging.debug('Matrix.create inputs %s, %s, %s', source, filename, file_key) ds_key = cls.make_new_id(source, filename) # logging.debug('Matrix.create ds_key %s', ds_key) max_hashes = rows * bands data = { 'ds_key': '%s' % ds_key, 'source': '%s' % source, 'filename': '%s' % filename, 'file_key': '%s' % file_key, 'random_seeds': [(settings.max_mask & random.getrandbits(settings.max_bits)) for _ in xrange(max_hashes)], 'rows': rows, 'bands': bands, 'shingle_type': '%s' % shingle_type, 'minhash_modulo': minhash_modulo, } Matrix.insert_row(data = data) matrix = Matrix.find(ds_key) # logging.debug('Matrix.create returning %s', matrix) return matrix
Example #22
Source File: dataset.py From locality-sensitive-hashing with MIT License | 5 votes |
def get_random_bits(max_hashes): return [random.getrandbits(get_max_bits()) for _ in xrange(max_hashes)]
Example #23
Source File: xmpp.py From minemeld-core with Apache License 2.0 | 5 votes |
def _xmpp_session_start(self, event): LOG.debug('%s - _xmpp_session_start', self.name) self._xmpp_client.get_roster() self._xmpp_client.send_presence() if self.sequence_number is None: self.sequence_number = random.getrandbits(64) self._xmpp_publish('INIT') self._xmpp_client_ready.set()
Example #24
Source File: deimos-test.py From deimos with Apache License 2.0 | 5 votes |
def __init__(self, trials=10): self.token = "%08x" % random.getrandbits(32) self.trials = trials self.tasks = [] self.statuses = {} self.log = log.getChild("scheduler") self.loggers = {}
Example #25
Source File: test_zlib.py From ironpython2 with Apache License 2.0 | 5 votes |
def check_big_compress_buffer(self, size, compress_func): _1M = 1024 * 1024 fmt = "%%0%dx" % (2 * _1M) # Generate 10MB worth of random, and expand it by repeating it. # The assumption is that zlib's memory is not big enough to exploit # such spread out redundancy. data = ''.join([binascii.a2b_hex(fmt % random.getrandbits(8 * _1M)) for i in range(10)]) data = data * (size // len(data) + 1) try: compress_func(data) finally: # Release memory data = None
Example #26
Source File: conftest.py From torf with GNU General Public License v3.0 | 5 votes |
def _generate_random_file(dirpath, filename=None, hidden=False): filesize = random.randint(1e3, 1e6) filecontent = bytearray(random.getrandbits(8) for _ in range(filesize)) if filename is None: filename = '' filename += ':' + _randstr() if hidden: filename = '.' + filename filepath = os.path.join(testdir_base, dirpath, filename) with open(filepath, 'wb') as f: f.write(filecontent) assert os.path.getsize(filepath) == filesize return filepath
Example #27
Source File: cli.py From invenio-app-ils with MIT License | 5 votes |
def generate(self): """Generate.""" size = self.holder.eitems["total"] doc_pids = self.holder.pids("documents", "pid") objs = [ { "pid": self.create_pid(), "document_pid": random.choice(doc_pids), "description": "{}".format(lorem.text()), "internal_notes": "{}".format(lorem.text()), "urls": [ { "value": "https://home.cern/science/physics/dark-matter", "description": "Dark matter" }, { "value": "https://home.cern/science/physics/antimatter", "description": "Anti matter" }, ], "open_access": bool(random.getrandbits(1)), } for pid in range(1, size + 1) ] self.holder.eitems["objs"] = objs
Example #28
Source File: FMOperation.py From sprutio with GNU General Public License v3.0 | 5 votes |
def _generate_id(): return str(time.time()) + ("%032x" % random.getrandbits(16))
Example #29
Source File: helpers.py From sprutio with GNU General Public License v3.0 | 5 votes |
def random_hash(): hash_str = random.getrandbits(128) return "%032x" % hash_str
Example #30
Source File: UploadHandler.py From sprutio with GNU General Public License v3.0 | 5 votes |
def random_hash(): hash_str = random.getrandbits(128) return "%032x" % hash_str