Esempio n. 1
0
 def write_to_board(self):
     self.board.tree.delete(*self.board.tree.get_children())
     self.race = Race(self.db, race_number, self.os)
     self.class_names = iter(self.race.class_names)
     self.break_result_list = False
     self.break_loop_list = True
     self.write_result_list()
Esempio n. 2
0
 def set_class_buttons(self, races):
     # Henter ønsket løp fra Combobox
     global race_number
     race_number = self.combo_races.current()
     self.race = Race(self.db, race_number, self.os)
     #        # Lager knapper for hver klasse
     try:
         if self.buttons:
             for button in self.buttons:
                 button.destroy()
     except:
         self.buttons = list()
     i = 0
     j = 0
     for class_name in self.race.class_names:
         self.buttons.append(
             tk.Button(self.ctr_left,
                       text=class_name,
                       command=partial(self.write_admin_list,
                                       class_name)).grid(row=i,
                                                         column=j,
                                                         padx=10))
         i += 1
         if i >= 30:  # Her bør vi regne ut hvor mange knapper man kan ha i høyden før man legger til ny knappekolonne
             j += 1
             i = 0
Esempio n. 3
0
 def write_prewarn_list(self):
     #print("write_to_last_list - break_pre =  {}".format(break_pre))
     if not break_pre:
         self.race = Race(self.db, race_number)
         prewarn_list= []
         self.pre.tree.delete(*self.pre.tree.get_children())
         prewarn_list = self.race.make_prewarn_list()
         for name in reversed(prewarn_list):
             self.pre.LoadinTable(name)
         self.pre_tree_alarm = self.pre.after(5000, self.write_prewarn_list)
Esempio n. 4
0
 def make_loop_list(self):
     loop_list = []
     result_list = []
     race = Race(self.db, race_number, self.os)
     for class_name in race.class_names:
         # Henter resultatliste for klassen
         result_list = race.make_result_list(class_name)
         if result_list:  # Sjekker om det er deltaker i klassen
             loop_list.extend([self.line_shift()])
             loop_list.extend([self.class_heading(class_name)])
             loop_list.extend(result_list)
     return loop_list
Esempio n. 5
0
 def write_to_last(self):
     # Alle de boolske variablene settes for å stoppe innlesing fra databasen nå man endre bilde
     global break_res
     break_res = False
     global break_adm
     break_adm = True   
     global break_pre
     break_pre = True
     self.break_pre_list = True
     self.break_board_list = True
     self.break_loop_list = True 
     self.break_last_list = False
     self.board.tree.delete(*self.board.tree.get_children())
     self.race = Race(self.db, race_number)
     self.write_last_list()
Esempio n. 6
0
 def write_to_board(self):
     global break_res
     break_res = False
     global break_adm
     break_adm = True
     global break_pre
     break_pre = True
     self.board.tree.delete(*self.board.tree.get_children())
     self.race = Race(self.db, race_number)
     self.class_names = iter(self.race.class_names)
     self.break_pre_list = True
     self.break_board_list = False
     self.break_loop_list = True
     self.break_last_list = True
     self.write_board_list()
Esempio n. 7
0
 def pdf_list(self, results):#, one_active_class, class_name, page_break):
     pdf = pdfgen.Pdf()
     race = Race(self.db, race_number)
     if results:
         pdf.result_list(race, one_active_class.get(), active_class, page_break.get(), with_points.get() )
     else:
         pdf.start_list(race, for_start.get(), one_active_class.get(), active_class, page_break.get())
Esempio n. 8
0
 def write_result_list(self):  # Skriver resultat liste per klasse
     if not self.break_result_list:
         class_list = []
         class_name = self.get_next_element(self.class_names)
         self.race = Race(self.db, race_number, self.os)
         if class_name is None:
             self.class_names = iter(self.race.class_names)
             class_name = self.get_next_element(self.class_names)
         self.board.tree.delete(*self.board.tree.get_children())
         result_list = self.race.make_result_list(class_name)
         # Her må jeg sjekke om det er noen i klassen
         if result_list:
             class_list.extend([self.line_shift()])
             class_list.extend([self.class_heading(class_name)])
             class_list.extend(result_list)
             for name in reversed(class_list):
                 self.board.LoadinTable(name)
         else:
             self.write_result_list()
         self.board_tree_alarm = self.board.after(5000,
                                                  self.write_result_list)
Esempio n. 9
0
 def write_prewarn_list(self):
     prewarn_list = []
     self.race = Race(self.db, race_number, self.os)
     #Her legger jeg inn en resultatliste som bare inneholde de som er i mål, DNS og DSQ
     self.pre.tree.delete(*self.pre.tree.get_children())
     self.find_runner()
     for runner in self.runners:
         runner = list(runner)
         runner[10] = self.race.set_tag(runner[10])
         # sjekker om løperen ikke er kommet i mål.
         if runner[10] == 'ute':
             #Regner ut tiden som skal vises i Vindu. Ikke på resultatlister
             try:
                 runner[8] = self.race.get_time(runner[14])
             except:
                 if runner[10] == 'dns':
                     runner[8] = 'DNS'
         if not runner[8]:
             runner[8] = runner[10]
         prewarn_list.insert(0, self.race.set_runner_details(runner))
     for name in reversed(prewarn_list):
         self.pre.LoadinTable(name)
     self.pre_tree_alarm = self.pre.after(200, self.write_prewarn_list)
Esempio n. 10
0
 def write_to_finish(self):
    # self.finish.tree.delete(*self.finish.tree.get_children())
     self.race = Race(self.db, race_number)
    #self.class_names = iter(self.class_names)
     self.write_finish_list()
