Python random.getstate() Examples
The following are 30
code examples of random.getstate().
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: runner.py From skeltorch with MIT License | 7 votes |
def save_states(self): """Saves the states inside a checkpoint associated with ``epoch``.""" checkpoint_data = dict() if isinstance(self.model, torch.nn.DataParallel): checkpoint_data['model'] = self.model.module.state_dict() else: checkpoint_data['model'] = self.model.state_dict() checkpoint_data['optimizer'] = self.optimizer.state_dict() checkpoint_data['random_states'] = ( random.getstate(), np.random.get_state(), torch.get_rng_state(), torch.cuda.get_rng_state() if torch.cuda.is_available() else None ) checkpoint_data['counters'] = self.counters checkpoint_data['losses_epoch'] = self.losses_epoch checkpoint_data['losses_it'] = self.losses_it checkpoint_data.update(self.save_states_others()) self.experiment.checkpoint_save(checkpoint_data, self.counters['epoch'])
Example #2
Source File: solution.py From tiny_python_projects with MIT License | 6 votes |
def test_scramble(): """Test scramble""" state = random.getstate() random.seed(1) assert scramble("a") == "a" assert scramble("ab") == "ab" assert scramble("abc") == "abc" assert scramble("abcd") == "acbd" assert scramble("abcde") == "acbde" assert scramble("abcdef") == "aecbdf" assert scramble("abcde'f") == "abcd'ef" random.setstate(state) # --------------------------------------------------
Example #3
Source File: test_single_turn_dialog.py From cotk with Apache License 2.0 | 6 votes |
def base_test_restart(self, dl): with pytest.raises(ValueError): dl.restart("unknown set") for set_name in dl.data.keys(): with pytest.raises(ValueError): dl.restart(set_name) record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, batch_size=3, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0 assert dl.batch_size[set_name] == 3 #rng_state_st = random.getstate() dl.restart(set_name, shuffle=True) #rng_state_ed = random.getstate() #assert operator.eq(rng_state_st, rng_state_ed) assert dl.batch_id[set_name] == 0 record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0
Example #4
Source File: install.py From BioQueue with Apache License 2.0 | 6 votes |
def get_random_secret_key(): import random import hashlib import time try: random = random.SystemRandom() using_sysrandom = True except NotImplementedError: import warnings warnings.warn('A secure pseudo-random number generator is not available ' 'on your system. Falling back to Mersenne Twister.') using_sysrandom = False chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$^&*(-_=+)' if not using_sysrandom: random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), 'BioQueue')).encode('utf-8') ).digest()) return ''.join(random.choice(chars) for i in range(50))
Example #5
Source File: model.py From simple-effective-text-matching-pytorch with Apache License 2.0 | 6 votes |
def save(self, states, name=None): if name: filename = os.path.join(self.args.summary_dir, name) else: filename = os.path.join(self.args.summary_dir, f'{self.prefix}_{self.updates}.pt') params = { 'state_dict': { 'model': self.network.state_dict(), 'opt': self.opt.state_dict(), 'updates': self.updates, }, 'args': self.args, 'random_state': random.getstate(), 'torch_state': torch.random.get_rng_state() } params.update(states) if self.args.cuda: params['torch_cuda_state'] = torch.cuda.get_rng_state() torch.save(params, filename)
Example #6
Source File: test_dataloader.py From cotk with Apache License 2.0 | 6 votes |
def base_test_restart(self, lp: LanguageProcessing): with pytest.raises(ValueError): lp.restart("unknown set") for set_name in lp.data.keys(): with pytest.raises(ValueError): lp.restart(set_name) record_index = copy.copy(lp.index[set_name]) lp.restart(set_name, batch_size=3, shuffle=False) assert record_index == lp.index[set_name] assert lp.batch_id[set_name] == 0 assert lp.batch_size[set_name] == 3 #rng_state_st = random.getstate() lp.restart(set_name, shuffle=True) #rng_state_ed = random.getstate() #assert operator.eq(rng_state_st, rng_state_ed) assert lp.batch_id[set_name] == 0 record_index = copy.copy(lp.index[set_name]) lp.restart(set_name, shuffle=False) assert record_index == lp.index[set_name] assert lp.batch_id[set_name] == 0
Example #7
Source File: test_dataloader.py From cotk with Apache License 2.0 | 6 votes |
def base_test_get_batches(self, lp: LanguageProcessing): lp_cp = copy.deepcopy(lp) for set_name in lp.data.keys(): #rng_state = random.getstate() lp_batches = iter(lp.get_batches(set_name, 3, False)) #random.setstate(rng_state) lp_cp.restart(set_name, 3, False) while True: res_cp = lp_cp.get_next_batch(set_name) if res_cp is None: break res = next(lp_batches) assert sorted(res_cp.keys()) == sorted(res.keys()) for key in res_cp.keys(): if isinstance(res_cp[key], np.ndarray): assert (res_cp[key] == res[key]).all() else: assert res_cp[key] == res[key]
Example #8
Source File: common.py From jet-bridge with MIT License | 6 votes |
def get_random_string(length, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', salt=''): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), salt)).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length))
Example #9
Source File: crypto.py From bioforum with MIT License | 6 votes |
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Return a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode() ).digest() ) return ''.join(random.choice(allowed_chars) for i in range(length))
Example #10
Source File: test_language_generation.py From cotk with Apache License 2.0 | 6 votes |
def base_test_restart(self, dl): with pytest.raises(ValueError): dl.restart("unknown set") for set_name in dl.data.keys(): with pytest.raises(ValueError): dl.restart(set_name) record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, batch_size=3, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0 assert dl.batch_size[set_name] == 3 #rng_state_st = random.getstate() dl.restart(set_name, shuffle=True) #rng_state_ed = random.getstate() #assert operator.eq(rng_state_st, rng_state_ed) assert dl.batch_id[set_name] == 0 record_index = copy.copy(dl.index[set_name]) dl.restart(set_name, shuffle=False) assert record_index == dl.index[set_name] assert dl.batch_id[set_name] == 0
Example #11
Source File: crypto.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), settings.SECRET_KEY)).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length))
Example #12
Source File: __init__.py From picklable-itertools with MIT License | 6 votes |
def verify_tee(n, original, seed): try: state = random.getstate() iterators = list(tee(original, n=n)) results = [[] for _ in range(n)] exhausted = [False] * n while not all(exhausted): # Upper argument of random.randint is inclusive. Argh. i = random.randint(0, n - 1) if not exhausted[i]: if len(results[i]) == len(original): assert_raises(StopIteration, next, iterators[i]) assert results[i] == original exhausted[i] = True else: if random.randint(0, 1): iterators[i] = cPickle.loads( cPickle.dumps(iterators[i])) elem = next(iterators[i]) results[i].append(elem) finally: random.setstate(state)
Example #13
Source File: crypto.py From python2017 with MIT License | 6 votes |
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), settings.SECRET_KEY)).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length))
Example #14
Source File: _simple_replay_buffer_with_rand_state.py From rl_swiss with MIT License | 6 votes |
def __init__( self, max_rb_size_per_task, observation_dim, action_dim, discrete_action_dim=False, policy_uses_pixels=False, policy_uses_task_params=False, concat_task_params_to_policy_obs=False, random_seed=2001 ): prev_py_rand_state = python_random.getstate() python_random.seed(random_seed) self._py_rand_state = python_random.getstate() python_random.setstate(prev_py_rand_state) self._obs_dim = observation_dim self._act_dim = action_dim self._max_rb_size_per_task = max_rb_size_per_task self._disc_act_dim = discrete_action_dim self._policy_uses_pixels = policy_uses_pixels self._policy_uses_task_params = policy_uses_task_params self._concat_task_params_to_policy_obs = concat_task_params_to_policy_obs p = self._get_partial() self.task_replay_buffers = defaultdict(p)
Example #15
Source File: utils.py From CSBDeep with BSD 3-Clause "New" or "Revised" License | 6 votes |
def choice(population, k=1, replace=True): ver = platform.sys.version_info if replace and (ver.major,ver.minor) in [(2,7),(3,5)]: # python 2.7 or 3.5 # slow if population is large and not a np.ndarray return list(np.random.choice(population, k, replace=replace)) else: try: # save state of 'random' and set seed using 'np.random' state = random.getstate() random.seed(np.random.randint(np.iinfo(int).min, np.iinfo(int).max)) if replace: # sample with replacement return random.choices(population, k=k) else: # sample without replacement return random.sample(population, k=k) finally: # restore state of 'random' random.setstate(state)
Example #16
Source File: subset.py From diogenes with MIT License | 6 votes |
def __iter__(self): y = self._y subset_size = self.__subset_size n_subsets = self.__n_subsets count = Counter(y) n_categories = len(count) proportions = {key: 1.0 / n_categories for key in count} n_choices = {key: int(proportions[key] * subset_size) for key in proportions} indices = {key: np.where(y == key)[0] for key in count} seed(self.__random_state_seed) random_state = getstate() for i in xrange(n_subsets): setstate(random_state) samples = {key: sample(indices[key], n_choices[key]) for key in count} random_state = getstate() all_indices = np.sort(np.concatenate(samples.values())) yield (all_indices, self._col_names, {'sample_num': i})
Example #17
Source File: utils.py From lang2program with Apache License 2.0 | 6 votes |
def random_seed(seed=None): """Execute code inside this with-block using the specified seed. If no seed is specified, nothing happens. Does not affect the state of the random number generator outside this block. Not thread-safe. Args: seed (int): random seed """ if seed is None: yield else: py_state = random.getstate() # save state np_state = np.random.get_state() random.seed(seed) # alter state np.random.seed(seed) yield random.setstate(py_state) # restore state np.random.set_state(np_state)
Example #18
Source File: subset.py From diogenes with MIT License | 6 votes |
def __iter__(self): y = self._y subset_size = self.__subset_size positive_cases = np.where(y)[0] negative_cases = np.where(np.logical_not(y))[0] seed(self.__random_state_seed) random_state = getstate() for prop_pos in self.__proportions_positive: setstate(random_state) positive_sample = sample(positive_cases, int(subset_size * prop_pos)) negative_sample = sample(negative_cases, int(subset_size * (1 - prop_pos))) random_state = getstate() # If one of these sets is empty, concatentating them casts to float, so we have # to cast it back (hence the astype) all_indices = np.sort(np.concatenate([positive_sample, negative_sample])).astype(int) yield (all_indices, self._col_names, 'prop_positive={}'.format(prop_pos))
Example #19
Source File: penis.py From 26-Cogs with GNU General Public License v3.0 | 6 votes |
def penis(self, ctx, *users: discord.Member): """Detects user's penis length This is 100% accurate. Enter multiple users for an accurate comparison!""" if not users: await self.bot.send_cmd_help(ctx) return dongs = {} msg = "" state = random.getstate() for user in users: random.seed(user.id) dongs[user] = "8{}D".format("=" * random.randint(0, 30)) random.setstate(state) dongs = sorted(dongs.items(), key=lambda x: x[1]) for user, dong in dongs: msg += "**{}'s size:**\n{}\n".format(user.display_name, dong) for page in pagify(msg): await self.bot.say(page)
Example #20
Source File: random.py From cupy with MIT License | 6 votes |
def do_setup(deterministic=True): global _old_python_random_state global _old_numpy_random_state global _old_cupy_random_states _old_python_random_state = random.getstate() _old_numpy_random_state = numpy.random.get_state() _old_cupy_random_states = cupy.random.generator._random_states cupy.random.reset_states() # Check that _random_state has been recreated in # cupy.random.reset_states(). Otherwise the contents of # _old_cupy_random_states would be overwritten. assert (cupy.random.generator._random_states is not _old_cupy_random_states) if not deterministic: random.seed() numpy.random.seed() cupy.random.seed() else: random.seed(99) numpy.random.seed(100) cupy.random.seed(101)
Example #21
Source File: utils.py From lang2program with Apache License 2.0 | 6 votes |
def random_seed(seed=None): """Execute code inside this with-block using the specified seed. If no seed is specified, nothing happens. Does not affect the state of the random number generator outside this block. Not thread-safe. Args: seed (int): random seed """ if seed is None: yield else: py_state = random.getstate() # save state np_state = np.random.get_state() random.seed(seed) # alter state np.random.seed(seed) yield random.setstate(py_state) # restore state np.random.set_state(np_state)
Example #22
Source File: _session.py From flexx with BSD 2-Clause "Simplified" License | 6 votes |
def get_random_string(length=24, allowed_chars=None): """ Produce a securely generated random string. With a length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ allowed_chars = allowed_chars or ('abcdefghijklmnopqrstuvwxyz' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') try: srandom = random.SystemRandom() except NotImplementedError: # pragma: no cover srandom = random logger.warning('Falling back to less secure Mersenne Twister random string.') bogus = "%s%s%s" % (random.getstate(), time.time(), 'sdkhfbsdkfbsdbhf') random.seed(hashlib.sha256(bogus.encode()).digest()) return ''.join(srandom.choice(allowed_chars) for i in range(length))
Example #23
Source File: crypto.py From openhgsenti with Apache License 2.0 | 6 votes |
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), settings.SECRET_KEY)).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length))
Example #24
Source File: crypto.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Return a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode() ).digest() ) return ''.join(random.choice(allowed_chars) for i in range(length))
Example #25
Source File: crypto.py From python with Apache License 2.0 | 6 votes |
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), settings.SECRET_KEY)).encode('utf-8') ).digest()) return ''.join(random.choice(allowed_chars) for i in range(length))
Example #26
Source File: crypto.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyz' 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'): """ Returns a securely generated random string. The default length of 12 with the a-z, A-Z, 0-9 character set returns a 71-bit value. log_2((26+26+10)^12) =~ 71 bits """ if not using_sysrandom: # This is ugly, and a hack, but it makes things better than # the alternative of predictability. This re-seeds the PRNG # using a value that is hard for an attacker to predict, every # time a random string is required. This may change the # properties of the chosen random sequence slightly, but this # is better than absolute predictability. random.seed( hashlib.sha256( ("%s%s%s" % ( random.getstate(), time.time(), settings.SECRET_KEY)).encode('utf-8') ).digest()) return ''.join([random.choice(allowed_chars) for i in range(length)])
Example #27
Source File: subset.py From diogenes with MIT License | 6 votes |
def __iter__(self): y = self._y subset_size = self.__subset_size n_subsets = self.__n_subsets count = Counter(y) size_space = float(sum(count.values())) proportions = {key: count[key] / size_space for key in count} n_choices = {key: int(proportions[key] * subset_size) for key in proportions} indices = {key: np.where(y == key)[0] for key in count} seed(self.__random_state_seed) random_state = getstate() for i in xrange(n_subsets): setstate(random_state) samples = {key: sample(indices[key], n_choices[key]) for key in count} random_state = getstate() all_indices = np.sort(np.concatenate(samples.values())) yield (all_indices, self._col_names, {'sample_num': i})
Example #28
Source File: iterator.py From pytorch-nlp with MIT License | 5 votes |
def use_internal_state(self): """Use a specific RNG state.""" old_state = random.getstate() random.setstate(self._random_state) yield self._random_state = random.getstate() random.setstate(old_state)
Example #29
Source File: solution6_map.py From tiny_python_projects with MIT License | 5 votes |
def test_choose(): """Test choose""" state = random.getstate() random.seed(1) assert choose('a') == 'a' assert choose('b') == 'b' assert choose('c') == 'C' assert choose('d') == 'd' random.setstate(state) # --------------------------------------------------
Example #30
Source File: solution4_list_comprehension.py From tiny_python_projects with MIT License | 5 votes |
def test_choose(): """Test choose""" state = random.getstate() random.seed(1) assert choose('a') == 'a' assert choose('b') == 'b' assert choose('c') == 'C' assert choose('d') == 'd' random.setstate(state) # --------------------------------------------------