Ejemplo n.º 1
0
    def __init__(self, hours, 
            taskdb=TASK_DB, wantdb=WANT_DB, breakdb=BREAK_DB):
        
        
        self.hours = hours
        self.generator = TimeSlotGenerator(hours)
       
        self.task_adapter = TaskJsonAdapter(file_name = taskdb)
        self.want_adapter = WantJsonAdapter(file_name = wantdb)
        self.break_adapter = BreakJsonAdapter(file_name = breakdb)


        self.scorer = Scorer(db= None, tasks= self.task_adapter.items)

        self.i_index = 0
        self.g_index = 0
        self.n_index = 0

        self.i_items = []
        self.g_items = []
        self.n_items = []

        # fill the items in
        self._fill_items() 


        self.schedule = self.make_schedule()
Ejemplo n.º 2
0
def exam(data: list,
         src_lang: str,
         dest_lang: str,
         random_test: bool = False) -> None:
    print(
        f"Let's start with a {src_lang.upper()} to {dest_lang.upper()} test!")
    scorer = Scorer()
    for elem in data:
        if random_test and random() >= 0.5:
            _lang = src_lang
            src_lang = dest_lang
            dest_lang = _lang
        try:
            ### put this into a function
            os.system('clear')
            src_word = elem[src_lang]
            dest_word = elem[dest_lang]
            comment = elem.get('comment', str())
            answer = str()
            scorer.print_stats()
            first_attempt = True
            while answer != dest_word:
                answer = input(
                    f"\n------\nTranslate {src_word if not comment else f'{src_word} ({comment})'} from {src_lang.upper()} to {dest_lang.upper()}:\n\n"
                ).strip()
                if answer != dest_word:
                    print('\nBad guess, m**********r')
                    if first_attempt:
                        scorer.failure()
                    first_attempt = False
            if first_attempt:
                scorer.success()
            print('\n')
        except KeyError:
            print(f"{elem} doesn't have the appropriate keys!")
    scorer.print_final_score()
    async def dictionary_attack(self, cipher_text):
        """Schedules the sub-tasks to perform a dictionary attack on the given cipher-text."""
        keys = deque()
        candidate_key = CandidateKey(cipher_text, {}, {}, self.frequencies)
        tasks = self.dictionary_attack_tasks(candidate_key, keys)

        while len(tasks) > 0:
            new_tasks = set()

            for task in asyncio.as_completed(tasks):
                sub_tasks = await task
                new_tasks = new_tasks.union(sub_tasks)

            tasks = new_tasks

        return Scorer(self.dictionary, self.frequencies).best_key([candidate_key] + list(keys))
Ejemplo n.º 4
0
    def setUp(self):

        two_days = datetime.datetime.today() + datetime.timedelta(days=2)
        three_days = datetime.datetime.today() + datetime.timedelta(days=3)
        five_days = datetime.datetime.today() + datetime.timedelta(days=5)
        seven_days = datetime.datetime.today() + datetime.timedelta(days=7)

        self.exam = Exam('Test Exam', seven_days)
        self.project = Project('Test Project', five_days)
        self.paper = Paper('Test Paper', three_days)
        self.homework = Homework('Test Homework', two_days)

        self.db = MockDB()
        self.db.save(self.exam)
        self.db.save(self.project)
        self.db.save(self.paper)
        self.db.save(self.homework)
        
        self.scorer = Scorer(self.db, [self.exam, self.project, self.paper, self.homework])
