Exemplo n.º 1
0
    def __init__(self, raw, kernel_dir=None):
        # Read a header_t structure
        self.hdr = my_from_buffer_copy(X86DumpHeader, raw)
        assert self.hdr.magic == CPU_STATE_MAGIC
        assert self.hdr.version == CPU_STATE_VERSION

        if not is_valid_type(self.hdr.type):
            # INVALID state
            self.cpus = []
            self.mem = X86DumpMemory("")
        else:
            # VALID state
            # Read 0+ cpu_state_t structures
            self.cpus = []
            next_byte = sizeof(header_t)
            for i in range(self.hdr.cpusno):
                cpu = my_from_buffer_copy(X86DumpCpuState, raw[next_byte:])
                next_byte += sizeof(cpu_state_t)
                self.cpus.append(cpu)

            # Read memory
            self.mem = X86DumpMemory(raw[next_byte:])

            # Fix DR7 register (if needed)
            # for i in range(len(self.cpus)):
            #    self.__fix_dr7(i)

        # Parse kernel's symbols
        kernel_md5 = self.hdr.kernel_checksum
        if isfile(KERNEL) and md5(open(KERNEL)) == kernel_md5:
            self.kernel = Elf(KERNEL)
        elif kernel_dir and isfile(joinpath(kernel_dir, kernel_md5)):
            self.kernel = Elf(joinpath(kernel_dir, kernel_md5))
        else:
            self.kernel = None
Exemplo n.º 2
0
    def test_duration_update(self):
        
        elf = Elf(1)
        elf_future = Elf(2)
        elf_future.wait_till_next_day()

        toypool = ToyPool()
        toy1 = Toy(1, "2014 1 1 8 0", 116)
        toy2 = Toy(2, "2014 1 1 8 0", 116)
        toy3 = Toy(3, "2014 1 1 8 0", 117)
        toy4 = Toy(4, "2014 1 1 8 0", 117)
        toy5 = Toy(5, "2014 1 1 8 0", 118)
        toy6 = Toy(6, "2014 1 1 8 0", 118)
        toypool.push_toy_in_waiting_list(toy1)
        toypool.push_toy_in_waiting_list(toy2)
        toypool.push_toy_in_waiting_list(toy3)
        toypool.push_toy_in_waiting_list(toy4)
        toypool.push_toy_in_waiting_list(toy5)
        toypool.push_toy_in_waiting_list(toy6)

        toypool.update_available_toy_list_according_to_elf(elf)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        toy = toypool.get_next_shortest_toy_for_elf(elf)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        toy = toypool.get_next_longest_toy_for_elf(elf)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        toy6 = Toy(6, "2014 1 1 9 5", 118)
        toypool.push_toy_in_waiting_list(toy6)
        toypool.update_available_toy_list_according_to_elf(elf_future)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        #print toypool.get_available_toy_duration()
        #print toypool.get_hash_toy_duration_timestamp()

        toy = toypool.get_toy_by_duration_for_elf(elf, 118)
        toy = toypool.get_toy_by_duration_for_elf(elf, 118)
        toy = toypool.get_toy_by_duration_for_elf(elf, 118)

        #print toypool.get_available_toy_duration()
        #print toypool.get_hash_toy_duration_timestamp()

        self.assertEquals(toypool.get_available_toy_duration(), [116, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 118])
Exemplo n.º 3
0
def powerAvailableEstimation(big_jobs, boosters, hrs):
    '''
      Assume a rating of 0.25, total gain in ratings that can be obtained for different jobs 
    '''

    total_gain              = 0.0;
    ratio_big_jobs_boosters = len(big_jobs) / float( len(big_jobs)  + len(boosters) );

    #Dummy Elf
    dummy_elf               = Elf(0);
    dummy_elf.rating        = 0.25;

    work_start_time         = 540; #All boosters are played with maximum sanctioned time

    shuffle(boosters);

    for job in boosters:

        #Assume the work starts at 9:00 on start of the day
        next_available_time, work_duration = \
            assign_elf_to_toy(work_start_time, dummy_elf, job[1], hrs);

        dummy_elf.update_elf(hrs, Toy(0, '2014 01 01 01 01' ,job[1]), work_start_time, work_duration); #Every toy has default arrival time(irrelevant)

        #Flip a coin and play a big job based on above probability
        if random.random() < ratio_big_jobs_boosters:
            #Big Job Played - Measure the gain
            if dummy_elf.rating > 0.25:
                total_gain += (dummy_elf.rating - 0.25);
            #Reinitialize the dummy_elf
            dummy_elf               = Elf(0);
            dummy_elf.rating        = 0.25;


    return total_gain;
Exemplo n.º 4
0
def main():
    with open("input.txt", "+r") as file:
        recipes = int(file.readlines()[0])

    # set up initial state
    scoreboard = [3, 7]
    elf1 = Elf(0)
    elf2 = Elf(1)
    print(elf1.current_index)

    # main update loop
    while scoreboard.__len__() < recipes + 12:

        # Calculate next recipe and append to scoreboard
        next_recipe = scoreboard[elf1.current_index] + scoreboard[
            elf2.current_index]

        if next_recipe > 9:
            scoreboard.append(1)
            scoreboard.append(next_recipe - 10)
        else:
            scoreboard.append(next_recipe)

        # set new current recipes for both elves
        elf1.cycle(scoreboard)
        elf2.cycle(scoreboard)

    for i in range(recipes, recipes + 10):
        print(scoreboard[i], end='', flush=True)
Exemplo n.º 5
0
def symbols(f):
    syms = {}

    f = Elf(f)
    for s in ["tcstartring"]:
        s = f.getSymbol(s)
        assert s
        syms[s.getName()] = (s.getAddress(), s.getSize(), f.getOffset(s.getAddress()))
    for s in [".tcring0", ".tcring1", ".tcring2", ".tcring3", ".tcringvm"]:
        s = f.getSection(s)
        assert s
        syms[s.getName()] = (s.getLowAddr(), s.getSize(), s.getOffset())

    return syms