Esempio n. 11
0
class Tab(tk.Frame):
    def __init__(self,name,*args,**kwargs):
        width = int(kwargs['width'])
        height = int(kwargs['height'])
        left_w = int(width*0.07)
        mid_w = int(width - 2 * left_w)
        self.table_w = mid_w
        ##self.idx=0
        self.runners=[]
        tab_type = kwargs['tab_type']
        self.db = Database(kwargs['database'])
        if 'pre_database'in kwargs:
            self.pre_db = Database(kwargs['pre_database'])
        self.race_number = None
        self.class_name = None
        self.name = None
        self.print_results = False
        self.race = None
        self.break_result_list = False
        self.break_loop_list = False
        self.break_last_list = False
        break_adm = True
        break_res = True
        break_pre = True
        if sys.platform == "win32":
            self.log_file = open("ospeaker.log", "w")
        else:
            self.log_file = open("/var/log/ospeaker.log", "w")

       #Standard frame for alle tabs
        tk.Frame.__init__(self)
        # create all of the main containers
        self.top_frame = tk.Frame(self, bg='white')#, width=100, height=50)  # , pady=3)
        center = tk.Frame(self,  bg='black')#, width=50, height=40)  # , padx=3, pady=3)
        btm_frame = tk.Frame(self,  bg='black')#, width=450, height=45)  # , pady=3)

        # layout all of the main containers
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.top_frame.grid(row=0, sticky="ew")
        center.grid(row=1, sticky="nsew")
        btm_frame.grid(row=2, sticky="ew")

        # create the center widgets
        center.grid_rowconfigure(0, weight=1)
        center.grid_columnconfigure(0, weight=0)

        self.ctr_left = tk.Frame(center, bg='black',width=left_w, height=100)  # , padx=3, pady=3)
        ctr_mid = tk.Frame(center, width=mid_w, height=100)  # , padx=3, pady=3)
        ctr_right = tk.Frame(center,  bg='black', width=left_w, height=100)  # , padx=3, pady=3)
        
        self.ctr_left.grid(row=0, column=0, sticky="ns")
        ctr_mid.grid(row=0, column=1, sticky="nsew")
        ctr_right.grid(row=0, column=2, sticky="nsew")

    #   Logo Banner
        pixels_x = 700
        pixels_y = int(pixels_x * 0.144)
        if sys.platform == "win32":
            img = ImageTk.PhotoImage(Image.open("C:\Program Files (x86)\Brikkespy\images\\black_MILO_banner.png").resize((pixels_x, pixels_y)))
        else:
            img = ImageTk.PhotoImage(Image.open("/etc/black_MILO_banner.png").resize((pixels_x, pixels_y)))

        label = tk.Label(btm_frame,bg="black", image = img)
        label.image = img 
        label.pack(side = "bottom", fill = "both", expand = "yes")
        head = hdn.get_heading('resultater')
        heading = list(head.keys())
        columnwidth = [item[0] for item in head.values()]
        anchor = [item[1] for item in head.values()]

        # Spesifiser for de forskjellige vinduene
 
        if tab_type == 'adm':
            # Tabell for de som er i mål
            self.finish =  Table(ctr_mid, width=mid_w, height=height, row_height=30, heading=heading, columnwidth=columnwidth, anchor=anchor)
            # inne.tree.bind("<Double-1>", self.onclick_out)
            # Tabell for de som er ute i skogen
            self.out =  Table(ctr_mid, width=mid_w, height=height, row_height=30,  heading=heading, columnwidth=columnwidth, anchor=anchor)
            # ute.tree.bind("<Double-1>", self.onclick_out)
            tk.Label(self.top_frame, text="Løp:").grid(row=0, column=1, sticky='w')
            # Combobox med alle løp i databasen
            self.combo_races = TTK.Combobox(self.top_frame, width=30, values=list(zip(*self.db.races))[1])
            self.combo_races.grid(row=0, column=2, sticky='w')
            self.combo_races.bind("<<ComboboxSelected>>", self.set_class_buttons)
            # Checkboxes
            # Setter om det skal være sideskift for printing
            self.check = tk.Checkbutton(self.top_frame, text="Print med sideskift", variable=page_break).grid(row=0, column=3, sticky='w')
            self.check2 = tk.Checkbutton(self.top_frame, text="Print aktiv_klasse", variable=one_active_class).grid(row=0, column=4, sticky='w')
            self.check3 = tk.Checkbutton(self.top_frame, text="Print lister for start", variable=for_start).grid(row=0, column=5, sticky='w')
            self.check4 = tk.Checkbutton(self.top_frame, text="Print lister med poeng", variable=with_points).grid(row=0, column=6, sticky='w')

        elif tab_type == 'results':
            self.board = Table(ctr_mid, width=mid_w, height=height, row_height=30, heading=heading, columnwidth=columnwidth, anchor=anchor)
            # self.res.tree.bind("<Double-1>", self.onclick_res)
            # Buttons
            class_button = tk.Button(self.top_frame, text='Klassevis', bg='white', command=partial(self.write_to_board))
            loop_button = tk.Button(self.top_frame, text='Loop', bg='white', command=partial(self.write_to_loop))
            last_button = tk.Button(self.top_frame, text='Siste', bg='white', command=partial(self.write_to_last))
            class_button.grid(row=0, column=0)
            loop_button.grid(row=0, column=1)
            last_button.grid(row=0, column=2)

        elif tab_type == 'finish':
            self.finish = Table(ctr_mid, width=mid_w, height=height, row_height=30, heading=heading, columnwidth=columnwidth, anchor=anchor)
            # self.res.tree.bind("<Double-1>", self.onclick_res)
            # Buttons
            class_button = tk.Button(self.top_frame, text='Klassevis', bg='white', command=partial(self.write_to_finish))
            class_button.grid(row=0, column=0)

        elif tab_type == 'prewarn':
            self.pre = Table(ctr_mid, width=mid_w, height=height, row_height=30, heading=heading, columnwidth=columnwidth, anchor=anchor)
            # Buttons
            self.button = tk.Button(self.top_frame, text='Forvarsel', command=partial(self.write_to_prewarn))
            self.button.grid(row=0, column=0)

        elif tab_type == 'poengo':

            head = hdn.get_heading('poengo')
            heading = list(head.keys())
            columnwidth = [item[0] for item in head.values()]
            anchor = [item[1] for item in head.values()]
            self.poengo = Table(ctr_mid, width=mid_w, height=height, row_height=30, heading=heading, columnwidth=columnwidth, anchor=anchor)
            # Buttons
            self.button = tk.Button(self.top_frame, text='PoengO', command=partial(self.write_poengo))
            self.button.grid(row=0, column=0)
            self.button = tk.Button(self.top_frame, text='csv', command=partial(self.write_poengo_csv))
            self.button.grid(row=0, column=1)

    def write_to_admin(self, class_name):
        global break_res
        break_res = True
        global break_pre
        break_pre = True
        global break_adm
        break_adm = False
        self.write_admin_list(class_name)


