示例#1
0
def random(request):
    random_title=random2.choice(util.list_entries())
    entry_detail=markdown2.markdown(util.get_entry(random_title))
    context={
        'entry_title':random_title,
        'entry_detail':entry_detail
        }
    return render(request,'encyclopedia/detail.html',context)
示例#2
0
def play():
    user = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors\n")
    computer = random2.choice(['r', 'p', 's'])

    if user == computer:

        return 'YOU WON!'

    return 'YOU LOST!'
示例#3
0
def synonymIfExists(sentence):
    for (word, t) in tag(sentence):
        if paraphraseable(t):
            syns = synonyms(word, t)
            if syns:
                if len(syns) > 1:
                    List1 = list(syns)
                    yield random.choice(List1)
                    continue
        yield word
示例#4
0
文件: pp.py 项目: VairusFerrar/fgh
def kot():
    sho = [
        'Вашего кота зовут Манник, вы вроде мне про него рассказывали ./Он вообще такой дебил, что написать про это можно целую книгу . Живёт он с вами, просит вечно жрачку, на что конечно-же уходит много денег .',
        'Могу сказать про него в переносном смысле - мужик который нихрена не делает и сидиит днями за телевизором . Чем-то похож на вас.',
        'Серая мышь, которая бесит своим поведением',
        'Довольно милая, но агрессивная зараза.'
    ]
    ka = random2.choice(sho)
    speak(ka)
    return listen
示例#5
0
文件: pp.py 项目: VairusFerrar/fgh
def mem():
    sho = [
        'Мне коробочку сока, пожалуйста - Какой вам сок? - Любой… - Я годится? - Ну давайте ягодицу. Каких только названий не придумают эти рекламщики',
        'Любой парень будет у ваших ног. Главное с первого удара попасть ему в челюсть. Ха Ха Ха',
        'Есть люди, кто достает мобильник из кармана, чтоб посмотреть время, потом убирает его и вспоминает, что забыл время посмотреть',
        'Надпись на калитке: "Стучите громче, глухая собака!"',
        'Не буду навязываться, захочет напишет" подумали оба',
        'В последнее время я стал намного ближе к природе. Совсем озверел'
    ]
    ka = random2.choice(sho)
    speak(ka)
    return listen
示例#6
0
文件: pp.py 项目: VairusFerrar/fgh
def roulette():
    sho = [
        'У нас мертвяк! Может быть на том свете тебе повезёт больше. Покойся с миром.',
        'Вот это смельчак! Ты выжил после нажатия на курок! Больше так не рискуй. Подумай о маме и папе!',
        'Вы выжили! Но постарайтесь не рисковать!',
        'На этот раз тебе повезло, но будет ли так в следующий раз?',
        'Удача на твоей стороне! А давай еще?',
        'Задумайся, стоит ли попробовать еще, если ДА то зачем тебе это?',
    ]
    ka = random2.choice(sho)
    speak("Вы зарядили 1 патрон и раскрутили барабан: " + ka)
    speak("Я вас слушаю")
    return listen
示例#7
0
    def take_input(self):
        h = input('What is your name?')
        g = int(
            input(
                'Enter the number of character you want to be in your baby name.'
            ))
        f = input("Enter your spouse name.")
        #print("Among one thousand names, Possible baby names are")
        first_let = h[0]
        let_anywhere = f[0]

        #print(h,g)
        # Characters to generate the random word
        rest_char = [
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
        ]
        i = 0
        while i < 10001:
            i = i + 1

            #List to carry the character
            my_char = []
            my_char_len = len(my_char)
            # List to carry the word after joining them
            word = []
            while my_char_len < g:
                my_char_len = my_char_len + 1
                pull = random2.choice(rest_char)
                my_char.append(pull)
            #print(my_char)
            # use of join built-in function to join the character in the my_char list and make a single word
            name = ("".join(my_char))
            word.append(name)
            #print('No name with letter',first_let)
            # print(word)
            # To create the file if not created and to apend the data in the file
            f1 = open("names.txt", 'a+')
            if name[0] == first_let:
                f1.write("\n" + name)
                f1.close()
            else:
                pass

            # to read the data from the file
            f2 = open("names.txt", 'r')
            content = f2.read()
        print(len(content))
        #return content
        print('These are the possible baby names.', content.upper())
        os.remove("names.txt")