Exemplo n.º 6
0
def main():
    with open("input.txt", "+r") as file:
        score_output = file.readlines()[0]

    match_check = [int(char) for char in score_output]

    # Expanding on initial state prevents having to check for length each round
    scoreboard = [3, 7, 1, 0, 1, 0, 1]
    elf1 = Elf(4)
    elf2 = Elf(6)

    # main update loop
    while True:

        # Calculate next recipe and append to scoreboard
        next_recipe = scoreboard[elf1.current_index] + scoreboard[elf2.current_index]

        if next_recipe > 9:
            scoreboard.append(1)
            if scoreboard[scoreboard.__len__() - match_check.__len__():] == match_check:
                break
            scoreboard.append(next_recipe-10)
        else:
            scoreboard.append(next_recipe)

        if scoreboard[scoreboard.__len__()-match_check.__len__():] == match_check:
            break

        # set new current recipes for both elves
        elf1.cycle(scoreboard)
        elf2.cycle(scoreboard)

    print(scoreboard.__len__()-match_check.__len__())
Exemplo n.º 7
0
    def __init__(self, num_elves):
        self.elves = []
        for i in xrange(1, num_elves + 1):
            elf = Elf(i)
            heapq.heappush(self.elves, (elf.next_available_time, elf))

        self.pending_toys = SortedCollection(key=itemgetter(1))
Exemplo n.º 8
0
def add_elf():
    global elves_list
    id = str(uuid.uuid4())
    name = str(input("podaj imie elfa \n "))
    elf = Elf(id, name, level)
    elves_list.append(elf)
    print("Dodano : " + str(elf))
    menu()
def create_elves(NUM_ELVES):
    """ Elves are stored in a sorted list using heapq to maintain their order by next available time.
    List elements are a tuple of (next_available_time, elf object)
    :return: list of elves
    """
    list_elves = []
    for i in xrange(1, NUM_ELVES + 1):
        list_elves.append(Elf(i))
    return list_elves
Exemplo n.º 10
0
def enter():
    global ui, elf, tile, tile_under, time

    ui = Ui()
    elf = Elf()
    tile = Tile()
    tile_under = Tile_under()
    time = get_time()

    game_world.add_object(tile_under, 0)
    game_world.add_object(tile, 1)
    game_world.add_object(elf, 2)
Exemplo n.º 11
0
def powerRequiredEstimation(big_jobs, hrs):
    """

    :param big_jobs:  List of Big Jobs
    :param hrs:  Hrs Object
    :return:
    """
    power_per_unit   = [];
    #Dummy Elf
    dummy_elf        = Elf(0);
    dummy_elf.rating = 0.25;


    for job in big_jobs:
        #Play the toys at min rating at 9:00 on start of the day
        sanctioned, unsanctioned = breakDownWork(dummy_elf.next_available_time, dummy_elf, job[1], hrs);
        power_per_unit.append(unsanctioned);

    total_power    = sum(power_per_unit);
    power_per_unit = [i/float(total_power) for i in power_per_unit];

    return power_per_unit;
Exemplo n.º 12
0
    def __init__(self, NUM_ELVES, toy_file):
        #Output file
        self.hrs                      = Hours()
        self.NUM_ELVES                = NUM_ELVES;
        self.ref_time                 = datetime.datetime(2014, 1, 1, 0, 0);
        self.toy_baskets              = dict();
        self.max_duration_log         = 11.0;  #Predetermined from analysis
        self.elves                    = dict(); #elf_id -> (elf Object, list of allocated toys, optimimum toy workflow)
        self.boost_productive_th      = 24; #All jobs with hr duration less than this qualify as boosters

        self.create_toy_baskets(toy_file)

        #Every elf maintains list of toys which it has to optically work on
        for i in xrange(1, NUM_ELVES+1):
            elf = Elf(i);
            self.elves[elf.id]  = (elf, [], []);
Exemplo n.º 13
0
    def setUp(self):
        toy_file = os.path.join(os.getcwd(), '..', 'DATA', 'toys_rev2.csv')
        self.toy_empty_pool = ToyPool()
        self.toy_filled_pool = ToyPool()
        self.toy_filled_pool.add_file_content(toy_file, 10)

        self.elf = Elf(1)
        self.toy_small_pool = ToyPool()
        self.toy1 = Toy(1, "2014 1 1 8 0", 600)
        self.toy2 = Toy(2, "2014 1 1 9 3", 60)
        self.toy3 = Toy(3, "2014 1 1 10 0", 2)
        self.toy4 = Toy(4, "2014 1 1 9 5", 60)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy1)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy2)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy3)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy4)
Exemplo n.º 14
0
 def initialize_all(self):
     print("Welcome to Kafustrok. Light blesses you. ")
     for i in range(self._DIMENSION):
         for j in range(self._DIMENSION):
             self._lands[i][j] = Land()
     for i in range(self._total_num):
         pos = self.get_un_occupied_position()
         if i < self._m:
             self.lands[pos.x][pos.y].occupied_obj = Monster(pos.x, pos.y, i, self)
         elif i < self._m + self._e:
             self.lands[pos.x][pos.y].occupied_obj = Elf(pos.x,pos.y, i - self._m, self)
         elif i < self._m + self._e + self._w:
             self.lands[pos.x][pos.y].occupied_obj = Warrior(pos.x, pos.y, i - self._m - self._e, self)
             self._teleportable_obj.append(self.lands[pos.x][pos.y].occupied_obj)
         else:
             self.lands[pos.x][pos.y].occupied_obj = Potion(pos.x, pos.y, i - self._m - self._e - self._w, self)
             self._teleportable_obj.append(self.lands[pos.x][pos.y].occupied_obj)
