def play_game(trie): letters = Cubes().shuffle() board = Board(letters) print board print 'You have 3 minutes - press Ctrl-C to finish early' bar = ProgressBar(60) try: event = Event() for i in range(60): bar.show(i) event.wait(3) bar.finish() os.system('say "time is up, stop boggling"') except KeyboardInterrupt: pass raw_input('\nPress <ENTER> to see answers') results = board_search(board, trie) answers = Answers() answers.add(results) print answers
def show_answers(trie, letters): board = Board(letters) results = board_search(board, trie) answers = Answers() answers.add(results) print board print answers
def show_answers_hex(trie, input_str): row_letters, row_starts = parse_letters_hex(input_str) board = HexBoard(row_letters, row_starts) print board results = board_search(board, trie) answers = Answers() answers.add(results) print answers
def on_message(self, mobj): yield from self.check_spam_message(mobj) # Troll member if user is banned author = mobj.author if self.users.is_member_banned(author.id): reply = Answers.get_banned_trolling() yield from self.message(mobj.channel, reply.format(author.mention))
def main_bak(): from answers import Answers # sets = ['a', 'ab', 'b', 'c', 'd', 'e'] sets = ['a', 'ab', 'b', 'c', 'd', 'e'] ans = [] for j, s in enumerate(sets): print("Dealing with {} set".format(s)) for i in tqdm.tqdm(range(12)): ans.append(get_answer(s, i)) # print(get_answer('a', 0)) correct_ans = Answers().a + Answers().ab + Answers().b + Answers( ).c + Answers().d + Answers().e comparison = np.array(correct_ans) == np.array( ans) # boolean comparison correct_cnt = np.sum(comparison) correct_set_cnt = [] for i in range(0, 12 * len(sets), 12): correct_set_cnt.append(np.sum(comparison[i:i + 12])) print(correct_cnt, "------------", correct_cnt / len(correct_ans)) print(correct_set_cnt) print(ans) with open( "./results/answers.txt", 'a' ) as file: # results folder is there, answers.txt will be created if needed file.write( str(datetime.datetime.now()) + " " + str(args.seed) + "\n") file.write(','.join(map(str, ans)) + "\n") file.write(','.join(map(str, correct_set_cnt)) + "\n") file.write('\n')
class AnswersTest(unittest.TestCase): def setUp(self): self.answers = Answers() def test_empty(self): self.assertEquals(0, self.answers._calc_points()) def test_duplicates(self): word = 'abc' self.answers.add([word, word, word]) self.assertEquals(1, self.answers._calc_points()) self.answers.add([word]) self.assertEquals(1, self.answers._calc_points()) def test_dict(self): self.answers.add(['aaa', 'bbb', 'cccc']) d = self.answers._make_dict() self.assertEquals(['aaa', 'bbb'], d[3]) self.assertEquals(['cccc'], d[4])
async def post(self): json_data = await self.request.json() answers = Answers() # save userdata for statistic if 'callback_query' in json_data: # press button on inline keyboard button_data = json_data['callback_query']['data'] answer_data = { 'chat_id': json_data['callback_query']['from']['id'], 'text': answers.getAnswer(button_data, self.request.app)} await self.send_answer_callback_query({'callback_query_id': json_data['callback_query']['id']}) await self.send_message(answer_data) return web.json_response({}) user_id = json_data['message']['from']['id'] username = json_data['message']['from'].get('username','') first_name = json_data['message']['from'].get('first_name','') last_name = json_data['message']['from'].get('last_name','') user_data = {'user_id': user_id, 'user_name': '{} ({} {})'.format(username, first_name, last_name)} if user_id not in self.request.app.chats: self.request.app.chats[user_id] = user_data self.request.app.logger.info(user_data) chat_id = json_data['message']['chat']['id'] if 'text' in json_data['message']: text = json_data['message']['text'] answer = answers.getAnswer(text,self.request.app) if text[:5] == '/help': result_data = { 'method': 'sendMessage', 'chat_id': chat_id, 'text': answers.getAnswer(text, self.request.app), 'reply_to_message_id': json_data['message']['message_id'], 'reply_markup': answers.getHelpKeyboard()} else: result_data = {'method': 'sendMessage','chat_id': chat_id, 'text': answer} else: result_data = {'method': 'sendMessage','chat_id': chat_id, 'text': answers.BAD_REQUEST_ANSWER} if result_data['text'] == answers.BAD_REQUEST_ANSWER: sticker_data = {'chat_id': chat_id, 'sticker': answers.getSticker()} await self.send_sticker(sticker_data) return web.json_response(result_data)
def build(self): screen_manager = ScreenManager() main_menu_screen = MainMenu(name='main_menu') questions_screen = Questions(name='questions') evidence_unique_screen = EvidenceUnique(name='evidence_unique') test_screen = Test(name='test') result_screen = Result(name='result') answers_screen = Answers(name='answers') evidence_screen = Evidence(name='evidence') screen_manager.add_widget(main_menu_screen) screen_manager.add_widget(questions_screen) screen_manager.add_widget(evidence_unique_screen) screen_manager.add_widget(test_screen) screen_manager.add_widget(result_screen) screen_manager.add_widget(answers_screen) screen_manager.add_widget(evidence_screen) return screen_manager
def setUp(self): self.answers = Answers()
import tkinter as tk from tkinter import ttk from tkinter import messagebox from answers import Answers from Counter import Counter from help import Help import sys import os answer = Answers() largeFont = ("Verdana", 12) class GameWindow(tk.Tk): # args - any number of arguments # kwargs - any number of key word arguments def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self, "Who wants to be a millionare") self.container = tk.Frame(self) self.container.grid(row=0, columnspan=2, sticky="nsew") self.container.grid_rowconfigure(0, weight=1) self.container.grid_columnconfigure(0, weight=1) frame = StartGame(self.container, self) frame.grid(row=0, column=0, sticky="nsew") frame.tkraise()
# -*- coding: utf-8 -*- import os import telebot from keyboard import KeyboardMenu from answers import Answers TOKEN = os.getenv('TOKEN') ADMIN_ID = 281452837 BOT = telebot.TeleBot(TOKEN) ANSWERS = Answers() DATABASE = ANSWERS.config.database MENU = KeyboardMenu() def check_error(message): """ Принимает на вход сообщеник и проверяет, является ли оно командой бота Нужно для того, чтобы внутри потока можно было отлавливать команды Запускает команду, открывает главное меню или сообщает об ошибке """ commands = { '/start': start_message, '/help': help_message, '/buses': buses_message, '/slavyanki': slavyanki_message, '/suburbans': suburbans_message, '/file': file_message, '/menu': menu_message } if message.text in commands: commands[message.text](message)
def reset(): global annotator, answer_catalog annotator = annotator.reset() answer_catalog = Answers() # return index() return ""
def initialize(): global annotator, answer_catalog, analysis annotator = Annotator() answer_catalog = Answers() analysis = Analysis()
def update_user(self, member, user, channel, check_is_conflicted=False, silent=False, is_new_data=True): result = types.SimpleNamespace() result.rank = result.name = False result.api_error = None self.logger.debug('Update member {0} with game name {1} from channel {2}'.format(member, user.nickname, channel)) mention = member.mention old_rank = user.rank.lower() try: # Getting user elo using RiotAPI server = self.users.get_or_create_server(channel.server.id) region = server.parameters.get_region() rank, game_user_id, nickname = self.riot_api.get_user_info( region, user_id=user.game_id, nickname=user.nickname) rank = rank.lower() if check_is_conflicted: confirmed_user = server.find_confirmed_user(game_user_id) if confirmed_user: if confirmed_user.discord_id != user.discord_id: if not silent: error_reply = 'Не могу поставить тебе ник `{0}`, {1}, он уже занят за <@!{2}>'\ .format(nickname, mention, confirmed_user.discord_id) yield from self.message(channel, error_reply) return result # Changing game nickname - 'unconfirming' user if user.game_id != game_user_id: user.confirmed = False # Checking high-elo if not user.is_confirmed: if rank in EloBot.confirmation_ranks: self.logger.debug('User {0} requested {1} using nickname \'{2}\', putting him to {3}' .format(member, rank, nickname, EloBot.rollback_rank).encode('utf-8')) required_hash = UserData.create_hash(game_user_id, member.id) is_hash_correct = self.riot_api.check_user_verification(game_user_id, required_hash, region) if is_hash_correct: self.logger.debug('User {0} already has correct hash, confirming it'.format(member)) yield from self.confirm_user(user, server, member, channel, silent=silent) else: self.logger.debug('User {0} is not confirmed, setting default rank'.format(member)) rank = EloBot.rollback_rank.lower() if not silent and (is_new_data or rank != old_rank): confirm_reply = '{0}, если ты правда с хай-эло - выставь `{1}` в коде верификации ' \ '(`Настройки->About->Verification` в клиенте) и подтверди свой ник ' \ 'командой `!confirm`. А пока что будешь с таким рангом :3'\ .format(mention, required_hash) yield from self.message(channel, confirm_reply) rank_changed = rank != old_rank # Saving user to database self.users.update_user(user, game_user_id, nickname, rank) # Updating users role on server roles_manager = RolesManager(channel.server.roles) role_success, new_role, roles_changed = yield from roles_manager.set_user_role(self.client, member, rank) result.rank = rank_changed or roles_changed # Updating user nickname nick_manager = NicknamesManager(self.users) new_name = nick_manager.get_combined_nickname(member, user) nick_success = True if new_name: nick_success, has_new_nickname = yield from self.change_member_nickname(member, new_name) result.name = has_new_nickname # Replying if not silent and (is_new_data or result.rank): if role_success: emojis = self.emoji.s(channel.server) if is_new_data: answer = Answers.generate_answer(member, new_role.name, emojis) else: # Replace rank text with emojis rank_old_text = emojis.get(old_rank) if not rank_old_text: rank_old_text = old_rank rank_new_text = emojis.get(rank) if not rank_new_text: rank_new_text = rank # Form a reply if rank_changed: answer = '{0}, твое эло изменилось [{1} -> {2}]'\ .format(member.mention, rank_old_text, rank_new_text) else: answer = 'Эй {0}, вернулся к нам на канал? Выставил тебе твой ранк {1}'\ .format(member.mention, rank_new_text) if answer: if not user.is_confirmed: answer = '{0}\nКстати, можешь подтвердить свой ник командой `!confirm`, ' \ 'чтобы никто его не занял'.format(answer) yield from self.message(channel, answer) else: yield from self.message(channel, 'Эй, {0}, у меня недостаточно прав чтобы выставить твою роль, ' 'скажи админу чтобы перетащил мою роль выше остальных.'.format(mention)) if not nick_success: nick_error_reply = '{0}, поменяй себе ник на `{1}` сам, у меня прав нет.'.format(mention, new_name) yield from self.message(channel, nick_error_reply) except RiotAPI.UserIdNotFoundException as _: api_working = self.check_api_if_needed() if api_working: requested_nickname = user.nickname yield from self.clear_user_data(member, channel.server) if not silent: if is_new_data: error_reply = '{0}, ты рак, нет такого ника `{1}` в лиге на `{2}`. '\ .format(member.mention, requested_nickname, region.upper()) else: error_reply = '{0}, не нашел твоего ника `{1}` при обновлении, очистил твои данные'\ .format(member.mention, requested_nickname) yield from self.message(channel, error_reply) else: if not silent and is_new_data: api_url = 'https://developer.riotgames.com/api-status/' yield from self.message(channel, '{0}, судя по всему рито сломали их API. ' 'Проверь тут ({1}), если все в порядке - напиши о проблеме `{2}` ({3}). ' 'Но вообще я и сам ему напишу...' .format(member.mention, api_url, self.owner, self.owner.mention)) yield from self.message(self.owner, 'Тут на `{0}` юзер `{1}` пытается установить себе ник `{2}`, ' 'а АПИ лежит...'.format(channel.server, member, user.nickname)) except RiotAPI.RiotRequestException as e: result.api_error = e.error_code if not silent and is_new_data: error_reply = '{0}, произошла ошибка при запросе к RiotAPI, попробуй попозже.'.format(member.mention) yield from self.message(channel, error_reply) except RolesManager.RoleNotFoundException as _: if not silent and is_new_data: yield from self.message(channel, 'Упс, тут на сервере роли не настроены, не получится тебе роль поставить, {0}. ' 'Скажи админу чтобы добавил роль `{1}`'.format(mention, rank)) return result
return result events_ = {} with open(filename, "r") as infile: for line in infile: elements = line.strip().split("\t") elements = elements[0].split(',') id_ = elements[0] event = Events(id_, elements[3], elements[2]) events_[id_] = event answers = {} with open(filename3, "r") as infile: for line in infile: elements = line.strip().split("\t") id_ = elements[0] answer = Answers(id_, elements[1], elements[2]) answers[id_] = answer while (1): x = random.randint(1, 25) print(questions[x.__str__()].question) user_answer = input() if user_answer == "STOP": break else: answers[questions[x.__str__()].question_id].answer = user_answer print(get_result(x.__str__()))