ConDict

Check-in [d015fb4871]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:offline translate
Timelines: family | ancestors | descendants | both | testing
Files: files | file ages | folders
SHA1:d015fb4871509b436f5c827a558dc5dab89f57aa
User & Date: zorro 2012-10-04 18:04:36
Context
2012-10-05
09:08
optimize add-function check-in: f7cdee11f4 user: alzay tags: testing
2012-10-04
18:04
offline translate check-in: d015fb4871 user: zorro tags: testing
2012-10-03
18:41
add tesinto ticket #063281f6ba check-in: fd1ef2e7e3 user: zorro tags: testing
Changes
Hide Diffs Unified Diffs Ignore Whitespace Patch

Changes to condt.py.

273
274
275
276
277
278
279






280
281
282
283
284
285
286
...
320
321
322
323
324
325
326



327
328
329
330
331
332
333
...
350
351
352
353
354
355
356














357
358
359
360
361
362
363
364
365
366
367

368
369
370
371
372
373
374
375
376
...
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
...
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
...
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
        return 'en'
    def command_ru(self, text):
        """ru-en translate"""
        print(self.command_enru(text, 'ru'))
        return 'ru'
    def command_enru(self, text, tr_type):
        """translate, only with online"""






        if not self.online:
            return "Offline, please test connect with '.connect' command"
        result = get_translate(text, tr_type)
        if not result or result['code'] != 200:
            self.command_connect()
            return "Error, not foud translate"
        return result['text']
................................................................................
            try:
                en = input('En [' + en_words + ']:') if en_words else input('En: ')
                if not en:
                    if not en_words:
                        raise IncorrectDbData()
                    else:
                        en = en_words



                try:
                    ru_words = self.command_enru(en, 'en')[0]
                except Exception as e:
                    if DEBUG: print(e)
                    ru_words = None
                ru = input('Ru [' + ru_words + ']:') if ru_words else input('Ru: ')
                if not ru:
................................................................................
                    break
                continue
            # may be use "else"
            print("Words added successfully, ID={0}".format(translate_id))
            break
        cur.close()
        return 'add'















    def command_add_kinds(self, cur, en, ru):
        """SQL queries for add-command"""
        token = hashlib.md5(bytes(en, 'utf-8')).hexdigest()
        # search token
        sql_list = "SELECT `token` FROM `term` WHERE `token`=(?)"
        cur.execute(sql_list, (token,))
        if not cur.fetchone():
            # insert in to tables
            sql_list1 = "INSERT INTO `term` (`token`, `en`) VALUES ((?), (?))"
            cur.execute(sql_list1, (token, prepare_str(en)))

        cur.execute("SELECT `id` FROM `translate` WHERE `term`=(?) AND `user_id`=(?)", (token, self.user_id))
        if cur.fetchone(): raise DublicationDbData()
        # add translate row
        sql_list2 = "INSERT INTO `translate` (`term`, `user_id`, `rus`) VALUES (?, ?, ?)"
        cur.execute(sql_list2, (token, self.user_id, prepare_str(ru)))
        translate_id = cur.lastrowid
        # add progress row
        sql_list3 = "INSERT INTO `progress` (`translate_id`) VALUES (?)"
        cur.execute(sql_list3, (translate_id,))
................................................................................
                cur.execute("UPDATE `test` SET `finished`=(?) WHERE `id`=(?)", (datetime.datetime.now(), test_id))
                # update progress
                cur.executemany("UPDATE `progress` SET `all`=`all`+1, `error`=`error`+:error WHERE `translate_id`=:translate_id", progress)
        except sqlite3.DatabaseError as er:
            self.prer(er)
            print("Error")
        else:
            print("Test successfully finished")
            self.print_test_result(to_save)
        cur.close()

    def print_test_result(self, tests, print_right=False):
        """print test info"""
        right, error = 0, 0
        print("*******YOUR RESULT********")
        for q in tests:
            if q['error']:
                error += 1
                print("Q#{0} (Error): {1}\n[correct] {2}\n[you] {3}\n".format(q['num'],q['question'],q['answer'],q['enter']))
            else:
                right += 1
                if print_right:
                    print("Q#{0}: {1}\n[correct] {2}\n[you] {3}\n".format(q['num'],q['question'],q['answer'],q['enter']))
        print("**************************")
        print("Result: {0} error(s) from {1}".format(error,(right + error)))

    def gen_question(self, cur, type_test, alreadyq):
        """genaration question for any test"""
        sql_list = "SELECT `translate`.`id`, `term`.`en`, `translate`.`rus` FROM `translate` LEFT JOIN `term` ON (`translate`.`term`=`term`.`token`) WHERE `translate`.`user_id`=" + str(self.user_id) + " AND (`translate`.`id` NOT IN (" + ", ".join(alreadyq) + "))"
        cur.execute(sql_list)
        for_search = cur.fetchall()
        if not for_search:
................................................................................
            print("Error, use <.testlist N> (N - number)")
        except sqlite3.DatabaseError as er:
            self.prer(er)
            print("Error")
        cur.close()
        return 'tetslist'


    def command_testinfo(self, arg=None):
        cur = self.connect.cursor()
        try:
            test_id = int(arg)
            # test info
            sql_list = "SELECT `test`.`id`, `test`.`name`, `test`.`created`, `test`.`finished` FROM `test` WHERE `test`.`user_id`=(?) AND `test`.`id`=(?);"
            cur.execute(sql_list, (self.user_id, test_id))
................................................................................
            finished = datetime.datetime.strptime(test[3], "%Y-%m-%d %H:%M:%S.%f")
            print("ID={0}, type: {1}, created: {2}, finished: {3}\n".format(test[0], test[1], created.strftime("%d.%m.%Y %H:%M:%S"), finished.strftime("%d.%m.%Y %H:%M:%S")))
            # results
            cur.execute("SELECT `result`.`number`, `result`.`question`, `result`.`answer`, `result`.`enter`, `result`.`error` FROM `result` WHERE `result`.`test_id`=(?) ORDER BY `result`.`number`;", (test_id,))
            for_print = []
            for row in cur.fetchall():
                for_print.append({'num': row[0], 'question': row[1], 'answer': row[2], 'enter': row[3], 'error': row[4]})
            self.print_test_result(for_print, True)
        except (ValueError, TypeError) as er:
            self.prer(er)
            print("Error, use <.tesinfo ID> (ID - number)")
        except sqlite3.DatabaseError as er:
            self.prer(er)
            print("Error")
        cur.close()
        return 'testinfo'








>
>
>
>
>
>







 







>
>
>







 







>
>
>
>
>
>
>
>
>
>
>
>
>
>











>
|
|







 







|
|


|












|







 







<







 







|









273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
...
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
...
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
...
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
...
691
692
693
694
695
696
697

698
699
700
701
702
703
704
...
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
        return 'en'
    def command_ru(self, text):
        """ru-en translate"""
        print(self.command_enru(text, 'ru'))
        return 'ru'
    def command_enru(self, text, tr_type):
        """translate, only with online"""
        global DEBUG
        # found in offline DB
        alreadyEx = self.alreadyex(text, tr_type)
        if alreadyEx: 
            if DEBUG: print("[offline]")
            return alreadyEx[0]
        if not self.online:
            return "Offline, please test connect with '.connect' command"
        result = get_translate(text, tr_type)
        if not result or result['code'] != 200:
            self.command_connect()
            return "Error, not foud translate"
        return result['text']
................................................................................
            try:
                en = input('En [' + en_words + ']:') if en_words else input('En: ')
                if not en:
                    if not en_words:
                        raise IncorrectDbData()
                    else:
                        en = en_words
                # check en translate
                if self.alreadyex(en): raise DublicationDbData
                # get translate
                try:
                    ru_words = self.command_enru(en, 'en')[0]
                except Exception as e:
                    if DEBUG: print(e)
                    ru_words = None
                ru = input('Ru [' + ru_words + ']:') if ru_words else input('Ru: ')
                if not ru:
................................................................................
                    break
                continue
            # may be use "else"
            print("Words added successfully, ID={0}".format(translate_id))
            break
        cur.close()
        return 'add'

    def alreadyex(self, enru, typetr='en'):
        """check en words in DB"""
        cur = self.connect.cursor()
        if typetr == 'en':
            addstr = "SELECT `rus` FROM `translate` WHERE `term`=(?) AND `user_id`=(?)"
            params = (hashlib.md5(bytes(enru, 'utf-8')).hexdigest(), self.user_id)
        else:
            addstr = "SELECT `term`.`en` FROM `translate` LEFT JOIN `term` ON (`translate`.`term`=`term`.`token`) WHERE `translate`.`rus` LIKE (?) AND `translate`.`user_id`=(?) LIMIT 1;"
            params = (prepare_str(enru), self.user_id)
        cur.execute(addstr, params)
        result = cur.fetchone()
        cur.close()
        return result

    def command_add_kinds(self, cur, en, ru):
        """SQL queries for add-command"""
        token = hashlib.md5(bytes(en, 'utf-8')).hexdigest()
        # search token
        sql_list = "SELECT `token` FROM `term` WHERE `token`=(?)"
        cur.execute(sql_list, (token,))
        if not cur.fetchone():
            # insert in to tables
            sql_list1 = "INSERT INTO `term` (`token`, `en`) VALUES ((?), (?))"
            cur.execute(sql_list1, (token, prepare_str(en)))
        # done in self.alreadyex
        # cur.execute("SELECT `id` FROM `translate` WHERE `term`=(?) AND `user_id`=(?)", (token, self.user_id))
        # if cur.fetchone(): raise DublicationDbData()
        # add translate row
        sql_list2 = "INSERT INTO `translate` (`term`, `user_id`, `rus`) VALUES (?, ?, ?)"
        cur.execute(sql_list2, (token, self.user_id, prepare_str(ru)))
        translate_id = cur.lastrowid
        # add progress row
        sql_list3 = "INSERT INTO `progress` (`translate_id`) VALUES (?)"
        cur.execute(sql_list3, (translate_id,))
................................................................................
                cur.execute("UPDATE `test` SET `finished`=(?) WHERE `id`=(?)", (datetime.datetime.now(), test_id))
                # update progress
                cur.executemany("UPDATE `progress` SET `all`=`all`+1, `error`=`error`+:error WHERE `translate_id`=:translate_id", progress)
        except sqlite3.DatabaseError as er:
            self.prer(er)
            print("Error")
        else:
            print("Test successfully finished, ID={}.".format(test_id))
            self.print_test_result(to_save, test_id, False)
        cur.close()

    def print_test_result(self, tests, test_id, print_right=False):
        """print test info"""
        right, error = 0, 0
        print("*******YOUR RESULT********")
        for q in tests:
            if q['error']:
                error += 1
                print("Q#{0} (Error): {1}\n[correct] {2}\n[you] {3}\n".format(q['num'],q['question'],q['answer'],q['enter']))
            else:
                right += 1
                if print_right:
                    print("Q#{0}: {1}\n[correct] {2}\n[you] {3}\n".format(q['num'],q['question'],q['answer'],q['enter']))
        print("**************************")
        print("Test ID={2}. Result: {0} error(s) from {1}".format(error,(right + error), test_id))

    def gen_question(self, cur, type_test, alreadyq):
        """genaration question for any test"""
        sql_list = "SELECT `translate`.`id`, `term`.`en`, `translate`.`rus` FROM `translate` LEFT JOIN `term` ON (`translate`.`term`=`term`.`token`) WHERE `translate`.`user_id`=" + str(self.user_id) + " AND (`translate`.`id` NOT IN (" + ", ".join(alreadyq) + "))"
        cur.execute(sql_list)
        for_search = cur.fetchall()
        if not for_search:
................................................................................
            print("Error, use <.testlist N> (N - number)")
        except sqlite3.DatabaseError as er:
            self.prer(er)
            print("Error")
        cur.close()
        return 'tetslist'


    def command_testinfo(self, arg=None):
        cur = self.connect.cursor()
        try:
            test_id = int(arg)
            # test info
            sql_list = "SELECT `test`.`id`, `test`.`name`, `test`.`created`, `test`.`finished` FROM `test` WHERE `test`.`user_id`=(?) AND `test`.`id`=(?);"
            cur.execute(sql_list, (self.user_id, test_id))
................................................................................
            finished = datetime.datetime.strptime(test[3], "%Y-%m-%d %H:%M:%S.%f")
            print("ID={0}, type: {1}, created: {2}, finished: {3}\n".format(test[0], test[1], created.strftime("%d.%m.%Y %H:%M:%S"), finished.strftime("%d.%m.%Y %H:%M:%S")))
            # results
            cur.execute("SELECT `result`.`number`, `result`.`question`, `result`.`answer`, `result`.`enter`, `result`.`error` FROM `result` WHERE `result`.`test_id`=(?) ORDER BY `result`.`number`;", (test_id,))
            for_print = []
            for row in cur.fetchall():
                for_print.append({'num': row[0], 'question': row[1], 'answer': row[2], 'enter': row[3], 'error': row[4]})
            self.print_test_result(for_print, test_id, True)
        except (ValueError, TypeError) as er:
            self.prer(er)
            print("Error, use <.tesinfo ID> (ID - number)")
        except sqlite3.DatabaseError as er:
            self.prer(er)
            print("Error")
        cur.close()
        return 'testinfo'

Changes to db.sqlite.

cannot compute difference between binary files