Exemplo n.º 15
0
    soln_file = os.path.join(os.getcwd(), '..', 'DATA', 'my_solution_fifth_num_elves_%d_prod_%s_minutes_%d_ratio_random_%s_min_duration_%d.csv' % (NUM_ELVES, PRODUCTIVITY_THRESHOLD_STR, MINUTES_LEFT_END_OF_DAY, RATIO_RANDOM_STR, MIN_DURATION))

    # Objet hours
    hrs = Hours()

    # Fichier dans lequel logger la solution
    w = open(soln_file, 'wb')
    wcsv = csv.writer(w)
    wcsv.writerow(['ToyId', 'ElfId', 'StartTime', 'Duration', 'Original_Toy_Duration', 'Old_Productivity', 'New_Productivity', 'Sanctioned', 'Unsanctioned'])

    # Iteration par elfe
    tmp = range(NUM_ELVES)
    random.shuffle(tmp)
    for i in tmp:
        num_elf = i + 1
        elf = Elf(num_elf)

        # Definition du nom de la file des jouets
        toy_file = os.path.join(os.getcwd(), "..", "DATA", "toy_for_elf_number_%d_out_of_%d.csv" % (num_elf, NUM_ELVES))

        # Création du pool de jouets
        mytoypool = ToyPool()
        mytoypool.add_file_content(toy_file)

        c = 0

        # Début de l'algorithme
        while not mytoypool.empty():

            c += 1
Exemplo n.º 16
0
    return optimize(*args);



# ======================================================================= #
# === MAIN === #

if __name__ == '__main__':
    args  = list(sys.argv[1:]);

    start = time.time();
    NUM_ELVES = 900;
    #Construct workflows for toys and dump them
    toy_file  = os.path.join(os.getcwd(), 'data/toys_rev2.csv');
    santa     = Santas_lab(NUM_ELVES, toy_file);
    santa.allocate_baskets_to_elf();

    #Contruct parameters as a list
    elf_worflows = [ (Elf(i), copy.copy(santa.elves[i][1]), copy.copy(santa.elves[i][2]) ) for i in xrange(1, NUM_ELVES+1) ];

    #Create a Thread pool.
    pool     = Pool();
    results  = pool.map( optimize_wrapper, elf_worflows );

    pool.close();
    pool.join();

    print("Last Job Completed in year : " + str(max(results)));
    print 'total runtime = {0}'.format(time.time() - start);