# Result lists
    def write_to_board(self):
        global break_res
        break_res = False
        global break_adm
        break_adm = True
        global break_pre
        break_pre = True
        self.board.tree.delete(*self.board.tree.get_children())
        self.race = Race(self.db, race_number)
        self.class_names = iter(self.race.class_names)
        self.break_pre_list = True
        self.break_board_list = False
        self.break_loop_list = True
        self.break_last_list = True
        self.write_board_list()

    def write_to_loop(self):
        # Alle de boolske variablene settes for å stoppe innlesing fra databasen nå man endre bilde
        global break_res
        break_res = False
        global break_adm
        break_adm = True
        global break_pre
        break_pre = True
        #print("write_to_loop - {}".format(break_res))
        self.break_pre_list = True
        self.break_board_list = True
        self.break_loop_list = False
        self.break_last_list = True
        self.board.tree.delete(*self.board.tree.get_children())
        self.race = Race(self.db, race_number)
        self.write_loop_list(0)

    def write_to_last(self):
        # Alle de boolske variablene settes for å stoppe innlesing fra databasen nå man endre bilde
        global break_res
        break_res = False
        global break_adm
        break_adm = True   
        global break_pre
        break_pre = True
        self.break_pre_list = True
        self.break_board_list = True
        self.break_loop_list = True 
        self.break_last_list = False
        self.board.tree.delete(*self.board.tree.get_children())
        self.race = Race(self.db, race_number)
        self.write_last_list()

    def write_to_prewarn(self):
        # Alle de boolske variablene settes for å stoppe innlesing fra databasen nå man endre bilde
        global break_res
        break_res = True
        global break_adm
        break_adm = True   
        global break_pre
        break_pre = False
        self.write_prewarn_list()

    def write_to_finish(self):
       # self.finish.tree.delete(*self.finish.tree.get_children())
        self.race = Race(self.db, race_number)
       #self.class_names = iter(self.class_names)
        self.write_finish_list()

    def write_admin_list(self, class_name):
        #print("write_to_admin_list - break_adm =  {}".format(break_adm))
        if not break_adm:
            active_class = class_name
            # denne kjøres kontinuerlig så og derfor må jeg sette flagg som ikke endrer urangerte listeri/
            # kontinuerlig. Her setter jeg randomize lik False
            self.randomized = False
            if self.class_name:
                self.finish.after_cancel(self.finish_tree_alarm)
                self.out.after_cancel(self.out_tree_alarm)

            # Her legger jeg inn en resultatliste som bare inneholde de som er i mål, DNS og DSQ
            self.finish.tree.delete(*self.finish.tree.get_children())
            result_list = self.race.make_result_list(class_name)
            self.write_table(result_list,'res')
            self.finish_tree_alarm = self.finish.after(5000, self.write_admin_list, class_name)
            self.class_name = class_name

            # Her legger jeg inn en resultatliste som bare inneholder de som er ute
            self.out.tree.delete(*self.out.tree.get_children())
            out_list = self.race.make_result_list(class_name, 'out')
            self.write_table(out_list,'out')
            self.out_tree_alarm = self.out.after(5000, self.write_admin_list, class_name)

    def write_finish_list(self):
        self.finish.tree.delete(*self.finish.tree.get_children())
        all_lists = []
        for class_name in self.race.class_names:
            # Henter resultatliste for klassen
            result_list = self.race.make_result_list(class_name)
            if result_list:  # Sjekker om det er deltaker i klassen
                all_lists.extend(result_list)
        finish_list = [i for i in all_lists if not ((i['tag'] == 'arr') or i['tag'] == 'dns')]
        finish_list = (sorted(finish_list, key=lambda i: str(i['Innkomst'])))
        # Her må jeg sjekke om det er noen i klassen
        if finish_list:
            for name in (finish_list):
                self.finish.LoadinTable(name)
        self.finish_tree_alarm = self.finish.after(500, self.write_finish_list)

    def write_board_list(self):  # Skriver resultat liste per klasse
        #print("write_to_board_list - break_res =  {}".format(break_res))
        if not self.break_board_list and not break_res:
            class_list = []
            class_name = self.get_next_element(self.class_names)
            print('Klasse {}'.format(class_name))
            if class_name is None:
                self.class_names = iter(self.race.class_names)
                class_name = self.get_next_element(self.class_names)
            self.board.tree.delete(*self.board.tree.get_children())
            result_list = self.race.make_result_list(class_name)
            # Her må jeg sjekke om det er noen i klassen
            if result_list:
                class_list.extend([hdn.line_shift()])
                class_list.extend([hdn.class_heading(class_name)])
                class_list.extend(result_list)
                for name in reversed(class_list):
                    self.board.LoadinTable(name)
            else:
                self.write_board_list()
            self.board_tree_alarm = self.board.after(5000, self.write_board_list)

    def write_loop_list(self, loop):
        #print("write_to_loop_list - break_res =  {}".format(break_res))
        if not self.break_loop_list and not break_res:
            loop_list = self.make_loop_list()
            loop_list = loop_list[loop:] + loop_list[:loop]
            loop_length = len(loop_list)
            if loop >= loop_length:
                loop = 0
            self.board.tree.delete(*self.board.tree.get_children())
            for name in reversed(loop_list):
                self.board.LoadinTable(name)
            loop += 1
            self.board_tree_alarm = self.board.after(1000, self.write_loop_list, loop)

    def write_last_list(self):
        #print("write_to_last_list - break_res =  {}".format(break_res))
        if not self.break_last_list and not break_res:
            last_list = []
            last_list = self.make_last_list()
            self.board.tree.delete(*self.board.tree.get_children())
            if last_list:
                for name in reversed(last_list):
                    self.board.LoadinTable(name)
            else:
                self.write_board_list()
            self.board_tree_alarm = self.board.after(5000, self.write_last_list)

    def write_prewarn_list(self):
        #print("write_to_last_list - break_pre =  {}".format(break_pre))
        if not break_pre:
            self.race = Race(self.db, race_number)
            prewarn_list= []
            self.pre.tree.delete(*self.pre.tree.get_children())
            prewarn_list = self.race.make_prewarn_list()
            for name in reversed(prewarn_list):
                self.pre.LoadinTable(name)
            self.pre_tree_alarm = self.pre.after(5000, self.write_prewarn_list)

    def write_poengo(self):
        self.poengo.tree.delete(*self.poengo.tree.get_children())
        self.poeng = Race(self.db, race_number)
        self.write_poengo_list()

    def write_poengo_list(self):  # Skriver resultat liste per klasse
        self.poengo.tree.delete(*self.poengo.tree.get_children())
        results_list = self.make_treeview_list(self.poeng.make_point_list())
        for name in reversed(results_list):
            self.poengo.LoadinTable(name)
        self.poengo_tree_alarm = self.poengo.after(5000, self.write_poengo_list)

    def write_poengo_csv(self):
        poeng = Race(self.db, race_number)
        results = poeng.make_point_list()
        self.write_csv_list(results, poeng.heading)
   
    def write_csv_list(self, results, heading):
        result_writer = csv.writer(open("resultater.csv", "w"))
        if 'klatresek' in heading: 
            heading.remove('klatresek')
        if 'sprintsek' in heading:
            heading.remove('sprintsek')
        csv_list = []
        csv_list.append(heading)
        for result in results:
            res = []
            for key in heading:
                if key in result.keys():
                    res.append(result[key])
                else:
                    res.append('')
            csv_list.append(res)
        result_writer.writerows(csv_list)
    
    def make_treeview_list(self, results):
        tree_results=[]
        for result in results:
            tree_results.append(self.poeng.set_poengo_text(result))
        return tree_results

    def write_table(self, data, table):
        for name in reversed(data):
            if table == 'res':
                self.finish.LoadinTable(name)
            else:
                self.out.LoadinTable(name)

    def make_loop_list(self):
        loop_list = []
        result_list = []
        for class_name in self.race.class_names:
            # Henter resultatliste for klassen
            result_list = self.race.make_result_list(class_name)
            if result_list:  # Sjekker om det er deltaker i klassen
                loop_list.extend([hdn.line_shift()])
                loop_list.extend([hdn.class_heading(class_name)])
                loop_list.extend(result_list)
        return loop_list

    def make_last_list(self):
        last_list = []
        last_list = self.race.make_last_list()
        return last_list


    # Denne brukes når det dobbelklikkes på navn i tabellen. Foreløpig så skjer det ingen ting. peker til update runners som er kommentert ut under.
    def onclick_out(self, race):
        self.update_runner_table()
 
    # Denne brukes når det dobbelklikkes på navn i tabellen. Foreløpig så skjer det ingen ting. peker til update runners som er kommentert ut under.
    def onclick_res(self, race):
        #self.res.after_cancel(self.res_tree_alarm)
        #item = str(self.res.tree.focus())
        #class_name = self.res.tree.item(item, "value")[2]
        #self.write_result_list(class_name)
        self.update_runner_table()
    def get_next_element(self, my_itr):
        try:
            return next(my_itr)
        except StopIteration:
            return None

    # Henter løpene og lager knapper for hver eneste klasse i løpet.
    def set_class_buttons(self, races):
        # Henter ønsket løp fra Combobox
        global race_number
        race_number = self.combo_races.current()
        self.race = Race(self.db, race_number)