示例#8
0
def get_text_messages(message):
    print(message.text)
    if message.text == "Привет":
        bot.send_message(message.chat.id, "Привет, друг!", reply_markup=markup)
    if (message.text == "Расскажи анекдот" or message.text == "/joke"):
        with open('jokes.txt', 'r') as nnn:
            joke = [line.strip() for line in nnn]
            nnn.close()
        ran = random2.choice(joke)
        bot.send_message(message.chat.id, ran, reply_markup=markup)
    if (message.text.startswith('/roll')
            or message.text.startswith(b"\xF0\x9F\x8E\xB2".decode("utf-8"))):
        message.text.strip(" ")
        print(message.text)
        bot.send_message(message.chat.id,
                         random2.randint(1, 100),
                         reply_markup=markup)
    if message.text == b"\xF0\x9F\x92\xB0".decode("utf-8"):
        bot.send_message(message.chat.id,
                         'money money money',
                         reply_markup=markup)
    if message.text.lower() == "спасибо":
        bot.send_message(message.chat.id,
                         'Всегда пожалуйста!',
                         reply_markup=markup)
    if message.text == b"\xF0\x9F\x98\x82".decode("utf-8"):
        bot.send_message(message.chat.id,
                         'Рад, что тебе весело!',
                         reply_markup=markup)
    if message.text.lower() == 'скажи погоду':
        owm = pyowm.OWM('6d00d1d4e704068d70191bad2673e0cc', language="ru")
        place = 'Островец'
        weather_advice = ""
        observation = owm.weather_at_place(place)
        w = observation.get_weather()
        veter = (str(round(w.get_wind()["speed"])))
        vlazhnost = (str(round(w.get_humidity())))
        temperatura = (str(round(w.get_temperature('celsius')["temp"])))
        if float(temperatura) <= 15:
            weather_advice += "советую одеться потеплее "
        if float(veter) >= 10:
            weather_advice += "сегодня ветренно "
        bot.send_message(message.chat.id,
                         'В городе' + ' ' + place + ' ' + 'сейчас' + ' ' +
                         w.get_detailed_status() + ', ветер' + ' ' + veter +
                         ' ' + 'метров в секунду' + ', влажность' + ' ' +
                         vlazhnost + ' ' + 'процентов' + ', температура' +
                         ' ' + temperatura + ' ' + 'градусов по Цельсию,' +
                         weather_advice,
                         reply_markup=markup_2)
示例#9
0
	def get_boxes_for_images(self, anno_dir):
		width = self.image_width
		height = self.image_height
		category_list = self.filters
		boxes_dataset = []
		# for i, name in enumerate(category_list):
		# 	self.add_class("cloud", i+1, name)
		df = pd.DataFrame(columns=["image_id","EncodedPixels","CategoryId","Width","Height"])
		train_dataset = CloudDataset(df[:training_set_size])
		for i, row in df.iterrows():
			self.add_image("cloud", 
						   image_id=row.name, 
						   path='../understanding_cloud_organization/train_images/'+str(row.image_id), 
						   labels=row['CategoryId'],
						   annotations=row['EncodedPixels'], 
						   height=row['Height'], width=row['Width'])
		for i in range(50):
			image_id = random.choice(train_dataset.image_ids)
			# print(train_dataset.image_reference(image_id))
			
			# image = resize_image(self.image_info[image_id]['path'])
			info = self.image_info[image_id]
				
			mask = np.zeros((IMAGE_SIZE, IMAGE_SIZE, len(info['annotations'])), dtype=np.uint8)
			# labels = []
			
			for m, (annotation, label) in enumerate(zip(info['annotations'], info['labels'])):
				sub_mask = np.full(info['height']*info['width'], 0, dtype=np.uint8)
				annotation = [int(x) for x in annotation.split(' ')]
				
				for i, start_pixel in enumerate(annotation[::2]):
					sub_mask[start_pixel: start_pixel+annotation[2*i+1]] = 1

				sub_mask = sub_mask.reshape((info['height'], info['width']), order='F')
				sub_mask = cv2.resize(sub_mask, (IMAGE_SIZE, IMAGE_SIZE), interpolation=cv2.INTER_NEAREST)
				
				mask[:, :, m] = sub_mask
				# labels.append(int(label)+1)
				print(mask)
				boxes_frame.append(mask)

			boxes_dataset.append(boxes_frame)
				
			# return mask, np.array(labels)

			# convert mask to bounding box

		# return mask, np.array(labels)
		return boxes_dataset