Exemplo n.º 17
0
class ToyPoolTest(unittest.TestCase):

    def setUp(self):
        toy_file = os.path.join(os.getcwd(), '..', 'DATA', 'toys_rev2.csv')
        self.toy_empty_pool = ToyPool()
        self.toy_filled_pool = ToyPool()
        self.toy_filled_pool.add_file_content(toy_file, 10)

        self.elf = Elf(1)
        self.toy_small_pool = ToyPool()
        self.toy1 = Toy(1, "2014 1 1 8 0", 600)
        self.toy2 = Toy(2, "2014 1 1 9 3", 60)
        self.toy3 = Toy(3, "2014 1 1 10 0", 2)
        self.toy4 = Toy(4, "2014 1 1 9 5", 60)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy1)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy2)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy3)
        self.toy_small_pool.push_toy_in_waiting_list(self.toy4)

    def test_walk_all_durations(self):

        toy_pool = ToyPool()
        toy1 = Toy(1, "2014 1 1 9 5", 30)
        toy2 = Toy(2, "2014 1 1 10 5", 20)
        toy3 = Toy(3, "2014 1 1 8 5", 10)
        toy_pool.push_toy_in_waiting_list(toy1)
        toy_pool.push_toy_in_waiting_list(toy2)
        toy_pool.push_toy_in_waiting_list(toy3)

        elf_pool = ElfPool(2)

        elf1 = elf_pool.next_available_elf()
        toy_pool.update_available_toy_list_according_to_elf(elf1) # 1 et 2 dans available

        # On prends un 31
        toy = toy_pool.get_toy_by_duration_for_elf(elf1, 30)
        self.assertEquals(toy, toy3)

    def test_behaviour(self):

        toy_pool = ToyPool()
        toy1 = Toy(1, "2014 1 1 9 5", 20)
        toy2 = Toy(2, "2014 1 1 8 5", 30)
        toy3 = Toy(3, "2014 1 1 8 3", 15)
        toy_pool.push_toy_in_waiting_list(toy1)
        toy_pool.push_toy_in_waiting_list(toy2)
        toy_pool.push_toy_in_waiting_list(toy3)

        elf_pool = ElfPool(2)

        elf1 = elf_pool.next_available_elf()

        toy_pool.update_available_toy_list_according_to_elf(elf1) # 1 et 2 dans available

        # on essaye de prendre un duration 10
        toy = toy_pool.get_toy_by_duration_for_elf(elf1, 10)
        self.assertTrue(toy is None)

        # on essaye de prendre un duration 30
        toy = toy_pool.get_toy_by_duration_for_elf(elf1,30)
        self.assertEquals(toy, toy2)

        # on pousse l'elfe au lendemain
        elf1.wait_till_next_day()

        # on mets à jour
        toy_pool.update_available_toy_list_according_to_elf(elf1)

        # changment d'elfe
        elf2 = elf_pool.next_available_elf()

        # On essaye de prendre un duration 14
        toy = toy_pool.get_toy_by_duration_for_elf(elf2, 14)
        self.assertTrue(toy is None)

        # On essaye de prendre un duration 21
        toy = toy_pool.get_toy_by_duration_for_elf(elf2, 21)
        self.assertEquals(toy, toy3)


    def test_duration_update(self):
        
        elf = Elf(1)
        elf_future = Elf(2)
        elf_future.wait_till_next_day()

        toypool = ToyPool()
        toy1 = Toy(1, "2014 1 1 8 0", 116)
        toy2 = Toy(2, "2014 1 1 8 0", 116)
        toy3 = Toy(3, "2014 1 1 8 0", 117)
        toy4 = Toy(4, "2014 1 1 8 0", 117)
        toy5 = Toy(5, "2014 1 1 8 0", 118)
        toy6 = Toy(6, "2014 1 1 8 0", 118)
        toypool.push_toy_in_waiting_list(toy1)
        toypool.push_toy_in_waiting_list(toy2)
        toypool.push_toy_in_waiting_list(toy3)
        toypool.push_toy_in_waiting_list(toy4)
        toypool.push_toy_in_waiting_list(toy5)
        toypool.push_toy_in_waiting_list(toy6)

        toypool.update_available_toy_list_according_to_elf(elf)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        toy = toypool.get_next_shortest_toy_for_elf(elf)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        toy = toypool.get_next_longest_toy_for_elf(elf)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        toy6 = Toy(6, "2014 1 1 9 5", 118)
        toypool.push_toy_in_waiting_list(toy6)
        toypool.update_available_toy_list_according_to_elf(elf_future)

        self.assertEquals(toypool.get_available_toy_duration(), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 117, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 117, 118])

        #print toypool.get_available_toy_duration()
        #print toypool.get_hash_toy_duration_timestamp()

        toy = toypool.get_toy_by_duration_for_elf(elf, 118)
        toy = toypool.get_toy_by_duration_for_elf(elf, 118)
        toy = toypool.get_toy_by_duration_for_elf(elf, 118)

        #print toypool.get_available_toy_duration()
        #print toypool.get_hash_toy_duration_timestamp()

        self.assertEquals(toypool.get_available_toy_duration(), [116, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_timestamp().keys()), [116, 118])
        self.assertEquals(sorted(toypool.get_hash_toy_duration_values().keys()), [116, 118])

        #print toypool.get_hash_toy_duration_timestamp()

    
    def test_get_next_longest_toy(self):

        self.elf.wait_till_next_day()
        self.toy_small_pool.update_available_toy_list_according_to_elf(self.elf)

        self.assertEquals(self.toy_small_pool.length_waiting_list(), 0)
        self.assertEquals(self.toy_small_pool.length_available_list(), 4)

        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [2, 60, 600])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_timestamp().keys()), [2, 60, 600])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_values().keys()), [2, 60, 600])
        toy = self.toy_small_pool.get_next_longest_toy_for_elf(self.elf)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [2, 60])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_timestamp().keys()), [2, 60])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_values().keys()), [2, 60])

        self.assertEquals(toy, self.toy1)

        self.assertEquals(self.toy_small_pool.length_waiting_list(), 0)
        self.assertEquals(self.toy_small_pool.length_available_list(), 3)

        toy = self.toy_small_pool.get_next_longest_toy_for_elf(self.elf)
        self.assertEquals(toy.get_duration(), 60)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [2, 60])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_timestamp().keys()), [2, 60])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_values().keys()), [2, 60])

        toy = self.toy_small_pool.get_next_longest_toy_for_elf(self.elf)
        self.assertEquals(toy.get_duration(), 60)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [2])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_timestamp().keys()), [2])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_values().keys()), [2])

        toy = self.toy_small_pool.get_next_longest_toy_for_elf(self.elf)
        self.assertEquals(toy.get_duration(), 2)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_timestamp().keys()), [])
        self.assertEquals(sorted(self.toy_small_pool.get_hash_toy_duration_values().keys()), [])

        toy = self.toy_small_pool.get_next_longest_toy_for_elf(self.elf)
        self.assertTrue(toy is None)

    def test_get_next_shortest_toy(self):

        self.elf.wait_till_next_day()
        self.toy_small_pool.update_available_toy_list_according_to_elf(self.elf)

        self.assertEquals(self.toy_small_pool.length_waiting_list(), 0)
        self.assertEquals(self.toy_small_pool.length_available_list(), 4)

        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [2, 60, 600])
        toy = self.toy_small_pool.get_next_shortest_toy_for_elf(self.elf)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [60, 600])


        self.assertEquals(toy, self.toy3)

        self.assertEquals(self.toy_small_pool.length_waiting_list(), 0)
        self.assertEquals(self.toy_small_pool.length_available_list(), 3)

        toy = self.toy_small_pool.get_next_shortest_toy_for_elf(self.elf)
        self.assertEquals(toy.get_duration(), 60)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [60, 600])

        toy = self.toy_small_pool.get_next_shortest_toy_for_elf(self.elf)
        self.assertEquals(toy.get_duration(), 60)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [600])

        toy = self.toy_small_pool.get_next_shortest_toy_for_elf(self.elf)
        self.assertEquals(toy.get_duration(), 600)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [])

        toy = self.toy_small_pool.get_next_shortest_toy_for_elf(self.elf)
        self.assertTrue(toy is None)

    def test_push_toy_in_available_list(self):

        self.assertEquals(self.toy_small_pool.length_waiting_list(), 4)
        self.assertEquals(self.toy_small_pool.length_available_list(), 0)

        toy_timestamp, toy = self.toy_small_pool.pop_toy_from_waiting_list()

        self.toy_small_pool.push_toy_in_available_list(toy)
        
        self.assertEquals(self.toy_small_pool.length_waiting_list(), 3)
        self.assertEquals(self.toy_small_pool.length_available_list(), 1)

        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [600])

        self.assertTrue(self.toy_small_pool.has_available_toy(self.toy1))
        self.assertFalse(self.toy_small_pool.has_available_toy(self.toy2))
        self.assertFalse(self.toy_small_pool.has_available_toy(self.toy3))
        self.assertFalse(self.toy_small_pool.has_available_toy(self.toy4))

        self.elf.wait_till_next_day()
        self.toy_small_pool.update_available_toy_list_according_to_elf(self.elf)

        self.assertEquals(self.toy_small_pool.length_waiting_list(), 0)
        self.assertEquals(self.toy_small_pool.length_available_list(), 4)

        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [2, 60, 600])

        self.assertTrue(self.toy_small_pool.has_available_toy(self.toy1))
        self.assertTrue(self.toy_small_pool.has_available_toy(self.toy2))
        self.assertTrue(self.toy_small_pool.has_available_toy(self.toy3))
        self.assertTrue(self.toy_small_pool.has_available_toy(self.toy4))

        toy_of_duration_1 = self.toy_small_pool.get_toy_by_duration_for_elf(self.elf, 1)
        self.assertTrue(toy_of_duration_1 is None)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [2, 60, 600])

        toy_of_duration_3 = self.toy_small_pool.get_toy_by_duration_for_elf(self.elf, 3)
        self.assertEquals(toy_of_duration_3, self.toy3)

        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [60, 600])

        self.assertEquals(self.toy_small_pool.length_available_list(), 3)

        toy_of_duration_50 = self.toy_small_pool.get_toy_by_duration_for_elf(self.elf, 50)
        self.assertTrue(toy_of_duration_50 is None)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [60, 600])

        toy_of_duration_60 = self.toy_small_pool.get_toy_by_duration_for_elf(self.elf, 60)
        self.assertTrue(toy_of_duration_60 is not None)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [60, 600])

        toy_of_duration_65 = self.toy_small_pool.get_toy_by_duration_for_elf(self.elf, 65)
        self.assertTrue(toy_of_duration_65 is not None)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [600])

        # Jouet trop grand
        toy_of_duration_650 = self.toy_small_pool.get_toy_by_duration_for_elf(self.elf, 650)
        self.assertTrue(toy_of_duration_650 is not None)
        self.assertEquals(self.toy_small_pool.get_available_toy_duration(), [])

    def test_pop_toy_from_waiting_list(self):
        
        self.assertEquals(self.toy_small_pool.length_waiting_list(), 4)

        toy_timestamp, toy = self.toy_small_pool.pop_toy_from_waiting_list()

        self.assertEquals(toy_timestamp, 8*60)
        self.assertEquals(toy, self.toy1)

        self.assertEquals(self.toy_small_pool.length_waiting_list(), 3)

    def test_empty(self):
        self.assertTrue(self.toy_empty_pool.empty())
