def do_quote(): while True: quote_list = [] print( "\n\nHello wise internet user, so you want to brew some good quotes!" "Choose the options we can serve u now:\n" "1. Quote of the Day\n" "2. Search the keyword you wish to see quotes on ( a movie, an author, anything)\n" "3. Show some random titles to search quotes on\n" "4. Just show some random quotes ( in case u r in a hurry)\n") choice = int(input("Enter your Choice: ")) print() if choice == 1: qOtD = [] qOtD = list(wikiquote.quote_of_the_day()) print("\n{} \n \t\t\t --{}".format(qOtD[0], qOtD[1])) break elif choice == 2: search_result = [] srch_txt = input("Enter the keyword you wish to search: ") search_result = list(wikiquote.search(srch_txt)) if search_result: print("\nEnter the item number you wish to see a quote on: \n") for x, item in enumerate(search_result, 1): print("{}. {}".format(x, item)) srch_choice = int(input()) srch_strng = search_result[srch_choice - 1] quote_list = list(wikiquote.quotes(srch_strng, max_quotes=5)) print() for i, item in enumerate(quote_list, 1): print("{}. {}\n".format(i, item)) break else: print("no quotes on that! try again.....") elif choice == 3: rand_ttls = list(wikiquote.random_titles(max_titles=5)) print("\nEnter the item number you wish to see a quote on: \n") for i, item in enumerate(rand_ttls, 1): print("{}. {}".format(i, item)) srch_choice = int(input()) srch_strng = rand_ttls[srch_choice - 1] quote_list = list(wikiquote.quotes(srch_strng, max_quotes=5)) for m, item in enumerate(quote_list, 1): print("{}. {}\n".format(m, item)) break elif choice == 4: rand_ttls = list(wikiquote.random_titles(max_titles=5)) rnd_str = random.choice(rand_ttls) try: print(random.choice(wikiquote.quotes(rnd_str))) break except UnboundLocalError: print( "[!] Sorry, some technical glitch occured, please try again!" )
def generate_random_quote(): quotes = [] #create empty quotes list for t in wikiquote.random_titles(): quotes.append(wikiquote.quotes(t)) quotes.append(generate_asip_quote()) quotes.append(wikiquote.quotes('King of the Hill (season 2)')) return quotes
def play_hangman(guess): status = get_current_status() correct_ans = get_current_status()['current_word'] # Randomly select a word if status['current_word'] == "": word = random_titles(max_titles=1) string = word[0] status['current_word'] = string correct_ans = string idxs = [False] * len(string) status['idxs'] = idxs status['wrong_word'] = [] status['final'] = "" else: string = correct_ans idxs = status['idxs'] idxs, score = make_idxs(guess, status['current_word'], idxs) status['idxs'] = idxs hangman = get_hangman_store() word_solved = False # Main game loop if len(status['wrong_word']) != 8 and not word_solved: current_word = get_display_word(string, idxs) status['print_word'] = current_word print(current_word) print('Previous Guesses: {0}'.format(' '.join(status['wrong_word']))) # Get player's next letter guess next_letter = get_next_letter(status['wrong_word'], guess) if score is False: status['hang_man_drawing'] = hangman[len(status['wrong_word'])] print(status['hang_man_drawing']) status['wrong_word'].append(next_letter) # Check if word is completely solved if False not in idxs: status['final'] = '\n' + 'Congratulations! You won!' status['current_word'] = "" return status print() if len(status['wrong_word']) == 8: status['final'] = '\n' + 'Try again next time!' status['current_word'] = "" return status # The game is over: reveal the word #if not word_solved: return status
def get_quote(): while True: try: titles = wq.random_titles(max_titles=1) print("found title: ", titles) quote = wq.quotes(titles[0])[0] return quote except: continue
async def _quote(self, ctx, *query): if ' '.join(query): res = wikiquote.quotes(random.choice( wikiquote.search(' '.join(query).strip()))) if not res: return await ctx.reply(f'No quotes from {" ".join(query).strip()}') return await ctx.reply(f'```\n{res[0]}\n~{" ".join(query).strip()}```') def check(author): def inner_check(message): return message.author == author return inner_check try: await ctx.reply("Would you like a random quote? `Yes/No`\nYou have 30 seconds to respond") answer = await self.bot.wait_for('message', check=check, timeout=30) except asyncio.TimeoutError: return await ctx.reply("You took too long, stupid slow human") if "y" in answer.content.lower(): author = random.choice(wikiquote.random_titles()) res = random.choice(wikiquote.quotes(author)) return await ctx.reply(f'```\n{res}\n~{author}```') elif not "n" in answer.content.lower(): return await ctx.reply("Invalid choice!") try: await ctx.reply("What would you like to search for? \nYou have 30 seconds to respond") answer = await self.bot.wait_for('message', check=check, timeout=30) except asyncio.TimeoutError: return await ctx.reply("You took too long, stupid slow human") search_res = wikiquote.search(answer.content.strip()) res = "" for i in search_res: res += f'{search_res.index(i) + 1}. {i}\n' def check2(author): def inner_check(message): if message.author != author: return False try: int(message.content) return True except ValueError: return False return inner_check try: await ctx.reply(f'(Respond with the number. You have 30 seconds)\nGet random quote from topic:\n```\n{res}```') answer = await self.bot.wait_for('message', check=check2, timeout=30) except asyncio.TimeoutError: return await ctx.reply("You took too long, stupid slow human") await ctx.reply(f'Random result from topic: `{search_res[int(answer.content) - 1]}`' f'\n\n```\n{random.choice(wikiquote.quotes(search_res[int(answer.content) - 1]))}```')
def get_quote(): titles = wikiquote.random_titles() for title in titles: lower_title = title.lower() print('trying title', title) quotes = None if title.startswith('List of'): continue if any(w in lower_title for w in bad_titles): continue try: quotes = wikiquote.quotes(title, max_quotes=1000) except (NoSuchPageException, DisambiguationPageException): pass if not quotes: continue quotes = [q for q in quotes if len(q) < 140] random.shuffle(quotes) for quote in quotes: # Don't use lines of dialogue if '\n' in quote: continue # Not interested in brackets if '[' in quote: continue # Assume this is a quote from a character and not a person if ':' in quote[:20]: continue # Assume this is an external link and not a quote if lower_title in quote.lower(): continue # Strip enclosing quotes if quote[0] == quote[-1] and quote[0] in ('"', "'"): quote = quote[1:-2] words = quote.split() if len(words) < 4: continue if any(w in quote.lower() for w in bad_words): continue new_quote = ' \U0001f44f '.join(words) if len(new_quote) <= 140: print('Chosen quote from', title) return new_quote # Couldn't find matching quotes return None
def quoteMe(self, sc): self.rand = wikiquote.random_titles(max_titles=1)[0] quotes = wikiquote.quotes(self.rand, max_quotes=1) message = "" for quote in quotes: if len(quote) < 80: message = quote if message: self.send_message(sc, message + ", Who am I?") else: self.send_message(sc, quotes[0] + ", Who am I?")
def qfind(query): Authorlist = findtitles(query=query) if Authorlist == []: return ["NoAuthorFound", wikiquote.random_titles(max_titles=7)] else: Authorlist.sort() for i in Authorlist: if query.lower() == i.lower(): qt = ranlist(i) if qt == []: Authorlist.remove(i) continue else: Authorlist.remove(i) return ["Success", choice(qt), i, Authorlist] for i in Authorlist: if query.lower() in i.lower() or i.lower() in query.lower(): qt = ranlist(i) if qt == []: Authorlist.remove(i) continue else: Authorlist.remove(i) return ["Success", choice(qt), i, Authorlist] Quotelist = [] Resultlist = [] for i in Authorlist: try: a = wikiquotes.get_quotes(i, "english") except: pass else: Quotelist = a del a try: c = wikiquote.quotes(i, max_quotes=5) except: c = [] for k in c: if k not in Quotelist: Quotelist.append(k) for j in Quotelist: if query.lower() in j.lower(): Resultlist.append([j, i]) if Resultlist != []: Resultlist.sort() Quote = choice(Resultlist) Authorlist.remove(Quote[1]) return ["Success", Quote[0], Quote[1], Authorlist] else: return ["NoQuoteFound", Authorlist]
def find_quotes(): i = 0 first = "" second = "" third = "" dict = {} while i < 3: quote_index = wikiquote.random_titles() try: title = random.choice(quote_index) quotes = wikiquote.quotes(title) if not quotes: raise EmptyException except DisambiguationPageException: quotes = wikiquote.qotd() title = quotes[1] except EmptyException: quotes = wikiquote.qotd() title = quotes[1] syl = 0 line = "" for word in quotes[0].split(" "): if "." in word: syl += sylco(word) line += word line += " " break syl += sylco(word) line += word line += " " if not first and syl is 5: first = line dict[first] = title i += 1 elif not second and syl is 7: second = line dict[second] = title i += 1 elif not third and syl is 5: third = line dict[third] = title i += 1 # save_path = "C:/Users/natha/Documents/Personal Projects/quotes/Haikus" # file = os.path.join(save_path, dict[first]+".txt") # f = open(file, "w") # f.write('\n' + "Haiku:" + '\n' + first + '\n' + second + '\n' + third + '\n') # f.write('\n' + "Authors:" + '\n' + dict[first] + '\n' + dict[second] + '\n' + dict[third]) content = '\n' + "Haiku:" + '\n' + first + '\n' + second + '\n' + third + '\n' content += '\n' + "Haiku:" + '\n' + first + '\n' + second + '\n' + third + '\n' return dict[first], content
def get_random(ctx, title): titles = ( random_titles(lang=ctx.obj["lang"]) if not title else search(title, lang=ctx.obj["lang"]) ) if titles: try: quote = random.choice(quotes(titles[0], lang=ctx.obj["lang"])) print(pretty(quote, titles[0])) except DisambiguationPageException: return 2 except NoSuchPageException: return 1 return 0
async def quote(ctx): global quote_lang quote = None source = None while (quote == None and source == None): sources = [] while (sources == []): sources = wikiquote.random_titles(lang=quote_lang) choices = [] i = 0 while (choices == [] and i < len(sources)): source = sources[i] choices = wikiquote.quotes(source, lang=quote_lang) i += 1 quote = random.choice(choices) await ctx.send(f"{quote}\n- {source}")
def main(): if len(argv) > 1: print(hypify(" ".join(argv[1:]))) else: while True: try: titles = wq.random_titles(max_titles=1) print("found title: ", titles) quote = wq.quotes(titles[0])[0] except: continue break print("got quote:\n", quote) hype = hypify(quote) while hype is None: hype = hypify(quote) print(hype)
def main(): if len(argv) > 1: print(hypify(" ".join(argv[1:]))) else: while True: try: titles = wq.random_titles(max_titles=1) print("found title: ", titles) quote= wq.quotes(titles[0])[0] except: continue break print("got quote:\n", quote) hype = hypify(quote) while hype is None: hype = hypify(quote) print(hype)
def quotegetir(): wikii = wikiquote.random_titles(max_titles=3) wikiism = str(wikii[0]) quoteee = wikiquote.quotes(wikiism, max_quotes=5) quotee = quoteee[0].replace('?', '.').replace('!', '.').split('.') quote = quotee[0] if ',' in quote: quote = quote.split(',')[1] elif ':' in quote: quote = quote.split(':')[1] elif ';' in quote: quote = quote.split(';')[1] quotelist = quote.split(' ') if len(quotelist) > 7: quotelist = quotelist[0:7] x = len(quotelist) z = random.randint(0, x) for i in range(0, z): if i == 0: y = quotelist[0] + " " elif i == z - 1: y = y + quotelist[z - 1] else: y = y + " " + quotelist[i] translator = Translator() translation = translator.translate(y, dest='tr').text return translation
async def quote(self, choice): """Generating a random quote or get the quote of the day. **Dependencies**: pip install wikiquote Keyword arguments: choice -- either 'QOTD' (Quote of the day) or 'R' (Random) """ if choice.upper() == 'QOTD': quote = wikiquote.quote_of_the_day() await self.bot.say("'{}' -- {}".format(quote[0], quote[1])) elif choice.upper() == 'R': while True: authors = wikiquote.random_titles(max_titles=5) random_author = random.choice(authors) if random_author.isdigit(): continue random_quote = random.choice(wikiquote.quotes(random_author)) await self.bot.say("'{}' -- {}" .format(random_quote, random_author)) break
speak(f"Temperature of {city} is {ans1}") elif 'joke' in que: que=que.replace(que,'') joke=pyjokes.get_joke(language='en',category='neutral') speak(joke) elif 'quote of the day' in que: que=que.replace(que,'') quot=wikiquote.quote_of_the_day(lang='en') speak(quot[0]) speak(f'By: {quot[1]}') elif 'quote' in que: que=que.replace(que,'') tit=wikiquote.random_titles(max_titles=5) quote=wikiquote.quotes(tit[0],max_quotes=1) speak(quote) elif 'shutdown' in que: que=que.replace(que,'') speak('Do you really want to shutdown your PC') speak('Yes: Shutdown\nNo: Terminate shutdown') y_n=str(Listen()) if 'yes' in y_n: speak('Shutting down your PC...') os.system("shutdown /s /t 1") elif 'no' in y_n: speak('Shutdown process stop')
Distances: N x N array (N being number of atoms present) containing all pairwise distances between atoms I.e., Entry[i][j] is the absolute distance between atoms i and j Adjacent: N x N array of 0s and 1s identifying the "Truth" of a given atom pairing being neighbours based on the criterion of R_Cut I.e., Dist<R_Cut returns a 1 for that entry as the condition has been met All diagonal elements are set to 0 as it is meaningless to be your own neighbour. """ A, B = read(filename) Atoms = [np.column_stack((B[i], A[i]))][0] Distances = np.zeros((55, 55), dtype=np.float) Temp = np.array(np.delete(Atoms, (0), axis=1), dtype=np.float64) for i in range(len(Atoms)): for j in range(len(Atoms)): Euc = (Temp[i, 0] - Temp[j, 0])**2 + ( Temp[i, 1] - Temp[j, 1])**2 + (Temp[i, 2] - Temp[j, 2])**2 Distances[i][j] = np.sqrt(Euc) Adjacent = (Distances < R_Cut).astype( int) #Evaluate if a pair are within R_Cut of eachother np.fill_diagonal(Adjacent, 0) return Distances, Adjacent print(wikiquote.quotes(wikiquote.random_titles(max_titles=1)[0])) #A,B=Adjacency_Matrix(filename, 0, 3.0)
def handle_random_quote_intent(self, message): randomtitles = [] while randomtitles is None or randomtitles == []: randomtitles = wikiquote.random_titles(lang=self.wikilang) quote, title = self.getRandomQuote(randomtitles) self.speak(quote + ' (' + title + ')')
def prog_iter(system: dict = None, quantities: list = None, settings: dict = None, start: int = 0, end: int = None, step: int = None, n_frames_extract: int = None): print("Welcome to this LoDiS post-processing scheme." "This script takes energy.out and movie.xyz files as arguments " "unless otherwise specified by name in the following input " "requests.") #Below is the general scheme by which one takes the trajectory input. start_time = time.time() print("Initialising" + wikiquote.quotes(wikiquote.random_titles(max_titles=1))[0]) System = {**Utility.default_system, **({} if System is None else System)} Settings = { **Utility.default_settings, **({} if Settings is None else Settings) } Metadata = {} FileDirectory = System['base_dir'] MovieFileLocation = FileDirectory + System['movie_file_name'] EnergyFileLocation = FileDirectory + System['energy_file_name'] MovieFile = read(MovieFileLocation, index=':') all_positions = [atoms.get_positions() for atoms in MovieFile] all_atoms = [atoms.get_chemical_symbols() for atoms in MovieFile] Species = set(all_atoms) NFrames = len(all_positions) NAtoms = len(all_atoms) del (MovieFile, all_positions, all_atoms) Metadata['Species'] = Species Metadata['NFrames'] = NFrames Metadata['NAtoms'] = NAtoms print("This trajectory contains ", NAtoms, " atoms of type(s) ", Species, " over ", NFrames, " frames.") # Checking input arguments if step is not None and n_frames_extract is not None: raise ValueError( 'step and n_frames_extract cannot be specified simultaneously') if not (0 <= start <= NFrames): raise ValueError('start is out of range') if end is None: end = NFrames if not (start <= end <= NFrames): raise ValueError('end is out of range') n_frames_in_range = end - start if step is None and n_frames_extract is None: step = 1 if step is None: # Finding the maximum step that spreads out in the range evenly step = math.floor(n_frames_in_range / n_frames_extract) end = start + n_frames_extract * step range_frames = range(start, end, step) if n_frames_extract is not None: assert len(range_frames) == n_frames_extract n_frames_extract = len(range_frames) print() print('Analyzing from frame %d (t = %.2E) to frame %d (t = %.2E) ' 'with step of %d frame(s) (%.2E), in total %d frames' % (start, start * step, end, end * step, step, step * step, n_frames_extract)) # Checking and sanitizing input if quantities is None: quantities = [] quantities = [ Utility.input2key(quantity_input) for quantity_input in quantities ] quantities_dep = [d for q in quantities for d in explode_dependencies(q)] quantities_dep = Utility.ordered_set(quantities_dep) # Inflate classes _ = [] for q, params in quantities_dep: _.append(q(params, System, Settings, Metadata)) key2quantities = dict(zip(quantities_dep, _)) quantities_dep = _ quantities = [key2quantities[q] for q in quantities] quantities2key = {v: k for (k, v) in key2quantities.items()} print("Calculating/Extracting the following quantities:") print([q.display_name for q in quantities]) quantities_only_dep = [q for q in quantities_dep if q not in quantities] if len(quantities_only_dep) != 0: print("With the following intermediates") print([q.display_name for q in quantities_only_dep]) formats = [] for q in quantities: *dimen, dtype = q.get_dimensions(NAtoms, len(Species)) if dimen == [1]: # scalar data dimen = n_frames_extract else: dimen = n_frames_extract, *dimen formats.append((Utility.key2input(quantities2key[q]), dimen, dtype)) yield Metadata, formats print() print("Let's do this! Time to rock and roll...") results = {} results['Metadata'] = Metadata for i_frame in range_frames: results_cache = {} for quantity in quantities_dep: if __debug__: quantity_start = time.time() result = quantity.calculate(i_frame, results_cache, Metadata) key = quantities2key[quantity] quantity_delta = time.time() - quantity_start print('frame', i_frame, key, 'took', '%.2f ms' % (quantity_delta.total_seconds() * 1000)) results_cache[key] = result if key[1] is None: results_cache[key[0]] = result # For dependency accessor for quantity in quantities: key = quantities2key[quantity] results[Utility.key2input(key)] = results_cache[key] yield results print('Got the data, boss!') for quantity in quantities_dep: quantity.cleanup() program_end = time.time() print('Post proccessing finished, took ', (program_end - start_time), ' seconds.')
def test_random(self): for lang in wikiquote.langs.SUPPORTED_LANGUAGES: results = wikiquote.random_titles(lang=lang, max_titles=20) self.assertTrue(len(results) == 20)
def test_random(self): for lang in wikiquote.supported_languages(): results = wikiquote.random_titles(lang=lang, max_titles=20) self.assertTrue(len(results) == 20)
import wikiquote, random from mastodon import Mastodon f = open('settings.py', 'r') exec(f.read(), globals()) f.close() i = 0 author_list = wikiquote.random_titles(max_titles=20, lang=wiki_lang) while 1: try: quotes = wikiquote.quotes(author_list[i], lang=wiki_lang) text = '"%s"\n\n%s' % (quotes[0], author_list[i]) if len(text) < 500: break except Exception: print('disambigous page') i += 1 if i == len(author_list): print('No quote avalable.') exit(1) print(text) masto = Mastodon(client_id='pytooter_clientcred.secret', access_token='pytooter_usercred.secret', api_base_url=mastodon_url) masto.log_in(mastodon_email, mastodon_password,
def getquote(type: str, userid: str): if type == "qotd": (qt, autor) = wikiquote.quote_of_the_day() Suggestions = [] for i in wikiquote.random_titles(max_titles=10): Suggestions.append({ "label": i, "value": i, "emoji": { "name": "qauthor", "id": "847687409034330132" } }) return { "embeds": [{ "color": 3092791, "title": "Quote of the Day:", "description": f"{qt}\n- {autor}", "thumbnail": { "url": "https://cdn.discordapp.com/attachments/789798190353743874/796948926590615572/oie_transparent_1.png" }, "footer": { "text": "Quotes from Wikiquote", "icon_url": "https://cdn.discordapp.com/attachments/789798190353743874/794948919594450944/QqJDyLtUbgAAAAASUVORK5CYII.png" } }], "components": [{ "type": 1, "components": [{ "type": 3, "custom_id": json.dumps({ "sfn": "quote", "subc": "sgtns", "userid": userid }), "placeholder": "🔎 Try searching", "options": Suggestions }] }, { "type": 1, "components": [{ "type": 2, "style": 1, "emoji": { "name": "qauthor", "id": "847687409034330132" }, "label": "Search Quote from Author", "custom_id": json.dumps({ "bfn": "quote", "subc": "are", "userid": userid }) }] }] } else: res = requests.get("http://api.quotable.io/random").json() qt = res["content"] autor = res["author"] Suggestions = findtitles(query=autor) if Suggestions == []: Suggestions = wikiquote.random_titles(max_titles=10) if autor in Suggestions: Suggestions.remove(autor) Options = [] shuffle(Suggestions) for i in Suggestions: if len(Options) < 26: Options.append({ "label": i, "value": i, "emoji": { "name": "qauthor", "id": "847687409034330132" } }) else: break return { "embeds": [{ "color": 3092791, "title": "Random Quote:", "description": f"{qt}\n- {autor}", "thumbnail": { "url": "https://cdn.discordapp.com/attachments/789798190353743874/796948926590615572/oie_transparent_1.png" }, "footer": { "text": "Powered by Quotable API", "icon_url": "https://cdn.discordapp.com/attachments/839610105858752522/839610124271484938/download.jpeg" } }], "components": [{ "type": 1, "components": [{ "type": 3, "custom_id": json.dumps({ "sfn": "quote", "subc": "sgtns", "userid": userid }), "placeholder": "🔎 Try searching", "options": Options }] }, { "type": 1, "components": [{ "type": 2, "style": 1, "emoji": { "name": "quote", "id": "847687355481718794" }, "label": "Another One!", "custom_id": json.dumps({ "bfn": "quote", "subc": "getran", "userid": userid }) }, { "type": 2, "style": 2, "label": "Search Quote from Author", "emoji": { "name": "qauthor", "id": "847687409034330132" }, "custom_id": json.dumps({ "bfn": "quote", "subc": "are", "userid": userid }) }] }] }
def test_unsupported_lang(self): with self.assertRaisesRegex( wikiquote.UnsupportedLanguageException, "Unsupported language: foobar" ): wikiquote.random_titles(lang="foobar")
from Kernels import KB_Dist as KB import Distances as Dist import cna import cn import ptm print("Welcome to this LoDiS post-processing scheme." "This script takes energy.out and movie.xyz files as arguments" "unless otherwise specified by name in the following input" "requests.") #Below is the general scheme by which one takes the trajectory input. Energy, Trajectory, Elements, filepath = Read.Manual_Input() wikiquote.quotes(wikiquote.random_titles(max_titles=1))[0] #A little bit of proof-of-concept code to plot the first #few PDDFs using this scheme. if __name__ == '__main__': Positions=[];Distances=[];PDDF=[] for x in range(5): Positions.append(np.column_stack((Elements[x],Trajectory[x]))) Distances.append(Dist.Distance.Euc_Dist(Positions[x])) #All possible pairings PDDF.append(Kernels.Kernels.KDE_Uniform(Distances[x],0.25)) plt.plot(PDDF[x][0],PDDF[x][1]) plt.show()