示例#10
0
async def граната(ctx):
    emb = discord.Embed(title=random2.choice(granata),
                        colour=discord.Color.green())

    emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
    emb.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
    emb.set_image(
        url=
        "https://i.siteapi.org/l9q5FHblgIocYbq5v2U1RYYY9NM=/fit-in/330x/top/filters:format(webp)/0cef3703d382b3d.s.siteapi.org/img/11a73eb3a7cd0bb6c616222d9a01548fd71aa7ad.jpg"
    )
    emb.set_thumbnail(
        url="http://images.aif.ru/007/382/5810c4d77d79c3d828377e1fd3e5f9ed.jpg"
    )

    await ctx.send(embed=emb)
示例#11
0
def sendEmail(request, email, npm, nama):
    letters_and_digits = string.ascii_letters + string.digits
    r_result = ''.join((random.choice(letters_and_digits) for i in range(10)))
    message = 'Hi, ' + nama
    message1 = '\r\nKami dari KPU mengundang anda untuk melakukan pemilu silahkan klik link berikut : '
    link = 'https://docs.djangoproject.com '
    user = '******' + npm
    message2 = '\r\n     Password : '******'Pemilihan umum ketua HMJ dan PRESMA 2021',
              password,
              '*****@*****.**', [email],
              fail_silently=False)
    sendpass = {'showpass': r_result}
    return render(request, 'form/result.php', sendpass)
示例#12
0
async def снайпер(ctx):
    emb = discord.Embed(title=random2.choice(snaiper),
                        colour=discord.Color.green())

    emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
    emb.set_footer(text=ctx.author.name, icon_url=ctx.author.avatar_url)
    emb.set_image(
        url=
        "https://go4.imgsmail.ru/imgpreview?key=50592ce8b177f788&mb=imgdb_preview_766"
    )
    emb.set_thumbnail(
        url=
        "http://files.storeland.ru/web/upload/sitefiles/6/513/512843/flag-snajper-chernyje-berety.jpg"
    )

    await ctx.send(embed=emb)
示例#13
0
def start_game(quotes):
    quote = choice(quotes)
    remaining_guesses = 4
    print("Here's a quote: ")
    print(quote["text"])
    print(quote["author"])
    guess = ""

    while guess.lower() != quote["author"].lower() and remaining_guesses > 0:
        guess = input(
            f"Who said this quote? Guesses remaining: {remaining_guesses}\n")
        if guess.lower() == quote["author"].lower():
            print("You got it right!")
            break
        remaining_guesses -= 1
        if remaining_guesses == 3:
            res = requests.get(f"{base_url}{quote['bio-link']}")
            soup = BeautifulSoup(res.text, "html.parser")
            birth_date = soup.find(class_="author-born-date").get_text()
            birth_place = soup.find(class_="author-born-location").get_text()
            print(
                f"Heres's a hint: The author was born on {birth_date} {birth_place}"
            )
        elif remaining_guesses == 2:
            print(
                f"Here's a hint: The author's first name starts with: {quote['author'][0]}"
            )
        elif remaining_guesses == 1:
            last_initial = quote["author"].split(" ")[1][0]
            print(
                f"Here's a hint: The author's last name starts with: {last_initial}"
            )
        else:
            print(
                f"Sorry you ran out of guesses. The answer was {quote['author']}"
            )

    again = ""
    while again.lower() not in ('y', 'yes', 'n', 'no'):
        again = input("Would you like to play again (y/n)?")
    if again.lower() in ('yes', 'y'):
        return start_game(quotes)
    else:
        print("Ok, goodbye!")