Ejemplo n.º 5
0
class Scheduler(object):

    def __init__(self, hours, 
            taskdb=TASK_DB, wantdb=WANT_DB, breakdb=BREAK_DB):
        
        
        self.hours = hours
        self.generator = TimeSlotGenerator(hours)
       
        self.task_adapter = TaskJsonAdapter(file_name = taskdb)
        self.want_adapter = WantJsonAdapter(file_name = wantdb)
        self.break_adapter = BreakJsonAdapter(file_name = breakdb)


        self.scorer = Scorer(db= None, tasks= self.task_adapter.items)

        self.i_index = 0
        self.g_index = 0
        self.n_index = 0

        self.i_items = []
        self.g_items = []
        self.n_items = []

        # fill the items in
        self._fill_items() 


        self.schedule = self.make_schedule()
   
 
 
    def _fill_items(self):
 
        for task in self.task_adapter.items:
            
            placement = self.scorer.get_placement(task)
    
            if placement == 'I':
                self.i_items.append(task)
            
            elif placement == 'G':
                self.g_items.append(task)

            elif placement == 'R':
                self.n_items.append(task)
 
            elif placement == 'N':
                self.n_items.append(task)
            else:
                pass

 
  
    def _reset_index(self): 
        self.i_index = 0
        self.g_index = 0
        self.n_index = 0
        return
   
    
    def make_schedule(self, repeat_items=True):
        
        schedule = []
        time_slots = self.generator.time_slots
        
        chosen_item_list = self.i_items
        chosen_index = self.i_index

        number = 1


        for slot in time_slots:
           
            #breaks get 15 min slots
            if slot == 15:

                print("A break")
                number_items = len(self.break_adapter.items)
                random_int = random.randint(0, number_items-1)
                schedule.append({"number" : number, "timeslot" : slot, "item" : self.break_adapter.get_ith_json(random_int)})

            #a want or task
            else:
                random_int = random.randint(1,2)
                
                # a want
                if random_int == 1:

                    print("A want")
                    number_items = len(self.want_adapter.items)
                    random_int = random.randint(0, number_items-1)
                    schedule.append({"number" : number, "timeslot" : slot, "item" : self.want_adapter.get_ith_json(random_int)})

                # a task
                else:
          
                    print("A task")          
                    
                    if self.i_index < len(self.i_items):
                        print("Item in I bucket")
                        chosen_item_list = self.i_items
                        chosen_index = self.i_index
                        self.i_index = self.i_index + 1
                    else:
                        if self.g_index < len(self.g_items): 
                            print("Item in G bucket")
                            chosen_item_list = self.g_items
                            chosen_index = self.g_index
                            self.g_index = self.g_index + 1
                        else:
                            if self.n_index < len(self.n_items):
                                print("Item in N bucket")                
                                chosen_item_list = self.n_items
                                chosen_index = self.n_index
                                self.n_index = self.n_index + 1
                            else:
                                # we will need to reset or quit
                                if repeat_items:                 
                                    print("Resetting buckets")
                                    self._reset_index()
                                    #starts off with the first thing of the most recent list
                                    chosen_index = 0
                                else:
                                    #return schedule
                                    pass
                    
                    
                    task = chosen_item_list[chosen_index]
                    placement = self.scorer.get_placement(task)
                   
                    task_struct = {
                        "class" : "Task",
                        "type" : str(type(task)),
                        "description" : task.name,
                        "due_date" : str(task.due_date),
                        "score" : task.get_score(),
                        "placement" : placement      
                    } 
                    schedule.append({"number" : number, "timeslot" : slot, "item" : task_struct}) 
                   
        
            number = number + 1

        return schedule
        

    def print_schedule(self):

        in_minutes = self.hours*60
        total = 0


        for item in self.schedule:
           

            total = total + item["timeslot"]
            time_remaining = in_minutes - total

            print("|--------------------------------->")
            
            print("|Activity length : %s minutes\n|Activity : %s\n|Time Spent : %s minutes\n|Time Remaining : %s minutes" % (
                item["timeslot"], item["item"], total, time_remaining))
 

        print("|--------------------------------->")
Ejemplo n.º 6
0
 def __init__(self):
     self.root = TrieNode()
     self.scorer = Scorer()