Exemplo n.º 18
0
    def __normalize(self, typ, hdr, cpus, mem):
        elf = Elf(self.kernel)

        for i in range(hdr.cpusno):
            c = cpus[i]

            #### Normalize task-register (TR) ####
            c.sregs_state.tr.present  = 0x1
            c.sregs_state.tr.type     = 0xb
            c.sregs_state.tr.limit    = 0x68

            if typ == PRE_TESTCASE:
                # Use 'main' TSS
                c.sregs_state.tr.base     = elf.getSymbol('tss0').getAddress()
                c.sregs_state.tr.dpl      = 0x0
                c.sregs_state.tr.selector = 0x8
            else:
                pop = lambda x,y: struct.unpack("I", mem[x + 4 * y:(x + 4 * y) + 4])[0]

                # Choose the correct TSS for current CPL
                rsp = c.regs_state.rsp + c.sregs_state.ss.base
                if exception_has_error_code(c.exception_state.vector):
                    rsp += 4

                stack_cs_sel  = pop(rsp, 2)
                stack_cs = parse_seg(stack_cs_sel, c, mem)
                if stack_cs is not None:
                    c.sregs_state.tr.dpl      = stack_cs.dpl
                    c.sregs_state.tr.base     = elf.getSymbol(DPL_TO_TSS[stack_cs.dpl][0]).getAddress()
                    c.sregs_state.tr.selector = DPL_TO_TSS[stack_cs.dpl][1]

            #### Normalize MSR registers ####
            c.msrs_state.n = 3

            c.msrs_state.msr_regs[0].idx = X86_MSR_IA32_SYSENTER_CS
            c.msrs_state.msr_regs[0].val = 0x68

            c.msrs_state.msr_regs[1].idx = X86_MSR_IA32_SYSENTER_ESP
            c.msrs_state.msr_regs[1].val = 0x800

            c.msrs_state.msr_regs[2].idx = X86_MSR_IA32_SYSENTER_EIP
            c.msrs_state.msr_regs[2].val = elf.getSection('.tcring0').getLowAddr()

            #### Normalize segment descriptors ####

            # Fix granularity bits (both in pre- and post-states)
            c.sregs_state.cs.g     = 1
            c.sregs_state.ds.g     = 1
            c.sregs_state.es.g     = 1
            c.sregs_state.fs.g     = 1
            c.sregs_state.gs.g     = 1
            c.sregs_state.ss.g     = 1

            if typ == PRE_TESTCASE:
                # PRE-normalization
                gdt = elf.getSymbol('gdt').getAddress()

                for s in [c.sregs_state.ds, c.sregs_state.es, c.sregs_state.fs,
                          c.sregs_state.gs, c.sregs_state.ss]:
                    # Mark as accessed
                    s.type |= 1

                    # Fix GDT
                    gdt_index = s.selector >> 3
                    gdt_addr  = gdt + (gdt_index * 8) + 4
                    data = struct.unpack("I", mem[gdt_addr:gdt_addr+4])[0]
                    data |= 0x100
                    data = struct.pack("I", data)
                    mem = mem[:gdt_addr] + data + mem[gdt_addr+4:]

        return (hdr, cpus, mem)
