Best Python code snippet using avocado_python
control.py
Source:control.py  
...32    if len(lists) > 0:33        for i in range(len(lists)):34            kb_data.append(((lists[i], i, "learn_words_from_list"),))35    kb = flexy_keyboard(kb_data)36    await bot.send_message(session.get_user_id(), "What do you want to learn now?",37                           reply_markup=kb)38async def learn_all_words(query: types.CallbackQuery, callback_data: dict):39    """40    learn all words from spaced_repetition41    :param query:42    :param callback_data:43    :return:44    """45    logger.debug(str(query.from_user.id)46                 + " learn_all_words  " + str(callback_data))47    n = int(callback_data['data'])48    session, isValid = await authorize(query.from_user.id, with_lang=True)49    if not isValid:50        return51    hids = sr.get_items_to_learn(52        (session.get_user_id(), session.active_lang()),53        upper_recall_limit=1.0, n_words=n)54    logger.debug("{}, found {} tasks to do", session.get_user_id(), len(hids))55    if len(hids) == 0:56        if session.status == '/test':57            await bot.send_message(session.get_user_id(),58                                   'You should add at least one word with /addwords command to start training')59        return True60    words = mysql_connect.fetch_by_hids(session.get_user_id(), hids)61    logger.debug("{}, fetched {} tasks to do", session.get_user_id(), len(words))62    session.words_to_learn = words63    session.current_word = 064    if not session.has_more_words_to_learn():65        # Case 2: doing reading errors66        await bot.send_message(session.get_user_id(), "Let's revise some words")67        await reading.do_reading_errors(query, callback_data)68    else:69        # Case 1: reading exercises70        await start_learning(session)71async def learn_words_from_list(query: types.CallbackQuery, callback_data: dict):72    logger.debug(str(query.from_user.id)73                 + " learn_all_words  " + str(callback_data))74    session, isValid = await authorize(query.from_user.id, with_lang=True)75    if not isValid:76        return77    lists = mysql_connect.get_list_names(query.from_user.id, session.active_lang())78    list_name = lists[int(callback_data['data'])]79    logger.info("{} learns {}", query.from_user.id, list_name)80    text_hid = mysql_connect.fetchone('SELECT text_hid FROM user_texts WHERE user=%s AND list_name=%s',81                                      (session.get_user_id(), list_name))82    if text_hid is not None:83        summary = mysql_connect.fetchone('SELECT summary FROM text_summary WHERE user=%s AND hid=%s',84                                         (session.get_user_id(), text_hid[0]))85        if summary is not None:86            # (word, definition, mode, hid)]87            session.words_to_learn = list()88            session.words_to_learn.append((summary[0], list_name, 20, text_hid[0]))89            k = to_one_row_keyboard(['Words', 'Summary'], [0, 1],90                                    ['text_words', 'text_summary'])91            await bot.send_message(session.get_user_id(),92                                   'You created a summary for text _{}_.\n'93                                   'Would you like to learn words or continue with your summary?'94                                   .format(list_name),95                                   reply_markup=k)96            return97    hids = mysql_connect.get_hids_for_list(query.from_user.id, list_name)98    logger.info("{} has {} tasks from list {}", query.from_user.id, len(hids), list_name)99    hids_all = sr.get_items_to_learn(100        (session.get_user_id(), session.active_lang()),101        upper_recall_limit=0.5)102    logger.info("{} has {} tasks to learn", query.from_user.id, len(hids_all))103    hids = list(set(hids) & set(hids_all))104    logger.info("{} has {} tasks from list {} to learn", query.from_user.id, len(hids), list_name)105    # hids = list() #FIXME NOW delete after testing!!!106    if len(hids) == 0:107        sentence_hids = mysql_connect.get_sentence_hids(query.from_user.id, list_name)108        sentence_hids = ilt.get_objects(sentence_hids, '1 day', session.get_user_id(),109                                        session.active_lang(), "SENTENCE", 10)110        logger.info("{} has {} sentences from list {} to learn", query.from_user.id, len(sentence_hids), list_name)111        await bot.send_message(query.from_user.id, "You have {} sentences from list {} to learn"112                               .format(len(sentence_hids), list_name))113        if len(sentence_hids) > 0:114            session.current_level = 10  # Syntax learning115            await learn_sentences(query.from_user.id, list_name, session, sentence_hids)116        else:117            session.current_level = 20  # Text learning118            await texts.text_summarization(query.from_user.id, list_name, session)119    else:120        words = mysql_connect.fetch_by_hids(session.get_user_id(), hids)121        logger.debug("{}, fetched {} tasks to do", session.get_user_id(), len(words))122        session.words_to_learn = words123        session.current_word = 0124        await start_learning(session)125async def learn_sentences(user, list_name, session, hids):126    sentences = mysql_connect.fetch_sentences(session.get_user_id(), list_name)127    if len(sentences) == 0:128        return129    await bot.send_message(user, "You've done all the tasks from list _{}_. "130                                 "Now let's do some grammar exercises.".format(list_name))131    # 0. word, 1. definition, 2. mode, 3. hid132    # 0. sentence, 1. translation, 2. mode, 3. hid133    sent_to_learn = list()134    if hids is not None:135        for s in sentences:136            if s[3] in hids:137                sent_to_learn.append(s)138    else:139        sent_to_learn = sentences140    session.words_to_learn = sent_to_learn141    session.current_word = 0142    await start_learning(session)143# Get reply from the user and filter the data: set number and shuffle144async def start_learning(session):145    """146    :param session:147    :return:148    """149    words = session.words_to_learn150    words = sort_words(words)151    session.words_to_learn = words152    # await bot.send_message(session.get_user_id(), "Check if you remember these words")153    await do_learning(session)154# The learning loop, reading task 1155async def do_learning(session):156    session, isValid = await authorize(session.get_user_id())157    if not isValid:158        return159    await do_learning1(session)160async def do_learning1(session):161    if not session.has_more_words_to_learn():162        await reading.do_reading_errors1(session)163    else:164        session = await get_session(session.get_user_id())165        if session is None:166            return167        word = session.get_current_word()  # 0. word, 1. definition, 2. mode, 3. hid168        if word is None:169            await bot.send_message(session.get_user_id(), RESTART)170            logger.error(str(session.get_user_id()) + " word is None")171            return172        if word[2] == 0:173            # Do reading exercises174            session.current_level = word[2]175            logger.debug("{} started level {}", session.get_user_id(), word[2])176            keyboard = to_one_row_keyboard(["I remember", "Show meaning"],177                                           data=[0, 1],178                                           action=["I_remember", "show"])179            hint = get_hint(word[1])180            word_context = await get_context(word, True)181            await bot.send_message(session.get_user_id(), word_context + "\n" + hint,182                                   reply_markup=keyboard, parse_mode=types.ParseMode.HTML)183        elif word[2] == 2:184            session.current_level = word[2]185            logger.debug("{} started level {}", session.get_user_id(), word[2])186            if session.subscribed:187                logger.debug("{} is subscribed", session.get_user_id())188                session.status = tasks[2]189                word_context = await get_context(word, False)190                word_context = re.sub(r'\b' + word[0] + r'\b',191                                      ' ... ',192                                      word_context,193                                      flags=re.I)194                await bot.send_message(session.get_user_id(),195                                       "<b>SAY</b> this word: <b>" + word[1] + "</b>\n"196                                       + word_context,197                                       parse_mode=types.ParseMode.HTML)198            else:199                level_up(session)200                await do_learning(session)201        elif word[2] == 3:202            session.current_level = word[2]203            logger.debug("{} started level {}", session.get_user_id(), word[2])204            if session.subscribed:205                logger.debug("{} is subscribed", session.get_user_id())206                session.status = tasks[2]207                await bot.send_message(session.get_user_id(),208                                       "*LISTEN* and *SAY* this word: *{}*\n{}".209                                       format(word[0], word[1]))210                voice = text2speech.get_voice(word[0], session.active_lang())211                await bot.send_audio(chat_id=session.get_user_id(),212                                     audio=voice,213                                     performer=word[1], caption=None,214                                     title=word[0])215            else:216                level_up(session)217                await do_learning(session)218        elif word[2] == 1:219            session.current_level = word[2]220            logger.debug("{} started level {}", session.get_user_id(), word[2])221            session.status = tasks[1]222            word_context = await get_context(word, False)223            word_context = re.sub(r'\b' + word[0] + r'\b',224                                  ' ... ',225                                  word_context,226                                  flags=re.I)227            await bot.send_message(session.get_user_id(),228                                   "<b>WRITE</b> the correct word for the definition:\n"229                                   "<b>" + word[1] + "</b>\n" + word_context,230                                   parse_mode=types.ParseMode.HTML)231        # SENTENCES232        # Unscramble233        elif word[2] == 10:234            session.current_level = word[2]235            logger.debug("{} started level {}", session.get_user_id(), word[2])236            await syntaxis.unscramble(session, word)237async def get_context(word, zero_context):238    contexts = mysql_connect.get_context_by_hid(word[3])239    word_context = ''240    if contexts is not None:241        for context in contexts:242            word_context += re.sub(r'\b' + word[0] + r'\b',243                                   '<b>' + word[0] + '</b>',244                                   context,245                                   flags=re.I)246            word_context += '\n'247    if len(word_context) == 0:248        if zero_context:249            word_context = '<b>' + word[0] + '</b>'...fake_populate.py
Source:fake_populate.py  
...5def get_server_id(name):6    return Server.upsert(name, 27000)7def get_workstation_id(name):8    return Workstation.add(name)9def get_user_id(name):10    return User.add(name)11def get_product_id(server_id, internal_name, in_use, total):12    p = products[internal_name]13    p['license_out'] = in_use14    p['license_total'] = total15    return Product.upsert(server_id=server_id, internal_name=internal_name, **p)16def random_date():17    """18    This function will return a random datetime between two datetime19    objects.20    """21    start_date = datetime.now() + timedelta(-15)22    start = datetime.strptime(start_date.strftime('%Y-%m-%d %I:%M:%S'), '%Y-%m-%d %I:%M:%S')23    end = datetime.strptime(datetime.now().strftime('%Y-%m-%d %I:%M:%S'), '%Y-%m-%d %I:%M:%S')24    delta = end - start25    int_delta = (delta.days * 24 * 60 * 60) + delta.seconds26    random_second = random.randrange(int_delta)27    return start + timedelta(seconds=random_second)28def check_in(server_id, h, data):29    while True:30        dt = random_date()31        if dt < data['time_out']:32            History.update(h, dt, server_id)33            return34def populate():35    server_1 = get_server_id('gis-license-1')36    server_2 = get_server_id('gis-license-2')37    update_1 = Updates.start(server_1)38    update_2 = Updates.start(server_2)39    dummy_data = [40        # server 141        (update_1, server_1, {'user_id': get_user_id('Gus'),42                              'workstation_id': get_workstation_id('Gus-PC'),43                              'product_id': get_product_id(server_1, 'ARC/INFO', 0, 3),44                              'time_out': random_date()}, False),45        (update_1, server_1, {'user_id': get_user_id('Ted'),46                              'workstation_id': get_workstation_id('Ted-PC'),47                              'product_id': get_product_id(server_1, 'ARC/INFO', 0, 3),48                              'time_out': random_date()}, False),49        (update_1, server_1, {'user_id': get_user_id('Lin'),50                              'workstation_id': get_workstation_id('Lin-PC'),51                              'product_id': get_product_id(server_1, 'VIEWER', 0, 5),52                              'time_out': random_date()}, True),53        (update_1, server_1, {'user_id': get_user_id('Sue'),54                              'workstation_id': get_workstation_id('Ted-PC'),55                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),56                              'time_out': random_date()}, False),57        (update_1, server_1, {'user_id': get_user_id('Ike'),58                              'workstation_id': get_workstation_id('Ike-PC'),59                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),60                              'time_out': random_date()}, False),61        (update_1, server_1, {'user_id': get_user_id('Mary'),62                              'workstation_id': get_workstation_id('Mary-PC'),63                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),64                              'time_out': random_date()}, False),65        (update_1, server_1, {'user_id': get_user_id('Sally'),66                              'workstation_id': get_workstation_id('Sally-PC'),67                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),68                              'time_out': random_date()}, False),69        (update_1, server_1, {'user_id': get_user_id('Ron'),70                              'workstation_id': get_workstation_id('Ron-PC'),71                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),72                              'time_out': random_date()}, False),73        (update_1, server_1, {'user_id': get_user_id('Bill'),74                              'workstation_id': get_workstation_id('Bill-PC'),75                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),76                              'time_out': random_date()}, True),77        (update_1, server_1, {'user_id': get_user_id('Nancy'),78                              'workstation_id': get_workstation_id('Nancy-PC'),79                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),80                              'time_out': random_date()}, True),81        (update_1, server_1, {'user_id': get_user_id('Will'),82                              'workstation_id': get_workstation_id('Will-PC'),83                              'product_id': get_product_id(server_1, 'EDITOR', 5, 10),84                              'time_out': random_date()}, True),85        (update_1, server_1, {'user_id': get_user_id('Sam'),86                              'workstation_id': get_workstation_id('Sam-PC'),87                              'product_id': get_product_id(server_1, 'DESKTOPBASICP', 2, 2),88                              'time_out': random_date()}, False),89        (update_1, server_1, {'user_id': get_user_id('Pat'),90                              'workstation_id': get_workstation_id('Pat-PC'),91                              'product_id': get_product_id(server_1, 'DESKTOPBASICP', 2, 2),92                              'time_out': random_date()}, False),93        (update_1, server_1, {'user_id': get_user_id('Alf'),94                              'workstation_id': get_workstation_id('Alf-PC'),95                              'product_id': get_product_id(server_1, 'DESKTOPADVP', 1, 4),96                              'time_out': random_date()}, False),97        (update_1, server_1, {'user_id': get_user_id('Sam'),98                              'workstation_id': get_workstation_id('Sam-PC'),99                              'product_id': get_product_id(server_1, '3DANALYSTP', 2, 4),100                              'time_out': random_date()}, False),101        (update_1, server_1, {'user_id': get_user_id('Pat'),102                              'workstation_id': get_workstation_id('Pat-PC'),103                              'product_id': get_product_id(server_1, '3DANALYSTP', 2, 4),104                              'time_out': random_date()}, False),105        # server 2106        (update_2, server_2, {'user_id': get_user_id('Bob'),107                              'workstation_id': get_workstation_id('Pat-PC'),108                              'product_id': get_product_id(server_2, 'ARC/INFO', 2, 3),109                              'time_out': random_date()}, False),110        (update_2, server_2, {'user_id': get_user_id('Kim'),111                              'workstation_id': get_workstation_id('Alf-PC'),112                              'product_id': get_product_id(server_2, 'ARC/INFO', 2, 3),113                              'time_out': random_date()}, False),114        (update_2, server_2, {'user_id': get_user_id('Joe'),115                              'workstation_id': get_workstation_id('Joe-PC'),116                              'product_id': get_product_id(server_2, 'VIEWER', 0, 10),117                              'time_out': random_date()}, True),118        (update_2, server_2, {'user_id': get_user_id('Liz'),119                              'workstation_id': get_workstation_id('Joe-PC'),120                              'product_id': get_product_id(server_2, 'VIEWER', 0, 10),121                              'time_out': random_date()}, True),122        (update_2, server_2, {'user_id': get_user_id('Pam'),123                              'workstation_id': get_workstation_id('Pam-PC'),124                              'product_id': get_product_id(server_2, 'EDITOR', 1, 10),125                              'time_out': random_date()}, False),126        (update_2, server_2, {'user_id': get_user_id('Ann'),127                              'workstation_id': get_workstation_id('Ann-PC'),128                              'product_id': get_product_id(server_2, 'DESKTOPBASICP', 0, 2),129                              'time_out': random_date()}, True),130        (update_2, server_2, {'user_id': get_user_id('Bob'),131                              'workstation_id': get_workstation_id('Bob-PC'),132                              'product_id': get_product_id(server_2, 'NETWORK', 2, 2),133                              'time_out': random_date()}, False),134        (update_2, server_2, {'user_id': get_user_id('Kim'),135                              'workstation_id': get_workstation_id('Kim-PC'),136                              'product_id': get_product_id(server_2, 'NETWORK', 2, 2),137                              'time_out': random_date()}, False),138    ]139    for d in dummy_data:140        id = History.add(d[0], d[1], **d[2])141        if d[3]:142            check_in(server_id=d[1], h=id, data=d[2])143    Updates.end(update_1, 'UP', '')144    Updates.end(update_2, 'UP', '')145if __name__ == "__main__":...db.py
Source:db.py  
...6    def user_exists(self, user_id):7        """ÐÑовеÑÑем, еÑÑÑ Ð»Ð¸ ÑÐ·ÐµÑ Ð² базе"""8        result = self.cursor.execute("SELECT `id` FROM `users` WHERE `user_id` = ?", (user_id,))9        return bool(len(result.fetchall()))10    def get_user_id(self, user_id):11        """ÐоÑÑаем id ÑзеÑа в базе по его user_id"""12        result = self.cursor.execute("SELECT `id` FROM `users` WHERE `user_id` = ?", (user_id,))13        return result.fetchone()[0]14    def add_user(self, user_id):15        """ÐобавлÑем ÑзеÑа в базÑ"""16        self.cursor.execute("INSERT INTO `users` (`user_id`) VALUES (?)", (user_id,))17        return self.conn.commit()18    def add_record(self, user_id, operation, value):19        """Создаем запиÑÑ Ð¾ доÑ
одаÑ
/ÑаÑÑ
одаÑ
"""20        self.cursor.execute("INSERT INTO `records` (`users_id`, `operation`, `value`) VALUES (?, ?, ?)",21                            (self.get_user_id(user_id),22                             operation == "+",23                             value))24        return self.conn.commit()25    def get_records(self, user_id, within="all"):26        """ÐолÑÑаем иÑÑоÑÐ¸Ñ Ð¾ доÑ
одаÑ
/ÑаÑÑ
одаÑ
"""27        if (within == "day"):28            result = self.cursor.execute(29                "SELECT * FROM `records` WHERE `users_id` = ? AND `date` BETWEEN datetime('now', 'start of day') AND datetime('now', 'localtime') ORDER BY `date`",30                (self.get_user_id(user_id),))31        elif (within == "week"):32            result = self.cursor.execute(33                "SELECT * FROM `records` WHERE `users_id` = ? AND `date` BETWEEN datetime('now', '-6 days') AND datetime('now', 'localtime') ORDER BY `date`",34                (self.get_user_id(user_id),))35        elif (within == "month"):36            result = self.cursor.execute(37                "SELECT * FROM `records` WHERE `users_id` = ? AND `date` BETWEEN datetime('now', 'start of month') AND datetime('now', 'localtime') ORDER BY `date`",38                (self.get_user_id(user_id),))39        else:40            result = self.cursor.execute("SELECT * FROM `records` WHERE `users_id` = ? ORDER BY `date`",41                                         (self.get_user_id(user_id),))42        return result.fetchall()43    def addTask(self, user_id, taskname, description, deadline):44        """Создаем запиÑÑ Ð¾ задаÑе"""45        self.cursor.execute(46            "INSERT INTO `tasks` (`users_id`, `taskname`, `description`, `deadline`) VALUES (?, ?, ?, ?)",47            (self.get_user_id(user_id),48             taskname,49             description,50             deadline))51        return self.conn.commit()52    def delTask(self, users_id, task_id):53        """УдалÑем запиÑÑ Ð¾ задаÑе"""54        self.cursor.execute("DELETE FROM `tasks` WHERE `users_id` = (?) AND `id` = (?)",55                            (self.get_user_id(users_id), task_id))56        return self.conn.commit()57    def getTasks(self, users_id):58        """ÐолÑÑаем вÑе запиÑи Ñ Ð·Ð°Ð´Ð°Ñами СÐРТÐРÐÐÐÐЫ ÐÐ ÐÐÐÐÐÐÐУ"""59        self.cursor.execute("SELECT * FROM `tasks` WHERE `users_id` = (?) "60                            "ORDER BY `deadline`", (self.get_user_id(users_id), ))61        tasks = self.cursor.fetchall()62        return tasks63    def getTime(self, users_id):64        """ÐолÑÑаем вÑÐµÐ¼Ñ ÐÐÐÐÐÐÐÐ"""65        self.cursor.execute("SELECT deadline FROM tasks WHERE users_id = (?) ",66                            (self.get_user_id(users_id), ))67        deadline = self.cursor.fetchall()68        return deadline69    def getTaskname(self, users_id):70        """ÐолÑÑаем Ð½Ð°Ð·Ð²Ð°Ð½Ð¸Ñ Ð·Ð°Ð´Ð°Ñ"""71        self.cursor.execute("SELECT taskname FROM tasks WHERE users_id = (?) ",72                            (self.get_user_id(users_id), ))73        taskname = self.cursor.fetchall()74        return taskname75    def addAlarm(self, user_id, notif):76        """Создаем запиÑÑ Ð¾ вкл/вÑкл Ñведомлений"""77        self.cursor.execute("INSERT INTO `alarm` (`users_id`, `notif`) VALUES (?, ?)",78                            (self.get_user_id(user_id), notif))79        return self.conn.commit()80    def getAlarm(self, users_id):81        """ÐолÑÑаем знаÑение ÑоÑÑоÑÐ½Ð¸Ñ Ñведомлений"""82        self.cursor.execute("SELECT notif FROM alarm WHERE users_id = (?) ORDER BY id DESC LIMIT 1",83                            (self.get_user_id(users_id), ))84        alarm = self.cursor.fetchall()85        return alarm86    def AlarmOff(self):87        """ÐÑклÑÑаем вÑе ÑÐ²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ (иÑполÑзÑеÑÑÑ Ð¿Ñи пеÑезапÑÑке боÑа)"""88        self.cursor.execute("DELETE FROM `alarm`")89        return self.conn.commit()90def close(self):91    """ÐакÑÑваем Ñоединение Ñ ÐÐ"""...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