Ejemplo n.º 7
0
class Trie:
    def __init__(self):
        self.root = TrieNode()
        self.scorer = Scorer()

    def insert(self, s):
        self.insert_helper(self.root, s, 0)

    def insert_helper(self, node, s, i):
        if i == len(s):
            node.is_word = True
        else:
            curletter = s[i]
            if curletter not in node.children:
                node.children[curletter] = TrieNode()
            self.insert_helper(node.children[curletter], s, i + 1)

    def contains(self, s):
        return self.contains_helper(self.root, s)

    def contains_helper(self, node, s):
        if s == "":
            return node.is_word
        curletter = s[0]
        if curletter in node.children:
            return self.contains_helper(node.children[curletter], s[1:])
        else:
            return False

    # return a StartSequence that includes the word template
    def get_plays_constrained(self, start_seq, tiles, board, dist):
        templates = self.get_words_constrained(start_seq, tiles, board)

        plays = []
        x, y = start_seq.x, start_seq.y
        ish = start_seq.ish
        for template in templates:
            if not all(c is None for c in template) and len(template) >= dist:
                play = StartSequence(x, y, template, ish)
                score = self.score_play(play, board)
                play.points = score
                plays.append(play)
        return plays

    def get_words(self, template):
        return self.get_words_helper(template, self.root)

    def get_chars(self, template):
        # check that there is only one None in the template; error if > 1
        from functools import reduce
        num_blanks = reduce((lambda n, c: n + int(not c)), template, 0)
        if num_blanks != 1:
            raise RuntimeError(f"Template should have 1 blank. {num_blanks} blanks.")
        return self.get_chars_helper(template, self.root)

    def get_words_constrained(self, start_seq, tiles, board):
        s_list = []
        self.get_words_constrained_helper(start_seq, self.root, tiles, board, s_list)
        return s_list

    def get_words_helper(self, template, node, s = ""):
        # while we still have spaces left to fill
        if template != []:
            curspot = template[0]
            if curspot:
                child_words = []
                if curspot in node.children:
                    temps = s + curspot
                    child_words = self.get_words_helper(template[1:],
                        node.children[curspot], temps)
                return child_words
            else:
                words = []
                for next in node.children:
                    temps = s + next
                    child_words = self.get_words_helper(template[1:],
                        node.children[next], temps)
                    if child_words:
                        words.extend(child_words)
                return words
        else:
            if node.is_word:
                return [s]

    # get possible characters for first blank
    def get_chars_helper(self, template, node, c = ""):
        # while we still have spaces left to fill
        if template != []:
            curspot = template[0]
            if curspot:
                child_words = []
                if curspot in node.children:
                    child_words = self.get_chars_helper(template[1:],
                        node.children[curspot], c)
                return child_words
            else:
                chars = []
                for next in node.children:
                    child_words = self.get_chars_helper(template[1:],
                        node.children[next], next)
                    if child_words:
                        chars.extend(child_words)
                return chars
        else:
            if node.is_word:
                return [c]

    def get_words_constrained_helper(self, start_seq, node, tiles, board, s_list, s = []):
        curX, curY = start_seq.x, start_seq.y
        template = start_seq.template
        ish = start_seq.ish

        if template != []:
            curspot = template[0]
            if curspot:
                if curspot in node.children:
                    temps = s + [None]
                    if ish:
                        temp_start_seq = StartSequence(curX + 1, curY, template[1:], ish)
                    else:
                        temp_start_seq = StartSequence(curX, curY + 1, template[1:], ish)
                    child_words = self.get_words_constrained_helper(temp_start_seq,
                        node.children[curspot], tiles, board, s_list, temps)
            else:
                if node.is_word:
                    s_list.append(s)
                crosscheck = board.crosschecks[curY][curX].v_check if ish else board.crosschecks[curY][curX].h_check
                to_traverse = list(crosscheck.intersection(set(tiles)))

                for next in to_traverse:
                    if next in node.children:
                        temps = s + [next]
                        if ish:
                            temp_start_seq = StartSequence(curX + 1, curY, template[1:], ish)
                        else:
                            temp_start_seq = StartSequence(curX, curY + 1 , template[1:], ish)
                        remaining_tiles = tiles[:]
                        remaining_tiles.remove(next)
                        self.get_words_constrained_helper(temp_start_seq,
                            node.children[next], remaining_tiles, board, s_list, temps)
        else:
            if node.is_word:
                s_list.append(s)

    def score_play(self, play, board):
        x, y = play.x, play.y
        ish = play.ish
        template = play.template
        dX, dY = (1, 0) if ish else (0, 1)
        mult_score = 0
        base_score = 0
        factor = 1
        for c in template:
            if not c:
                mult_score += self.scorer.get_score_old(board.tiles[y][x])
            else:
                square_score, square_factor = self.scorer.get_score_new(x, y, c)
                mult_score += square_score
                factor *= square_factor
                base_score += self.score_helper(Coord(x, y), board, ish)
            x += dX
            y += dY
        return (mult_score * factor) + base_score

    def score_helper(self, coord, board, ish):
        base_score = 0
        dX, dY = (0, 1) if ish else (1, 0)
        x, y = coord[0] - 1, coord[1] - 1
        while (x >= 0 and y >= 0) and board.tiles[y][x]:

            base_score += self.scorer.get_score_old(board.tiles[y][x])
            x -= dX
            y -= dY
        x, y = coord[0] + 1, coord[1] + 1
        while (x < board.size and y < board.size) and board.tiles[y][x]:
            base_score += self.scorer.get_score_old(board.tiles[y][x])
            x += dX
            y += dY
        return base_score

    scrabble_words = None

    @staticmethod
    def words():
        if Trie.scrabble_words is None:
            with open("assets/scrabble_dictionary.txt") as f:
                words = f.read().lower().splitlines()
            Trie.scrabble_words = Trie()
            for word in words:
                Trie.scrabble_words.insert(word)
        return Trie.scrabble_words