#        # Lager knapper for hver klasse
        try:
           if self.buttons:
                for button in self.buttons:
                    button.destroy()
                self.button.clear()    
        except:
            self.buttons = []
        i = 0
        j = 0
        for class_name in self.race.class_names:
            if class_name:
                self.buttons.append(tk.Button(self.ctr_left, text=class_name, command=partial(self.write_to_admin, class_name)))
                self.buttons[i].grid(row=i,column=j, padx = 10)
                i += 1
                if i >= 30: # Her bør jeg regne ut hvor mange knapper man kan ha i høyden før man legger til ny knappekolonne
                    j += 1
                    i = 0

#   Denne brukes når det dobbelklikkes på navn i tabellen. Foreløpig så skjer detingen ting. peker til update runners som er kommentert ut under.
    def onclick_pre(self, race):
        self.write_loop_list()

    def dummy_func(self, name):
        print(name)
Esempio n. 12
0
 def find_99ers(self):
     race = Race(self.db, race_number)
     race.make_99_list()
Esempio n. 13
0
 def result_list(self):
     maxtime = 35  # minutter
     control_point = 50
     overtime_penalty = 35
     #race_number = 153
     #os = 'linux'
     #db = Database('local','linux')
     poengo = Race(self.db, self.race_number, self.os)
     poengo.get_names()
     names = poengo.runners
     race_controls = [
         101, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
         115, 116, 120, 121, 122, 123, 124
     ]
     race_controls = [str(i) for i in race_controls]
     results = []
     self.heading.extend(race_controls)
     for name in names:
         sum_points = 0
         time_penalty = 0
         control_points = 0
         bonus = 0
         text = poengo.set_runner_details(name)
         text['Tid'] = name[8]
         text['tag'] = poengo.set_tag(name[10])
         if text['Tid']:
             controls = list(text['Poster'].split())
             controls = list(set(controls))
             if '250' in controls:
                 controls.remove('250')
             if '100' in controls:
                 controls.remove('100')
             text['Poster'] = controls
             # Fills in with all race control codes into text and set them to ""
             for code in race_controls:
                 if code in controls:
                     text[code] = control_point
                     control_points = control_points + control_point
                 else:
                     text[code] = str('')
             sum_points = control_points
             overtime = text['Tid'] - timedelta(minutes=maxtime)
             if overtime.days == 0:
                 time_penalty = math.ceil(
                     overtime.seconds / 60) * -overtime_penalty
                 sum_points = sum_points + time_penalty
             try:
                 bonus = self.bonus_points()[text['Klasse']]
                 sum_points = sum_points + bonus
             except Exception:
                 text['Bonus'] = str('')
             text['Poengsum'] = (sum_points)
             text['Bonuspoeng'] = (bonus)
             text['Tidstraff'] = (time_penalty)
             text['Postpoeng'] = (control_points)
             text['Tid'] = str(text['Tid'])
             result = []
             for title in self.heading:
                 result.append(text[title])
             results.append(result)
     results = sorted(results, key=lambda tup: (tup[4]))  # , reverse=True)
     plass = 1
     for result in results:
         result[0] = plass
         plass += 1
     return results