Exemplo n.º 19
0
class ElfTest(unittest.TestCase):

    def setUp(self):
        self.elf1 = Elf(1)
        self.elf2 = Elf(2)

        # soln_file = os.path.join(os.getcwd(), 'test.csv')
        # self.wcsv = csv.writer(open(soln_file, "wb"))

    def test_num_of_working_minutes_left(self):

        self.assertEquals(self.elf1.num_of_working_minutes_left(), 600)

        self.elf1.set_next_available_time(600)

        self.assertEquals(self.elf1.num_of_working_minutes_left(), 600-60)

        self.elf1.set_next_available_time(540 + 595)

        self.assertEquals(self.elf1.num_of_working_minutes_left(), 5)

        self.elf1.set_next_available_time(540 + 605)

        self.assertEquals(self.elf1.num_of_working_minutes_left(), 0)

    def test_get_productivity(self):

        self.assertEquals(self.elf1.get_productivity(), 1.0)

        self.elf1.set_productivity(2.0)

        self.assertEquals(self.elf1.get_productivity(), 2.0)

    def test_wait_till_next_day(self):

        self.assertEquals(self.elf1.get_next_available_time(), 540)

        self.elf1.set_next_available_time(700)

        self.assertEquals(self.elf1.get_next_available_time(), 700)

        self.elf1.wait_till_next_day()

        self.assertEquals(self.elf1.get_next_available_time(), 1440+(9*60))

        self.elf1.wait_till_next_day()

        self.assertEquals(self.elf1.get_next_available_time(), (2*1440)+(9*60))
Exemplo n.º 20
0
 def setUp(self):
     self.elf1 = Elf(1)
     self.elf2 = Elf(2)
Exemplo n.º 21
0
from pus import Pus
from elf import Elf
from credentials import ELF_LOGIN, ELF_PASSWORD

if __name__ == "__main__":
    pus = Pus()

    print('Import list form Google Sheet...', end='', flush=True)
    homeworks = pus.get_homeworks()
    print(' done')

    elf = Elf()
    elf.logon(ELF_LOGIN, ELF_PASSWORD)
    elf.get_homeworks(homeworks)

    pus.update_sheet(homeworks)

    elf.get_gesture(homeworks)
    elf.get_indices(homeworks)
    elf.get_confirmation(homeworks)

    pus.update_gestures(homeworks)

    print('done')
Exemplo n.º 22
0
def DoTesting():
    print('ConvertToSigned(-1, 2)    =', Elf.ConvertToSigned(-1, 2))
    print('ConvertToSigned(0, 1)     =', Elf.ConvertToSigned(0, 1))
    print('ConvertToSigned(127, 1)   =', Elf.ConvertToSigned(127, 1))
    print('ConvertToSigned(128, 1)   =', Elf.ConvertToSigned(128, 1))
    print('ConvertToSigned(255, 1)   =', Elf.ConvertToSigned(255, 1))
    print('ConvertToSigned(0, 2)     =', Elf.ConvertToSigned(0, 2))
    print('ConvertToSigned(32767, 2) =', Elf.ConvertToSigned(32767, 2))
    print('ConvertToSigned(32768, 2) =', Elf.ConvertToSigned(32768, 2))
    print('ConvertToSigned(65535, 2) =', Elf.ConvertToSigned(65535, 2))
    print('ConvertToSigned(2147483647, 4) = ',
          Elf.ConvertToSigned(2147483647, 4))
    print('ConvertToSigned(2147483648, 4) = ',
          Elf.ConvertToSigned(2147483648, 4))
    print('ConvertToSigned(4294967295, 4) = ',
          Elf.ConvertToSigned(4294967295, 4))
    print('ConvertToSigned(9223372036854775807, 8)  = ',
          Elf.ConvertToSigned(9223372036854775807, 8))
    print('ConvertToSigned(9223372036854775808, 8)  = ',
          Elf.ConvertToSigned(9223372036854775808, 8))
    print('ConvertToSigned(18446744073709551615, 8) = ',
          Elf.ConvertToSigned(18446744073709551615, 8))

    try:
        print('ConvertToSigned(256, 1) = ', Elf.ConvertToSigned(256, 1),
              'FAIL')
    except ElfError as msg:
        print('ConvertToSigned(256, 1) exception :', msg)

    try:
        print('ConvertToSigned(65536, 2) = ', Elf.ConvertToSigned(65536, 2),
              'FAIL')
    except ElfError as msg:
        print('ConvertToSigned(65536, 2) exception :', msg)

    try:
        print('ConvertToSigned(4294967296, 4) = ',
              Elf.ConvertToSigned(4294967296, 4), 'FAIL')
    except ElfError as msg:
        print('ConvertToSigned(4294967296, 4) exception :', msg)

    try:
        print('ConvertToSigned(18446744073709551616, 8) = ',
              Elf.ConvertToSigned(18446744073709551616, 8), 'FAIL')
    except ElfError as msg:
        print('ConvertToSigned(18446744073709551616, 8) exception :', msg)
    return
Exemplo n.º 23
0
from elf import Elf
from hero import Hero

hero = Hero("H", 4)
print(hero.username)
print(hero.level)
print(str(hero))
elf = Elf("E", 4)
print(str(elf))
print(elf.__class__.__bases__[0].__name__)
print(elf.username)
print(elf.level)
Exemplo n.º 24
0
 def __init__(self, num_elves):
     self.elves = []
     for i in xrange(1, num_elves + 1):
         elf = Elf(i)
         heapq.heappush(self.elves, (elf.next_available_time, elf))
