我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用random.randint()。
def attack(opponent): rand_damage = random.randint(8,32) opponent['HP'] -= rand_damage ## if opponent['HP'] <= 0: ## opponent['HP'] = 0 ## return opponent ##print(opponent['HP']) ## else: return opponent
def client(host, port, n, task=None): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = pycos.AsyncSocket(sock) yield sock.connect((host, port)) print('%s connected' % n) # send arbitrary length of data msg = '%d: ' % n + '-' * random.randint(100,300) + '/' msg = msg.encode() yield sock.sendall(msg) sock.close() # pycos.logger.setLevel(pycos.Logger.DEBUG) # run 10 client tasks
def get_item(player): item_list = ["MRE", "First Aid Kit", "Meth-derived stim-pack"] print("You find a ", item_list[random.randint(0,2)], "your health increased by ", (abs(player['HP'] - 100)), "HP") return player['HP'] += abs(player['HP'] - 100)
def test_add_another_offset(self): topic_1 = uuidutils.generate_uuid() partition_1 = random.randint(0, 1024) until_offset_1 = random.randint(0, sys.maxsize) from_offset_1 = random.randint(0, sys.maxsize) app_name_1 = uuidutils.generate_uuid() offset_key_1 = "%s_%s_%s" % (app_name_1, topic_1, partition_1) my_batch_time = self.get_dummy_batch_time() used_values = {} self.kafka_offset_specs.add(topic=topic_1, partition=partition_1, app_name=app_name_1, from_offset=from_offset_1, until_offset=until_offset_1, batch_time_info=my_batch_time) used_values[offset_key_1] = { "topic": topic_1, "partition": partition_1, "app_name": app_name_1, "from_offset": from_offset_1, "until_offset": until_offset_1 } kafka_offset_specs = self.kafka_offset_specs.get_kafka_offsets( app_name_1) offset_value_1 = kafka_offset_specs.get(offset_key_1) self.assertions_on_offset(used_value=used_values.get(offset_key_1), offset_value=offset_value_1) self.assertEqual(1, len(self.kafka_offset_specs.get_kafka_offsets( app_name_1)))
def test_int_property(self, x_series_device, seed): # Reset the pseudorandom number generator with seed. random.seed(seed) with nidaqmx.Task() as task: task.ci_channels.add_ci_count_edges_chan( x_series_device.ci_physical_chans[0].name) # Test property default value. assert task.in_stream.offset == 0 # Test property setter and getter. value_to_test = random.randint(0, 100) task.in_stream.offset = value_to_test assert task.in_stream.offset == value_to_test value_to_test = random.randint(-100, 0) task.in_stream.offset = value_to_test assert task.in_stream.offset == value_to_test # Test property deleter. del task.in_stream.offset assert task.in_stream.offset == 0
def test_uint_property(self, x_series_device, seed): # Reset the pseudorandom number generator with seed. random.seed(seed) with nidaqmx.Task() as task: task.ai_channels.add_ai_voltage_chan( x_series_device.ai_physical_chans[0].name) task.timing.cfg_samp_clk_timing(1000) # Test property initial value. assert task.timing.samp_clk_timebase_div == 100000 # Test property setter and getter. value_to_test = random.randint(500, 10000) task.timing.samp_clk_timebase_div = value_to_test assert task.timing.samp_clk_timebase_div == value_to_test # Test property deleter. del task.timing.samp_clk_timebase_div assert task.timing.samp_clk_timebase_div == 100000
def _process_event(self, event): 'Processes an event sent to the bot.' unknown_reactions = [ 'I don\'t think I understand you correctly.\nCould you rephrase what you meant?', 'I\'m not sure I know what you mean by that.', 'Could you elaborate on this?', 'I couldn\'t catch what you meant.\nCould you say it differently?', ] is_understandable = False self._send_typing(event['channel']) for keyword in self._keywords: if keyword in event['text']: is_understandable = True if is_understandable: self._send_typing(event['channel']) self._send_menus(event) elif not is_understandable: self._send_message( event['channel'], unknown_reactions[random.randint(0, len(unknown_reactions) - 1)]) return
def augment_data(self, v_img_): # TODO: create a separate class for augmentation imsize = self.imsize for img in v_img_: #randomly flip if randint(0,65535)>32767: img[:,:,:] = img[:,:,::-1] #adjust gamma gamma = np.random.uniform(0.77,1.3, size=(imsize[0],1,1)) img **= gamma #randomly crop image coinflip = lambda:randint(0,1) if coinflip(): idx = lambda x:slice(None,x) else: idx = lambda x:slice(-x,None) if coinflip(): n = randint(0,imsize[1]/4) idx = (slice(None), idx(n), slice(None)) else: n = randint(0,imsize[2]/4) idx = (slice(None), slice(None), idx(n)) img[idx] = 0. return v_img_
def roll(text, limit=1000): groups = dice_pattern.findall(text) if len(groups) > limit: return [] result = [] for group in groups: sub_result = [] if group[0]: if group[0].startswith('-'): sign = -1 else: sign = 1 for _ in range(int(group[1])): n = int(group[2]) if n > limit: return [] sub_result.append(sign * random.randint(1, n)) elif group[3]: sub_result.append(int(group[3])) result.append(sub_result) return result
def begin(self): x = random.randint(self.x_range[0], self.x_range[1]) f = self.func(x) T = self.T0 while T > self.T_min: for i in range(self.K): new_x = self.gen_new_x(x, T) f_x = self.func(new_x) delta_E = f_x - f # if delta_E < 0: f = f_x x = new_x break else: #p_k = 1.0 / (1 + np.exp(- delta_E / self.func(T))) p_k = np.exp(- delta_E / T) if random.random() < p_k: f = f_x x = new_x break T *= self.delta return x
def __call__(self, img, mask): if self.padding > 0: img = ImageOps.expand(img, border=self.padding, fill=0) mask = ImageOps.expand(mask, border=self.padding, fill=0) assert img.size == mask.size w, h = img.size th, tw = self.size if w == tw and h == th: return img, mask if w < tw or h < th: return img.resize((tw, th), Image.BILINEAR), mask.resize((tw, th), Image.NEAREST) x1 = random.randint(0, w - tw) y1 = random.randint(0, h - th) return img.crop((x1, y1, x1 + tw, y1 + th)), mask.crop((x1, y1, x1 + tw, y1 + th))
def downloadFilesSave(links, fileFormat): # main function if (links == 'EMPTY'): # if links list is empty return ' NO LINKS FOUND !' for link in links: name = random.randint(0, 10000001) if (name in os.listdir(os.getcwd())): # random name to files name = random.randint(0, 10000001) if (format not in ['zip', 'png', 'jpg', 'jpeg', 'tiff', 'bmp', 'svg', 'gif']): try: saveFile=open(str(name)+'.' + fileFormat, 'w') saveFile.write(urllib2.urlopen(link).read()) saveFile.close() except urllib2.URLError: pass else: try: saveFile=open(str(name)+'.' + fileFormat, 'wb') saveFile.write(urllib2.urlopen(link).read()) saveFile.close() except urllib2.URLError: pass return ' {} DOWNLOADS SUCCESSFULL YET !'.format(len(os.listdir(os.getcwd())))
def genkey(n=0): n = n or random.randint(0, P) n &= ~7 n &= ~(128 << 8 * 31) n |= 64 << 8 * 31 return n # def str2int(s): # return int(hexlify(s), 16) # # return sum(ord(s[i]) << (8 * i) for i in range(32)) # # def int2str(n): # return unhexlify("%x" % n) # # return ''.join([chr((n >> (8 * i)) & 255) for i in range(32)]) #################################################
def wait_for(image, runescape_window): # adding a possible failsafe in here time_entered = time.time() # could add a failsafe in here incase we misclick or something, this # should be something to come back to failsafe_count = 0 while(True): found = pyautogui.locateOnScreen(image, region=(runescape_window.top_left_corner[0], runescape_window.top_left_corner[1], runescape_window.bottom_right_corner[ 0] - runescape_window.top_left_corner[0], runescape_window.bottom_right_corner[1] - runescape_window.top_left_corner[1])) if found != None: break elif failsafe_count > 10: print("We can't seem to fix the problem so the script is now aborting") quit() elif time.time()-time_entered > 5 : failsafe_count += 1 print('We appear to be stuck so attempting to move the mouse and see if this fixes it') #print('For debug:') #print(runescape_window.bottom_right_corner[0], runescape_window.top_left_corner[0]) #print(runescape_window.bottom_right_corner[1], runescape_window.top_left_corner[1]) realmouse.move_mouse_to(random.randint(runescape_window.top_left_corner[0], runescape_window.bottom_right_corner[0]), random.randint(runescape_window.top_left_corner[1], runescape_window.bottom_right_corner[1])) #pyautogui.click() time_entered = time.time()
def prevent_logout(top_left_corner, bottom_right_corner, runescape_window): seed = random.random() x, y = pyautogui.size() if seed > 0.5: # opens up the sale history tab for 5 seconds then returns to ge tab while(True): realmouse.move_mouse_to(random.randint(0,x), random.randint(0,y)) if len(list(pyautogui.locateAllOnScreen('Tools/screenshots/sale_history_button.png', region=(top_left_corner[0], top_left_corner[1], bottom_right_corner[0]-top_left_corner[0], bottom_right_corner[1]-top_left_corner[1]))))>0: move_mouse_to_box('Tools/screenshots/sale_history_button.png', top_left_corner, bottom_right_corner) pyautogui.click() time.sleep(9*random.random()+1) move_mouse_to_box('Tools/screenshots/grand_exchange_button.png', top_left_corner, bottom_right_corner) pyautogui.click() break else: # examines the money pouch examine_money(bottom_right_corner) # pass in an image and a search region
def generate_example(seq_length, min_val, max_val): """ Creates a list of (a,b) tuples where a is random[min_val,max_val] and b is 1 in only two tuples, 0 for the rest. The ground truth is the addition of a values for tuples with b=1. :param seq_length: length of the sequence to be generated :param min_val: minimum value for a :param max_val: maximum value for a :return x: list of (a,b) tuples :return y: ground truth """ # Select b values: one in first X% of the sequence, the other in the second Y% b1 = random.randint(0, int(seq_length * FIRST_MARKER / 100.) - 1) b2 = random.randint(int(seq_length * SECOND_MARKER / 100.), seq_length - 1) b = [0.] * seq_length b[b1] = 1. b[b2] = 1. # Generate list of tuples x = [(random.uniform(min_val, max_val), marker) for marker in b] y = x[b1][0] + x[b2][0] return x, y
def sample_hparams(): hparams = {} for k, sample_range in ranges.items(): if isinstance(sample_range, (LogRange, LinearRange)): if isinstance(sample_range[0], int): # LogRange not valid for ints hparams[k] = random.randint(sample_range[0], sample_range[1]) elif isinstance(sample_range[0], float): start, end = sample_range if isinstance(sample_range, LogRange): start, end = np.log10(start), np.log10(end) choice = np.random.uniform(start, end) if isinstance(sample_range, LogRange): choice = np.exp(choice) hparams[k] = choice return hparams
def sample(self, batch_size): """Sample a batch of experiences. Parameters ---------- batch_size: int How many transitions to sample. Returns ------- obs_batch: np.array batch of observations act_batch: np.array batch of actions executed given obs_batch rew_batch: np.array rewards received as results of executing act_batch next_obs_batch: np.array next set of observations seen after executing act_batch done_mask: np.array done_mask[i] = 1 if executing act_batch[i] resulted in the end of an episode and 0 otherwise. """ idxes = [random.randint(0, len(self._storage) - 1) for _ in range(batch_size)] return self._encode_sample(idxes)
def test_against_numpy_nanstd(self): source = [np.random.random((16, 12, 5)) for _ in range(10)] for arr in source: arr[randint(0, 15), randint(0, 11), randint(0, 4)] = np.nan stack = np.stack(source, axis = -1) for axis in (0, 1, 2, None): for ddof in range(4): with self.subTest('axis = {}, ddof = {}'.format(axis, ddof)): from_numpy = np.nanstd(stack, axis = axis, ddof = ddof) from_ivar = last(istd(source, axis = axis, ddof = ddof, ignore_nan = True)) self.assertSequenceEqual(from_numpy.shape, from_ivar.shape) self.assertTrue(np.allclose(from_ivar, from_numpy))
def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024): if not out_filename: out_filename = in_filename + '.crypt' iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16)) encryptor = AES.new(key, AES.MODE_CBC, iv) filesize = os.path.getsize(in_filename) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(struct.pack('<Q', filesize)) outfile.write(iv) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += ' ' * (16 - len(chunk) % 16) outfile.write(encryptor.encrypt(chunk))
def rotate_slaves(self): "Round-robin slave balancer" slaves = self.sentinel_manager.discover_slaves(self.service_name) if slaves: if self.slave_rr_counter is None: self.slave_rr_counter = random.randint(0, len(slaves) - 1) for _ in xrange(len(slaves)): self.slave_rr_counter = ( self.slave_rr_counter + 1) % len(slaves) slave = slaves[self.slave_rr_counter] yield slave # Fallback to the master connection try: yield self.get_master_address() except MasterNotFoundError: pass raise SlaveNotFoundError('No slave found for %r' % (self.service_name))
def choose_boundary(): global _prefix if _prefix is None: hostid = socket.gethostbyname(socket.gethostname()) try: uid = `os.getuid()` except: uid = '1' try: pid = `os.getpid()` except: pid = '1' _prefix = hostid + '.' + uid + '.' + pid timestamp = '%.3f' % time.time() seed = `random.randint(0, 32767)` return _prefix + '.' + timestamp + '.' + seed
def getRandomPixePositionl(): """ Returns the position of a random pixel in the image """ # Get image size width, height = getSize() # Get random pixel a, b = random.randint(0, width - 1), random.randint(0, height - 1) # Debug if args.debug: print('...debug -> random pixel: %d , %d' % (a, b)) return a, b
def perturb(self): ''' Peturb the paramter by choosing a random value between val_min and val_max. Will choose a random number with precision specified by decimals. Will optionally pick the min or the max value after a specified number of perturb calls ''' if self.n == self.n_max - 1: # Choose and extreme value self.val = random.sample([self.val_min, self.val_max], 1)[0] self.n = 0 else: if self.decimals == 0: self.val = random.randint(self.val_min,self.val_max) else: self.val = random.random() * (self.val_max - self.val_min + 10**-self.decimals) + (self.val_min - 0.5 * 10**-self.decimals) self.val = round(self.val, ndigits=self.decimals) if self.n_max > 0: self.n += 1
def encode(image, number): '''Encodes the key into the image. Note: number is the str of a bin!''' width, height = image.size # Make sure that the image is large enough if width < len(number): return False line = randint(0,height) column = width - len(number) -1 px = image.load() for i, char in enumerate(number): i += column color = ((px[i, line][2] // 10) * 10) + int(char) px[i, line]= (px[i,line][0], px[i,line][1], color) image.save('encoded.png', 'PNG', quality=100) return True
def unique_books(user, books, result_count): """ Return unique random books from given list of books. :param django.contrib.auth.models.User user: The request user. :param django.db.models.query.QuerySet[.models.Book] books: The given list of books. :param int result_count: The count of unique books. :return set[.models.Book]: The unique books. """ books = Book.exclude_private_books(user, books) unique = set() if len(books) > START_RECOMMEND: while len(unique) < result_count: unique.add(books[random.randint(0, len(books) - 1)]) return unique
def update_p95(self, value): r_len = 0 r_exists = True if self.reservoir == None: r_exists = False else: r_len = len(self.reservoir) if not r_exists: self.reservoir = [] if r_len < self.RESERVOIR_SIZE: self.reservoir.append(value) else: self.reservoir[random.randint(0, self.RESERVOIR_SIZE - 1)] = value self.num_samples += 1
def __setMail(self, email): code = random.randint(1000,9999) re = RecoveryEmail(jid=self.jid, email=email, code=code) self.s.merge(re) self.s.commit() msg = ( 'Please verify your e-mail address by sending ' '"code %s" via XMPP back.' ) % str(code) self.__sendMail(email, 'verification code for pimux.de', msg) message =( 'A confirmation code was sent to %s. ' 'Please now send "code XXXX" back where XXXX is your ' 'code to verify your e-mail address.' ) % email return message
def random_context(): result = {} if random.getrandbits(1): result["function_name"] = RunLambdaCliTest.random_string() if random.getrandbits(1): result["function_version"] = RunLambdaCliTest.random_string() if random.getrandbits(1): result["invoked_function_arn"] = RunLambdaCliTest.random_string() if random.getrandbits(1): result["memory_limit_in_mb"] = str(random.randint(100, 200)) if random.getrandbits(1): result["aws_request_id"] = RunLambdaCliTest.random_string() if random.getrandbits(1): result["log_group_name"] = RunLambdaCliTest.random_string() if random.getrandbits(1): result["log_stream_name"] = RunLambdaCliTest.random_string() if random.getrandbits(1): result["identity"] = RunLambdaCliTest.random_identity() if random.getrandbits(1): result["client_context"] = RunLambdaCliTest.random_client_context() return result
def act(self, observation, last_reward): if len(self.fun) == 0: print("\nFUN", end="") fun_length = random.randint(5, 15) self.actions = self.actions[::-1] self.fun = sum([[a] * fun_length for a in self.actions], []) elif self.fun[0] == self.actions[0]: print(">" if self.fun[0] == 2 else "<", end="") action = self.fun.pop(-1) if last_reward > 0: # lose print("TENSAI!!!!!") self.fun = [0] * 5 # stop a while to shout return action
def send_request(self, method: str, params): _id = random.randint(0, 2 ** 16) # TODO(renfred) guarantee uniqueness. body = { "jsonrpc": "2.0", "id": _id, "method": method, "params": params, } body = json.dumps(body, separators=(",", ":")) content_length = len(body) request = ( "Content-Length: {}\r\n" "Content-Type: application/vscode-jsonrpc; charset=utf8\r\n\r\n" "{}".format(content_length, body)) log("SENDING REQUEST: ", request) self.conn.write(request) return self.read_message(_id)
def fetch (src, save, db, collection, p, f): """This is the worker function to get the next recipe from the pending queue, save it, and put all the related urls on the pending queue for other workers to process""" while True: url = p.get() if url in f.queue: p.task_done() else: try: recipe = src(url) if save: recipe.save() if db is not None and collection is not None: recipe.store(db, collection) f.put(url) map(lambda x: p.put(x), filter(lambda link: link != url, recipe.getOtherRecipeLinks())) except ValueError: print '[warning] could not fetch:', url p.task_done() if PAUSE_CRAWLER: # pause a random interval between PAUSE_TIME_RANGE seconds before continuing sleep(randint(PAUSE_TIME_RANGE[0], PAUSE_TIME_RANGE[1]))
def get_batch(): ran = random.randint(600, data_size) #print(ran) image = [] label = [] label_0 = [] n_pic = ran # print(n_pic) for i in range(batch_size * n_steps): frame_0 = cv2.imread('./cropedoriginalPixel2/%d.jpg' % (n_pic+i), 0) frame_0 = cv2.resize(frame_0, (LONGITUDE, LONGITUDE)) frame_0 = np.array(frame_0).reshape(-1) image.append(frame_0) #print(np.shape(image)) for i in range(batch_size): frame_1 = cv2.imread('./cropedoriginalPixel2/%d.jpg' % (n_pic + batch_size * (i+1) ), 0) frame_1 = cv2.resize(frame_1, (LONGITUDE, LONGITUDE)) frame_1 = np.array(frame_1).reshape(-1) label.append(frame_1) for i in range(batch_size): frame_2 = cv2.imread('./cropedoriginalUS2/%d.jpg' % (n_pic + batch_size * (i+1) ), 0) frame_2 = cv2.resize(frame_2, (LONGITUDE, LONGITUDE)) frame_2 = np.array(frame_2).reshape(-1) label_0.append(frame_2) return image , label , label_0
def get_train_batch(noise=0): ran = random.randint(600, data_size) #print(ran) image = [] label = [] label_0 = [] n_pic = ran # print(n_pic) for i in range(batch_size ): frame_0 = cv2.imread('./cropedoriginalPixel2/%d.jpg' % (n_pic+i), 0) frame_0 = add_noise(frame_0, n = noise) frame_0 = cv2.resize(frame_0, (LONGITUDE, LONGITUDE)) frame_0 = np.array(frame_0).reshape(-1) image.append(frame_0) #print(np.shape(image)) for i in range(batch_size): frame_1 = cv2.imread('./cropedoriginalPixel2/%d.jpg' % (n_pic + batch_size * (i+1) ), 0) frame_1 = cv2.resize(frame_1, (LONGITUDE, LONGITUDE)) frame_1 = np.array(frame_1).reshape(-1) label.append(frame_1) return image , label
def start_appium(self): """ ??appium p:appium port bp:bootstrap port :return: ??appium???? """ aport = random.randint(4700, 4900) bpport = random.randint(4700, 4900) self.__start_driver(aport, bpport) U.Logging.debug( 'start appium :p %s bp %s device:%s' % (aport, bpport, self.device)) U.sleep(10) return aport
def mkdir_file(self): """ :return:????????? """ ini = U.ConfigIni() result_file = str(ini.get_ini('test_case', 'log_file')) result_file_every = result_file + '/' + \ time.strftime("%Y-%m-%d_%H_%M_%S{}".format(random.randint(10, 99)), time.localtime(time.time())) file_list = [ result_file, result_file_every, result_file_every + '/log', result_file_every + '/per', result_file_every + '/img', result_file_every + '/status'] if not os.path.exists(result_file): os.mkdir(result_file) for file_path in file_list: if not os.path.exists(file_path): os.mkdir(file_path) return result_file_every
def generateHash(tamanho=10): gerado = "" for i in range(tamanho): gerado += chr(rand(65,90)) return gerado
def generateIntHash(tamanho=10): gerado = "" for i in range(tamanho): gerado += str(rand(0,9)) return int(gerado)
def stick_mesh(width, height, depth): x = max(width,height,depth) * unit + unit step = unit/20 stick = cube([x,step,step]) b = cube([x,step,step]) b += translate([0,x,0])( cube([x,step,step]) ) b += cube([step,x,step]) b += translate([x,0,0])( cube([step,x,step]) ) b = b + translate([0,0,x])(b) b += cube([step,step,x]) b += translate([0,x,0])(cube([step,step,x])) b += translate([x,0,0])(cube([step,step,x])) b += translate([x,x,0])(cube([step,step,x])) sticks = [] for i in range(2000): trans = [randint(int(-100 * x*2/3),int(x*100*2/3))/100.0 for i in range(3)] rot = [randint(0,3600)/10. for i in range(3)] sticks.append(translate([x/2,x/2,x/2])( translate(trans)(rotate(rot)(stick)) )) b = b + union()(*sticks) b = b * cube(x+step) return b
def random_different_from(top_range, number_to_not_repeat): result = random.randint(0, top_range-1) while result == number_to_not_repeat: result = random.randint(0, top_range-1) return result
def get_item(player): item_list = ["MRE", "First Aid Kit", "Meth-derived stim-pack"] print("You find a ", item_list[random.randint(0, 2)], "your health increased by ", (abs(player['HP'] - 100)), "HP") player['HP'] += (abs(player['HP'] - 100)) return player
def attack(opponent): rand_damage = random.randint(8, 32) opponent['HP'] -= rand_damage print(rand_damage, " damage!") return opponent