Esempio n. 14
0
class Tab(tk.Frame):
    def __init__(self, name, *args, **kwargs):
        self.os = kwargs['os']
        width = int(kwargs['width'])
        height = int(kwargs['height'])
        left_w = int(width * 0.07)
        mid_w = int(width - 2 * left_w)
        self.table_w = mid_w
        self.idx = 0
        self.runners = []
        tab_type = kwargs['tab_type']
        self.db = Database(kwargs['database'], kwargs['os'])
        self.race_number = None
        self.class_name = None
        self.name = None
        self.print_results = False
        self.race = None
        self.break_result_list = False
        self.break_loop_list = False
        if self.os == 'linux':
            self.log_file = open("/var/log/brikkespy.log", "w")
        else:
            self.log_file = open("brikkespy.log", "w")

    #Standard frame for alle tabs
        tk.Frame.__init__(self)
        # create all of the main containers
        self.top_frame = tk.Frame(
            self, bg='white')  #, width=100, height=50)  # , pady=3)
        center = tk.Frame(
            self, bg='black')  #, width=50, height=40)  # , padx=3, pady=3)
        btm_frame = tk.Frame(self,
                             bg='black')  #, width=450, height=45)  # , pady=3)

        # layout all of the main containers
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.top_frame.grid(row=0, sticky="ew")
        center.grid(row=1, sticky="nsew")
        btm_frame.grid(row=2, sticky="ew")

        # create the center widgets
        center.grid_rowconfigure(0, weight=1)
        center.grid_columnconfigure(0, weight=0)

        self.ctr_left = tk.Frame(center, bg='black', width=left_w,
                                 height=100)  # , padx=3, pady=3)
        ctr_mid = tk.Frame(center, width=mid_w,
                           height=100)  # , padx=3, pady=3)
        ctr_right = tk.Frame(center, bg='black', width=left_w,
                             height=100)  # , padx=3, pady=3)

        self.ctr_left.grid(row=0, column=0, sticky="ns")
        ctr_mid.grid(row=0, column=1, sticky="nsew")
        ctr_right.grid(row=0, column=2, sticky="nsew")

        #   Logo Banner
        pixels_x = 700
        pixels_y = int(pixels_x * 0.144)
        if self.os == 'linux':
            img = ImageTk.PhotoImage(
                Image.open("/etc/black_MILO_banner.png").resize(
                    (pixels_x, pixels_y)))
        else:
            img = ImageTk.PhotoImage(
                Image.open("black_MILO_banner.png").resize(
                    (pixels_x, pixels_y)))

        label = tk.Label(btm_frame, bg="black", image=img)
        label.image = img
        label.pack(side="bottom", fill="both", expand="yes")
        heading = [
            'Plass', 'Navn', 'Klubb', 'Klasse', 'Starttid', 'Tid', 'Differanse'
        ]
        columnwidth = [0.07, 0.26, 0.20, 0.1, 0.1, 0.1, 0.1]
        anchor = ['center', 'w', 'w', 'center', 'center', 'center', 'center']

        # Spesifiser for de forskjellige vinduene
        if tab_type == 'results':
            self.board = Table(ctr_mid,
                               width=mid_w,
                               height=height,
                               row_height=30,
                               heading=heading,
                               columnwidth=columnwidth,
                               anchor=anchor)
            #    self.res.tree.bind("<Double-1>", self.onclick_res)
            # Buttons
            class_button = tk.Button(self.top_frame,
                                     text='Klassevis',
                                     bg='white',
                                     command=partial(self.write_to_board))
            loop_button = tk.Button(self.top_frame,
                                    text='Loop',
                                    bg='white',
                                    command=partial(self.write_to_loop))
            class_button.grid(row=0, column=0)
            loop_button.grid(row=0, column=1)

        elif tab_type == 'prewarn':
            self.pre_db = Database('Prewarn', self.os)
            self.pre = Table(ctr_mid,
                             width=mid_w,
                             height=height,
                             row_height=30,
                             heading=heading,
                             columnwidth=columnwidth,
                             anchor=anchor)
            # Buttons
            self.button = tk.Button(self.top_frame,
                                    text='Forvarsel',
                                    command=partial(self.write_prewarn_list))
            self.button.grid(row=0, column=0)

        elif tab_type == 'adm':
            # Tabell for de som er i mål
            self.finish = Table(ctr_mid,
                                width=mid_w,
                                height=height,
                                row_height=30,
                                heading=heading,
                                columnwidth=columnwidth,
                                anchor=anchor)
            #        inne.tree.bind("<Double-1>", self.onclick_out)
            # Tabell for de som er ute i skogen
            self.out = Table(ctr_mid,
                             width=mid_w,
                             height=height,
                             row_height=30,
                             heading=heading,
                             columnwidth=columnwidth,
                             anchor=anchor)
            #        ute.tree.bind("<Double-1>", self.onclick_out)
            tk.Label(self.top_frame, text="Løp:").grid(row=0,
                                                       column=1,
                                                       sticky='w')
            # Combobox med alle løp i databasen
            self.combo_races = TTK.Combobox(self.top_frame,
                                            width=30,
                                            values=list(
                                                zip(*self.db.races))[1])
            self.combo_races.grid(row=0, column=2, sticky='w')
            self.combo_races.bind("<<ComboboxSelected>>",
                                  self.set_class_buttons)
            #        Checkboxes
            # Setter om det skal være sideskift for printing
            self.check = tk.Checkbutton(self.top_frame,
                                        text="Print med sideskift",
                                        variable=page_break,
                                        background='white').grid(row=0,
                                                                 column=3,
                                                                 sticky='w')
            self.check2 = tk.Checkbutton(self.top_frame,
                                         text="Print aktiv_klasse",
                                         variable=one_active_class,
                                         background='white').grid(row=0,
                                                                  column=4,
                                                                  sticky='w')
            self.check3 = tk.Checkbutton(self.top_frame,
                                         text="Print lister for start",
                                         variable=for_start,
                                         background='white').grid(row=0,
                                                                  column=5,
                                                                  sticky='w')

