def randomize_direction(self): rand = random.randint(0, 45) rand_dir = random.randint(0, 3) if rand_dir == 0: self.set_rotation(rand) elif rand_dir == 1: self.set_rotation(180 - rand) elif rand_dir == 2: self.set_rotation(180 + rand) elif rand_dir == 3: self.set_rotation(360 - rand)
def crossover(ind1, ind2): point1, point2 = 0, 255 while point1 == 0: point1 = random.randint(0,255) while point2 == 255: point2 = random.randint(0,255) if point1 > point2: # make sure point1 <= point2 point1, point2 = point2, point1 child0 = ind1[:point1] + ind2[point1:point2] + ind1[point2:] child1 = ind2[:point1] + ind1[point1:point2] + ind2[point2:] return (child0,child1)
def GenFeaturePool(self): feature_pool = [] for i in xrange(self.featNum): x1, y1 = random_point_within_circle() x2, y2 = random_point_within_circle() feat = Feature() feat.scale = random.randint(0, 2) feat.landmark_id1 = random.randint(0, landmark_n-1) feat.landmark_id2 = random.randint(0, landmark_n-1) feat.offset1_x = x1 * self.radius feat.offset1_y = y1 * self.radius feat.offset2_x = x2 * self.radius feat.offset2_y = y2 * self.radius feature_pool.append[feat] return feature_pool
def render(self, hypha): # print "Rendering " + str(self.tendril_id) + " " + str(self.loc) + " " + str(self.tcenter) # Periodically update the closest hyphae and tendril. The # less often you do this, the faster the simulation runs! if (random.randint(1,200) == 1): self.update_closest_tendril(hypha) self.update_closest_hyphae(hypha) if (not self.connected): self.fungal(hypha) self.branch(hypha) self.update() # Draw the shape. glLoadIdentity() glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPointSize(self.radius) # Draw shadow glColor4f(0.0, 0.0, 0.0, 0.5) glBegin(GL_POINTS) glVertex2f((self.loc[0]+self.radius/2)*PIXEL_SCALE_FACTOR, (self.loc[1]-self.radius/2)*PIXEL_SCALE_FACTOR) glEnd() # Draw the dots at the vertices if (self.connected): glColor4f(1.0, 0.0, 0.0, 1.0) else: glColor4f(1.0, 1.0, 1.0, 1.0) glBegin(GL_POINTS) glVertex2f(self.loc[0]*PIXEL_SCALE_FACTOR, self.loc[1]*PIXEL_SCALE_FACTOR) glEnd()
def generateAllPatrons(self, model): for i in range(1000): name = 'person %s' % i departureTime = 0 #decide departure times based on percantage of total patrons. if i <= 10: departureTime = 180.0 elif i > 10 and i <= 30: departureTime = 240.0 elif i > 30 and i <= 60: departureTime = 300.0 elif i > 60 and i <= 100: departureTime = 360.0 elif i > 100 and i <= 200: departureTime = 420.0 elif i > 200 and i <= 300: departureTime = 480.0 elif i > 300 and i <= 350: departureTime = 540.0 elif i > 350 and i <= 450: departureTime = 600.0 elif i > 450 and i <= 550: departureTime = 660.0 elif i > 550 and i < 999: departureTime = 720.0 arrivalTime = random.randint(0, 120) person = Person(model.areaA[6], 'a', model, name, departureTime, arrivalTime ) self.patrons.append(person) self.patrons = sorted(self.patrons, key=lambda person: person.arrivalTime)
def read_options(): global opts,args p = OptionParser() p.add_option("-M","--model",metavar = "MODEL_PATH.py", action = "store", dest = "model_name", help = "Model to be used for current experiment") p.add_option("-E","--extractor",metavar = "EXTRACTOR_PATH.py", action = "store", dest = "extractor_name", help = "Extractor to be used for current experiment") p.add_option("-t","--test-file", metavar = "FILE", action = "store", dest = "test_file", help = "file model will be evaluated on") p.add_option("-n","--name",metavar = "NAME", action = "store", dest = "experiment_name", help = "Name given to experiment") p.add_option("-S","--pickled-extractor",metavar = "PICKLED_EXTRACTOR", action = "store", dest = "pickled_extractor", help = "Pickled extractor to be used for current experiment\n\ --extractor must be specified") p.add_option("-P","--pickled-model",metavar = "PICKLED_MODEL", action = "store", dest = "pickled_model", help = "Pickled model to be used for current experiment\n\ --model must be specified") p.add_option("-N","--window-size",metavar = "N", type = "int", default = 1, action = "store", dest = "window_size", help = "Window size to segment thread stream into") p.add_option("-B","--bandwidth",metavar = "BW", action = "store", dest = "bandwidth",type = "int",default = 1000, help = "Bandwidth limit. Default is 1000") p.add_option("-v","--verbose", action = "store_true", dest = "verbose", help = "print extra debug information") (opts,args) = p.parse_args() print opts,args if not opts.extractor_name: opts.extractor_name = opts.model_name if opts.experiment_name and opts.experiment_name.endswith('RANDOM'): opts.experiment_name = opts.experiment_name.replace( 'RANDOM', str(random.randint(100,999))) return opts,args
def get_train_test_data(self,data,percent_split): ftestList,ltestlist,fvalidList,lvalidList,ftrainList,ltrainList=[],[],[],[],[],[] noOfTrainSamples = len(data)*(1-percent_split) noOfTestSamples = len(data)-noOfTrainSamples self.batchsize = int(noOfTestSamples) noOfTrainSamples = int((noOfTrainSamples - self.prevData)/noOfTestSamples) for i in range(int(noOfTrainSamples)*self.batchsize): #ltrainList.append(data.iloc[i:i+self.prevData, 2:].as_matrix()) ftrainList.append(data.iloc[i:i+self.prevData, 0:2].as_matrix()) ltrainList = data.iloc[0:int(noOfTrainSamples)*self.batchsize, 2:].values for i in range(self.batchsize): fvalidList.append(data.iloc[i:i + self.prevData, 0:2].as_matrix()) lvalidList = data.iloc[0:self.batchsize, 2:].values randNum = random.randint(0,noOfTrainSamples) for i in range(randNum,randNum+self.batchsize): ftestList.append(data.iloc[i:i + self.prevData, 0:2].as_matrix()) ltestlist = data.iloc[randNum: randNum+self.batchsize, 2:].values return np.array(ftestList),np.array(ltestlist),np.array(ftrainList),np.array(ltrainList),np.array(fvalidList),np.array(lvalidList)
def get_macid(): '''获取macid,此值是通过mac地址经过算法变换而来,对同一设备不变''' macid = '' chars = 'abcdefghijklnmopqrstuvwxyz0123456789' size = len(chars) for i in range(32): macid += list(chars)[random.randint(0, size - 1)] return macid
def test_multiple(self): """ Torture test of mutliple server, mutliple object, multile client hitting servers concurrently, """ try: import grequests except ImportError: raise nose.SkipTest("grequests not available") import grequests from exhibitionist.objectRegistry import ObjectRegistry from exhibitionist.decorators import http_handler import random registry = ObjectRegistry() @http_handler(r'/{{objid}}', __registry=registry) class Handler(ExhibitionistRequestHandler): def get(self, *args, **kwds): self.write(str(id(context.object))) N_SERVERS = 3 N_CONC_CONNS = 20 for i in range(10): try: servers = [] for i in range(N_SERVERS): servers.append(get_server().add_handler(Handler).start()) assert len(servers) == N_SERVERS urls=[] objs=[object() for i in range(N_CONC_CONNS)] # use integers for i in range(N_CONC_CONNS): # 50 connections at once o = objs[i] r = random.randint(0, N_SERVERS-1) assert r < N_SERVERS s = servers[r] urls.append(s.get_view_url("Handler", o, __registry=registry)) assert len(urls) == len(objs) jobs = [grequests.get(url) for url in urls] results = grequests.map(jobs) for i,r in enumerate(results): self.assertTrue(str(id(objs[i])) == r.content) finally: for s in servers: try: s.stop() except: pass
def adivina(): import random num = random.randint(1,100) print('Estoy pensando en un número del 1 al 100...') op = int(input('¡Adivínalo!: ')) while op != num: op = int(input('Prueba otra vez: ')) print('¡Enhorabuena, has acertado!')
def say(text): voice = gTTS(text, lang='ru') unique_file = 'audio_' + str(random.randint(0, 10000)) + ".mp3" #audio_10.mp3 voice.save(unique_file) playsound.playsound(unique_file) os.remove(unique_file) print(f"Ассистент: {text}")
def pickIndex(self) -> int: n = random.randint(1, self.s) for i, w in enumerate(self.weights): if n <= w: return i # Your Solution object will be instantiated and called as such: # obj = Solution(w) # param_1 = obj.pickIndex()
def upload_image_path(instance, filename): print(instance) # print(filename) new_filename = random.randint(1, 3910209312) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format( new_filename=new_filename, final_filename=final_filename )
def shuffle(self): """ Returns a random shuffling of the array. :rtype: List[int] """ nums = list(self.__nums) for i in xrange(len(nums)): j = random.randint(i, len(nums) - 1) nums[i], nums[j] = nums[j], nums[i] return nums
def pickIndex(self) -> int: target = random.randint(0, self.total - 1) l, r = 0, len(self.cum) - 1 while l < r: mid = (l + r) // 2 if self.cum[mid] <= target: l = mid + 1 else: r = mid return l
def my_method(): rand = random.randint(0, 9) logger.info(f"rand={rand}") if rand % 3 == 0: return True elif rand % 3 == 1: return False else: raise int("a")
def execute(self, the_knapsack, the_aleatory, debug=False): # variables self.my_knapsack = the_knapsack self.my_aleatory = the_aleatory self.curve = [] self.current_efos = 0 g_best = None # DF - Best fitness all iterations Q = self.__generate_population_aleatory() # 3.3 initialization # get best solution - wolves alpha g_best = Q[0] pos_g_best = 0 t = 0 while t < self.max_efos: for it in range(self.pop_size): # get current best binary individual Xα # de igual manera se hacen las 10 iteraciones, no supone una mejora significativa MAX() # maxim = max([k.fitness for k in Q]) for i in range(self.pop_size): # TODO revisar n_item if g_best.fitness < Q[i].fitness: g_best = Q[i] pos_g_best = i pos_qr1_qr2_selected = [] # select position of qr1 and qr2 randomly # -1 porque ya que se tiene el alpha while len(pos_qr1_qr2_selected) < ELITISM_WOLVES - 1: r = random.randint(0, self.pop_size - 1) if r not in pos_qr1_qr2_selected and r != pos_g_best: # TODO refactor numpy choice k=n, replace= false pos_qr1_qr2_selected.append(r) # Apply mutation on qM(t) by Equations (8) and (11)//Adaptive mutation ft = self.__get_differentiation_control_factor(t) q_m = self.__apply_adaptive_mutation(Q, pos_g_best, pos_qr1_qr2_selected, ft) # Obtain qC(t) by crossover by Equations (12) and (13)//Crossover q_c = self.__obtain_crossover(Q[it].quantum_theta, q_m) # create solution object for evaluate fitness q_c_solution = GreyWolfSolution.init_owner(self) q_c_solution.quantum_initialization(q_c) if q_c_solution.fitness > Q[it].fitness: Q[it] = q_c_solution else: Q[it].quantum_theta = ( np.array(Q[it].quantum_theta) + self.__update_by_rgwo(Q.copy(), t, it)).tolist() t += 1 self.my_best_solution = GreyWolfSolution.init_solution(g_best) return g_best
def hill_climbing_with_random_walk(initial_prop_of_items, random_walk_prob, max_super_best_steps): print("Hill Climbing with random walk") print("Initial Prop of items:", initial_prop_of_items) print("Random walk probability", random_walk_prob) print("Max No. of steps without improvement", max_super_best_steps) import random solutionsChecked = 0 x_curr = Initial_solution( initial_prop_of_items) # x_curr will hold the current solution x_best = x_curr[:] # x_best will hold the best solution f_curr = evaluate( x_curr)[:] # f_curr will hold the evaluation of the current soluton f_best = f_curr[:] #Best solution in neighbourhood f_super_best = f_curr[:] # begin local search overall logic ---------------- count = 0 #number of iteration with out improvement while (count < max_super_best_steps): Neighborhood = OneflipNeighborhood( x_curr ) # create a list of all neighbors in the neighborhood of x_curr eeta = random.uniform(0, 1) if (eeta > random_walk_prob): f_best[0] = 0 for s in Neighborhood: # evaluate every member in the neighborhood of x_curr solutionsChecked = solutionsChecked + 1 if (evaluate(s)[0] > f_best[0]): # and (evaluate(s)[1]< maxWeight): x_curr = s[:] # find the best member and keep track of that solution f_best = evaluate(s)[:] # and store its evaluation else: x_curr = Neighborhood[random.randint(0, len(Neighborhood) - 1)] if (evaluate(x_curr)[0] > f_super_best[0]): #to remember best solution f_super_best = evaluate(x_curr)[:] #best solution so far x_super_best = x_curr[:] change = 1 #To record change count = count + 1 #counting number of iterations without improvement if (change == 1): #Reseting count and change count = 0 change = 0 print_results(solutionsChecked, f_super_best, x_super_best) print("\n\n\n")
def verifycode(req): # 1. 创建画布Image对象 img = Image.new(mode='RGB', size=(120, 30), color=(220, 220, 180)) # 2. 创建画笔 ImageDraw对象 draw = ImageDraw.Draw(img, 'RGB') # 3. 画文本,画点,画线 # 随机产生0-9, A-Z, a-z范围的字符 chars = '' while len(chars) < 4: flag = random.randrange(3) char = chr(random.randint(48, 57)) if not flag else \ chr(random.randint(65, 90)) if flag == 1 else \ chr(random.randint(97, 122)) # 排除重复的 if len(chars) == 0 or chars.find(char) == -1: chars += char # 将生成的验证码的字符串存入到session中 req.session['verifycode'] = chars font = ImageFont.truetype(font='static/fonts/hktt.ttf', size=25) for char in chars: xy = (15 + chars.find(char) * 20, random.randrange(2, 8)) draw.text(xy=xy, text=char, fill=(255, 0, 0), font=font) for i in range(200): xy = (random.randrange(120), random.randrange(30)) color = (random.randrange(255), random.randrange(255), random.randrange(255)) draw.point(xy=xy, fill=color) # 4. 将画布对象转成字节数据 buffer = BytesIO() # 缓存 img.save(buffer, 'png') # 指定的图片格式为png # 5. 清场(删除对象的引用) del draw del img return HttpResponse( buffer.getvalue(), # 从BytesIO对象中获取字节数据 content_type='image/png')
def basic_purchase(number_of_items): item1 = random.choice( ['pens', 'pencils', 'rulers', 'sweets', 'KitKats', 'Mars Bars']) item2 = random.choice( ['Twix', 'Kitkats', 'cans of coke', 'bottles of Lucozade']) unit_price1 = round(random.randint(0, 2) + random.random(), 2) unit_price2 = round(random.randint(0, 2) + random.random(), 2) quantity1, quantity2 = randint(2, 4), randint(2, 4) if number_of_items == 1: quantity2 = 0 total = unit_price1 * quantity1 + unit_price2 * quantity2 if total < 5: note = 5 elif total < 10: note = 10 else: note = 20 name = name_chooser() if number_of_items == 2: q = name + ' buys ' + str( quantity1) + ' ' + item1 + ' at £' + round_2_money( unit_price1) + ' each and ' + str( quantity2) + ' ' + item2 + ' at £' + round_2_money( unit_price2 ) + ' each. ' + name + ' pays with a £' + str( note) + ' note. How much change does ' + str( name) + ' get?' ans = '£' + round_2_money(note - ( (quantity1 * unit_price1) + quantity2 * unit_price2)) else: q = name + ' buys ' + str( quantity1) + ' ' + item1 + ' at £' + round_2_money( unit_price1) + ' each. ' + name + ' pays with a £' + str( note) + ' note. How much change does ' + str( name) + ' get?' ans = "£" + round_2_money(note - ((quantity1 * unit_price1))) return q, ans
def generateStr(length=-1): try: if (length == -1): length = random.randint(1, 5) alpha = "abcdefghijklmnopqrstuvwxyz0123456789" alpha += alpha.upper() return (''.join([alpha[i] for i in range(length)])) except Exception as e: print(CustomError("Test.py generateStr() function, lines 26-30")) print(e) return False
def one_permutation(self, true_shapley, total_nums, agent_action_choices, agent_nums, get_noise): agent_action_choices = deepcopy(agent_action_choices) predicted_shapley = [0 for i in range(total_nums)] total_shapley = [0 for i in range(total_nums)] num_runs = [0 for i in range(total_nums)] previous_predicted_shapley = deepcopy(predicted_shapley) errors = [] differences = [] i = 0 total_value = self.get_score_ILP(agent_action_choices, '1' * total_nums, get_noise) for q in range(2): nums = [random.randint(0, 1) for k in range(total_nums)] const_value = self.get_score_ILP(agent_action_choices, ''.join([str(k) for k in nums]), get_noise) for current_num in range(total_nums): other_run = deepcopy(nums) other_run[current_num] = 1 - nums[current_num] other_value = self.get_score_ILP( agent_action_choices, ''.join([str(k) for k in other_run]), get_noise) if nums[current_num] == 1: diff = const_value - other_value else: diff = other_value - const_value num_runs[current_num] += 1 total_shapley[current_num] += diff predicted_shapley[current_num] = total_shapley[current_num] / ( i + 1) errors.append( np.linalg.norm( np.array(predicted_shapley) - np.array(true_shapley))) differences.append( np.linalg.norm( np.array(previous_predicted_shapley) - np.array(predicted_shapley))) previous_predicted_shapley = deepcopy(predicted_shapley) i += 1 normalization_constant = total_value / np.sum(predicted_shapley) if np.sum(predicted_shapley) != 0: predicted_shapley = [ i * normalization_constant for i in predicted_shapley ] for i in range(len(agent_nums)): self.one_permutation_shapley_final[ agent_nums[i]] += predicted_shapley[i] return predicted_shapley
def _get_proxy(self): """获取代理 IP""" if LOCAL: return requests.get(LOCAL_PROXY_URL).text.strip() else: random_num = random.randint(0, 10) if random_num % 2: time.sleep(1) return requests.get(PROXY_URL).text.strip() else: return requests.get(LOCAL_PROXY_URL).text.strip()
def __init__(self): word_num = random.randint(0, 4) super().__init__(word_num, False) self.guesses = 6 self.active = True self.solved = [] self.wrong = [] self.blank = [] self.embed = None self.name = "Hangman!" self.hang_word = self.get_word()
async def fox(self, ctx): async with ctx.channel.typing(): async with aiohttp.ClientSession() as cs: async with cs.get("https://some-random-api.ml/img/fox") as r: data = await r.json() embed = discord.Embed(title="Your fox pic:", colour=random.randint(0, 0xffffff)) embed.set_image(url=data['link']) embed.set_footer(text="https://some-random-api.ml/img/fox") await ctx.send(embed=embed)
def ex11_4(): while True: x = random.randint(1, 1000000) if (x % 7 == 0) and (x % 13 == 0) and (x % 15 == 0): print("The number %d meets the criteria! Yay :)" % x) # I think "break" is more fitting here break else: print("The number %d doesn't meets the criteria, we'll try again" % x) print(x)
def get_code(): TOTAL = '0123456789' TOTAL_LENGTH = len(TOTAL) CODE_LENGTH = 6 random = Random() verification = '' for i in range(CODE_LENGTH): verification += TOTAL[random.randint(0, TOTAL_LENGTH - 1)] return verification
async def cat(self, ctx): async with ctx.channel.typing(): async with aiohttp.ClientSession() as cs: async with cs.get("http://aws.random.cat/meow") as r: data = await r.json() embed = discord.Embed(title="Meow", colour=random.randint(0, 0xffffff)) embed.set_image(url=data['file']) embed.set_footer(text="http://random.cat/") await ctx.send(embed=embed)
def GetRandomIp(self): ''' 随机生成IP :return: ''' RANDOM_IP_POOL = ['192.168.10.222/0'] random = Random() str_ip = RANDOM_IP_POOL[random.randint(0, len(RANDOM_IP_POOL) - 1)] str_ip_addr = str_ip.split('/')[0] str_ip_mask = str_ip.split('/')[1] ip_addr = struct.unpack('>I', socket.inet_aton(str_ip_addr))[0] mask = 0x0 for i in range(31, 31 - int(str_ip_mask), -1): mask = mask | (1 << i) ip_addr_min = ip_addr & (mask & 0xffffffff) ip_addr_max = ip_addr | (~mask & 0xffffffff) return socket.inet_ntoa( struct.pack('>I', random.randint(ip_addr_min, ip_addr_max)))
def dataTest(): # Query for distinct cuisines cuisineDistinctQuery = recipe_list.query.with_entities( recipe_list.cuisine).distinct() # Create List from distinct query cuisinesList = sorted([row.cuisine for row in cuisineDistinctQuery]) # Blank list to contain counts of cuisine types counts = [] # Blank list to contain random colors generates colors = [] for value in cuisinesList: count = recipe_list.query.filter_by(cuisine=value).count() counts.append(count) colors.append("#{:06x}".format(random.randint(0, 0xFFFFFF))) # Query for distinct main ingredient ingredientDistinctQuery = recipe_list.query.with_entities( recipe_list.ingredients).distinct() # Create list from distinct ingredient query ingredientsList = sorted( [row.ingredients for row in ingredientDistinctQuery]) # Blank list to contain counts of cuisine types ingcounts = [] # Blank list to contain random colors generates ingcolors = [] for value in ingredientsList: count = recipe_list.query.filter_by(ingredients=value).count() ingcounts.append(count) ingcolors.append("#{:06x}".format(random.randint(0, 0xFFFFFF))) # Queries the database, returns all values ordered by recipe name field recipeQuery = recipe_list.query.order_by(recipe_list.name).all() return render_template('index2.html', counts=counts, cuisinesList=cuisinesList, colors=colors, ingredientsList=ingredientsList, ingcounts=ingcounts, ingcolors=ingcolors, recipeQuery=recipeQuery)
def random_str(self, minlength=None, maxlength=None): str = '' chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789!@#$%^&*()<>?/{}[]|,.;:\+-~ ' length = len(chars) - 1 random = Random() if self.maxlength <= 0: str = '' return (str) else: for i in xrange(self.minlength, random.randint(self.minlength, self.maxlength) + 1): #print i str += chars[random.randint(0, length)] return (str)
def __commerce_purchase_products(self, e_commerce_agents): """ 厂商从产品种类中采购商品 """ for e_commerce_agent in e_commerce_agents: product_diversity = random.randint(1, 15) if product_diversity >= len(self.category_schedule.agents): for category_agent in self.category_schedule.agents: self.__generate_product(e_commerce_agent, category_agent) else: selected_category_agents = random.sample( self.category_schedule.agents, product_diversity) for category_agent in selected_category_agents: self.__generate_product(e_commerce_agent, category_agent)
def generate(args): # load data stroke_train, stroke_val, label_train, label_val, label2char, char2label, max_len, all_strokes, all_lbls = load_data(args.data_dir, args.model_dir) vocabulary = len(label2char) test_set = DataLoader(stroke_val, label_val, batch_size=args.batch_size, max_seq_length=args.max_seq_len, embedding_len=args.embedding_len, vocabulary=vocabulary) train_set = DataLoader(stroke_train, label_train, batch_size=args.batch_size, max_seq_length=args.max_seq_len, embedding_len=args.embedding_len, vocabulary=vocabulary) data_set = DataLoader(all_strokes, all_lbls, batch_size=args.batch_size, max_seq_length=args.max_seq_len, embedding_len=args.embedding_len, vocabulary=vocabulary) # construct the sketch-rnn model here: reset_graph() model = Generation_model(args=args, vocabulary=vocabulary) args.is_training = False args.batch_size = 1 sample_model = Generation_model(args=args, reuse=True, vocabulary=vocabulary) sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) # print( # # "The embedding matrix: " + sess.run(model.embedding_matrix, feed_dict={}) # # ) # loads the weights from checkpoint into our model load_checkpoint(sess, FLAGS.log_root) index = random.randint(0,len(train_set.charlabel)) index_char = train_set.charlabel[index] x = train_set.strokes[index] label = label2char[index_char][0] print(label) sample_strokes, m = sample(sess, sample_model, seq_len=args.max_seq_len, temperature=0.9, index_char = index_char, args=args) sample_strokes[:, 2] = sample_strokes[:, 3] # change because we don't input the sequence, so we don't change at the to_big_stroke strokes = to_normal_strokes(sample_strokes) x_strokes = to_normal_strokes(x) draw_strokes(x_strokes, svg_fpath='sample/origin_' + label + '.svg') draw_strokes(strokes, svg_fpath='sample/gen_' + label + '.svg')
def randomized_partition(self, nums, left, right): pivot = random.randint(left, right) # change position nums[pivot], nums[right] = nums[right], nums[pivot] i = left - 1 for j in range(left, right): if nums[j] < nums[right]: i += 1 nums[j], nums[i] = nums[i], nums[j] i += 1 nums[i], nums[right] = nums[right], nums[i] return i
def generate_random_pos_in_environment(environment: dict): """ Generate a random position (x : meters, y : meters, theta : radians) and near the 'center' with a nearby valid goal position. - Note that the obstacle_traversible and human_traversible are both checked to generate a valid pos_3. - Note that the "environment" holds the map scale and all the individual traversibles if they exists - Note that the map_scale primarily refers to the traversible's level of precision, it is best to use the dx_m provided in examples.py """ map_scale = float(environment["map_scale"]) # Combine the occupancy information from the static map and the human if "human_traversible" in environment.keys(): # in this case there exists a "human" traversible as well, and we # don't want to generate one human in the traversible of another global_traversible = np.empty(environment["map_traversible"].shape) global_traversible.fill(True) map_t = environment["map_traversible"] human_t = environment["human_traversible"] # append the map traversible global_traversible = np.stack([global_traversible, map_t], axis=2) global_traversible = np.all(global_traversible, axis=2) # stack the human traversible on top of the map one global_traversible = np.stack([global_traversible, human_t], axis=2) global_traversible = np.all(global_traversible, axis=2) else: global_traversible = environment["map_traversible"] # Generating new position as human's position pos_3 = np.array([0, 0, 0]) # start far out of the traversible # continuously generate random positions near the center until one is valid while not within_traversible(pos_3, global_traversible, map_scale): new_x = random.randint(0, global_traversible.shape[0]) new_y = random.randint(0, global_traversible.shape[1]) new_theta = 2 * np.pi * random.random() # bound by (0, 2*pi) pos_3 = np.array([new_x, new_y, new_theta]) return pos_3
def sample_images(training_set=True, n_frames=int(10.0 / 0.03), steering_offset=1): """Returns a list of n filenames for pictures in consecutive order, paired with the steering commands. steering offset is the number of frames in the future that we are trying to predict.""" folders = glob.glob('./data_dir/*') lengths = [len(i) for i in (glob.glob(i + '/*') for i in folders)] f_and_l = list(zip(folders, lengths)) training_frac = 0.8 while True: curr_folder = weighted_choice(f_and_l) angles = get_angles(curr_folder) if training_set: #Use first 80% of data file_num = random.randint(0, int(0.8 * n_files)) else: #Use last 20% of data file_num = random.randint(int(0.8 * n_files + 1), n_files) # (.8 * n_files, 1) ?? #Sorting all these files might matter, it might not. #Since it is asynchronous, it probably doesn't matter, but #if it does, we should just keep a sorted variable around. filename = sorted( glob.glob(curr_folder + '/*.jpg')[file_num], key=lambda x: int(x.replace('frame', '').replace('.jpg', ''))) image = open_image(curr_folder + '/' + filename) image = pre_process_image(image, 0) steering_angle = retrieve_angle(curr_folder, file_num, n_files) yield image, steering_angle
def sendMoneyOrderToMerchant(merchant_ip_address, stub, digitalCashServer): with open('Unused_MO.txt', 'r') as fh: line = fh.readlines() if not line: print("No MOs to send, please select Mode = 1 next") return Request = line[0] line = line[1:] with open('Unused_MO.txt', 'w') as fh: for l in line: fh.write(l) with open('Used_MO.txt', 'a') as fh: fh.write(Request) fh.write("\n") d = Request.split(" ") digitalCashServer.MO_Pairs_data = d moneyOrderHelper = MoneyOrderHelper(numberOfMoneyOrders, numberOfSecretPairs, pub_key) Message = moneyOrderHelper.decrpyt_amount(d[1]) key = random.randint(0, 1234) #key = "\x00"+os.urandom(4)+"\x00" key = str(key) #print (BitVector(intVal = int(Message), size = 1024).get_bitvector_in_ascii()) hash_val = moneyOrderHelper.generate_signature( key, Message) #BitCommit (Message, key) Hash_and_key = hash_val + ',' + key with grpc.insecure_channel(merchant_ip_address) as channel: try: grpc.channel_ready_future(channel).result(timeout=1) except grpc.FutureTimeoutError: print("<--- Connection timeout. Unable to connect to port. --->") return None else: print("** Connected to merchant server. **") stub = digitalCashService_pb2_grpc.digitalCashServiceStub(channel) response = stub.sendToMerchantFromCustomer( digitalCashService_pb2.Message(messageData=Hash_and_key)) print(response.message)
def shock( rfid, mode ): global stamp, realstamp, punmqtt devices = slaves.get_device( rfid ) slave_id = slaves.get_id( rfid ) if realstamp[ rfid ] > 0 and realstamp[ rfid ] < int( datetime.timestamp( datetime.now()) ): showLogo() realstamp[ rfid ] = 0 for dev in devices: if tordevices.support_function( dev['device'], 'tens' ): device = tordevices.get_device( dev['device'] ) funcs = tordevices.get_functions( dev['device'], 'tens' ) for i in funcs: if int(datetime.timestamp( datetime.now()) ) > stamp[ rfid ]: value = random.randint(0, 30) counter = random.randint(0, 30) if value == 1: mode = randint(1,6) if mode == 1: seconds = 10 elif mode == 2: seconds = 30 elif mode == 3: seconds = 60 elif mode == 4: seconds = 90 elif mode == 5: seconds = 120 elif mode == 6: seconds = 160 stamp[ rfid ] = int(datetime.timestamp( datetime.now() )) + seconds + counter +random.randint(10, 120) realstamp[ rfid ] = int(datetime.timestamp( datetime.now() )) + seconds + counter if device['protocol'] == "MQTT": punmqtt.publish('punisher/slave/'+str(slave_id)+'/shock', '{"seconds": '+str(seconds)+', "countdown": '+str(counter)+'}' ) if i['image'] != "": showfunc( i['image'] )
def createRooms(self, bspTree): if (self.child_1) or (self.child_2): # recursively search for children until you hit the end of the branch if (self.child_1): self.child_1.createRooms(bspTree) if (self.child_2): self.child_2.createRooms(bspTree) if (self.child_1 and self.child_2): bspTree.createHall(self.child_1.getRoom(), self.child_2.getRoom()) else: # Create rooms in the end branches of the bsp tree w = random.randint(bspTree.ROOM_MIN_SIZE, min(bspTree.ROOM_MAX_SIZE, self.width - 1)) h = random.randint(bspTree.ROOM_MIN_SIZE, min(bspTree.ROOM_MAX_SIZE, self.height - 1)) x = random.randint(self.x, self.x + (self.width - 1) - w) y = random.randint(self.y, self.y + (self.height - 1) - h) self.room = Rect(x, y, w, h) bspTree.createRoom(self.room)
def _process_valid_message(body, number): from_name = get_name_from_number(number) from_phone = number message_body = parse.get_message_body(body) to_name = parse.get_message_to(body) # TODO: not random ID guess_id = str(random.randint(1,99999)) # we sms g_id out so people can guess! # if we know tagged user, we will forward the text body if user_exists(user_name): to_phone = get_number_from_name(user_name) create_message(from_name, from_phone, message_body, to_name, to_phone, guess_id) send_message_and_id(message_body, guess_id, to_number) # send the text! # user doesn't exist but we save the message body anyway else: to_phone = '' create_message(from_name, from_phone, message_body, to_name, to_phone, guess_id)
def pic_capture(): # All-Purpose camera taking function from picamera import PiCamera # IF THIS IS NOT RUN ON A RASPBERRY PI CAMERA, IT WILL NOT WORK from random import random # Import the needed modules for the functions to run camera = PiCamera() # Create instance of Camera camera.rotation = 90 # Change this variable if orientation is bad picture_name = (str(input('Pick a photo name:\n '))) if picture_name == '': picture_name = ('pic' + str(random.randint(0, 10000))) # If too lazy to type a name, auto assign one named pic, plus some number between 0 and 10,000 # # Be sure to add in a thing that will remove spaces picture_numerator = 0 # user input variable that asks for how many pictures to be taken. while True: picture_numerator = (int(input('How many photos?:\n '))) # Ask user input for how many photos if picture_numerator == '': picture_numerator = 3 # Default is 3 pictures elif picture_numerator <= 0: continue break # # Make sure to add a thing that checks if the input is an integer picture_numerator_counter = 0 # Variable for determining number of pics taken camera.start_preview() # Turn the preview window on, note that this takes up the entire screen. sleep(2) # preview for two seconds before taking a picture while picture_numerator_counter < picture_numerator: sleep(2) camera.capture(picture_name + str(picture_numerator_counter) + '.jpg') picture_numerator_counter += 1 # Sleep, take a picture, save, increase the number counter of pics taken camera.stop_preview()
def find_solution(self): # Generate 25 random solutions # repeat until stop criteria # s <- Randomized Greedy (Best of LC) # s_ <- LS(s) # Update(s_, best_sollution) # return best_solution # Initialization phase self.LC = self.get_permutations() best_S = self.S best_cost = self.cost for _ in xrange(25): s_greedy = self.randomized_greedy() C_min, C_max = self.LC[0][0], self.LC[-1][0] self.LRC = self.LC[:C_min + self.alpha * (C_max - C_min)] rand = random.randint(0,len(self.LRC)) s_grasp = [self.LRC[rand][1]] s_BL, cost_BL = self.local_search(s_greedy) if cost_BL < best_cost: best_cost = cost_BL best_S = s_BL
#反射,通过字符串模式导入模块,可以方便切换 tmp = 'mysqlhelper' func = 'count' model = __import__(tmp) ggg = getattr(model, func) print ggg() #通过字符串模式导入函数,需要先找到函数getattr import random print random.random() print random.random()*10 #生成0-1之间的随机数 print random.randint(1,5) #生成1-5间的整形随机数 print random.randrange(1,3) #生成1和2,不会生成3,整形 print random.randint(100000,999999) #生成6位随机数 code = [] for i in range(6): if i == random.randint(1,5): code.append(str(random.randint(1,5))) else: tmp = random.randint(65,90) code.append(chr(tmp))
def shooting(self): for i in range(self.bullets): x = random.randint(0, self.width-1) y = random.randint(0, self.height-1) self.dungeon[x, y] = 0 self.counting()
def uniqueCode(seed): one_part = time.time() two_part = random.randint(10000000, 999999999) unique_id = str(int(one_part + two_part)) return unique_id[:seed]
def setUniqueId(): one_part = time.time() two_part = random.randint(1000, 10000000000) unique_id = one_part + two_part return unique_id
file2 = '/Users/spenceraxani/Documents/Nuclear_Decay/Data/binned_proton_100MeV.txt' #this one, bootstrap date1, value1 = numpy.loadtxt(file1, unpack=True) date2, value2 = numpy.loadtxt(file2, unpack=True) p_corr_list = [] new_temp_dict = {} temp_values_dict = {} another_dict = {} temp_another_dict = {} print("Calculating the bootstrapping distribution ...") for i in range(trials): for i in range(len(date1)): new_temp_dict[date1[i]] = [value1[i]] #here, column[0] is the date. So element [date] in dictionary is [value(column[1])] for j in range(len(date2)): if date2[j] in new_temp_dict: new_temp_dict[date2[j]].append(value2[random.randint(0,len(value2)-1)]) #print(random.randint(0,len(value2))) for k in new_temp_dict: if len(new_temp_dict[k]) == 2: temp_values_dict[k]=new_temp_dict[k] list1 = [] list2 = [] for i in temp_values_dict: list1.append(float(temp_values_dict[i][0])) list2.append(float(temp_values_dict[i][1])) x = array("d",list1) y = array("d",list2) p_corr_list.append(correlation(x,y)) #this list now holds all the various values for the pearsons correlation #print(correlation(x,y)) #print(pearsonr(x, y)) new_temp_dict = {}
state <<= 1; grovepi.ledBar_setBits(ledbar, state) time.sleep(.2) # bounce to the left for i in range(0,9): # bit shift right and update state >>= 1; grovepi.ledBar_setBits(ledbar, state) time.sleep(.2) time.sleep(.3) print "Test 16) Random" for i in range(0,21): state = random.randint(0,1023) grovepi.ledBar_setBits(ledbar, state) time.sleep(.2) time.sleep(.3) print "Test 17) Invert" # set every 2nd LED on - 341 or 0x155 state = 341 for i in range(0,5): grovepi.ledBar_setBits(ledbar, state) time.sleep(.2) # bitwise XOR all 10 LEDs on with the current state state = 0x3FF ^ state
def passphrase(pass_len=4, min_word_len=4, seed="seed.txt"): """ pass_len: Password length min_word: Minimum seed: Text file containing a big text """ import random import re fp = open(seed) txt = fp.read() fp.close() chars = [',', '!', ';', '$', '%', '@', '&', '*', '<', '>', '.', "'", ':', '?', '"','-'] txt = re.sub('[%s]' % ''.join(chars), '', txt) words = txt.split() #print words print pass_len print len(words) # Minimum word lenght passum = "" passphrase = "" passw = "" passdash = "" altern = "" idx = 0 print "Word List\n--------------" while idx < pass_len: # Mixing to make more random. N = random.randint(0, 600) for k in range(N): word = random.choice(words) if len(word) >= min_word_len: print word passphrase = "".join([passphrase, word, " "]) passw = "".join([passw, word[0]]) passum = "".join([passum, word]) passdash = "".join([passdash, word, "-"]) _word = "".join( [word[0].upper(), word[1:].lower()]) altern = "".join([ altern, _word ]) idx = idx + 1 passdash = passdash[:-1] enc = altern enc = altern.replace('a','@') enc = enc.replace('i','!') enc = enc.replace('b','8') enc = enc.replace('b','8') enc = enc.replace('o','0') enc = enc.replace('E','3') enc = enc.replace('s','5') enc = enc.replace('c','(') enc = enc.replace('I','&') enc = enc.replace('g','9') enc = enc.replace('v','\/') print "\nPassphrase all words" print ".........................." print passphrase print "\nPassphrase all words joined" print ".........................." print passum print "\nPassphrase separated by dash" print ".........................." print passdash print "\nUpper / Lower case alternate password" print ".........................." print altern print "\nPassphrase number encoded" print ".........................." print enc print "\nPassphrase initial of all words\t\t" print ".........................." print passw
def rollDice(): for i in range(0, 7): roll = int(random.randint(1,6)) rollCount[roll - 1] += 1 return rollCount
import random from random import shuffle from faker import Faker from barnum import gen_data import csv fake = Faker() ON_US_INDICATOR = ['ON','OFF'] DebitCredit = ['CR','DR'] bank= ['0','8','9'] select = '1' #ATM_FLAG = ['1','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'] ATM_FLAG = ['1','0'] with open('largetrns.csv','w') as f1: writer=csv.writer(f1, delimiter=',',lineterminator='\n',) writer.writerow(['rownum'] +['TXN_ROUTING_TRANSIT'] + ['DEBIT_CREDIT_INDICATOR'] +['Bank']+ \ ['AccountID'] + ['Amount'] + ['ON_US_INDICATOR'] + \ ['COMPANY_NAME'] + ['DATE_POSTED']+ ['City_State_Zip'] + ['ATM_FLAG'] +['RDCFLAG']) for i in range(500): row = [i] + [random.choice(Python_aba_transit_numbers.aba)] + \ [DebitCredit[random.randint(0,len(DebitCredit)-1)]] + \ [random.choice(bank)] + \ [random.choice(python_account_ID.accountid)] + \ [max ( max((randrange(0,101,1)-99),0)* randrange(20000,500000,1),randrange(5,35000,1))] + \ [ON_US_INDICATOR[random.randint(0,len(ON_US_INDICATOR)-1)]] + \ [gen_data.create_company_name()] + \ [gen_data.create_birthday(min_age=1, max_age=8)] + \ [gen_data.create_city_state_zip()] + \ [random.choice(ATM_FLAG)* max((randrange(0,101,1)-99),0)] + [random.choice(ATM_FLAG)* max((randrange(0,101,1)-99),0)] writer.writerow(row)
sys.exit() xres = int(sys.argv[1]) yres = int(sys.argv[2]) matrix = [ [Point(x,y) for x in xrange(xres)] for y in xrange(yres)] f = open(sys.argv[3], 'wb') f.write("P3\n{0} {1}\n 255\n".format(xres, yres)) #header ''' #plot_point(Point(1,2)) plot_line(0,0,200,50, matrix, [255,0,0]) #octant 1 plot_line(0,0,20,5, matrix, [0,255,0]) plot_line(0,100,150,100, matrix, random_color()) #horizontal plot_line(100,0,100,175, matrix, random_color()) #vertical plot_line(150,130,0,0, matrix, random_color()) #octant 5 plot_line(0,0, 50, 100, matrix, random_color()) #octant 2 plot_line(120,40,30,10, matrix, random_color())#octant 6 plot_line(0,100,100,75, matrix, random_color()) #octant 8 plot_line(125,100,25,125, matrix, random_color()) #octant 4 plot_line(0,150,50,50, matrix, random_color()) #octant 7 plot_line(75,75,25,175, matrix, random_color()) #octant 3 ''' for x in xrange(300): plot_line(xres/2, yres/2, random.randint(0,xres-1), random.randint(0,yres-1), matrix, random.choice([[255,0,0], [0,255,0], [0,0,255]])) plot_screen(f, matrix) #print matrix print 'Done!' f.close()
def get_id(self): eid = self.attr('id') if not eid: eid = 'pyxl%d' % random.randint(0, sys.maxint) self.set_attr('id', eid) return eid
['PREFERRED_CHANNEL']+['PRIMARY_BRANCH_NO']+['DEPENDANTS_COUNT']+['SEG_MODEL_ID']+['SEG_MODEL_TYPE']+\ ['SEG_MODEL_NAME']+['SEG_MODEL_GROUP']+['SEG_M_GRP_DESC']+['SEG_MODEL_SCORE']+['ARMS_MANUFACTURER']+['AUCTION']+\ ['CASHINTENSIVE_BUSINESS']+['CASINO_GAMBLING']+['CHANNEL_ONBOARDING']+['CHANNEL_ONGOING_TRANSACTIONS']+['CLIENT_NET_WORTH']+\ ['COMPLEX_HI_VEHICLE']+['DEALER_PRECIOUS_METAL']+['DIGITAL_PM_OPERATOR']+['EMBASSY_CONSULATE']+['EXCHANGE_CURRENCY']+\ ['FOREIGN_FINANCIAL_INSTITUTION']+['FOREIGN_GOVERNMENT']+['FOREIGN_NONBANK_FINANCIAL_INSTITUTION']+['INTERNET_GAMBLING']+\ ['MEDICAL_MARIJUANA_DISPENSARY']+['MONEY_SERVICE_BUSINESS']+['NAICS_CODE']+['NONREGULATED_FINANCIAL_INSTITUTION']+\ ['NOT_PROFIT']+['PRIVATELY_ATM_OPERATOR']+['PRODUCTS']+['SALES_USED_VEHICLES']+['SERVICES']+\ ['SIC_CODE']+['STOCK_MARKET_LISTING']+['THIRD_PARTY_PAYMENT_PROCESSOR']+['TRANSACTING_PROVIDER']+['HIGH_NET_WORTH']+['HIGH_RISK']+['RISK_RATING']+['USE_CASE_SCENARIO']) #Loop for number of accounts to generate start=10786147 acct_list=[] #JS - Update code 1/26/2016 #JS - Create list of SSNs up to 20M and use that to pull from liSSNMaster=[] for i in xrange(30000000): liSSNMaster.append(''.join(str(random.randint(0,9)) for _ in xrange(9))) #JS - Only create as many records as the SSN list has available #JS - Use xrange instead of range to minimize memory allocation liSSNMaster = list(set(liSSNMaster)) if len(liSSNMaster) < 18500000: liSSNMaster=[] for i in xrange(50000000): liSSNMaster.append(''.join(str(random.randint(0,9)) for _ in xrange(9))) liSSNMaster = list(set(liSSNMaster)) for i in xrange(18500000): #Initiate High Risk Flags #Politically Exposed Person PEP='No' #Customer with a Suspicous Activity Report SAR='No' #Customer with a closed account
from random import random print("Welcome to Mastermind! This is a programme written in python 3.") input() print("If you do not know the rules to this game, look it up.") input() one = random.randint(1,6) two= random.randint(1,6) three = random.randint(1,6) four= random.randint(1,6) print("The computer has chosen four random numbers.") print("Type the first number of your guess here:") 1guess1 = input() print("Type the second number of your guess here:") 1guess2 = input() print("Type the third number of your guess here:") 1guess3= input() print("Type the fourth number of your guess here:") 1guess4 = input() print() print("Here are your guess ratings.") if 1guess1 == one: print(black) elif 1guess1 == two or 1guess1 == three or 1guess1 == four: print(white) else: print("Nothing")
from random import random for roll in xrange(10): print random.randint(1, 6)
def random_word(min_syllable=2, max_syllable=6): return ''.join(random_syllable() for x in range(random.randint(min_syllable, max_syllable))) #@UnusedVariable
def individuum(): return params_to_ind([random.randint(0,256) for i in range(i_length)])
def createSSNs(N): liSSN=[] for i in xrange(N): liSSN.append(''.join(str(random.randint(0,9)) for _ in xrange(9))) return liSSN