示例#14
0
def find_match(source_word):
	"""Finds the best match for a source word"""

	min_dist = 100
	# min_dist = len(source_word) * 2
	optimal_words = []

	target_file = open('common_words.txt', 'r')

	# FIXME: Runtime of this is O(n^2). Can we improve this?
	for line in target_file:
		target_word = line.rstrip()

		if distance(source_word, target_word) == min_dist:
			# Add this word to the list
			optimal_words.append(target_word)

		if distance(source_word, target_word) < min_dist:
			min_dist = distance(source_word, target_word)
			# re-initialize the list, with only this word as a possible correction
			optimal_words = [target_word]

	return choice(optimal_words)
示例#15
0
def randomstrnum(a):
    letters_and_digits = string.ascii_letters + string.digits
    r_result = ''.join((random.choice(letters_and_digits)
                        for i in range(a)))
    print(r_result)
def random_string_generator(size=10,
                            chars=string.ascii_lowercase + string.digits):
    return ''.join(random2.choice(chars) for _ in range(size))
示例#17
0
import mouseinfo
import time
import platform
import random2
import pyautogui
liste = [
    'i', 'v', 'm', 'l', 'b', 'd', "d", "e", "f", "w", "u", "y", "s", "a", "z",
    "x", "2", "3", "j", "r", "p"
]
print(random2.choice(liste))
time.sleep(5)
a = 1
while a == 1:
    pyautogui.typewrite(random2.choice(liste))
    pyautogui.typewrite(random2.choice(liste))
    pyautogui.typewrite(random2.choice(liste))
    time.sleep(0.2)
    pyautogui.press('enter')
示例#18
0
                current_list.append(lab[i, j + 1])
                not_visited.append(lab[i, j + 1])
        if i + 1 <= 9:
            if lab[i + 1, j] not in list_of_visited:  #2
                current_list.append(lab[i + 1, j])
                not_visited.append(lab[i + 1, j])
        if i - 1 >= 0:
            if lab[i - 1, j] not in list_of_visited:  #3
                current_list.append(lab[i - 1, j])
                not_visited.append(lab[i - 1, j])
        if j - 1 >= 0:
            if lab[i, j - 1] not in list_of_visited:  #4
                current_list.append(lab[i, j - 1])
                not_visited.append(lab[i, j - 1])
        if len(current_list) != 0:
            next_step = random2.choice(
                current_list)  #случайный элемент непустой последовательности.
        itemindex = find_index(lab, n, m, next_step)
        print('item_index of next step', itemindex)
        print('next_step', next_step)
        print('list_of_visited', list_of_visited)
        print('current_list', current_list)
        current_point = next_step
        print('going to next step')
    else:
        if len(not_visited) != 0:
            next_step = random2.choice(not_visited)

print('lab', lab)
print('final print of visited', list_of_visited)

#from website
示例#19
0
def random_page(request):
    random_selected = random2.choice(util.list_entries())
    return HttpResponseRedirect(
        reverse("wiki", kwargs={"title": random_selected}))
示例#20
0
def rolling():
    diceim=ImageTk.PhotoImage(Image.open(random2.choice(dice)))
    imlabel.configure(image=diceim)
    imlabel.image = diceim
示例#21
0
文件: pp.py 项目: VairusFerrar/fgh
def coin():
    sho = ['Вы кинули монетку, выпал ОРЕЛ', 'Вы кинули монетку, выпала РЕШКА']
    ka = random2.choice(sho)
    speak(ka)
    return listen
示例#22
0
letters = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
    'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
    'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
]
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
symbols = ['!', '#', '$', '%', '&', '(', ')', '*', '+']

print("Welcome to the PyPassword Generator!")
nr_letters = int(input("How many letters would you like in your password?\n"))
nr_symbols = int(input(f"How many symbols would you like?\n"))
nr_numbers = int(input(f"How many numbers would you like?\n"))

password = ""

for i in range(1, nr_letters + 1):
    random = random2.choice(letters)
    password = password + random

for i in range(1, nr_symbols + 1):
    random_sym = random2.choice(symbols)
    password = password + random_sym

for i in range(1, nr_numbers + 1):
    random_num = random2.choice(numbers)
    password = password + random_num

print(f"Your password is {password}")
示例#23
0
文件: pp.py 项目: VairusFerrar/fgh
def goodbay():
    sho = ['До свидания', 'Всего хорошего', 'Жду нашей встречи']
    ka = random2.choice(sho)
    speak(ka)
    exit(0)
