def read_config(scan_config):
config_path = os.path.join(
os.path.dirname(os.path.realpath(sys.argv[0])), "config.json")
if os.path.isfile(config_path):
config['CONFIG_PATH'] = config_path
try:
with open(config_path, "r") as f:
c = json.loads(f.read())
except:
c = {}
config['LOCALE'] = c.get('LOCALE', 'en')
config['GOOGLEMAPS_KEY'] = c.get('GOOGLEMAPS_KEY', None)
config['CONFIG_PASSWORD'] = c.get('CONFIG_PASSWORD', None)
config['ACCOUNTS'] = c.get('ACCOUNTS', [])
scan_config.update_scan_locations(c.get('SCAN_LOCATIONS', {}))
if config.get('CONFIG_PASSWORD', None):
config['AUTH_KEY'] = ''.join(random.choice(string.lowercase) for _ in range(32))
python类choice()的实例源码
def random_user(self, settings, author, server):
filter_users = [server.get_member(x) for x in settings["Players"]
if hasattr(server.get_member(x), "name")]
legit_users = [x for x in filter_users if x.id != author.id and x is not x.bot]
users = [x for x in legit_users if settings["Players"][x.id]["Cookies"] > 0]
if not users:
user = "Fail"
else:
user = random.choice(users)
if user == user.bot:
users.remove(user.bot)
settings["Players"].pop(user.bot)
dataIO.save_json(self.file_path, self.system)
user = random.choice(users)
self.account_check(settings, user)
return user
def _clear_shop(self, ctx):
"""Wipes the entire shop list"""
user = ctx.message.author
settings = self.check_server_settings(user.server)
shop_name = settings["Config"]["Shop Name"]
await self.bot.say("Do you want to wipe the entire shop list? "
"You cannot undue this action.")
choice = await self.bot.wait_for_message(timeout=15, author=user)
if choice is None:
msg = "Cancelling shop wipe."
elif choice.content.title() == "No":
msg = "Cancelling shop wipe."
elif choice.content.title() == "Yes":
settings["Shop List"] = {}
dataIO.save_json(self.file_path, self.system)
msg = "The shop list has been cleared from the {} Shop".format(shop_name)
else:
msg = "Improper response. Cancelling shop wipe."
await self.bot.say(msg)
def _sort_setshop(self, ctx, choice: str):
"""Changes the sorting method for shop listings. Alphabetical, Lowest, Highest"""
server = ctx.message.server
settings = self.check_server_settings(server)
choice = choice.title()
if choice == "Alphabetical":
settings["Config"]["Sort Method"] = "Alphabet"
dataIO.save_json(self.file_path, self.system)
msg = "Changing sorting method to Alphabetical."
elif choice == "Lowest":
settings["Config"]["Sort Method"] = "Lowest"
dataIO.save_json(self.file_path, self.system)
msg = "Setting sorting method to Lowest."
elif choice == "Highest":
settings["Config"]["Sort Method"] = "Highest"
dataIO.save_json(self.file_path, self.system)
msg = "Setting sorting method to Highest."
else:
msg = "Please choose Alphabet, Lowest, or Highest."
await self.bot.say(msg)
def end(self, ctx):
"""Ends a raffle"""
if self.raffle["Config"]["Active"]:
if len(self.raffle["Players"]) > 0:
self.raffle["Config"]["Active"] = False
tickets = self.raffle["Config"]["Tickets"]
winning_ticket = random.choice(tickets)
winner = []
for subdict in self.raffle["Players"]:
if winning_ticket in self.raffle["Players"][subdict]["Tickets"]:
winner.append(subdict)
mention = "<@" + winner[0] + ">"
await self.bot.say("The winner of the raffle is...")
await asyncio.sleep(3)
await self.bot.say(mention + "! Congratulations, you have won!")
self.raffle["Config"]["Tickets"] = []
self.raffle["Players"] = {}
else:
self.raffle["Config"]["Active"] = False
await self.bot.say("Oh no! No one joined the raffle. Cancelling the raffle.")
dataIO.save_json(self.file_path, self.raffle)
else:
await self.bot.say("You need to start a raffle for me to end one!")
def game_outcomes(self, settings, players, target):
success_rate = self.calculate_success(settings, target)
good_out, bad_out = self.get_theme(settings)
results = []
for player in players:
chance = random.randint(1, 100)
if chance <= success_rate:
good_thing = random.choice(good_out)
good_out.remove(good_thing)
settings["Crew"][player.id] = {"Name": player.name, "Bonus": good_thing[1]}
settings["Players"][player.id]["Spree"] += 1
results.append(good_thing[0].format(player.name))
else:
bad_thing = random.choice(bad_out)
dropout_msg = bad_thing[0] + "```\n{0} dropped out of the game.```"
self.failure_handler(settings, player, bad_thing[1])
settings["Crew"].pop(player.id)
bad_out.remove(bad_thing)
results.append(dropout_msg.format(player.name))
self.save_system()
return results
def game_setup(self, author, data, mode):
racers = []
if mode == 'zoo':
if len(data['Players']) == 1:
bot_set = random.choice(animals)
racers = [Racer(bot_set[0], bot_set[1], self.bot.user)]
for user in data['Players']:
mobj = author.server.get_member(user)
animal_set = random.choice(animals)
racers.append(Racer(animal_set[0], animal_set[1], mobj))
else:
animal_set = (":turtle:", "slow")
if len(data['Players']) == 1:
racers = [Racer(animal_set[0], animal_set[1], self.bot.user)]
for user in data['Players']:
mobj = author.server.get_member(user)
racers.append(Racer(animal_set[0], animal_set[1], mobj))
return racers
def is_block_to_tx_valid(tx_id: str, bdb_connection: BigchainDB) -> bool:
"""
Checks if block with transaction is valid
:param tx_id: Id of transaction which should be included in the
:type tx_id: str
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:return: True if transactions is in block and block is valid
:rtype: bool
"""
node = random.choice(bdb_connection.nodes)
res = requests.get(node + bdb_connection.blocks.path + '?transaction_id=' + tx_id)
block_id = res.json()
if len(block_id) < 1 or len(block_id) > 1:
raise exceptions.TransactionIdNotFound(tx_id)
res = requests.get(node + bdb_connection.api_prefix + '/statuses?block_id=' + block_id[0])
if res.status_code != 200:
raise exceptions.BlockIdNotFound(block_id[0])
status = res.json()['status']
if status == 'valid':
return True
return False
def median(values):
"""Return the middle value, when the values are sorted.
If there are an odd number of elements, try to average the middle two.
If they can't be averaged (e.g. they are strings), choose one at random.
>>> median([10, 100, 11])
11
>>> median([1, 2, 3, 4])
2.5
"""
n = len(values)
values = sorted(values)
if n % 2 == 1:
return values[n/2]
else:
middle2 = values[(n/2)-1:(n/2)+1]
try:
return mean(middle2)
except TypeError:
return random.choice(middle2)
def main():
answer=random.choice(list(queens(10)))
prettyPrint(answer)
def move(self,field,time=1):
if field.getDrunk()!=self:
raise ValueError('Drunk.move called with drunk not in field')
for i in range(time):
pt=CompassPt(random.choice(CompassPt.possibles))
field.move(pt,1) # Drunk?????
def pwgen(length=None):
"""Generate a random pasword."""
if length is None:
# A random length is ok to use a weak PRNG
length = random.choice(range(35, 45))
alphanumeric_chars = [
l for l in (string.ascii_letters + string.digits)
if l not in 'l0QD1vAEIOUaeiou']
# Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
# actual password
random_generator = random.SystemRandom()
random_chars = [
random_generator.choice(alphanumeric_chars) for _ in range(length)]
return(''.join(random_chars))
def generate_name():
alphabet = 'abcdefghijklmnopqrstuvwxyz'
wordlist = []
with open ("words", 'r') as fo:
for word in fo:
if len(word) < 5:
continue
else:
wordlist.append(word.strip())
namelength = random.randrange(4)
pref = random.choice(wordlist)[0:3]
pref = pref[0].upper() + pref[1:3]
if random.random() > 0.5:
suff = random.choice(wordlist)[-3:]
else:
suff = random.choice(wordlist)[:3]
for i in range(namelength):
pref = pref + random.choice(alphabet)
name = pref + suff
return name
def _make_river(river_source,centre):
seen = set()
start = random.choice(river_source.vertices)
seen.add(start)
start.river = True
river_list = []
river_list.append(start)
q = queue.Queue()
q.put(start)
exceptions = []
while not q.empty():
curr = q.get()
next_item = None
for v in curr.v_neighbours:
if v in seen:
continue
seen.add(v)
if v and ((v.elevation <= curr.elevation or ((curr.elevation<2) and v.elevation>4)) and __centre_dist_inc(curr,v,centre)) and (v.elevation >= 0):
next_item = v
if next_item:
if len([i.terrain for i in next_item.neighbours if i.terrain <0]) > 1:
break
else:
q.put(next_item)
if next_item.river:
exceptions.append(next_item)
next_item.river = True
river_list.append(next_item)
if len(river_list) < 11:
for i in river_list:
if i not in exceptions:
i.river = False
return
return river_list
def sea_or_land(self,centre,max_dist,island):
x, y = self.centre.get_cords()
point = (x - centre[0])/max_dist,(y - centre[1])/max_dist
land = island.inside(point)
if not land:
self.terrain = -2
self.color = random.choice(color_palettes.ocean)
else:
self.terrain = 2
self.color = (50,150,0)
def make_mountain(self,polyList):
self.terrain = min(self.terrain+5, 11)
self.color = random.choice(color_palettes.terrain[11-self.terrain])
n = self.get_neighbours(polyList)
for i in n:
i.terrain = min(i.terrain+4,11)
i.color = random.choice(color_palettes.terrain[11-i.terrain])
def _init_gradients(self, vec_magnitude):
"""Initialize all gradient vectors to be in random directions with the same magnitude.
Args:
vec_magnitude (float): Magnitude of all gradient vectors.
"""
self._grad_vecs = [[(0, 0) for _ in range(self._width_in_squares+1)] for _ in range(self._length_in_squares+1)]
"""list[list[tuple(float, float)]]: Grid of gradient vectors."""
for x in range(self._width_in_squares+1):
for y in range(self._length_in_squares+1):
x_val = (random.random() - 0.5) * 2 * vec_magnitude
y_val = math.sqrt(vec_magnitude**2 - x_val**2) * random.choice([1, -1])
self._grad_vecs[y][x] = (x_val, y_val)
def random_question():
question = random.choice(list(bools.keys()))
answer = bools[question]
return question, answer
def random_string(length):
pool = string.ascii_letters + string.digits
return ''.join(random.choice(pool) for i in range(length))