def on_start(self, event):
ws = self.get_world().state
# pick a random object
self.state.target_obj, = random.sample(objects, 1)
# give one of it to the learner
ws.learner_inventory[self.state.target_obj] += 1
# save how many objects of this we have
self.state.initial_count = ws.teacher_inventory[self.state.target_obj]
# inform the world that we can expect to receive such an object
ws.teacher_accepts.add(self.state.target_obj)
self.set_message("I gave you {indef_object}. Give it back to me "
"by saying \"I give you {indef_object}\"."
.format(indef_object=msg.indef_article(
self.state.target_obj)))
# if I have one more of the target object, the learner solved the task.
python类sample()的实例源码
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return value[0][:-1], users[0]
else:
return value[0][:-1], users[0][:-1]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return value[0][:-1], users[0]
else:
return value[0][:-1], users[0][:-1]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return value[0][:-1], users[0]
else:
return value[0][:-1], users[0][:-1]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return users[0], value[0][:-1]
else:
return users[0][:-1], value[0][:-1]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "[-] Reloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return value[0], users[0]
else:
return value[0], users[0]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return value[0][:-1], users[0]
else:
return value[0][:-1], users[0][:-1]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return users[0], value[0][:-1]
else:
return users[0][:-1], value[0][:-1]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return value[0][:-1], users[0]
else:
return value[0][:-1], users[0][:-1]
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return users[0], value[0][:-1]
else:
return users[0][:-1], value[0][:-1]
webauthbrute_random_usersupport.py 文件源码
项目:darkc0de-old-stuff
作者: tuwid
项目源码
文件源码
阅读 34
收藏 0
点赞 0
评论 0
def getword():
lock = threading.Lock()
lock.acquire()
if len(words) != 0:
value = random.sample(words, 1)
words.remove(value[0])
else:
print "\nReloading Wordlist - Changing User\n"
reloader()
value = random.sample(words, 1)
users.remove(users[0])
lock.release()
if len(users) ==1:
return users[0], value[0][:-1]
else:
return users[0][:-1], value[0][:-1]
def _random_curve(self, nr_curves):
curves = []
for i in range(nr_curves-1):
curve = [(0,0)]
# exlcude the 0 and 255
_x = numpy.sort(random.sample(range(1, 255), 32))
_y = numpy.sort(random.sample(range(1, 255), 32))
#_x = numpy.sort(numpy.random.randint(1, 255, 2))
#_y = numpy.sort(numpy.random.randint(1, 255, 2))
# _x[0] and _x[1] can't be the same
curve.append((_x[0], _y[0]))
curve.append((_x[1], _y[1]))
curve.append((255,255))
curves.append(curve)
curves.append([(255,255)])
return curves
def _random_curve(self, nr_curves):
curves = []
for i in range(nr_curves-1):
curve = [(0,0)]
# exlcude the 0 and 255
_x = numpy.sort(random.sample(range(1, 255), 32))
_y = numpy.sort(random.sample(range(1, 255), 32))
#_x = numpy.sort(numpy.random.randint(1, 255, 2))
#_y = numpy.sort(numpy.random.randint(1, 255, 2))
# _x[0] and _x[1] can't be the same
curve.append((_x[0], _y[0]))
curve.append((_x[1], _y[1]))
curve.append((255,255))
curves.append(curve)
curves.append([(255,255)])
return curves
def sample(self, nb_samples):
sampled_character_folders = random.sample(self.character_folders, nb_samples)
random.shuffle(sampled_character_folders)
example_inputs = np.zeros((self.batch_size, nb_samples * self.nb_samples_per_class, np.prod(self.img_size)), dtype=np.float32)
example_outputs = np.zeros((self.batch_size, nb_samples * self.nb_samples_per_class), dtype=np.float32) #notice hardcoded np.float32 here and above, change it to something else in tf
for i in range(self.batch_size):
labels_and_images = get_shuffled_images(sampled_character_folders, range(nb_samples), nb_samples=self.nb_samples_per_class)
sequence_length = len(labels_and_images)
labels, image_files = zip(*labels_and_images)
angles = np.random.uniform(-self.max_rotation, self.max_rotation, size=sequence_length)
shifts = np.random.uniform(-self.max_shift, self.max_shift, size=sequence_length)
example_inputs[i] = np.asarray([load_transform(filename, angle=angle, s=shift, size=self.img_size).flatten() \
for (filename, angle, shift) in zip(image_files, angles, shifts)], dtype=np.float32)
example_outputs[i] = np.asarray(labels, dtype=np.int32)
return example_inputs, example_outputs
def make_pair_iter(self, rel):
rel_set = {}
pair_list = []
for label, d1, d2 in rel:
if d1 not in rel_set:
rel_set[d1] = {}
if label not in rel_set[d1]:
rel_set[d1][label] = []
rel_set[d1][label].append(d2)
while True:
rel_set_sample = random.sample(rel_set.keys(), self.config['query_per_iter'])
for d1 in rel_set_sample:
label_list = sorted(rel_set[d1].keys(), reverse = True)
for hidx, high_label in enumerate(label_list[:-1]):
for low_label in label_list[hidx+1:]:
for high_d2 in rel_set[d1][high_label]:
for low_d2 in rel_set[d1][low_label]:
pair_list.append( (d1, high_d2, low_d2) )
yield pair_list
def test_get_content_ids__fills_in_non_cached_content_up_to_pagination_amount(self):
with patch.object(self.stream, "get_cached_content_ids") as mock_cached:
cached_ids = random.sample(range(10000, 100000), self.stream.paginate_by - 1)
throughs = dict(zip(cached_ids, cached_ids))
mock_cached.return_value = cached_ids, throughs
# Fills up with one of the two that are available
all_ids = set(cached_ids + [self.site_content.id])
self.assertEqual(set(self.stream.get_content_ids()[0]), all_ids)
def add_random_feature_points(self, region_x, region_y, num_points):
"""Add a set number of randomly placed feature points in a region.
Args:
region_x (int): X coordinate of center point of desired region.
region_y (int): Y coordinate of center point of desired region.
num_points (int): Number of feature points to create.
"""
pnts = self.get_region(region_x, region_y)
chosen_indices = random.sample(range(0, len(pnts)), num_points)
chosen_feat_points = [pnts[i] for i in chosen_indices]
for x, y in chosen_feat_points:
self.add_feature_point(region_x, region_y, x, y)
def create_state(board_file, brains):
lines = [line.rstrip('\n') for line in board_file]
size = max(len(lines), max(len(line) for line in lines))
state = RoboRallyGameState(size)
for row in range(len(lines)):
for col in range(len(lines[row])):
char = lines[row][col]
cell = state.board.get_item((row, col))
if char == '#':
cell.content = make_wall()
elif char == '<':
cell.content = make_mounted(WEST)
elif char == '>':
cell.content = make_mounted(EAST)
elif char == 'v':
cell.content = make_mounted(SOUTH)
elif char == '^':
cell.content = make_mounted(NORTH)
elif char == '&':
cell.floor = None
elif char == '{':
cell.floor = LEFT_SPINNER
elif char == '}':
cell.floor = RIGHT_SPINNER
elif char.isdecimal():
cell.floor = FLAG + char
state.flags[int(char) - 1] = (row, col)
state.brains = brains
empty_cells = [cell for cell, pos in state.board.traverse() if not cell.content and cell.floor == EMPTY]
for cell, brain in zip(random.sample(empty_cells, len(brains) * NUM_ROBOTS_PER_BRAIN), brains * NUM_ROBOTS_PER_BRAIN):
cell.content = make_robot(brain, random.choice([NORTH, WEST, EAST, SOUTH]))
state.calculate_statistics()
return state
def bpr_loss(x, dynamic_user, item_embedding, config):
'''
bayesian personalized ranking loss for implicit feedback
parameters:
- x: batch of users' baskets
- dynamic_user: batch of users' dynamic representations
- item_embedding: item_embedding matrix
- config: model configuration
'''
nll = 0
ub_seqs = []
for u,du in zip(x, dynamic_user):
du_p_product = torch.mm(du, item_embedding.t()) # shape: max_len, num_item
nll_u = [] # nll for user
for t, basket_t in enumerate(u):
if basket_t[0] != 0 and t != 0:
pos_idx = torch.cuda.LongTensor(basket_t) if config.cuda else torch.LongTensor(basket_t)
# Sample negative products
neg = [random.choice(range(1, config.num_product)) for _ in range(len(basket_t))] # replacement
# neg = random.sample(range(1, config.num_product), len(basket_t)) # without replacement
neg_idx = torch.cuda.LongTensor(neg) if config.cuda else torch.LongTensor(neg)
# Score p(u, t, v > v')
score = du_p_product[t - 1][pos_idx] - du_p_product[t - 1][neg_idx]
#Average Negative log likelihood for basket_t
nll_u.append(- torch.mean(torch.nn.LogSigmoid()(score)))
nll += torch.mean(torch.cat(nll_u))
return nll
def _populate_mines(self):
"""
Method _populate_mines populates the cells of this minefield with
mines. Applies a random selection of simple constraints to where mines
may be placed, though about half of the mines are purely randomly
placed.
"""
if self.mine_count is None:
self.mine_count = int(0.15 * (self.height * self.width))
count = self.mine_count
selectionfuncs = [
lambda y: not (y % 2),
lambda y: bool(y % 2),
lambda y: not (y % 3),
]
yconstraint, xconstraint = random.sample(selectionfuncs * 2, 2)
for x in range(count):
while True:
rx, ry = random.randint(0, self.width - 1), random.randint(
0, self.height - 1)
if random.randint(0, 1):
if yconstraint(ry):
continue
if xconstraint(rx):
continue
c = self.board[rx][ry]
if c.contents == Contents.empty:
c.contents = Contents.mine
break