def conectaAleatorio(self): import random rand = ceil(i * (90 / 100)) for j in range(rand): v = random.sample(self.nodos, 1)[0] u = random.sample(self.nodos, 1)[0] if v == u: u = random.sample(self.nodos, 1)[0] if pesos is 0: self.aristas[(v, u)] = self.aristas[(u, v)] = pesos self.vecinos[v].add(u) self.vecinos[u].add(v) else: self.aristas[(v, u)] = self.aristas[(u, v)] = randint(1, 10) self.vecinos[v].add(u) self.vecinos[u].add(v) else: if pesos is 0: self.aristas[(v, u)] = self.aristas[(u, v)] = pesos self.vecinos[v].add(u) self.vecinos[u].add(v) else: self.aristas[(v, u)] = self.aristas[(u, v)] = randint(1, 10) self.vecinos[v].add(u) self.vecinos[u].add(v)
def generate_key(): ''' 生成16位卡密 ''' new_key = ''.join(random.sample(string.ascii_letters + string.digits, 16)) while new_key in key_dict: # 防止生成重复的卡密, 不过概率太低了。。。 new_key = ''.join( random.sample(string.ascii_letters + string.digits, 16)) return new_key
def password(strength, length): paswd = list(string.ascii_letters + string.digits + "!@#$%^&*()") if strength == 'strong': temp = random.sample(paswd, length) usrPassword = ''.join(temp) else: ranLst = ["Hello", "password", "birthday", "world", "charizma"] temp = random.sample(ranLst, len(ranLst)) usrPassword = ''.join(temp) return usrPassword
def propose(self, state: MechanismState) -> Optional["Outcome"]: if self.ufun_max is None or self.ufun_min is None: self.on_ufun_changed() if self.ufun_max < self.reserved_value: return None asp = (self.aspiration(state.relative_time) * (self.ufun_max - self.ufun_min) + self.ufun_min) if asp < self.reserved_value: return None if self.presorted: if len(self.ordered_outcomes) < 1: return None for i, (u, o) in enumerate(self.ordered_outcomes): if u is None: continue if u < asp: if u < self.reserved_value: return None if i == 0: return self.ordered_outcomes[i][1] if self.randomize_offer: return random.sample(self.ordered_outcomes[:i], 1)[0][1] return self.ordered_outcomes[i - 1][1] if self.randomize_offer: return random.sample(self.ordered_outcomes, 1)[0][1] return self.ordered_outcomes[-1][1] else: if asp >= 0.99999999999 and self.best_outcome is not None: return self.best_outcome if self.randomize_offer: return outcome_with_utility( ufun=self._utility_function, rng=(asp, float("inf")), issues=self._ami.issues, ) tol = self.tolerance for _ in range(self.n_trials): rng = self.ufun_max - self.ufun_min mx = min(asp + tol * rng, self.__last_offer_util) outcome = outcome_with_utility( ufun=self._utility_function, rng=(asp, mx), issues=self._ami.issues, ) if outcome is not None: break tol = math.sqrt(tol) else: outcome = (self.best_outcome if self.__last_offer is None else self.__last_offer) self.__last_offer_util = self.utility_function(outcome) self.__last_offer = outcome return outcome
def guarda(self): with open("Tarea3Completo.dat", "w") as crear: import random self.s = random.sample(self.nodos, 1)[0] self.t = random.sample(self.nodos, 1)[0] for nodos in self.nodos: if nodos == self.s: print(self.s[0], self.s[1], 4, file=crear) if nodos == self.t: print(self.t[0], self.t[1], 7, file=crear) if nodos is not self.s and nodos is not self.t: print(nodos[0], nodos[1], 8, file=crear)
def conectaAleatorioDir(self): import random rand = ceil(i * (50 / 100)) for j in range(rand): v = random.sample(self.nodos, 1)[0] u = random.sample(self.nodos, 1)[0] if v == u: u = random.sample(self.nodos, 1)[0] self.aristas[(v, u)] = 0 self.vecinos[v].add(u) else: self.aristas[(v, u)] = 0 self.vecinos[v].add(u)
def Aproval_randomizer(candidates_num, comittee_size, voters_num): list = [] for i in range(voters_num): f = random.sample(range(candidates_num), random.randint(1, comittee_size)) list.append(f) return list
def Breath_First_Search(self): with open("niveles.dat", "w") as crear: import random self.nodoInicio = random.sample(self.nodos, 1)[0] self.niveles = {} self.explorado = [] self.estado = [self.nodoInicio] self.niveles[self.nodoInicio] = 0 print(self.nodoInicio[0], self.nodoInicio[1], self.niveles[self.nodoInicio] + 1, file=crear) self.visitado = [self.nodoInicio] while self.estado: self.nodo = self.estado.pop(0) self.explorado.append(self.nodo) self.vecino = self.vecinos[self.nodo] for self.vecino in self.vecino: if self.vecino not in self.visitado: self.estado.append(self.vecino) self.visitado.append(self.vecino) self.niveles[self.vecino] = self.niveles[self.nodo] + 1 print(self.vecino[0], self.vecino[1], self.niveles[self.vecino] + 1, file=crear) for (x, y) in self.nodos: if (x, y) not in self.visitado: print(x, y, 0, file=crear) print(self.niveles) return self.explorado
def get_random_samples(file_names, samples_count_per_category): """ get random samples for log testing. Args: file_names: samples_count_per_category: Returns: """ checklist = np.zeros(samples_count_per_category * 10) final_list = [] iteration_number = 0 # Get a random sample for each category while 1: print("Iteration Number:", iteration_number) sample_names = random.sample(file_names, 10) for name in sample_names: category = int(name[0]) if checklist[category] < samples_count_per_category: checklist[category] += 1 final_list.append(name) if int(checklist.sum()) == (samples_count_per_category * 10): break iteration_number += 1 print(final_list) return final_list
def generate_data(data, samples, targeted=True, start=0, inception=False): """ Generate the input data to the attack algorithm. data: the images to attack samples: number of samples to use targeted: if true, construct targeted attacks, otherwise untargeted attacks start: offset into data to use inception: if targeted and inception, randomly sample 100 targets intead of 1000 """ inputs = [] targets = [] for i in range(samples): if targeted: if inception: seq = random.sample(range(1,1001), 10) else: seq = range(data.test_labels.shape[1]) for j in seq: if (j == np.argmax(data.test_labels[start+i])) and (inception == False): continue inputs.append(data.test_data[start+i]) targets.append(np.eye(data.test_labels.shape[1])[j]) else: inputs.append(data.test_data[start+i]) targets.append(data.test_labels[start+i]) inputs = np.array(inputs) targets = np.array(targets) return inputs, targets
def fit(self, data: np.array): """ Fits kmeans """ n_samples, _ = data.shape # initialize cluster centers self.centers = np.array(random.sample(list(data), self.k)) self.ini_centers = np.copy(self.centers) old_data_point_assignment = None n_iters = 0 while True: data_point_assignment = [ self.classify(datapoint) for datapoint in data ] # If data point assignments stop changing, then we find the model if data_point_assignment == old_data_point_assignment: print(f"Training finished.. {n_iters} iterations!") print(f"Points assignment: {data_point_assignment}") return old_data_point_assignment = data_point_assignment n_iters = n_iters + 1 # recalculate centers for i in range(self.k): points_idx = np.where(np.array(data_point_assignment) == i) datapoints = data[points_idx] self.centers[i] = datapoints.mean(axis=0)
def split_ids(ids, split): ids = sorted(ids.unique().tolist()) test_ids = sorted(random.sample(ids, int(split * len(ids)))) training_ids = list_diff(ids, test_ids) return Series(test_ids), Series(training_ids)
def sample(self, batch_size=None): # sample all transitions if batch_size is None: return Transition(*zip(*self.memory)) else: # sample with size: batch_size random_batch = random.sample(self.memory, batch_size) return Transition(*zip(*random_batch))
def getRandomNum(data, sample_size): random_values = random.sample(data, k=sample_size - 1) return random_values #def getSample(data, sample_size): # random_values = random.sample(data, k=sample_size) # return random_values
def selection(population, num_of_selection): _, max_score, where = weight_calculation(population) pop = population.copy() out = [] out.append(population[int(where)]) pop.pop(int(where)) out += random.sample(pop, k=num_of_selection - 1) return out
def balanced_sample(self): for i in range(self.batchnum): for j in self.pool: p = self.pool[j] imgpath = random.sample(p, 1)[0] self.cadidates.append([imgpath, j]) random.shuffle(self.cadidates)
def sample(self, count=4): """Return a sampling of the album, for use in jumbotron and as random album cover photos """ if count > self.photo_count(): count = self.photo_count() photo_set = self.photos return random.sample(set(photo_set), count)
def random_recipes(): for repeat in range(10): random_recipe = list( db.soomi_all_recipes.find({'category': '공식레시피'}, {'_id': 0})) soomi_random_recipe = (random.sample(random_recipe, 10)) # print(soomi_random_recipe) return jsonify({ 'result': 'success', 'recommend_recipes': soomi_random_recipe })
def CreateTimming(self, t): days = random.sample(self.Days, random.randint(1,3)) for i in days: s = random.randint(6, 17) ss = str(s).zfill(2) e = random.randint(1 , 6 ) + s es = str(e).zfill(2) ss = datetime.strptime(ss, '%H').time() es = datetime.strptime(es, '%H').time() m.Timming.objects.create(Tutor = t, Day = i, TimeStart = ss, TimeEnd = es)
def FillDataBase(self, n): a = random.sample(range(1000000000, 10000000000), n) for i in a: x = random.random() if x<0.3: self.CreateTutor(i) elif x>0.95: self.CreateBroker(i) else: self.CreateStudent(i)
def scheduling(self, agent_list: List[Agent], func: Callable[[Agent, List[Agent]], None]) -> None: current_state = copy.deepcopy(agent_list) order = random.sample(agent_list, len(agent_list)) for a in order: other_agents = [x for x in current_state if x is not a] func(a, other_agents) agent_list[:] = self.__clash_solution(copy.deepcopy(agent_list), current_state)
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 get_str(num=4): """ 获取随机字符串 :param num: :return: """ return ''.join( random.sample([ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a' ], num))
def randomly_select_K(sorted_c_r_list, perf_thresh, K, slope_thresh=0.0): import random while True: idx_list = random.sample(range(len(sorted_c_r_list)), K) sorted_idx_list = sorted(idx_list) selected_c_r_list = [] for idx in sorted_idx_list: if (sorted_c_r_list[idx][1] >= perf_thresh) or (sorted_c_r_list[idx][0] < slope_thresh): #If we selected one of the best points, then ignore and resample break else: selected_c_r_list.append(sorted_c_r_list[idx]) if len(selected_c_r_list) == K: return selected_c_r_list
def ruleta(lista, n): import random F, NF = [], [] f = len(lista.loc[d.fact == True, ]) nf = len(lista.loc[d.fact == False, ]) for i in range(0, f): F.append(i) for j in range(f, (f + nf)): NF.append(j) if len(NF) == 0: for k in range(0, 3): NF.append(k) listas = [(random.sample(F, k=2)), (random.sample(NF, k=2))] results = random.choices(listas, weights=[len(F), len(NF)], k=2) if results[0] == results[1]: salida = results[0] if results[0] != results[1]: dato1 = results[0] dato2 = results[1] salida = [dato1[0], dato2[0]] return (salida)
def load_video_features(fpath, max_length): feats = np.load( fpath, encoding='latin1' )[0] # encoding='latin1' to handle the inconsistency between python 2 and 3 if feats.shape[0] < max_length: dis = max_length - feats.shape[0] feats = np.lib.pad(feats, ((0, dis), (0, 0)), 'constant', constant_values=0) elif feats.shape[0] > max_length: inds = sorted(random.sample(range(feats.shape[0]), max_length)) feats = feats[inds] assert feats.shape[0] == max_length return np.float32(feats)
def getsalt(pwd, salt=None): '''获取密码并变成盐''' h = hashlib.md5() if not salt: l = "gijhskdgjeuirtu658499848609/,./'][" salt = ''.join(random.sample(l, 6)).replace(" ", "") password = pwd + salt h.update(password.encode()) mypwd = h.hexdigest() return mypwd, salt else: password = pwd + salt h.update(password.encode()) mypwd = h.hexdigest() return mypwd
def captcha(self, path=None, fmt='JPEG'): image = Image.new('RGB', (self.width, self.height), (255, 255, 255)) image = self.background(image) image = self.text(image, self.fonts, drawings=['warp', 'rotate', 'offset']) image = self.curve(image) image = self.noise(image) image = self.smooth(image) name = "".join(random.sample(string.lowercase + string.uppercase + '3456789', 24)) text = "".join(self._text) out = StringIO() image.save(out, format=fmt) if path: image.save(os.path.join(path, name), fmt) return name, text, out.getvalue()
def selection_population_function(population: [Genome],distances_avg,distances,cities,dates,fixture): # TORNEO random_list = random.sample(range(0, len(population)), len(population)) selected_population = [] population_length = len(population) for i in range(int(len(population)/2)): fitness_1 = fitness(population[random_list[i]], distances_avg, distances, cities, dates, fixture) fitness_2 = fitness(population[random_list[population_length - i - 1]], distances_avg, distances, cities, dates, fixture) if fitness_1 <= fitness_2: selected_population.append(population[random_list[i]]) else: selected_population.append(population[random_list[population_length - i - 1]]) return selected_population
def generate_events(self): """ This method should be overridden depending on the input format of input files. """ with open(self.input_path, 'r') as source: event = { Attr.id: ''.join(random.sample(string.ascii_letters + string.digits, 8)), Attr.date: ''.join(time.strftime("%Y%m%d", time.localtime())), Attr.source: 'NULL' } content = re.sub(r'\s', '', source.read()) # parse = self.parse(content) # event[Attr.content] = self.sep_sentence(parse) event[Attr.content] = self.sep_sentence(content) print('parse event {0}'.format(event[Attr.id])) self.events.append(event)
def typicalSampler(filename, percent=.01, sample_col=0): # Implements the standard non-streaming sampling method mean, standard_deviation = 0.0, 0.0 # Step 1: read file to pull out unique user_ids from file unique_ids = set() for row in filename: unique_ids.add(row.split(',')[sample_col]) # Step 2: subset to random 1% of user_ids user_sample = random.sample(unique_ids, int(len(unique_ids) * percent)) # Step 3: read file again to pull out records from the 1% user_id and compute mean withdrawn n = 0 sum1, sqsum1 = 0.0, 0.0 sum2, sqsum2 = 0.0, 0.0 mod = 10 filename.seek(0) for row in filename: record = row.split(',') uid = record[sample_col] if uid in user_sample: n = n + 1 transaction = float(record[3]) sum1 = sum1 + transaction sqsum1 = sqsum1 + pow(transaction, 2) # to prevent overflow,calculating means of buckets, # increasing bucket size by multiple of 10 # after we have 10 elements of size of prev bucket if (n % mod == 0): sum2 = sum2 + sum1 / mod sqsum2 = sqsum2 + sqsum1 / mod sum1 = 0 sqsum1 = 0 if (n % (mod * 10) == 0): sum2 = sum2 / 10 sqsum2 = sqsum2 / 10 mod = mod * 10 sum1 = 0 sqsum1 = 0 mean, standard_deviation = calculate(n, mod, sum1, sum2, sqsum1, sqsum2) ##<<COMPLETE>> return mean, standard_deviation
def register(request): """ Display form for registration **Context** registration form **Template:** :template:`register.html` """ if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): try: salt = hashlib.sha1(str(random()).encode("utf-8")).hexdigest()[:5] activation_key = hashlib.sha1((salt + form.cleaned_data["email"]).encode("utf-8")).hexdigest() key_expires = datetime.datetime.now() + datetime.timedelta(2) email_subject = 'Embigo - Potwierdzenie Rejestracji ' email_body = "Witaj %s, dziękujemy za rejestrację w Embigo. By zakończyć proces rejestracji musisz, w przeciągu" \ " 48 godzin kliknąć w poniższy link:\nhttp://%s/confirm/%s" % ( form.cleaned_data["username"], request.META["HTTP_HOST"], activation_key) send_mail(email_subject, email_body, '*****@*****.**', [form.cleaned_data["email"]], fail_silently=False) new_user = form.save() new_user.is_active = False new_user.save() new_space_user = SpaceUser(uid=uuid1(), rights=embigo_default_rights(), space=embigo_main_space(), user=new_user) new_space_user.save() colors = ["#FEE6AA","#FDD777","#FCC845","#FBBA13","#FEAAAA","#FD7777","#FC4545","#FB1313","#EBAAFE","#E077FD","#D545FC","#C913FB","#B9AAFE","#9077FD","#6745FC","#3E13FB","#AAE0FE","#77CEFD","#45BCFC","#13AAFB","#AAFECA","#77FDAB","#45FC8B","#13FB6C"] color = random.sample(colors, 1)[0]; embigo_user = EmbigoUser(user=new_user, activation_key=activation_key, key_expires=key_expires, hash_type='ACTIVATE_HASH') embigo_user.save() return HttpResponseRedirect(request.GET.get("next", "/"), RequestContext(request)) except SMTPRecipientsRefused: form.add_error("email","Błąd podczas wysyłania maila. Upewnij się czy wprowadzony adres e-mail jest poprawny.") except Exception as e: new_user.delete() raise e else: form = RegistrationForm() context = {'form': form} return render(request, 'register.html', context)
def randomSampleImages(origImagesLoc, dirName, destImagesLoc, total): list = [] imagesDirList = custom_listdir(origImagesLoc) for dataFilename in custom_listdir(dirName): dataFile = open(dirName+dataFilename, 'rb') #opens the file for reading reader = csv.reader(dataFile) for index,words in enumerate(reader): #skip table header line if index and len(words) > 1: #parse line and store needed data imageName = str(words[0]).strip() + ".jpg" #if image not found, skip it if imagesDirList.count(imageName) and not list.count(imageName): list.append(imageName) dataFile.close() list = random.sample(list, total) for image in list: shutil.move(origImagesLoc+image, destImagesLoc+image)
def _recommend(self): import random friend_rows = FacebookUser.objects.filter(user_id=self.targetUser.id) items = [] for fr in friend_rows: items.extend(FacebookFriendLike.objects.filter(friend_fid=fr.facebook_id)) selected = random.sample(xrange(len(items)), min(len(items),self.config.MAX_ITEMS*self.config.BUFFER_MULTIPLIER*10)) self.arr = [] for i in selected: item = {} item['type'] = items[i].category item['page_id'] = items[i].facebook_id item['name'] = items[i].name item['pic'] = items[i].pic item['page_url'] = items[i].page_url item['created_time'] = items[i].created_time self.arr.append(item) #pprint(self.arr) return self.arr
p = ["Python","is", "powerful","simple", "and so on..."] shuffle(p) print p print '-' * 50 # ------------------------------------------------------------------------------- # random.sample(sequence, k) # 从指定序列中随机获取指定长度的片断。 # sample函数不会修改原有序列。 from random import sample li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #从list中随机获取5个元素,作为一个片断返回 slc = sample(li, 5) print slc print li #原有序列并没有改变。 print '-' * 50 # ------------------------------------------------------------------------------- "".join(random.sample(string.letters, 10)) # 生成指定长度的随机字符串很容易 # 'kMmSgPVWIi' "".join(random.sample(string.letters, 10)) # 'feCTyRZrHv'
def _generate_indices(bound, count, token): random.seed(token) return random.sample(range(bound), count)
# 1. The computer selects four random digits (0 to 9). # 2. The player attempts to guess these digits, in order. # 3. The computer gives the player information as to the correctness of his guess. # a. For every digit guessed in order, a "Bull" is scored. # b. For every digit guessed out of order, a "Cow" is scored. # 4. The player continues making guesses until four Bulls are scored indicating that he has guessed all four digits correctly.# numbers = [] cows import random digits = '123456789' size = 4 chosen = ''.join(random.sample(digits,size)) #print chosen # Debug print '''I have chosen a number from %s unique digits from 1 to 9 arranged in a random order. You need to input a %i digit, unique digit number as a guess at what I have chosen''' % (size, size) guesses = 0 while True: guesses += 1 while True: # get a good guess guess = raw_input('\nNext guess [%i]: ' % guesses).strip() if len(guess) == size and \ all(char in digits for char in guess) \ and len(set(guess)) == size: break print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size if guess == chosen:
bucket_size=4 # read the input and make list of lists containing baskets AllItems=[] for line in input: line = line.strip().replace(',', "") smallList=[] for i in range(0,len(line)): smallList.append(line[i]) smallList.sort() AllItems.append(smallList) # print AllItems radomset=random.sample(AllItems,(58*len(AllItems))/100) randomSupport=(.8*.58*support) # create list if unique Items uniqueItem = [] for sublist in AllItems: for each in sublist: if each not in uniqueItem: uniqueItem.append(each) uniqueItem.sort()
def scatter_plot(self, other_feature, obs_nums=None): if obs_nums is None: obs_nums = random.sample(range(self.num_rows()), 50) v = self.view()