# Henter løpene og lager knapper for hver eneste klasse i løpet.

    def set_class_buttons(self, races):
        # Henter ønsket løp fra Combobox
        global race_number
        race_number = self.combo_races.current()
        self.race = Race(self.db, race_number, self.os)
        #        # Lager knapper for hver klasse
        try:
            if self.buttons:
                for button in self.buttons:
                    button.destroy()
        except:
            self.buttons = list()
        i = 0
        j = 0
        for class_name in self.race.class_names:
            self.buttons.append(
                tk.Button(self.ctr_left,
                          text=class_name,
                          command=partial(self.write_admin_list,
                                          class_name)).grid(row=i,
                                                            column=j,
                                                            padx=10))
            i += 1
            if i >= 30:  # Her bør vi regne ut hvor mange knapper man kan ha i høyden før man legger til ny knappekolonne
                j += 1
                i = 0

    def write_admin_list(self, class_name):
        global active_class
        active_class = class_name
        # denne kjøres kontinuerlig så og derfor må jeg sette flagg om ikke endrer urangerte listeri/
        # kontinuerlig. Her setter jeg randomize lik False
        self.randomized = False
        if self.class_name:
            self.finish.after_cancel(self.finish_tree_alarm)
            self.out.after_cancel(self.out_tree_alarm)

        # Her legger jeg inn en resultatliste som bare inneholde de som er i mål, DNS og DSQ
        self.finish.tree.delete(*self.finish.tree.get_children())
        result_list = self.race.make_result_list(class_name)
        self.write_table(result_list, 'res')
        self.finish_tree_alarm = self.finish.after(200, self.write_admin_list,
                                                   class_name)
        self.class_name = class_name

        # Her legger jeg inn en resultatliste som bare inneholder de som er ute
        self.out.tree.delete(*self.out.tree.get_children())
        out_list = self.race.make_result_list(class_name, 'out')
        self.write_table(out_list, 'out')
        self.out_tree_alarm = self.out.after(250, self.write_admin_list,
                                             class_name)

    def write_prewarn_list(self):
        prewarn_list = []
        self.race = Race(self.db, race_number, self.os)
        #Her legger jeg inn en resultatliste som bare inneholde de som er i mål, DNS og DSQ
        self.pre.tree.delete(*self.pre.tree.get_children())
        self.find_runner()
        for runner in self.runners:
            runner = list(runner)
            runner[10] = self.race.set_tag(runner[10])
            # sjekker om løperen ikke er kommet i mål.
            if runner[10] == 'ute':
                #Regner ut tiden som skal vises i Vindu. Ikke på resultatlister
                try:
                    runner[8] = self.race.get_time(runner[14])
                except:
                    if runner[10] == 'dns':
                        runner[8] = 'DNS'
            if not runner[8]:
                runner[8] = runner[10]
            prewarn_list.insert(0, self.race.set_runner_details(runner))
        for name in reversed(prewarn_list):
            self.pre.LoadinTable(name)
        self.pre_tree_alarm = self.pre.after(200, self.write_prewarn_list)

    def find_runner(self):
        nums = self.pre_db.read_start_numbers()
        for num in nums:
            if self.idx < num[0]:
                self.idx = num[0]
                try:
                    start_num = int(num[1])
                    runner = self.race.find_runner(start_num)
                    if runner:
                        self.runners.append(runner)
                except:
                    str_num = num
                    self.log_file.write("No startnumbers {0}: \n".format(
                        str(num)))
                    self.log_file.flush()

    def write_table(self, data, table):
        for name in reversed(data):
            if table == 'res':
                self.finish.LoadinTable(name)
            else:
                self.out.LoadinTable(name)

    # Denne brukes når det dobbelklikkes på navn i tabellen. Foreløpig så skjer det ingen ting. peker til update runners som er kommentert ut under.
    def onclick_out(self, race):
        self.update_runner_table()

    # Denne brukes når det dobbelklikkes på navn i tabellen. Foreløpig så skjer det ingen ting. peker til update runners som er kommentert ut under.
    def onclick_res(self, race):
        #self.res.after_cancel(self.res_tree_alarm)
        #item = str(self.res.tree.focus())
        #class_name = self.res.tree.item(item, "value")[2]
        #self.write_result_list(class_name)
        self.update_runner_table()

    def write_to_board(self):
        self.board.tree.delete(*self.board.tree.get_children())
        self.race = Race(self.db, race_number, self.os)
        self.class_names = iter(self.race.class_names)
        self.break_result_list = False
        self.break_loop_list = True
        self.write_result_list()

    def write_to_loop(self):
        self.board.tree.delete(*self.board.tree.get_children())
        self.break_result_list = True
        self.break_loop_list = False
        self.write_loop_list(0)

    def write_result_list(self):  # Skriver resultat liste per klasse
        if not self.break_result_list:
            class_list = []
            class_name = self.get_next_element(self.class_names)
            self.race = Race(self.db, race_number, self.os)
            if class_name is None:
                self.class_names = iter(self.race.class_names)
                class_name = self.get_next_element(self.class_names)
            self.board.tree.delete(*self.board.tree.get_children())
            result_list = self.race.make_result_list(class_name)
            # Her må jeg sjekke om det er noen i klassen
            if result_list:
                class_list.extend([self.line_shift()])
                class_list.extend([self.class_heading(class_name)])
                class_list.extend(result_list)
                for name in reversed(class_list):
                    self.board.LoadinTable(name)
            else:
                self.write_result_list()
            self.board_tree_alarm = self.board.after(5000,
                                                     self.write_result_list)

    def get_next_element(self, my_itr):
        try:
            return next(my_itr)
        except StopIteration:
            return None

    def make_loop_list(self):
        loop_list = []
        result_list = []
        race = Race(self.db, race_number, self.os)
        for class_name in race.class_names:
            # Henter resultatliste for klassen
            result_list = race.make_result_list(class_name)
            if result_list:  # Sjekker om det er deltaker i klassen
                loop_list.extend([self.line_shift()])
                loop_list.extend([self.class_heading(class_name)])
                loop_list.extend(result_list)
        return loop_list

    def write_loop_list(self, loop):
        if not self.break_loop_list:
            loop_list = self.make_loop_list()
            loop_list = loop_list[loop:] + loop_list[:loop]
            loop_length = len(loop_list)
            if loop >= loop_length:
                loop = 0
            self.board.tree.delete(*self.board.tree.get_children())
            for name in reversed(loop_list):
                self.board.LoadinTable(name)
            loop += 1
            self.board_tree_alarm = self.board.after(1000,
                                                     self.write_loop_list,
                                                     loop)

    def line_shift(self):
        text = {
            'Startnr': None,
            'Plass': str(''),
            'Navn': str(''),
            'Klubb': str(''),
            'Tid': str(''),
            'Differanse': str(''),
            'Klasse': str(''),
            'Starttid': str(''),
            'tag': str(''),
            'Brikkenr': str(''),
            'Poeng': str('')
        }
        return text

    def class_heading(self, class_name):
        text = {
            'Startnr': None,
            'Plass': str(''),
            'Navn': str('Klasse: ') + class_name,
            'Klubb': str(''),
            'Tid': str(''),
            'Differanse': str(''),
            'Klasse': str(''),
            'Starttid': str(''),
            'tag': str('title'),
            'Brikkenr': str(''),
            'Poeng': str('')
        }
        return text