Ejemplo n.º 8
0
class TestScorerClass(unittest.TestCase):

    def setUp(self):

        two_days = datetime.datetime.today() + datetime.timedelta(days=2)
        three_days = datetime.datetime.today() + datetime.timedelta(days=3)
        five_days = datetime.datetime.today() + datetime.timedelta(days=5)
        seven_days = datetime.datetime.today() + datetime.timedelta(days=7)

        self.exam = Exam('Test Exam', seven_days)
        self.project = Project('Test Project', five_days)
        self.paper = Paper('Test Paper', three_days)
        self.homework = Homework('Test Homework', two_days)

        self.db = MockDB()
        self.db.save(self.exam)
        self.db.save(self.project)
        self.db.save(self.paper)
        self.db.save(self.homework)
        
        self.scorer = Scorer(self.db, [self.exam, self.project, self.paper, self.homework])
        

    def tearDown(self):
        self.scorer = None
        

    def test_task_list(self):

        self.assertTrue(self.exam in self.scorer.task_list)
        self.assertTrue(self.project in self.scorer.task_list)
        self.assertTrue(self.paper in self.scorer.task_list)
        self.assertTrue(self.homework in self.scorer.task_list)

        self.assertEqual(self.scorer.score_total, 34)


    def test_print_all_scores(self):
        #self.scorer.print_all_scores()
        pass



    # MUST : revise this test, the scores will change
    # as the dates do... doh
    def test_get_mean(self):
        actual_mean = self.scorer.get_mean()
        expected_mean = 8
        self.assertEqual(actual_mean, expected_mean)


    # MAY : come back and fix the test so that the decimal goes
    # out to like 5 or so digits, rather than just flooring it
    def test_variance(self):
        actual_variance = int(self.scorer.get_variance())
        expected_variance = 4
        self.assertEqual(actual_variance, expected_variance)

    # MAY : same
    def test_standard_dev(self):

        actual_standard_dev = int(self.scorer.get_standard_dev())
        expected_standard_dev = 2
        self.assertEqual(actual_standard_dev, expected_standard_dev)

    def test_placement(self):
        #print (self.scorer.placement_list)
        pass