def draw_walls(self): """ This function draws walls """ walls = [] walls_1 = [] for i in range(rint(self.N // 4, self.N // 3)): walls.append( Wall(self.screen, rint(1, self.N - 4) * self.cell_size, rint(3, self.N // 2 - 2) * self.cell_size, rint(1, self.N // 4) * self.cell_size, rint(1, self.N // 4) * self.cell_size)) for j in range(walls[i].height // self.cell_size): for k in range(walls[i].width // self.cell_size): self.cells[walls[i].x // self.cell_size + j][walls[i].y // self.cell_size + k - 1][2] = -1 ind = 0 for i in walls: walls_1.append( Wall(self.screen, i.x, self.screen_width - i.y - i.width, i.height, i.width)) for j in range(walls_1[ind].height // self.cell_size): for k in range(walls_1[ind].width // self.cell_size): self.cells[walls_1[ind].x // self.cell_size + j][walls_1[ind].y // self.cell_size + k - 1][2] = -1 ind += 1 self.walls = walls self.walls_1 = walls_1 for i in self.walls: i.draw_wall() for i in self.walls_1: i.draw_wall()
def draw_bounding_box_class(org, compos, color_map=C.COLOR, line=2, show=False, is_return=False, name='img', wait_key=0): if not show and not is_return: return board = org.copy() class_colors = color_map for compo in compos: if compo.category not in class_colors: class_colors[compo.category] = (rint(0, 255), rint(0, 255), rint(0, 255)) corner = compo.put_bbox() board = cv2.rectangle(board, (corner[0], corner[1]), (corner[2], corner[3]), class_colors[compo.category], line) # board = cv2.putText(board, compo_class[i], (corners[i][0]+5, corners[i][1]+20), # cv2.FONT_HERSHEY_SIMPLEX, 0.5, class_colors[compo_class[i]], 2) if show: cv2.imshow(name, board) if wait_key is not None: cv2.waitKey(wait_key) return board
def mk_compose_ud(up_down): if up_down == 1: last_subbar().append([pick_scale_ch_prog(rint(4, 7)), app_beat()]) else: last_subbar().append([pick_scale_ch_prog(rint(1, 4)), app_beat()]) if last_subbar().count(-1) < len(last_subbar()) / 1.5 and rint(1, 2) == 1: last_subbar().append([-1, app_beat()])
def transistion(graph): """ Computes transition of a random source node to a new district and returns the proposed new district, the node, and its transition probabilities in both directions """ # Acquire a source node at random from the full set of available nodes and # produce a list of districts of its neighbouring nodes ncount = len(list(graph.nodes)) sourceNode = rint(1, ncount) nbors = list(graph.neighbors(sourceNode)) nbors_distrs = [] for node in nbors: nbors_distrs.append(graph.nodes[node]["distr"]) # Log the current and proposed new districts for computing transition # probabilities and sending forward to acceptance probability cur_distr = graph.nodes[sourceNode]["distr"] prop_distr = nbors_distrs[rint(0, len(nbors_distrs) - 1)] # Compute 'outbound' transition probability as number of neighbours in the # proposed district over the total number of neighbours # # Compute 'inbound' transition as the number of neighbours in the original # source district over the total number of neighbors trans_out = nbors_distrs.count(prop_distr) / len(nbors) trans_in = nbors_distrs.count(cur_distr) / len(nbors) trans = { "node": sourceNode, "prop_distr": prop_distr, "trans_out": trans_out, "trans_in": trans_in, } return trans
def spawn_enemies(self) -> None: # Roll a dice to see if enemy should spawn # Use the current score: the more score, the less seconds before an enemy spawns # This variable stores the average number of seconds before a zombie will spawn seconds = -log2(self.score + 1) / log2(6) + 2.4 # Roll the dice dice_roll = rint(1, max(FPS // 5, int(seconds * FPS))) # if dice roll is not equal to 1, end if dice_roll != 1: return # Spawn an enemy at random location x = rint(2 * self.screen_width, (MAP_WIDTH - 2) * self.screen_width) y = rint(2 * self.screen_height, (MAP_HEIGHT - 2) * self.screen_height) e = Zombie(x, y, self.zombie_xml, self, image=self.zombie_img) # Make sure they aren't on screen # If they were on screen, an enemy would just "pop" into existence # Also make sure they don't currently collide with anything while e.onscreen() or any(e.collides(o) for o in self.objects): x = rint(2 * self.screen_width, (MAP_WIDTH - 2) * self.screen_width) y = rint(2 * self.screen_height, (MAP_HEIGHT - 2) * self.screen_height) e.set_pos(x, y) # Activate the enemy and add it to the objects array e.activate() self.objects.append(e)
def generate_ratings(num_types, num_users, ratings_per_user=20, num_items=100, alpha=None, noise=-1, plsi=False): p = Poisson(ratings_per_user) ratings = [[rint(1,5) for i in range(num_items)] for i in range(num_types)] if alpha == None: alpha = [1]*num_types user_ratings = [] user_indices = [] type_dists = [] for i in range(num_users): ratings_per_user = p.sample() if plsi: type_dist = normalize([rand() for t in range(num_types)]) else: type_dist = dirichlet(alpha) type_dists.append(type_dist) rating = [] indices = [] for j in rsample(range(num_items), ratings_per_user): if rand() < noise: rating.append(rint(1,5)) else: type = sample(type_dist) rating.append(ratings[type][j]) indices.append(j) user_ratings.append(rating) user_indices.append(indices) user_ratings = user_indices, user_ratings return user_ratings, ratings, type_dists
def _add_label_data(self): for pat in self.pats: # If the patient needs an ED Return for num,enc in enumerate(pat.enc_list[:-1]): if rand.random() < pat.ed_return_prob: # change the lowest datetime to be within 30 days of the highest next_enc = pat.enc_list[num+1] next_enc.change_dt(enc.arrive_dt + dt.timedelta(days=rint(1,29))) enc.ed_return = 1 if rand.random() < 0.8: new_prc = Procedure(0) enc.add_prc(new_prc) if rand.random() < 0.8: new_dx = Diagnosis() new_dx.dx_code = 'B9'+str(rint(0,9))+'.'+str(rint(0,9)) enc.add_dx(new_dx) # If the patient needs an opioid overdose if pat.opioid_overdose: od_enc = rint(np.ceil(len(pat.enc_list)/2),len(pat.enc_list)-1) pat.enc_list[od_enc].overdose_enc() for enc in pat.enc_list[:od_enc]: if rand.random() < 0.9: enc.add_med(Medication(0,opioid=True)) if rand.random() < 0.8: op_dx = Diagnosis() op_dx.dx_code = 'F11.'+str(rint(0,9)) enc.add_dx(op_dx)
def get(self): # Create a background image Path = settings['static_path'] image = Image.new('RGB', (80, 30), (200,0,0)) draw = ImageDraw.Draw(image) n1,n2,n3,n4 = rint(1,9), rint(1,9), rint(1,9), rint(1,9) validcode = '{0}{1}{2}{3}'.format(n1,n2,n3,n4) self.session['validcode'] = validcode # Create a text image textImg = Image.new('RGB',(80,25),(0,0,0)) tmpDraw = ImageDraw.Draw(textImg) textFont = ImageFont.truetype(Path+'/arial.ttf',24) tmpDraw.text((0, 0), validcode, font = textFont, fill = (255,255,255)) textImg = textImg.rotate(5) # Create a mask (same size as the text image) mask = Image.new('L',(80, 25),0) mask.paste(textImg,(0,0)) # Paste text image with the mask image.paste(textImg,(10,0),mask) f = StringIO.StringIO() image.save(f, "PNG") self.set_header("Content-Type", "image/png") contents = f.getvalue() self.write(contents) f.close()
def get_free_cell(self): while True: i = rint(1, self.size - 1) j = rint(1, self.size - 1) if self.field[i][j] == self.cell_free: return [j, i]
def _gen_encounters(self,pats): csns = np.arange(self.num_enc)*(int(999999999/self.num_enc)) np.random.shuffle(csns) print("Number of CSNs: "+str(csns.shape[0])) mrn_list = self._mrn_list() for i,csn in enumerate(csns): tmp_enc = Encounter(csn) meds = np.random.choice(25,rint(0,8),replace=False) for med in meds: tmp_enc.add_med(Medication(med)) if rand.random() < .05: tmp_enc.add_med(Medication(0,opioid=True)) prcs = np.random.choice(25,rint(0,8),replace=False) for prc in prcs: tmp_enc.add_prc(Procedure(prc)) for _ in range(rint(1,5)): tmp_enc.add_dx(Diagnosis()) self.pat_dict[mrn_list[i]].add_csn(tmp_enc) for pat in pats: dates = [(enc.arrive_dt,enc) for enc in pat.enc_list] dates.sort(key=itemgetter(0)) pat.enc_list = [enc for (_,enc) in dates] return pats
def drawWindow(self,x,y,segsize,R,G,B): margin = segsize /3 half = segsize / 2 i = 0 type = rint(0,8) if type == 0: #filled, 1pixel frame self.drawRect(x + 1, y + 1, x + segsize - 1, y + segsize - 1, R,G,B) elif type == 1: #vertical self.drawRect(x + margin, y + 1, x + segsize - margin, y + segsize - 1, R,G,B) elif type == 2: #side-by-side pair self.drawRect(x + 1, y + 1, x + half - 1, y + segsize - margin, R,G,B) self.drawRect(x + half + 1, y + 1, x + segsize - 1, y + segsize - margin, R,G,B) elif type == 3: #blinds self.drawRect(x + 1, y + 1, x + segsize - 1, y + segsize - 1, R,G,B) if(segsize - 2 > 1): i = rint(0,int(segsize - 2)) self.drawRect (x + 1, y + 1, x + segsize - 1, y + i + 1, R * 0.3,G * 0.3,B * 0.3) elif type == 4: #vert stripes self.drawRect(x + 1, y + 1, x + segsize - 1, y + segsize - 1, R,G,B) self.drawRect(x + margin, y + 1, x + margin, y + segsize - 1, R * 0.7,G * 0.7,B * 0.7) self.drawRect(x + segsize - margin - 1, y + 1, x + segsize - margin - 1, y + segsize - 1, R * 0.3,G * 0.3,B * 0.3) elif type == 5: #wide horizontal self.drawRect(x + 1, y + 1, x + segsize - 1, y + segsize - margin, R,G,B) elif type == 6: #4-pane self.drawRect(x + 2, y + 1, x + segsize - 1, y + segsize - 1, R,G,B) self.drawRect(x + 2, y + half, x + segsize - 1, y + half, R * 0.2,G * 0.2,B * 0.2) self.drawRect(x + half, y + 1, x + half, y + segsize - 1, R * 0.2,G * 0.2,B * 0.2) elif type == 7: #single narrow self.drawRect(x + half - 1, y + 1, x + half + 1, y + segsize - margin, R,G,B) elif type == 8: # horizontal self.drawRect(x + 1, y + margin, x + segsize - 1, y + segsize - margin - 1, R,G,B)
def __init__(self, n:int, lb:int=1, ub:int=float('inf'), tree_ok=True): self.n = n if ub == float('inf'): ub = n*(n-1)/2 while True: if tree_ok: # tree graph # 10%くらいは木が生成されるように r = rint(1, 10) if (r<=2): self.edges = rtree(n).edges return # TODO: [line graph, star graph, complete graph] uf = UnionFind(n) self.edges = set() while(uf.group_count()>1 or len(self.edges)<lb): u = rint(0, n-1) v = rint(0, n-1) if (u==v): continue if (u>v): u,v=v,u self.edges.add((u, v)) uf.union(u, v) self.edges = list(self.edges) if len(self.edges) <= ub: return
def random_gradient(name): x = 1024 y = 768 img = Image.new("RGB", (x, y), "#FFFFFF") draw = ImageDraw.Draw(img) # r,g,b = rint(0,255), rint(0,255), rint(0,255) r, g, b = 178, 34, 34 # dr = (rint(r-65, r+65) - r)/y # dg = (rint(g-65, g+65) - g)/y # db = (rint(b-65, b+65) - b)/y color2 = [0, 81, 79] dr = color2[0] dg = color2[1] db = color2[2] dr = rint(dr - 50, dr) / 400 dg = rint(dg - 50, dg) / 400 db = rint(db - 50, db) / 400 print(dr, dg, db) for i in range(x): r, g, b = r + dr, g + dg, b + db draw.line((i, 0, i, y), fill=(int(r), int(g), int(b))) img.save(name + ".png", "PNG")
def randnumgame(name): numberofguess = 1 runprogram = True number = rint(0,20) print "Well, hello there ", name, " I'm thinking of an integer between 1-20, what am I thinking of?" while runprogram ==True: try: numguess = int(input("Enter integer between 1-20 (decimals will be rounded to nearest int), enter 999 to quit:" )) if numguess ==number: print "Wow, that was a good guess" print "You guessed in ", numberofguess, " guesses" if playagain(name) == 'y': number = rint(0,20) numberofguess = 1 else: runprogram =False elif numguess == 999: print "Thanks for playing, I'm sorry you gave up. Play again?" if playagain(name) == 'y': number = rint(0,20) numberofguess = 1 else: runprogram =False elif numguess>20: print "Number too large, enter a value between 1-20 (inclusive)" elif numguess<1: print "Number too small, enter a value between 1-20 (inclusive)" elif numguess > number: print "The number you entered is GREATER than the number I am thinking of" numberofguess += 1 else: print "The number you entered is LESS than the number I am thinking of" numberofguess += 1 except: print "Error, please enter an integer between 1-20"
def _fill_free_cell(self, cell_type): while (True): i = rint(1, self.size - 1) j = rint(1, self.size - 1) if self.field[i][j] == self.cell_free: self.field[i][j] = cell_type return [j, i]
def draw_circle(): coord_a0 = rint(10, int(11 * resolution_details[0] / 12)) coord_a1 = rint(10, int(11 * resolution_details[0] / 12)) diameter = rint(80, 350) coord_b0 = coord_a0 + diameter coord_b1 = coord_a1 + diameter center_coord = tuple([coord_a0, coord_a1, coord_b0, coord_b1]) draw.ellipse(center_coord, fill=get_one_color())
def tick(self): self.count -= 1 if self.count < 0: loc = self.scene.loc_by_sprite[self] self.scene.add_sprite(*loc,\ sprite=Sprite(color=self.rgb(),vector=(rint(-1,1),rint(-1,1))) ) self.count = self.delay
def draw_tree(node, board, line=-1): color = (rint(0, 255), rint(0, 255), rint(0, 255)) cv2.rectangle(board, (node['bounds'][0], node['bounds'][1]), (node['bounds'][2], node['bounds'][3]), color, line) cv2.putText(board, node['class'], (int((node['bounds'][0] + node['bounds'][2]) / 2) - 50, int((node['bounds'][1] + node['bounds'][3]) / 2)), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 4) if 'children' not in node: return for child in node['children']: draw_tree(child, board)
def fill_free_cell(game_map, cell_type): while (True): i = rint(1, game_map_size) j = rint(1, game_map_size) if game_map[i][j] == cell_free: game_map[i][j] = cell_type return [j, i]
def draw_tree(tree, board, line=-1): color = (rint(0, 255), rint(0, 255), rint(0, 255)) cv2.rectangle(board, (tree['bounds'][0], tree['bounds'][1]), (tree['bounds'][2], tree['bounds'][3]), color, line) if 'children' not in tree: return for child in tree['children']: draw_tree(child, board)
def __init__(self, number): self.number = number self.r_list = [rint(1, 20) for x in range(rint(10, 20))] # create a random list. lower = 0 high = len(self.r_list) - 1 self.quicksort(lower, high)
def take_dmg(self, p_dmg): if rint(1, 100) >= 9: self.hp -= p_dmg print("You hit the {0} with {1} damage!".format(self.name, p_dmg)) elif rint(1, 100) <= 9: p_dmg += (0.635 * p_dmg) self.hp -= p_dmg print("You hit the {0} with a critical hit, dealing {1} damage!".format(self.name, p_dmg)) return
def draw_region(region, board, color=None, show=False): if color is None: color = (rint(0, 255), rint(0, 255), rint(0, 255)) for point in region: board[point[0], point[1]] = color if show: cv2.imshow('region', board) cv2.waitKey() return board
def draw_region(region, broad, show=False): color = (rint(0, 255), rint(0, 255), rint(0, 255)) for point in region: broad[point[0], point[1]] = color if show: cv2.imshow('region', broad) cv2.waitKey(10) return broad
def generate_parameters(): offset = min_block_edge + 5 corner_top = rint(offset, img_height - offset) corner_left = rint(offset, img_width - offset) height = rint(min_block_edge, img_height - corner_top) width = rint(min_block_edge, img_width - corner_left) corner_bottom = corner_top + height corner_right = corner_left + width return corner_top, corner_left, corner_bottom, corner_right
def randgradient(): img = Image.new("RGB", (300,300), "#FFFFFF") draw = ImageDraw.Draw(img) r,g,b = rint(0,255), rint(0,255), rint(0,255) rh, gh, bh = hex(r)[2:], hex(g)[2:], hex(b)[2:] for i in range(300): draw.line((i,0,i,300), fill=(int(r),int(g),int(b))) img.save(rh + gh + bh + ".png", "PNG")
def make_fail_condition(): '''makes a transition that will fail''' lhs = rten() + 2 opr = ropr() if '>' in opr: rhs = random.rint(0, lhs-1) else: rhs = random.rint(lhs+1, 2*lhs) return AttributeTypes.Compare(AttributeTypes.Constant(lhs), opr, AttributeTypes.Constant(rhs))
def random_bbox(img_shape): # random.seed(seed) img_height, img_width = img_shape[:2] height = rint(5, 30) width = rint(5, 30) if img_height <= height or img_width <= width: return None row_min = rint(0, img_height - height - 1) col_min = rint(0, img_width - width - 1) return col_min, row_min, col_min + width, row_min + height
def get_free_cell(self): """ Return position of free sell [x, y] """ while True: i = rint(1, self.size - 2) j = rint(1, self.size - 2) if self.field[i][j] == self.cell_free: return [j, i]
def distancia(matriz): # escolhe aleatoriamente os centroides while True: nun = rint(0, len(matriz) - 1) if matriz[nun][2] == 1: break while True: nun2 = rint(0, len(matriz) - 1) if matriz[nun2][2] == -1: break return nun, nun2
def distancia(matriz):# escolhe aleatoriamente os centroides while True: nun=rint(0,len(matriz)-1) if matriz[nun][2]==1: break while True: nun2 = rint(0, len(matriz) - 1) if matriz[nun2][2] == -1: break return nun, nun2
def __init__(self): super(Cloud, self).__init__() # self.surf = pygame.image.load('cloud.png').convert() self.surf = pygame.Surface((30, 30)) self.surf.set_colorkey(BLACK, RLEACCEL) self.rect = self.surf.get_rect(center=( rint(SCREEN_WIDTH + 20, SCREEN_WIDTH + 100), rint(0, SCREEN_HEIGHT), ))
def rand_image(sizex, sizey, fname): im = Image.new('RGB', (sizex, sizey), 'white') draw = ImageDraw.Draw(im) bufx = [] for i in xrange(sizex * sizey): p = rint(0, 255), rint(0, 255), rint(0, 255) bufx.append(p) im.putdata(bufx) im.save(fname + '.png')
def windows() -> str: etc = ['WOW64', 'Win64; x64'] ver = ['10.0', '6.' + str(rint(0, 3))] main = 'Windows NT ' version = ver[rint(0, 1)] if version == '10.0' or bool(rint(0, 1)): version += '; ' + etc[rint(0, 1)] return main + version
def rand_image(sizex, sizey, fname): im = Image.new('RGB', (sizex, sizey), 'white') draw = ImageDraw.Draw(im) bufx = [] for i in xrange(sizex*sizey): p = rint(0, 255), rint(0, 255), rint(0, 255) bufx.append(p) im.putdata(bufx) im.save(fname + '.png')
def make(): N = 10 M = 20000 space = 200 overlap = 15 random.seed(123456789) data = datasets.MNIST('/tmp/data', train=True, download=True, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])) ndata = torch.ByteTensor(np.lib.pad(data.train_data.numpy(), ((0,0),(4,4),(0,0)), 'constant')) dataset_data = np.zeros((M, 36, 0)) dataset_labels = np.zeros((M, 36, 0)) s = np.append(data.train_labels.view(-1,1,1).repeat(1,36,1).numpy()[:M], ndata.numpy()[:M], axis=2) for i in range(N): p = np.random.permutation(s) d = np.roll(p[:,:,1:], (0, rint(-4,4), 0), (0,1,2)) if i == 0: dataset_data = d else: oq = rint(0, overlap-9) + 9 dd = np.append(np.zeros((M, 36, dataset_data.shape[2]-oq)), d, axis=2) dataset_data = np.append(dataset_data, np.zeros((M,36,28-oq)), axis=2) dataset_data += dd dataset_labels = np.append(dataset_labels, p[:,:,0:1], axis=2) dataset_labels = dataset_labels[:,0,:] # Creates a dataset of 60000 (28*N + (N-1)*overlap) * 36 images # containing N numbers in sequence and their labels images = [] if not os.path.exists('./images'): os.makedirs('./images') for i in range(M): ''' Randomly adding spacing bettween the numbers and then saving the images. ''' img = np.zeros((36, 0)) dist = torch.multinomial(torch.ones(N+1), space, replacement=True) for j in range(N+1): img = np.append(img, np.zeros((36, (dist==j).sum())), axis=1) img = np.append(img, dataset_data[i,:,28*j:28*(j+1)], axis=1) img = dataset_data[i,:,:] images.append(img) name = './images/img_' + ''.join(map(lambda x: str(int(x)), dataset_labels[i])) + '.png' imsave(name, img.clip(0, 255)) dataset_data = np.array(images) if not os.path.exists('./dataset'): os.makedirs('./dataset') np.save("./dataset/data", dataset_data) np.save("./dataset/labels", dataset_labels)
def pick_scale_ch_prog(scale_base): if min_maj == 1: if rint(1, 4) == 1: return ch_prog[count] - scale[scale_base] else: return ch_prog[count] + scale[scale_base] else: if rint(1, 4) == 1: return ch_prog[count] + scale[scale_base] else: return ch_prog[count] - scale[scale_base]
def draw_rectangle(): coord_a0 = rint(10, int(11 * resolution_details[0] / 12)) coord_a1 = rint(10, int(11 * resolution_details[1] / 12)) x_change = rint(80, 500) y_change = rint(80, 500) if x_change > y_change: y_change, x_change = x_change, y_change coord_b0 = coord_a0 + x_change coord_b1 = coord_a1 + y_change center_coord = tuple([coord_a0, coord_a1, coord_b0, coord_b1]) draw.rectangle(center_coord, fill=get_one_color())
def pick_scale_first(scale_base): if min_maj == 1: if rint(1, 4) == 1: return first_note()[0] - scale[scale_base] else: return first_note()[0] + scale[scale_base] else: if rint(1, 4) == 1: return first_note()[0] + scale[scale_base] else: return first_note()[0] - scale[scale_base]
def write_ten_numbers_to_file(): with open("numberFile.txt","w") as file_object: iterator = 0; while(iterator < 10): file_object.write(str(rint(0,10000))+"\n") iterator += 1 file_object.close()
def cornersarefree(totalmovelist): """return the next move if one of the corners are free, else return a side number. This function chooses a random number to pick which available corner or side move to use. """ cornerlist = ['0','2','6','8'] sidelist = ['1','3','5','7'] nextcornermove = [x for x in cornerlist if x not in totalmovelist] nextsidemove = [x for x in sidelist if x not in totalmovelist] if len(nextcornermove) !=0: randnum = rint(0,len(nextcornermove)-1) nextmove = nextcornermove[randnum] elif len(nextsidemove) !=0: randnum = rint(0,len(nextsidemove)-1) nextmove = nextsidemove[randnum] return nextmove
def gen_palette(colorNr = 2): interval = 256 / colorNr r, g, b = 0, 0, 0 for x in xrange(colorNr): dr = (rint(0,255) - r) / interval dg = (rint(0,255) - g) / interval db = (rint(0,255) - b) / interval start = x * int(interval) end = (x + 1) * int(interval) if x == (colorNr - 1): end = 256 for i in xrange(start, end): r,g,b = r+dr, g+dg, b+db palette.append((floorToMax(r, 255),floorToMax(g, 255),floorToMax(b, 255)))
def crossover(pai1, pai2): filho = [] for i in range(len(pai1)-1): if rint(0,1)==0: filho.append(pai1[i]) else: filho.append(pai2[i]) return filho
def init_roller(self): #initiative roller. The bonus is base on the MM if self.kind == 'hill': bonus = -1 elif self.kind == 'stone': bonus = 2 elif self.kind == 'dragon': bonus = 0 return str(rint (1,20) + bonus)
def getword(): """generates random word from large wordlist site""" wordsite = "http://www.mieliestronk.com/corncob_lowercase.txt" response = urllib2.urlopen(wordsite) txt = response.read() words = txt.splitlines() randnum = rint(0, len(words)-1) randword = words[randnum] #print randword return randword
def populate(): """Generates random data into the database.""" mongo.db.categories.drop() mongo.db.products.drop() mongo.db.news.drop() from random import randint as rint from faker import Factory fake = Factory.create() # create categories for i in range(5): name = fake.name().capitalize() mongo.db.categories.insert({ 'id': safename(name).lower(), 'name': name }) # create products for i in range(50): name = fake.name().capitalize() mongo.db.products.insert({ 'id': safename(name).lower(), 'name' : name, 'desc' : fake.text(), 'price': rint(40, 300), 'category': mongo.db.categories.find()[rint(0, 4)], 'images': ['/img/something.jpg'] }) # create news for i in range(15): name = fake.name().capitalize() mongo.db.news.insert({ 'id': safename(name).lower(), 'header': name, 'text': fake.text() }) return mongo.db.categories.find()
def generaterandnum(): """generates random 3 digit number. A little tricky because number should be able to start with zero""" # first generate rand 2 or 3 digit num secretnumb = str(rint(10, 1000)) # now add zero to beginning if 2-digit # first convert to string str(secretnumb) if len(secretnumb) == 2: secretnumb = "0" + secretnumb return secretnumb
def setmVal(self,x,y,r,g,b,a): #set colour to point newr = r + rint(-32,32) if newr > 255: newr = 254 if newr < 0: newr = 0 newg = g + rint(-32,32) if newg > 255: newg = 254 if newg < 0: newg = 0 newb = b + rint(-32,32) if newb > 255: newb = 254 if newb < 0: newb = 0 newa = a + rint(-32,32) if newa > 255: newa = 254 if newa < 0: newa = 0 stringR = '%x'%newr if(len(stringR) == 1): stringR = str(0) +'%x'%newr stringG = '%x'%newg if(len(stringG) == 1): stringG = str(0) +'%x'%newg stringB = '%x'%newb if(len(stringB) == 1): stringB = str(0) +'%x'%newb stringA = '%x'%newa if(len(stringA) == 1): stringA = str(0) +'%x'%newa self.mArray[x][y] = "#" + stringR + stringG + stringB + stringA print self.mArray[x][y]
def render_png(planets): """ Given a list of planets, create a PNG for the map, and return an open file-like object of the bytes for that PNG. """ # XXX For now, using PIL, which looks like ass (anti-aliasing, what's # that, never heard of it?), but will let us move forward with other # bits. img = Image.new("RGB", (map_size,map_size), "#FFFFFF") draw = ImageDraw.Draw(img) for p in planets: # The sample code I picked up randomly set colors, I'm good with # that for now. r,g,b = rint(0,255), rint(0,255), rint(0,255) draw.ellipse((p.x, p.y, p.x+planet_pixels, p.y+planet_pixels), fill=(int(r),int(g),int(b))) # Write to file object f = cStringIO.StringIO() img.save(f, "PNG") f.seek(0) return f
def main(argc, argv): t0 = time() seed = (argc > 1 and int(argv[1])) or 123456789 xmin = 1000000000000 ymin = 1000000000000 xmax = 5000000000000 ymax = 5000000000000 rseed(seed) for b in xrange(2, 64 + 1): for i in xrange(5000): x = rint(xmin, xmax) y = rint(ymin, ymax) assert(karatsuba_multiply(x, y, b) == (x * y)) t1 = time() dt = t1 - t0 print("[main] dt=%fs" % dt) return 0
def getRndColorPallete(noOfColors): colorPallete = [] r, g, b = rint(0,255), rint(0,255), rint(0,255) for i in range(noOfColors): dr = (rint(0,107)) dg = (rint(0,107)) db = (rint(0,107)) r, g, b = (r + dr) % 255, (g + dg) % 255, (b + db) % 255 colorPallete.append("#%02x%02x%02x" % (r, g, b)) return colorPallete
def __init__(self,bg=(0,0,0),snake=(0,240,0),apple=(255,0,0),snake_max_len=4): super(SnakeScene,self).__init__(tempo=360,bg=bg) self.snake = Sprite(color=snake,blend=False,z=10,trail=snake_max_len) self.add_sprite(0,0,self.snake) self.apple_time = 0 self.apple = Sprite(color=apple,blend=False,z=5) self.add_sprite(0,0,self.apple) self.snake_reset() self.apple_reset() self.points = 0 self._snake_dir = rint(0,4)
def randgradient(): img = Image.new("RGB", (300,300), "#FFFFFF") draw = ImageDraw.Draw(img) r,g,b = rint(0,255), rint(0,255), rint(0,255) dr = (rint(0,255) - r)/300. dg = (rint(0,255) - g)/300. db = (rint(0,255) - b)/300. for i in range(300): r,g,b = r+dr, g+dg, b+db draw.line((i,0,i,300), fill=(int(r),int(g),int(b))) img.save("out.png", "PNG")
def __init__(self, parent=None): """ """ QtGui.QMainWindow.__init__(self, parent) self.setMinimumSize(800,600) self.graph = NXObservedGraph() self.graphView = GraphicalGraph.create_view(self.graph, parent=self) nodes = [] nmax = 100 emax = 100 for p in range(nmax): node = self.graph.new_vertex(p, position=[rint(0,200), rint(0,200)], color=QtGui.QColor(rint(0,255),rint(0,255),rint(0,255))) nodes.append(node) for p in range(emax): self.graph.add_edge(nodes[rint(0,nmax-1)], nodes[rint(0,nmax-1)]) self.setCentralWidget(self.graphView)
def hp_roller(self): #Rolling hit points # out - the number to return starts with the HP bonus the monster has # d the die type # nd the number of dies to throw if self.kind == 'hill': out =40 d = 12 nd = 10 elif self.kind == 'stone': out = 60 d = 12 nd = 12 elif self.kind == 'dragon': out = 10 d = 8 nd = 5 i = 0 while i < nd: out += rint (1,d) i += 1 return str(out)
def DE(gen,f): output = open('saida.txt', 'w') result = open('result.txt', 'w') base = csv.reader(open('base.txt'), delimiter= ' ') entrada,pais, ngen = [], [], 0 for i in base: aux = [] for j in i: aux.append(float(j)) entrada.append(aux) pais = entrada cent1, cent2 = distancia(pais) for i in range(len(pais)): # calcula o fitness dos pais fit = fitness(pais[i], pais[cent1], pais[cent2]) pais[i].append(fit) while ngen < gen: # condicao de parada(nº de gerações) filhos = [] for i in range(len(pais)): if i == len(pais)-1: # para o ultimo elementos filho = crossover(pais[i], pais[0]) elif i == len(pais)-2: #para o penultimo filho = crossover(pais[i], pais[i+1]) else: if rint(0, 1) == 0: # Escolhe aleatoriamente entre crossover ou mutacao filho = mutacao(pais[i], pais[i+1], pais[i+2], f) else: filho = crossover(pais[i], pais[i+1]) filho.append(fitness(filho, pais[cent1], pais[cent2])) filhos.append(filho) pais = selecao(pais,filhos) cent1, cent2 = distancia(pais)# atualiza os centroides apos cada geracao ngen += 1 pais = normalize(pais) pais = k_means(pais,pais[cent1], pais[cent2]) for i in pais: output.write(str(i[-1]) + '\n') result.write(str(i) + '\n')
def default_position(self): """If there is no position obtained by get_view_data("position"), use the return value from this one""" return [rint(0,200)]*2
def test_avatar(self): user_id = self.user.id.val # Due to EOF both posts must be test separately # Bad post try: temp = tempfile.NamedTemporaryFile(suffix='.png') img = Image.new("RGB", (200, 200), "#FFFFFF") draw = ImageDraw.Draw(img) r, g, b = rint(0, 255), rint(0, 255), rint(0, 255) for i in range(200): draw.line((i, 0, i, 200), fill=(int(r), int(g), int(b))) img.save(temp, "PNG") temp.seek(0) request_url = reverse('wamanageavatar', args=[user_id, "upload"]) data = { 'filename': 'avatar.png', "photo": temp } _post_response(self.django_client, request_url, data) finally: temp.close() # Good post try: temp = tempfile.NamedTemporaryFile(suffix='.png') img = Image.new("RGB", (200, 200), "#FFFFFF") draw = ImageDraw.Draw(img) r, g, b = rint(0, 255), rint(0, 255), rint(0, 255) for i in range(200): draw.line((i, 0, i, 200), fill=(int(r), int(g), int(b))) img.save(temp, "PNG") temp.seek(0) request_url = reverse('wamanageavatar', args=[user_id, "upload"]) data = { 'filename': 'avatar.png', "photo": temp } _csrf_post_response(self.django_client, request_url, data, status_code=302) finally: temp.close() # Crop avatar request_url = reverse('wamanageavatar', args=[user_id, "crop"]) data = { 'x1': 50, 'x2': 150, 'y1': 50, 'y2': 150 } _post_response(self.django_client, request_url, data) _csrf_post_response(self.django_client, request_url, data, status_code=302)
def generateWindow(self): #GENERATE OUTLINE -- DONE #GENERATE FILLING #generate 1 of 4 levels of brightness # changed to 1-2 so that a majority are of low level brightness brightness = rint(0,1) brightwindow = rint(0,200) # every now and again, someone leaves a light on at work. if brightwindow == 22: brightness = 4 #test code # brightness = 2 if(brightness != 0): #generate initial RGB r = rint(1,64)*brightness-1 g = rint(1,64)*brightness-1 b = rint(1,64)*brightness-1 for i in range(self.width): for j in range(self.height): #outline of window should be black if (i == 0) or (i == self.width-1): self.mArray[i][j] = "#000000" elif (j == 0) or (j == self.height-1): self.mArray[i][j] = "#000000" else: # generate colour based off initial RGB #j == 0-3 # j == 4-7 newr = r + rint(-32,32) if newr > 255: newr = 254 if newr < 0: newr = 0 newg = g + rint(-32,32) if newg > 255: newg = 254 if newg < 0: newg = 0 newb = b + rint(-32,32) if newb > 255: newb = 254 if newb < 0: newb = 0 #g = newr #b = newr #convert to 2 digit hex number: stringR = '%x'%newr if(len(stringR) == 1): stringR = str(0) +'%x'%newr stringG = '%x'%newg if(len(stringG) == 1): stringG = str(0) +'%x'%newg stringB = '%x'%newb if(len(stringB) == 1): stringB = str(0) +'%x'%newb self.mArray[i][j] = "#" + stringR + stringG + stringB else: for i in range(self.width): for j in range(self.height): self.mArray[i][j] = "#000000"
def dropHandler(self, event): position = self.mapToScene(event.pos()) position = [position.x(), position.y()] self.scene().new_vertex(position=position, color=QtGui.QColor(rint(0,255),rint(0,255),rint(0,255)))