Exemplo n.º 25
0
def global_optimizer(sub_file, myToys, hrs, NUM_ELVES, output):
    """ Score the submission file, performing constraint checking. Returns the time (in minutes) when
    final present is complete.
    :param sub_file: submission file name. Headers: ToyId, ElfId, Start_Time, Duration
    :param myToys: toys dictionary
    :param hrs: hours object
    :return: time (in minutes) when final present is complete
    """
    file_handler = open(output, "wb")

    hrs = Hours()
    ref_time = datetime.datetime(2014, 1, 1, 0, 0)
    threshold_minute = hrs.convert_to_minute('2450 1 1 0 0')

    basket_toys_above_th = []
    basket_toys_below_th = []
    #Unchanged

    elf_availability = {}
    #Maintains the earliest time when elves finish their last jobs
    for i in range(1, NUM_ELVES + 1):
        elf_availability[i] = [0, 0]

    row_count = 0

    with open(sub_file, 'rb') as f:
        fcsv = csv.reader(f)
        fcsv.next()  # header
        for row in fcsv:
            row_count += 1
            if row_count % 50000 == 0:
                print 'Starting toy: {0}'.format(row_count)

            current_toy = int(row[0])
            current_elf = int(row[1])
            start_minute = hrs.convert_to_minute(row[2])
            duration = int(row[3])

            if start_minute > threshold_minute:
                basket_toys_above_th.append(current_toy)
            else:
                basket_toys_below_th.append((row[0], row[1], row[2], row[3]))

            if elf_availability[current_elf][0] < start_minute:
                elf_availability[current_elf][0] = start_minute
                elf_availability[current_elf][1] = duration

    myelves = []
    for i in elf_availability.keys():
        elf = Elf(i)
        elf.rating = 0.25
        elf.next_available_time = elf_availability[current_elf][0] + int(
            math.ceil(elf_availability[current_elf][1] / elf.rating))
        heapq.heappush(myelves, (elf.next_available_time, elf))

    while len(basket_toys_above_th) > 0:

        #Retrive the toy object
        current_toy_duration = myToys[basket_toys_above_th[0]]

        #Pick the next available elf and execute it
        elf_available_time, current_elf = heapq.heappop(myelves)
        work_start_time = elf_available_time

        current_elf.next_available_time, work_duration = \
                    assign_elf_to_toy(work_start_time, current_elf, current_toy_duration, hrs)




        current_elf.update_elf(hrs, Toy(basket_toys_above_th[0], '2014 01 01 01 01' ,current_toy_duration), \
            work_start_time, work_duration)

        # put elf back in heap
        heapq.heappush(myelves, (current_elf.next_available_time, current_elf))

        tt = ref_time + datetime.timedelta(seconds=60 * work_start_time)
        time_string = " ".join([
            str(tt.year),
            str(tt.month),
            str(tt.day),
            str(tt.hour),
            str(tt.minute)
        ])

        #Add it to the basket below the threshold
        basket_toys_below_th.append((basket_toys_above_th[0], current_elf.id,
                                     time_string, work_duration))

        del basket_toys_above_th[0]

    basket_toys_below_th = sorted(
        basket_toys_below_th,
        key=lambda element: hrs.convert_to_minute(element[2]))

    file_handler.write("ToyId,ElfId,StartTime,Duration\n")
    for obj in basket_toys_below_th:
        file_handler.write(
            str(obj[0]) + "," + str(obj[1]) + "," + str(obj[2]) + "," +
            str(obj[3]) + "\n")
    file_handler.close()
Exemplo n.º 26
0
def score_submission(sub_file, myToys, hrs, NUM_ELVES):
    """ Score the submission file, performing constraint checking. Returns the time (in minutes) when
    final present is complete.
    :param sub_file: submission file name. Headers: ToyId, ElfId, Start_Time, Duration
    :param myToys: toys dictionary
    :param hrs: hours object
    :return: time (in minutes) when final present is complete
    """

    myElves = {}
    complete_toys = []
    last_minute = 0
    row_count = 0
    unsactioned_time = 0
    with open(sub_file, 'rb') as f:
        fcsv = csv.reader(f)
        fcsv.next()  # header
        for row in fcsv:
            row_count += 1
            if row_count % 50000 == 0:
                print 'Starting toy: {0}'.format(row_count)

            current_toy = row[0]
            current_elf = int(row[1])
            start_minute = hrs.convert_to_minute(row[2])
            duration = int(row[3])

            unsactioned_time += hrs.get_sanctioned_breakdown(
                start_minute, duration)[1]

            if not current_toy in myToys:
                print 'Toy {0} not in toy dictionary.'.format(current_toy)
                exit(-1)
            elif myToys[current_toy].completed_minute > 0:
                print 'Toy {0} was completed at minute {1}'.format(
                    current_toy, myToys[current_toy].completed_minute)
                exit(-1)

            if not 1 <= current_elf <= NUM_ELVES:
                print '\n ** Assigned elf does not exist: Elf {0}'.format(
                    current_elf)
                exit(-1)

            # Create elf if this is the first time this elf is assigned a toy
            if not current_elf in myElves.keys():
                myElves[current_elf] = Elf(current_elf)

            # Check work starting constraints:
            # 1. within correct window of toy's arrival
            # 2. when elf is next allowed to work
            if myToys[current_toy].outside_toy_start_period(start_minute):
                print '\n ** Requesting work on Toy {0} at minute {1}: Work can start at {2} minutes'. \
                    format(current_toy, start_minute, myToys[current_toy].arrival_minute)
                exit(-1)
            if start_minute < myElves[current_elf].next_available_time:
                print '\n ** Elf {2} needs his rest, he is not available now ({0}) but will be later at {1}'. \
                    format(start_minute, myElves[current_elf].next_available_time, current_elf)
                exit(-1)

            # Check toy is complete based on duration and elf productivity
            if not myToys[current_toy].is_complete(
                    start_minute, duration, myElves[current_elf].rating):
                print '\n ** Toy {0} is not complete'.format(current_toy)
                exit(-1)
            else:
                complete_toys.append(int(current_toy))
                if myToys[current_toy].completed_minute > last_minute:
                    last_minute = myToys[current_toy].completed_minute

        # Since toy started on time and is complete, update elf productivity
            myElves[current_elf].update_elf(hrs, myToys[current_toy],
                                            start_minute, duration)

    if len(complete_toys) != len(myToys):
        print "\n ** Not all toys are complete. Only {0}".format(
            len(complete_toys))
        exit(-1)
    if max(complete_toys) != len(myToys):
        print "\n ** max ToyId != NUM_TOYS."
        print "\n   max(complete_toys) = {0} versus NUM_TOYS = {1}".format(
            max(complete_toys), len(myToys))
        exit(-1)
    else:
        score = last_minute * math.log(1.0 + len(myElves))
        print '\nSuccess!'
        print '  Score = {0}'.format(score)
        print '  Last minute = {0}'.format(last_minute)
        print '  Unsanctioned time = {0}'.format(unsactioned_time)