#set genome for random selection
fjun_head = fjun.readline()
for line in fjun:
    line = line.split("\n")[0]
    ln = line.split("\t")
    if ln[0] not in Genome:
        Genome[ln[0]] = []
    Genome[ln[0]] += [int(ln[1])]
    Chrom.append(ln[0])

#randomly select breaks for set times, calculate for enrichment ratio
for i in range(dataset):
    print(i)
    Randden[str(i)] = []
    for ji in range(rtime):
        rchrom = random.choice(Chrom)
        rpos = random.choice(Genome[rchrom])
        randomden = enrich_den_window(rchrom, rpos)
        Randden[str(i)] += [randomden]

    #run one-sample T-test
    sampmean = statistics.mean(sampdens)
    randmean = statistics.mean(Randden[str(i)])
    testres = stats.ttest_1samp(sampdens, randmean)
    pvalue = testres[1]
    oRandden.append([str(i), str(randmean), str(pvalue)])

#output
#breakpoints enrichment ratio
ohead = "Chrom\tPos\tEnrichmentRatio"
o.write(ohead + "\n")
示例#25
0
import random2
import tkinter
from PIL import ImageTk, Image

root = tkinter.Tk()
root.geometry('300x300')
root.title('Rolling Dice')

heading = tkinter.Label(root,text="The dice rolls to...", fg="red", bg="pink", font = "Arial 16 bold italic")
heading.pack()

dice = ['die1.png','die2.png','die3.png','die4.png','die5.png','die6.png']
diceim=ImageTk.PhotoImage(Image.open(random2.choice(dice)))

imlabel = tkinter.Label(root, image=diceim)
imlabel.image = diceim
imlabel.pack(expand=True)

def rolling():
    diceim=ImageTk.PhotoImage(Image.open(random2.choice(dice)))
    imlabel.configure(image=diceim)
    imlabel.image = diceim

button = tkinter.Button(root, text="Roll the Dice", command=rolling)
button.pack(expand=True)

root.mainloop()
示例#26
0
文件: r_n.py 项目: Jelly-Bee/train
def gener_num(leng):
    l_num = ''
    for i in range(0, leng):
        l_num += random2.choice(strings)
    l_num += '\r\n'
    return l_num
UPCASE_CHARACTERS = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'M', 'N', 'O', 'p',
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
]

SYMBOLS = [
    '@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>', '*', '(', ')',
    '<'
]

# combines all the character arrays above to form one array
COMBINED_LIST = DIGITS + UPCASE_CHARACTERS + LOCASE_CHARACTERS + SYMBOLS

# randomly select at least one character from each character set above
rand_digit = random2.choice(DIGITS)
rand_upper = random2.choice(UPCASE_CHARACTERS)
rand_lower = random2.choice(LOCASE_CHARACTERS)
rand_symbol = random2.choice(SYMBOLS)

# combine the character randomly selected above
# at this stage, the password contains only 4 characters but
# we want a 12-character password
temp_pass = rand_digit + rand_upper + rand_lower + rand_symbol

# now that we are sure we have at least one character from each
# set of characters, we fill the rest of
# the password length by selecting randomly from the combined
# list of character above.
for x in range(MAX_LEN - 4):
    temp_pass = temp_pass + random2.choice(COMBINED_LIST)
示例#28
0
import random2

hola = ["Hola", "Buenas", "Saludos", "Hola!", "Buenas!", "Saludos!"]
elhola = random2.choice(hola)

hoy = [
    "hoy",
    "esta vez",
    "esta ocasion",
    "esta oportunidad",
]
elhoy = random2.choice(hoy)

tetraemos = ["te traemos", "te compartimos"]
eltetraemos = random2.choice(tetraemos)

una = ["una pelicula", "una cinta", "un filme"]
eluna = random2.choice(una)

denombre = ["de nombre", "que se llama", "llamada"]
eldenombre = random2.choice(denombre)

nombre = input("El nombre: ")

dicen = ["dicen", "comentan", "he escuchado", "he oido"]
eldicen = random2.choice(dicen)

buenisima = [
    "que esta buenisima", "que esta re buena", "que esta genial",
    "que esta bien buena"
]