#   Denne brukes når det dobbelklikkes på navn i tabellen. Foreløpig så skjer detingen ting. peker til update runners som er kommentert ut under.

    def onclick_pre(self, race):
        self.write_loop_list()

    def dummy_func(self, name):
        print(name)
Esempio n. 15
0
 def write_poengo(self):
     self.poengo.tree.delete(*self.poengo.tree.get_children())
     self.poeng = Race(self.db, race_number)
     self.write_poengo_list()
Esempio n. 16
0
 def write_poengo_csv(self):
     poeng = Race(self.db, race_number)
     results = poeng.make_point_list()
     self.write_csv_list(results, poeng.heading)
Esempio n. 17
0
    def result_list(self, db, race_number):
        race = Race(db, race_number)
        
        invoice_level = db.read_invoicelevel(race_number)

        fmt = '%H:%M:%S'
        xmlns_uris = {'xsd':'http://www.w3.org/2001/XMLSchema',
                'xsi':'http://www.w3.org/2001/XMLSchema-instance'}

        root = ET.Element("ResultList", 
                iofVersion="3.0",
                xmlns='http://www.orienteering.org/datastandard/3.0',
                createTime= datetime.now().isoformat(), #"2015-05-04T11:21:33.5287906", 
                creator="Brikkespy", 
                status="Complete")

        self.add_XMLNS_attributes(root, xmlns_uris)
        event = ET.SubElement(root, "Event")
        ET.SubElement(event, "Name").text = race.race_name 
        startTime= ET.SubElement(event, "StartTime")
        ET.SubElement(startTime, "Date").text = race.race_date.strftime('%Y-%m-%d')#"Date"
        endTime= ET.SubElement(event, "EndTime")
        ET.SubElement(endTime, "Date").text = race.race_date.strftime('%Y-%m-%d')#"Date"