Exemplo n.º 27
0
    def optimize(self, NUM_ELVES, boosters, big_jobs):
        """
        :param elf_object:  Elf Object
        :param boosters:    List of (Toy_Id, Duration)
        :param big_jobs:    List of (Toy_Id, Duration)
        :return:
        """




        output                      = dict();

        file_handler                = open(  ("data/finalSubmission1"  + ".csv"), "wb"  );
        hrs                         = Hours();
        last_job_completed_year     = 0;

        min_desired_rating          = 0.32;

        total_no_of_toys            = len(boosters) + len(big_jobs);
        #Sort the big jobs in descending order of duration
        big_jobs.sort(key=operator.itemgetter(1),reverse=True);
        #Sort the boosters in ascending order of duration
        boosters.sort(key=operator.itemgetter(1));

        rating_change_index1 = 0;
        rating_change_index2 = 0;
        for i in range(0, len(big_jobs)):
            if int(big_jobs[i][1]/60.0) <= 300 and int(big_jobs[i][1]/60.0) > 200:
                rating_change_index1 = i;
            if int(big_jobs[i][1]/60.0) <= 200:
                rating_change_index2 = i;

        no_completed_toys           = 0;
        big_job_counter             = 0;


        elves = Queue.Queue();
        for i in xrange(1, NUM_ELVES+1):
            elf                     = Elf(i);
            elves.put(elf);


        while no_completed_toys < total_no_of_toys:
            if no_completed_toys % 10000 == 0:
                print(" Algorithm : Boost_Play , Boosters : " + str(len(boosters)) + " Big Jobs : " + str(len(big_jobs)));


            #print("**Seeking a rating : " + str(min_desired_rating));
            if len(big_jobs) == 0:
                break;

            #Pick an elf
            elf_object = elves.get();


            #Iterate through the boosters and increase the productivity
            no_of_toys_played = 0;
            while ( round(elf_object.rating,3) + 0.002 < round(min_desired_rating,3) ):

                if len(boosters) == 0 or no_of_toys_played > 20:
                    break;

                #Generate a random no
                random_toy = randint(0, len(boosters)-1);

                #Play the one with no unsanctioned time
                sanctioned, unsanctioned = self.breakDownWork(elf_object.next_available_time, elf_object, boosters[random_toy][1], hrs);

                if unsanctioned == 0:
                    completion_yr = self.play_elf(output, elf_object, boosters[random_toy][0], boosters[random_toy][1]);
                    #Remove the toy played
                    del boosters[random_toy];
                else:
                    #Play the first toy as it has the least amount of unsanctioned time
                    #Set the next available time to next day, 9:00 am
                    work_start_time = hrs.day_start  + int(hrs.minutes_in_24h * math.ceil(elf_object.next_available_time / float(hrs.minutes_in_24h)));
                    completion_yr   = self.play_elf(output, elf_object, boosters[0][0], boosters[0][1], work_start_time);

                    del boosters[0];

                if completion_yr > last_job_completed_year:
                    last_job_completed_year = completion_yr;
                no_completed_toys += 1;
                no_of_toys_played += 1;


            if len(big_jobs) > 0:

                if big_job_counter >= rating_change_index1:
                    min_desired_rating = 0.31;

                if big_job_counter >= rating_change_index2:
                    min_desired_rating = 0.29;


                #Play the first toy in the queue on the following day
                work_start_time = hrs.day_start  + int(hrs.minutes_in_24h * math.ceil(elf_object.next_available_time / float(hrs.minutes_in_24h)));
                completion_yr   = self.play_elf(output, elf_object, big_jobs[0][0], big_jobs[0][1], work_start_time);

                #completion_yr = play_elf(output, elf_object, big_jobs[0][0], big_jobs[0][1]);
                if completion_yr > last_job_completed_year:
                    last_job_completed_year = completion_yr;

                #Delete this toy
                del big_jobs[0];

                no_completed_toys += 1;
                big_job_counter   += 1;

            #Put the elf back in
            elves.put(elf_object);

        #Play naively
        myelves = []
        while not elves.empty():
            current_elf = elves.get();
            heapq.heappush(myelves, (current_elf.next_available_time, current_elf));


        if len(boosters) == 0:
            remaining_jobs = big_jobs;
        else:
            remaining_jobs = boosters;


        while len(remaining_jobs) > 0:

            print(" Algorithm : Naive , Boosters : " + str(len(boosters)) + " Big Jobs : " + str(len(remaining_jobs)));

            elf_available_time, current_elf = heapq.heappop(myelves);
            completion_yr   = self.play_elf(output, current_elf, remaining_jobs[0][0], remaining_jobs[0][1]);
            if completion_yr > last_job_completed_year:
                last_job_completed_year = completion_yr;
            # put elf back in heap
            heapq.heappush(myelves, (current_elf.next_available_time, current_elf));
            no_completed_toys += 1;

            print(current_elf.id);

            del remaining_jobs[0];


        for elf_id in output:
            #Sort the output based on work_start_time
            output[elf_id].sort(key=operator.itemgetter(3));
            #Flush the output of this elf to file
            for toy in  output[elf_id]:
                file_handler.write( str(toy[0]) + "," + str(elf_id) + "," \
                                    + str(toy[1]) + "," + str(toy[2]) + "\n");

        file_handler.close();

        return last_job_completed_year;