#        ET.SubElement(startTime, "Time").text = "Time"
#        endTime = ET.SubElement(event, "EndTime")
#        ET.SubElement(endTime, "Date").text = "Date"
#        ET.SubElement(endTime, "Time").text = "Time"
#
#        race = ET.SubElement(event, "Race")
#        ET.SubElement(race, "RaceNumber").text="1"
#        ET.SubElement(race, "Name").text = "Race runner"
#        ET.SubElement(race, "StartTime")
#        ET.SubElement(race, "EndTime")
        for race_class in race.classes:
            classresult =ET.SubElement(root, "ClassResult")
            results = race.make_result_list(race_class[1])
 #           print(results)
            rclass = ET.SubElement(classresult, "Class")
#        ET.SubElement(rclass, "ID").text = "1"
            ET.SubElement(rclass, "Name").text = race_class[1] 
            
#        course= ET.SubElement(classresult, "Course", raceNumber="1")
#        ET.SubElement(course, "Length").text = "4650"
#        ET.SubElement(course, "climb").text= "160"
        
            for runner in results:
               # print("runner Tag: {}".format(runner.get("tag")))
               # print("runner name: {}".format(runner.get("Navn")))
               # print("runner.get(Tid) {} ".format(runner.get("Tid")))
                eventor_personid = db.read_eventor_personid(runner.get('id'))
                if eventor_personid:
               #     print('Eventor person id {} '.format(eventor_personid[0][2]))
               #     print('Eventor club id {}'.format(eventor_personid[0][3]))
                    eventor_club = db.read_eventor_club(eventor_personid[0][3])
                    #print(eventor_club)
            #    print(runner)
                personresult= ET.SubElement(classresult, "PersonResult")
                person = ET.SubElement(personresult, "Person")
                if eventor_personid:
                    ET.SubElement(person, "Id").text =  str(eventor_personid[0][2])
                name = ET.SubElement(person, "Name")
                ET.SubElement(name, "Family").text = runner.get('Navn').split()[-1]
                ET.SubElement(name, "Given").text = runner.get("Navn").replace(' '+runner.get('Navn').split()[-1],'')
                organisation = ET.SubElement(personresult, "Organisation")
                if eventor_personid:
                    ET.SubElement(organisation, "Id").text = str(eventor_personid[0][3])
                ET.SubElement(organisation, "Name").text= runner.get("Klubb")
                #ET.SubElement(organisation, "Country", code="GBR").text= "Great Britain"
                result = ET.SubElement(personresult, "Result")
                ET.SubElement(result, "BibNumber").text= runner.get('Startnr')
                if runner.get('tag') != 'dns':
                    ET.SubElement(result, "StartTime").text ='' if  runner.get("Starttime") == None else runner.get('Starttime').isoformat()
                    ET.SubElement(result, "FinishTime").text ='' if runner.get("Innkomst") == None else runner.get("Innkomst").isoformat() #strftime(fmt)
                try:
#                    date_time = datetime.strptime(runner.get("Tid"), "%H:%M:%S")
#                    a_timedelta = date_time - datetime(1900, 1, 1)
                    ET.SubElement(result, "Time").text = str(int(runner.get('Time').total_seconds()))#.seconds()
                except:
                    ET.SubElement(result, "Time").text = str(runner.get("Tid"))#.seconds()
#                ET.SubElement(result, "TimeBehind").text = runner.get("Differanse")
#                ET.SubElement(result, "Position").text= runner.get("Plass")
                if runner.get('tag') == 'inne':
                    ET.SubElement(result, "Status").text="OK"
                if runner.get('tag') == 'dns':
                    ET.SubElement(result, "Status").text="DidNotStart"
                if runner.get('tag') == 'dsq':
                    ET.SubElement(result, "Status").text="Disqualified"
#        overall = ET.SubElement(result, "OverallResult")
#        ET.SubElement(overall, "Time").text="2001"
#        ET.SubElement(overall, "TimeBehind").text="0"
#        ET.SubElement(overall, "Position").text="1"
#        ET.SubElement(overall, "Status").text="ok"
                #controls = runner.Poster.split()

                times = '' if runner.get('Times') == None else runner.get('Times').split(',')
                for control in times[0:-2]:
                    if control.split()[0] != '99':
                        split =  ET.SubElement(result, "SplitTime")
                        ET.SubElement(split, "ControlCode").text = control.split()[0]
                        ET.SubElement(split, "Time").text = control.split()[1]
                ET.SubElement(result, "ControlCard").text = runner.get("Brikkenr")                
                if invoice_level:

                   # print("Amount {}".format(invoice_level[1][5]))
                   # print("Innvoice: {}".format(runner.get("Invoice")))
                    try:
                        ind = [el.index(runner.get("Invoice")) for i, el in enumerate(invoice_level) if runner.get("Invoice") in el][0]
                        person_level = invoice_level[[el.index(runner.get("Invoice")) for i, el in enumerate(invoice_level) if runner.get("Invoice") in el][0]]
                     #   print([(i, el.index(runner.get("Invoice"))) for i, el in enumerate(invoice_level) if runner.get("Invoice") in el])
                        assignedfee = ET.SubElement(result, "AssignedFee")
                        fee = ET.SubElement(assignedfee, "Fee")
                        ET.SubElement(fee, "Name").text = person_level[3]
                     #   print("Amount2 {}".format(person_level[5]))
                        amount = ET.SubElement(fee, "Amount")
                        amount.set("currency", "NOK")
                        amount.text = str(person_level[5])

                    except:
                        print('Invoice level id {} '.format(invoice_level[0][2]))
                    
               # print('Invoice level id {} '.format(invoice_level))
        tree = ET.ElementTree(root)
        file = "result.xml"

        with open(file, 'wb') as f:
            #f.write(b'<?xml version="1.0" encoding="UTF-8"?>');
            tree.write(f, encoding='utf-8', xml_declaration=True)