Exemplo n.º 1
0
 def build(self):
     screen = Screen()
     table = MDDataTable(pos_hint={
         'center_x': 0.5,
         'center_y': 0.5
     },
                         size_hint=(0.9, 0.6),
                         check=True,
                         rows_num=10,
                         column_data=[
                             ('No', dp(18)),
                             ('Food', dp(20)),
                             ('Calories', dp(20)),
                         ],
                         row_data=[
                             ('1', 'Burger', '300'),
                             ('2', 'Oats', '30'),
                             ('3', 'Oats', '30'),
                             ('4', 'Oats', '30'),
                             ('5', 'Oats', '30'),
                             ('6', 'Oats', '30'),
                             ('7', 'Oats', '30'),
                             ('8', 'Oats', '30'),
                             ('9', 'Oats', '30'),
                             ('10', 'Oats', '30'),
                         ])
     table.bind(on_check_press=self.check_press)
     table.bind(on_row_press=self.row_press)
     screen.add_widget(table)
     return screen
Exemplo n.º 2
0
    def build(self):
        # Define Screen
        screen = Screen()
        # Define Table
        table = MDDataTable(pos_hint={
            'center_x': 0.5,
            'center_y': 0.5
        },
                            size_hint=(0.9, 0.6),
                            check=True,
                            column_data=[("First Name", dp(30)),
                                         ("Last Name", dp(30)),
                                         ("Email Address", dp(30)),
                                         ("Phone Number", dp(30))],
                            row_data=[
                                ("John", "Elder", "*****@*****.**",
                                 "(123) 456-7891"),
                                ("Mary", "Elder", "*****@*****.**",
                                 "(123) 456-1123"),
                            ])

        # Bind the table
        table.bind(on_check_press=self.checked)
        table.bind(on_row_press=self.row_checked)

        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "BlueGray"
        #return Builder.load_file('table.kv')
        # Add table widget to screen
        screen.add_widget(table)
        return screen
Exemplo n.º 3
0
 def update_jobdata(self, *args):
     data = check_all_job_status().get('Jobs', [])
     for idx, job in enumerate(data):
         if job[1] == "Finished":
             job[1] = ("checkbox-marked-circle",
                       [39 / 256, 174 / 256, 96 / 256, 1], "Finished")
         else:
             job[1] = ("alert-circle", [1, 0, 0, 1], "Running")
         job.append(("information", [255 / 256, 165 / 256, 0, 1], ""))
     if len(data) == 1:
         data.append(data[0])
     self.job_data.clear_widgets()
     layout = AnchorLayout()
     data_tables = MDDataTable(
         size_hint=(0.9, 0.9),
         use_pagination=True,
         check=True,
         column_data=[
             ("Jobname", dp(50), self.sort_on_jobname),
             ("Progress", dp(30)),
             ("Status", dp(30)),
             ("Get information", dp(30)),
         ],
         row_data=data,
     )
     data_tables.bind(on_row_press=self.show_jobdata_info)
     # TODO: Rework color settings for better readability
     layout.add_widget(data_tables)
     self.job_data.add_widget(layout)
     self.job_table = data_tables
     return
Exemplo n.º 4
0
    def build(self):
        screen = Screen()
        data_table = MDDataTable(pos_hint={'center_x': 0.5, 'center_y': 0.5},
                                 size_hint=(0.9, 0.6),
                                 check=True,
                                 rows_num=10,
                                 column_data=[
                                     ("No.", dp(18)),
                                     ("Food", dp(20)),
                                     ("Calories", dp(20))
                                 ],
                                 row_data=[
                                     ("1", "Burger", "300"),
                                     ("2", "Oats", "200"),
                                     ("3", "Oats", "200"),
                                     ("4", "Oats", "200"),
                                     ("5", "Oats", "200"),
                                     ("6", "Oats", "200"),
                                     ("7", "Oats", "200"),
                                     ("8", "Oats", "200")

                                 ]
                                 )
        data_table.bind(on_row_press=self.on_row_press)
        data_table.bind(on_check_press=self.on_check_press)
        screen.add_widget(data_table)
        return screen
Exemplo n.º 5
0
class Table(GridLayout):

    def __init__(self):
        super().__init__(cols=1)

        self.table = MDDataTable(use_pagination=True,
            column_data=[
                ("Name", dp(30)),
                ("Value", dp(30)),
                ("Date", dp(30)),
                ("Label", dp(30)),
                ("Debit/Credit", dp(30))],
            row_data=[
                (f"{i + 1}", f"{(i+1) * 2}", "2020-09-"+f"{i+1}".rjust(2, '0'), "Pastry", "Debit")
                for i in range(30)])

        self.add_widget(self.table)
        self.button = Button(text="Remove")
        self.add_widget(self.button)

        self.button.bind(on_touch_down=self.on_pressed)
        self.table.bind(on_touch_down=self.on_pressed)
        self.table.bind(on_row_press=self.on_row_press)
        # self.remove_button.bind(on_press=callback)

    def on_row_press(self, instance_table, instance_row):
        print(instance_table, instance_row)

    def on_pressed(self, instance, touch):
        if touch.button == 'right':
            print('right mouse button clicked!')
Exemplo n.º 6
0
 def build(self):
     screen = Screen()
     table = MDDataTable(size_hint=(0.9, 0.6),
                         pos_hint={
                             'center_x': 0.5,
                             'center_y': 0.5
                         },
                         check=True,
                         rows_num=10,
                         column_data=[("No.", dp(30)), ("Food", dp(30)),
                                      ("Calories", dp(30))],
                         row_data=[("1", "Burger", "300"),
                                   ("2", "Burger", "300"),
                                   ("3", "Meggie", "400"),
                                   ("4", "Meggie", "400"),
                                   ("5", "Meggie", "400"),
                                   ("6", "Meggie", "400"),
                                   ("7", "Meggie", "400"),
                                   ("8", "Meggie", "400"),
                                   ("9", "Meggie", "400"),
                                   ("10", "Meggie", "400")])
     table.bind(on_check_press=self.check_press)
     table.bind(on_row_press=self.row_press)
     screen.add_widget(table)
     return screen
Exemplo n.º 7
0
    def add_table_screens(self, data):
        c_data = [data[i:i + 7] for i in range(0, len(data), 7)]
        plt = platform.system()
        if plt == 'Windows':
            font_size = '[size=10]'
        else:
            font_size = '[size=30]'
        for index, fragment in enumerate(c_data):
            row_data = []
            for item in fragment:
                if item.nav == 0:
                    continue
                prev_nav = tryout.get_prev_nav(item)
                p = round(abs(((item.nav - prev_nav) / prev_nav) * 100), 2)
                if prev_nav > item.nav:
                    nav_str = "[color=#FF0000]" + font_size + str(
                        item.nav) + "(" + str(p) + "%)[/size][/color]"
                elif prev_nav < item.nav:
                    nav_str = "[color=#448d08]" + font_size + str(
                        item.nav) + "(" + str(p) + "%)[/size][/color]"
                else:
                    nav_str = str(item.nav)

                sym_str = font_size + item.symbol + '[/size]'
                qty_str = font_size + str(item.quantity) + '[/size]'
                prc_str = font_size + str(item.price) + '[/size]'
                if plt == 'Windows':
                    row = [sym_str, qty_str, prc_str, nav_str]
                else:
                    row = [sym_str, qty_str, nav_str]

                row_data.append(row)
                if len(fragment) == 1:
                    row_data.append(['', '', '', ''])
            table = MDDataTable(
                size_hint=(1, 0.8),
                pos_hint={
                    'center_x': 0.5,
                    'center_y': 0.5
                },
                use_pagination=False,
                pagination_menu_pos='center',
                rows_num=7,
                check=False,
                column_data=[
                    ("Symbol", dp(20)),
                    ("Quantity", dp(20)),
                    ("NAV", dp(20)),
                ] if plt == 'Linux' else [
                    ("Symbol", dp(45)),
                    ("Quantity", dp(45)),
                    ("Price", dp(45)),
                    ("NAV", dp(45)),
                ],
                row_data=row_data,
            )

            table.bind(on_row_press=tryout.on_row_press)
            tableScreen = TableScreen(table, name='table' + str(index))
            self.screens.append(tableScreen)
Exemplo n.º 8
0
class Example(MDApp):
    def build(self):
        self.data_tables = MDDataTable(
            size_hint=(0.9, 0.6),
            use_pagination=True,
            check=True,
            column_data=[
                ("No.", dp(30)),
                ("Column 1", dp(30)),
                ("Column 2", dp(30)),
                ("Column 3", dp(30)),
                ("Column 4", dp(30)),
                ("Column 5", dp(30)),
            ],
            row_data=[
                (f'{i+1}', '4.1', '2.3', '82', '2.3', '0.82') for i in range(10)
            ]
        )
        self.data_tables.bind(on_row_press = self.on_row_press)
        self.data_tables.bind(on_check_press = self.on_check_press)

    def on_row_press(self, inst_table, inst_row):
        print(inst_table, inst_row)

    def on_check_press(self, inst_table, inst_row):
        print(inst_table, inst_row)

    def on_start(self):
        self.data_tables.open()
Exemplo n.º 9
0
    def build(self):
        screen = Screen()

        self.help_str = Builder.load_string(helper_string)

        screen.add_widget(self.help_str)



        table = MDDataTable(pos_hint = {'center_x':0.5,'center_y':0.5},size_hint = (0.9,0.6),check = True,rows_num=7,
                        column_data =[
                                    ("Food",dp(30)),
                                    ('Calories',dp(30)),
                                    ('Price',dp(30)),
                                    ('Must-Buy ?',dp(30)) ],
                        row_data = [
                                    ("Apple","300",'50','No'),
                                    ("Mango","300",'50','No'),
                                    ("Banana","300",'50','No'),
                                    ("Apple","300",'50','No'),
                                    ("Apple","300",'50','No'),
                                    ("Apple","300",'50','No'),
                                    ("Apple","300",'50','No'),
                                    ("Apple","300",'50','No'),] )
        table.bind(on_check_press = self.check_press)
        table.bind(on_row_press = self.row_press)

        self.help_str.get_screen('hello').add_widget(table)
        return screen
Exemplo n.º 10
0
    def add_table_screens(self, data):
        c_data = [data[i:i + 7] for i in range(0, len(data), 7)]
        plt = platform.system()
        if plt == 'Windows':
            font_size = '[size=10]'
        else:
            font_size = '[size=30]'
        for index, fragment in enumerate(c_data):
            row_data = []
            for item in fragment:
                if item.nav == 0:
                    continue
                cost = round(item.cost * item.quantity, 2)
                gain_loss = item.gain
                if gain_loss < 0:
                    gain_loss = "[color=#FF0000]" + font_size + str(
                        abs(round(gain_loss, 2))) + "[/size][/color]"
                else:
                    gain_loss = "[color=#448d08]" + font_size + str(
                        round(gain_loss, 2)) + "[/size][/color]"
                sym_str = font_size + item.symbol + '[/size]'
                cost_str = font_size + str(cost) + '[/size]'
                nav_str = font_size + str(item.nav) + '[/size]'
                if plt == 'Windows':
                    row = [sym_str, cost_str, nav_str, gain_loss]
                else:
                    row = [sym_str, cost_str, gain_loss]
                row_data.append(row)
            if len(fragment) == 1:
                row_data.append(
                    ['', '', '',
                     ''])  # hack. MDDatatable breaks if there just one row

            table = MDDataTable(size_hint=(1, 0.8),
                                pos_hint={
                                    'center_x': 0.5,
                                    'center_y': 0.5
                                },
                                use_pagination=False,
                                background_color=(0.2, .2, .2, 1),
                                rows_num=7,
                                check=False,
                                column_data=[
                                    ("Symbol", dp(20)),
                                    ("Cost", dp(20)),
                                    ("Gain", dp(20)),
                                ] if plt == 'Linux' else [
                                    ("Symbol", dp(45)),
                                    ("Cost", dp(45)),
                                    ("NAV", dp(45)),
                                    ("Gain", dp(45)),
                                ],
                                row_data=row_data)
            table.md_bg_color = (0.2, .2, .2, 1)
            table.bind(on_row_press=tryout.on_row_press)
            tableScreen = TableScreen(table, name='table_g' + str(index))
            self.screens.append(tableScreen)
Exemplo n.º 11
0
class BookListScreen(MDScreen):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.name = 'book_list_screen'

    def on_enter(self):
        print('Entered ' + self.name)
        self.this_loop = Clock.schedule_interval(self.loop, 0)
        try:
            book_ids = []
            borrowed = []
            row_datas = []
            for row in cur.execute('SELECT * FROM books '):
                book_ids.append(row[1])
            print(book_ids)
            for id in book_ids:
                borrowed.append(
                    cur.execute(
                        f'SELECT COUNT(*) FROM exchange WHERE book_id={id} AND status=1'
                    ).fetchall()[0][0])
            print(borrowed)
            print("Name", "ID", "Borrowed", "Available", "Total")
            for n, row in enumerate(cur.execute('SELECT * FROM books ')):
                row_datas.append((n + 1, row[0], row[1], borrowed[n],
                                  row[2] - borrowed[n], row[2]))
                print(n + 1, row[0], row[1], borrowed[n], row[2] - borrowed[n],
                      row[2])
            print(row_datas)
            self.data_table = MDDataTable(
                pos_hint={
                    'center_x': 0.5,
                    'center_y': 0.5
                },
                size_hint=(0.9, 0.9),
                #  check=True,
                rows_num=len(row_datas),
                column_data=[("No.", dp(15)), ("Name", dp(50)), ("ID", dp(20)),
                             ("Borrowed", dp(20)), ("Available", dp(20)),
                             ("Total", dp(20))],
                row_data=row_datas)
            self.ids["bookTable"].add_widget(self.data_table)
            self.data_table.bind(on_row_press=self.back)
        except Exception as e:
            print(e, "Table or data Not Found")

    def back(self, a, b):
        my_app.screen_manager.current = 'list_select_screen'

    def on_pre_leave(self):
        Clock.unschedule(self.this_loop)
        self.ids["bookTable"].remove_widget(self.data_table)
        print('Leaving ' + self.name)

    def loop(self, dt):
        pass
Exemplo n.º 12
0
class RootLayout(Screen):
    stop = threading.Event()

    def start_second_thread(self):
        threading.Thread(target=self.load_data).start()

    def load_data(self, *args):
        if TRIPS_SELECTED:
            for n_trip in TRIPS_SELECTED:
                post_request = requests.delete(
                    f'https://mobileapp-30e40.firebaseio.com/{n_trip}.json')

        get_request = requests.get(f'https://mobileapp-30e40.firebaseio.com/.json')
        trips_data = json.loads(get_request.content.decode())

        count = 0
        cols = ['data']
        values = []

        for trip, data in trips_data.items():
            lista = []
            lista.append(trip)
            for key, info in data.items():
                lista.append(info)

                if count == 0:
                    cols.append(key)
            count += 1
            values.append(lista)

        self.update_table(cols, values)

    def on_check_press(self, instance_table, current_row):
        '''Called when the check box in the table row is checked.'''
        if current_row[0] in TRIPS_SELECTED:
            TRIPS_SELECTED.remove(current_row[0])
        else:
            TRIPS_SELECTED.append(current_row[0])

    @mainthread
    def update_table(self, cols, values):
        self.table_box.clear_widgets()

        self.data_table = MDDataTable(
            column_data=[(col, dp(28)) for col in cols],
            row_data=values,

        )

        self.data_table.bind(on_check_press=self.on_check_press)

        self.table_box.add_widget(self.data_table)
Exemplo n.º 13
0
class Fun_Consultas():
    data_tables: MDDataTable

    def __init__(self, **kwargs):
        super(Fun_Consultas, self).__init__()

    def md_table(self):
        try:
            self.APP_PATH = os.getcwd()
            self.DB_PATH = self.APP_PATH + "/bd_example.db"

            con = sqlite3.connect(self.DB_PATH)
            cursor = con.cursor()

            query = "select id,patente,Bultos,Tienda,Guia,Odometro from Movimientos "
            cursor.execute(query)
            record = cursor.fetchall()

        except Exception as e:
            print(e)

        self.data_tables = MDDataTable(
            use_pagination=True,
            size_hint=(0.9, 0.6),
            check=False,
            sort=True,
            # name column, width column
            column_data=[
                ("Id", dp(20)),
                ("Patente", dp(20)),
                ("Bultos", dp(20)),
                ("Tienda", dp(40)),
                ("Guia", dp(20)),
                ("Odometro", dp(20)),
            ],
            row_data=record)
        self.data_tables.bind(on_row_press=Fun_Consultas.on_row_press)
        self.data_tables.bind(on_check_press=Fun_Consultas.on_check_press)

        self.data_tables.open()

    def on_row_press(instance_table, instance_row):
        no = instance_row.text
        print(no)

    def on_check_press(instance_table, current_row):
        print(instance_table, current_row)
Exemplo n.º 14
0
    def build(self):
        column_names = self.data_frame[1]
        values = self.data_frame[2]

        screen = Screen()
        data_table = MDDataTable(pos_hint={
            'center_x': 0.5,
            'center_y': 0.5
        },
                                 size_hint=(0.9, 0.6),
                                 check=True,
                                 rows_num=20,
                                 column_data=column_names,
                                 row_data=values)
        data_table.bind(on_row_press=self.on_row_press)
        data_table.bind(on_check_press=self.on_check_press)
        screen.add_widget(data_table)
        return screen
Exemplo n.º 15
0
    def build(self):

        screen = Screen()

        self.help_str = Builder.load_file("main.kv")

        screen.add_widget(self.help_str)
        users_tables = MDDataTable(
            pos_hint={
                'center_x': 0.5,
                'center_y': 0.5
            },
            size_hint=(1, 1),
            use_pagination=True,
            check=True,
            column_data=[
                ("Nom", dp(30)),
                ("Prenom", dp(30)),
                ("Code", dp(30)),
                ("Tel", dp(30)),
                ("Nombre d'étudiants", dp(30)),
            ],
            row_data=self.users,
        )

        users_tables.bind(on_check_press=self.user_check_press)
        users_tables.bind(on_row_press=self.row_press)

        students_tables = MDDataTable(pos_hint={
            'center_x': 0.5,
            'center_y': 0.5
        },
                                      size_hint=(1, 1),
                                      use_pagination=True,
                                      check=True,
                                      column_data=[
                                          ("Nom", dp(30)),
                                          ("Prenom", dp(30)),
                                          ("Code", dp(30)),
                                          ("Tel", dp(30)),
                                          ("code paraints", dp(30)),
                                      ],
                                      row_data=self.students)

        students_tables.bind(on_check_press=self.check_press)
        students_tables.bind(on_row_press=self.row_press)

        self.help_str.ids.screen_manager.get_screen(
            'manage_users').children[0].add_widget(users_tables)
        self.help_str.ids.screen_manager.get_screen(
            'manage_students').add_widget(students_tables)

        return screen
Exemplo n.º 16
0
 def __init__(self, data, **kwargs):
     super(HistorialDeUsuarioLayout, self).__init__(**kwargs)
     self.data = data
     self.orientation = 'vertical'
     self.padding = padding
     row_data = []
     for simulacion in data:
         tupla = (simulacion.id, str(simulacion.fecha),
                  simulacion.conversacion.culturaobjetivo.nombre,
                  simulacion.conversacion.nombre,
                  simulacion.calificaciondeusuario, "Detalles")
         row_data.append(tupla)
     table = MDDataTable(column_data=[("", dp(10)), ("FECHA", dp(30)),
                                      ("CULTURA OBJETIVO", dp(30)),
                                      ("CONVERSACIÓN", dp(30)),
                                      ("RESULTADO", dp(20)), ("", dp(30))],
                         row_data=row_data)
     table.bind(on_row_press=self.detallesdesimulacion)
     self.add_widget(table)
Exemplo n.º 17
0
 def data_table_set(self):
     data_table = MDDataTable(pos_hint={
         'center_x': 0.5,
         'center_y': 0.5
     },
                              size_hint=(0.9, 0.6),
                              check=True,
                              rows_num=10,
                              column_data=[("No.", dp(18)),
                                           ("Food", dp(20)),
                                           ("Calories", dp(20))],
                              row_data=[("1", "Burger", "300"),
                                        ("2", "Oats", "200"),
                                        ("3", "Oats", "200"),
                                        ("4", "Oats", "200"),
                                        ("5", "Oats", "200"),
                                        ("6", "Oats", "200"),
                                        ("7", "Oats", "200"),
                                        ("8", "Oats", "200")])
     data_table.bind(on_row_press=DemoApp.on_row_press)
     data_table.bind(on_check_press=DemoApp.on_check_press)
Exemplo n.º 18
0
 def on_enter(self, *args):
     global StaffName
     global StaffID
     self.ids.staff_name.text = StaffName
     query = "SELECT cs_code FROM staff_class WHERE sid=%s"
     val = (StaffID, )
     tmp_cursor.execute(query, val)
     result = tmp_cursor.fetchall()
     self.codes = ""
     for x in result:
         self.codes += x[0] + ","
     self.codes = self.codes.strip(',')
     query = "SELECT * FROM submission WHERE cs_code IN(" + self.codes + ") ORDER BY date DESC,time DESC"
     tmp_cursor.execute(query)
     result = tmp_cursor.fetchall()
     table_rows = []
     for x in result:
         q = "SELECT class,subject FROM staff_class WHERE cs_code=%s"
         v = (x[0], )
         tmp_cursor.execute(q, v)
         r = tmp_cursor.fetchone()
         table_rows.append((str(x[1]), str(x[2]), str(r[0]), str(r[1]),
                            str(x[0])))  # date,time,class,subject,cs_code
     if len(table_rows) > 0:
         data_table = MDDataTable(pos_hint={
             'center_x': 0.5,
             'center_y': 0.4
         },
                                  size_hint=(1, 1),
                                  check=True,
                                  rows_num=len(table_rows),
                                  column_data=[("Date", dp(30)),
                                               ("Time", dp(15)),
                                               ("Class", dp(18)),
                                               ("Subject", dp(18)),
                                               ("Code", dp(15))],
                                  row_data=table_rows)
         data_table.bind(on_check_press=self.check_press)
         self.ids.submission_list.add_widget(data_table)
Exemplo n.º 19
0
def view_ttd():
    """Create and open datatable dialog popup"""
    app = MDApp.get_running_app()  ## main app object reference
    data = lib.gen_ref_code.generate_reference_codes()
    ## create data rows for datatable \/
    table_data = [(
        item['codigo_ref'],
        f"{item['cls_nome'][:60]}{' [ . . . ]' if len(item['cls_nome']) > 60 else ''}",
        item['fase_corrente'] if item['fase_corrente'].strip() != '' else '-',
        item['fase_intermediaria']
        if item['fase_corrente'].strip() != '' else '-', item['dest_final'])
                  for item in data]

    datatable = MDDataTable(
        size_hint=(0.95, 0.9),
        column_data=[("Código de Referência", dp(40)),
                     ("Nome da Classe", dp(95)), ("Fase Corrente", dp(30)),
                     ("Fase Intermediária", dp(40)),
                     ("Destinação Final", dp(30))],
        rows_num=len(table_data) if len(table_data) > 0 else 1,
        row_data=table_data)
    datatable.bind(on_dismiss=lambda *x: app.root.switch_to_screen('pcd'))
    datatable.open()
Exemplo n.º 20
0
class Example(MDApp):
    def build(self):
        DATA = pd.read_excel("downloaded_medals.xls")
        DATA = DATA.iloc[:, 1:]
        cols = DATA.columns.values
        values = DATA.values

        self.data_tables = MDDataTable(size_hint=(0.9, 0.6),
                                       use_pagination=True,
                                       column_data=[(col, dp(30))
                                                    for col in cols],
                                       row_data=values)
        self.data_tables.bind(on_row_press=self.on_row_press)
        self.data_tables.bind(on_check_press=self.on_check_press)

        self.button = MDRectangleFlatButton(pos_hint={
            "center_x": .5,
            "center_y": .5
        },
                                            text="Abrir Tabla",
                                            on_release=self.open_table)

        return self.button

    def open_table(self, instance):
        self.data_tables.open()

    def on_row_press(self, instance_table, instance_row):
        '''Called when a table row is clicked.'''

        print(instance_table, instance_row)

    def on_check_press(self, instance_table, current_row):
        '''Called when the check box in the table row is checked.'''

        print(instance_table, current_row)
Exemplo n.º 21
0
class FirstScreen(Screen):  #Pantalla comparador de precios
    """Clase principal donde se ejecuta el modulo comparador de precios, en ella se inicializan las variables correspondientes que se
    utilizaran en el módulo"""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.app = MDApp.get_running_app()
        self.valorbarra = 0

        self.buttonactualizar = MDRectangleFlatIconButton(
            pos_hint={
                "center_x": .5,
                "top": .95
            },
            #size_hint = (.3,.1),
            icon="cart-arrow-down",
            text=" Precios",
        )
        self.msgactualiza = MDLabel(text='Actualizando, espera por favor',
                                    pos_hint={
                                        "center_x": .5,
                                        "top": .87
                                    },
                                    size_hint=(.8, .1),
                                    theme_text_color="Primary",
                                    font_style="Subtitle1",
                                    halign="center")

        self.barra = MDProgressBar(id="barrasss",
                                   value=0,
                                   pos_hint={
                                       "center_x": .5,
                                       "center_y": .80
                                   },
                                   size_hint=(.9, .1))

        self.etiqueta1 = MDLabel(text='Consultar por Tienda',
                                 pos_hint={
                                     "center_x": .5,
                                     "top": .80
                                 },
                                 size_hint=(.5, .1),
                                 theme_text_color="Primary",
                                 font_style="Subtitle1",
                                 halign="center")

        self.buttonche = MDFillRoundFlatButton(
            pos_hint={
                "x": .05,
                "y": .6
            },
            size_hint=(.40, .1),
            text="Chedraui",
            on_release=lambda x: self.verboton('che'))

        self.buttonsor = MDFillRoundFlatButton(
            pos_hint={
                "x": .55,
                "y": .6
            },
            size_hint=(.40, .1),
            text="Soriana",
            on_release=lambda x: self.verboton('sor'))

        self.buttonhbe = MDFillRoundFlatButton(
            pos_hint={
                "x": .05,
                "y": .45
            },
            size_hint=(.40, .1),
            #theme_text_color = "Primary",
            text="HBE",
            on_release=lambda x: self.verboton('hbe'))

        self.buttoncomer = MDFillRoundFlatButton(
            pos_hint={
                "x": .55,
                "y": .45
            },
            size_hint=(.40, .1),
            text="La Comer",
            on_release=lambda x: self.verboton('comer'))

        self.etiqueta2 = MDLabel(text='Consultar por Categoría',
                                 pos_hint={
                                     "center_x": .5,
                                     "top": .40
                                 },
                                 size_hint=(.5, .1),
                                 theme_text_color="Primary",
                                 font_style="Subtitle1",
                                 halign="center")

        self.buttonfrutas = MDFillRoundFlatButton(
            pos_hint={
                "x": .05,
                "y": .20
            },
            size_hint=(.25, .1),
            text="Frutas",
            on_release=lambda x: self.verboton('frutas'))

        self.buttonverduras = MDFillRoundFlatButton(
            pos_hint={
                "x": .35,
                "y": .20
            },
            size_hint=(.25, .1),
            text="Verduras",
            on_release=lambda x: self.verboton('verduras'))

        self.buttoncarnes = MDFillRoundFlatButton(
            pos_hint={
                "x": .65,
                "y": .20
            },
            size_hint=(.25, .1),
            text='Carnes',
            on_release=lambda x: self.verboton('carnes'))

        self.buttonlacteos = MDFillRoundFlatButton(
            pos_hint={
                "x": .20,
                "y": .05
            },
            size_hint=(.25, .1),
            text='Lácteos',
            on_release=lambda x: self.verboton('lacteos'))

        self.buttonenlatados = MDFillRoundFlatButton(
            pos_hint={
                "x": .50,
                "y": .05
            },
            size_hint=(.25, .1),
            text='Enlatados',
            on_release=lambda x: self.verboton('enlatados'))

        self.buttonactualizar.bind(on_press=lambda x: self.ActualizaPrecio())

        self.add_widget(self.buttonactualizar)

        self.add_widget(self.buttonche)
        self.add_widget(self.buttonsor)
        self.add_widget(self.buttonhbe)
        self.add_widget(self.buttoncomer)
        self.add_widget(self.etiqueta1)
        self.add_widget(self.etiqueta2)
        self.add_widget(self.buttonfrutas)
        self.add_widget(self.buttonverduras)
        self.add_widget(self.buttoncarnes)
        self.add_widget(self.buttonlacteos)
        self.add_widget(self.buttonenlatados)

        #food-steak carne food-drumstick
        #food-apple fruta
        #cheese lacteos
        #carrot verduras
        #dome-light
        #return self.button

    #def tabla(self, widget):

    def MuestraNotificacionComparador(self):
        """Se muestra las notificaciones que se anexaron al modulo del comparador de precios"""
        self.a = randint(1, 6)
        print(self.a)
        if self.a == 1:

            notification.notify(
                title='Como Actualizar los precios',
                message=
                'Puedes actualizar los precios de los productos pulsando el boton de Actualizar que se encuentra en'
                'la parte superior',
                timeout=20)
            snackbar = Snackbar(
                text=
                "Puedes actualizar los precios de los productos pulsando el boton de Actualizar que se encuentra en la parte superior"
            )
            snackbar.show()

        if self.a == 2:
            notification.notify(
                title='Visualización de los Precios',
                message=
                'Los precios pueden ser consultados deslizando la tabla que se muestra al consultar alguna categoría',
                timeout=20)
            snackbar = Snackbar(
                text=
                "Los precios pueden ser consultados deslizando la tabla que se muestra al consultar alguna categoría"
            )
            snackbar.show()

        pass

    def ActualizaPrecio(self):
        """Función desde la cual se obtienen los precios, se llama una funcion que esta en el fichero Actualiza Precios, se ejecutan hilos
        para obtener los precios simultaneamente, de esta manera se previene el congelamiento de la aplicación, en esta función tambien se
        llama a la funcion actualiza barra"""
        ap.main()

        self.add_widget(self.barra)
        self.add_widget(self.msgactualiza)
        self.buttonactualizar.disabled = True
        self.hiloactualiza = threading.Thread(
            target=self.actualizabarra
        )  # Inicializar un hilo llamando a una funcion
        self.hiloactualiza.start()

        #self.actualizabarra()

        self.dialog = MDDialog(
            title="Actualización de Precios",
            text=
            "Se actualizarán los precios que se muestran en cada una de las categorías del comparador de precios,"
            " este proceso puede demorar algunos  un par de minutos, por favor sea paciente",
            size_hint=[.9, .9],
            auto_dismiss=True,
            buttons=[
                MDFlatButton(text="CERRAR", on_release=self.dialog_close),
            ])
        self.dialog.open()

    def actualizabarra(self):
        """Funcion que actualiza la barra mostrada en el módulo comparador de precios"""
        #if ap.sor.correccion_datos_sor() == True:
        for a in range(100):
            self.valorbarra = self.valorbarra + 1
            self.barra.value = self.valorbarra
            sleep(1.3)

        sleep(5)
        self.remove_widget(self.msgactualiza)
        sleep(1)
        self.remove_widget(self.barra)

    def dialog_close(self, *args):  # Cierra el dialog del boton ayuda
        """Funcion que cierra el dialog que se despliega al oprimir el botón actualizar"""
        print("Cerrando Dialog")
        self.dialog.dismiss()

    def verboton(self, valor):
        self.MuestraNotificacionComparador()
        if valor == 'comer':
            datos = pd.read_csv("csv/info_lacomer.csv", encoding='utf8')
        elif valor == 'hbe':
            datos = pd.read_csv("csv/info_hbe.csv", encoding='utf8')
        elif valor == 'sor':
            datos = pd.read_csv("csv/info_sor.csv", encoding='utf8')
        elif valor == 'che':
            datos = pd.read_csv("csv/info_che.csv", encoding='utf8')
        elif valor == 'frutas':
            datos = pd.read_csv("csv/infofrutas.csv", encoding='utf8')
        elif valor == 'verduras':
            datos = pd.read_csv("csv/infoverduras.csv", encoding='utf8')
        elif valor == 'carnes':
            datos = pd.read_csv("csv/infocarnes.csv", encoding='utf8')
        elif valor == 'lacteos':
            datos = pd.read_csv("csv/infolacteos.csv", encoding='utf8')
        elif valor == 'enlatados':
            datos = pd.read_csv("csv/infoenlatados.csv", encoding='utf8')

        datos = datos.iloc[:,
                           1:]  # primer arg selecciona todas las filas, segundo
        cols = datos.columns.values
        values = datos.values

        self.table = MDDataTable(
            pos_hint={
                'center_x': 0.5,
                'center_y': 0.5
            },
            size_hint=(0.99, 0.99),
            #font_size = 10,
            #check= True,
            use_pagination=True,
            rows_num=10,
            column_data=[(col, dp(40)) for col in cols],
            row_data=values)

        self.table.bind(on_check_press=self.check_press)
        self.table.bind(on_check_press=self.row_press)

        self.table.open()
        print(valor)

    def my_callback(
        self, texto, popup_widget
    ):  # funcion que ayuda a cerrar el dialog del boton actualizar
        print(texto)
        print(popup_widget)

    def open_table(self, instance):
        """Despliega el contenido de la tabla correpondiente al boton pulsado"""
        #screen.add_widget(table)
        self.table.open()

    def check_press(self, instance_table, current_row):
        print(instance_table, current_row)

    def row_press(self, instance_table, instance_row):
        print(instance_table, instance_row)
        #self.sub_title = "Comparador"

    def on_pre_enter(self, *args):
        self.app.title = "Comparador de precios"

    pass
Exemplo n.º 22
0
    def load_approval_page(self):
        ContentNavigationDrawer.populateNavDrawerValues(self)
        query = f'''SELECT MEMORG.NAME AS ONAME, NEWCON.FIRST_NAME||' '||NEWCON.LAST_NAME AS NAME, 
        NEWCON.EMAIL AS EMAIL
        FROM CONTACT NEWCON, CONTACT_ORG CONORG, 
        CONTACT_ORG MEMCON, ORG MEMORG
        WHERE NEWCON.CONTACT_ID = CONORG.CONTACT_ID
        AND CONORG.STATUS='N' AND CONORG.MEMBER_FLAG='P'
        AND MEMORG.ORG_ID = CONORG.ORG_ID
        AND CONORG.ORG_ID = MEMCON.ORG_ID
        AND MEMCON.CONTACT_ID={globalvariables.var_userid}
        AND MEMCON.STATUS='Y'
        AND MEMCON.MEMBER_FLAG='Y' '''
        # run direct SQL
        stmt = ibm_db.exec_immediate(connection.conn, query)
        txnlist = ibm_db.fetch_both(stmt)
        if txnlist is False:
            warn_label = MDLabel(pos_hint={
                'center_x': 0.5,
                'center_y': 0.5
            },
                                 font_size='10sp',
                                 text="You do not have any approvals")
            self.ids['approval_float_lay'].add_widget(warn_label)
        else:
            print(txnlist)
            alist = []
            while (txnlist):
                alist.append([str(txnlist[0]), txnlist[1], txnlist[2]])
                txnlist = ibm_db.fetch_both(stmt)
            data_tables = MDDataTable(size_hint=(1, 1),
                                      rows_num=100,
                                      check=True,
                                      pos_hint={
                                          'center_x': 0.5,
                                          'center_y': 0.5
                                      },
                                      column_data=[
                                          ("Group", dp(40)),
                                          ("Name", dp(40)),
                                          ("Email", dp(40)),
                                      ],
                                      row_data=[(f"{i[0]}", f"{i[1]}",
                                                 f"{i[2]}") for i in alist])
            data_tables.bind(on_check_press=self.on_check_press)
            self.ids['approval_float_lay'].add_widget(data_tables)
            #Approve Button
            approve_button = MDFillRoundFlatIconButton(
                text="APPROVE",
                pos_hint={
                    'center_x': 0.3,
                    'center_y': 0.2
                },
                icon="thumb-up-outline",
                on_release=lambda x: self.approvereq())
            approve_button.md_bg_color = 0.211, 0.678, 0.054, 1  #Green color
            self.ids['approval_float_lay'].add_widget(approve_button)
            #Reject Button
            reject_button = MDFillRoundFlatIconButton(
                text="REJECT",
                pos_hint={
                    'center_x': 0.7,
                    'center_y': 0.2
                },
                icon="thumb-down-outline",
                on_release=lambda x: self.rejectreq())
            reject_button.md_bg_color = 0.858, 0.239, 0.086, 1  #Red color
            self.ids['approval_float_lay'].add_widget(reject_button)

            self.ids['approval_float_lay'].add_widget(
                MDFillRoundFlatIconButton(
                    text="BACK",
                    pos_hint={
                        'center_x': 0.5,
                        'center_y': 0.1
                    },
                    icon="arrow-left-bold-circle",
                    theme_text_color="Custom",
                    text_color=(0, 0, 1, 1),
                    on_release=lambda x: self.to_home_page()))
Exemplo n.º 23
0
class MainApp(MDApp):
    conn = sqlite3.connect('icacard.db')
    cur = conn.cursor()

    cur.execute("SELECT * FROM users")
    users = cur.fetchall()

    cur.execute("SELECT * FROM students")
    students = cur.fetchall()

    def build(self):

        screen = Screen()

        self.help_str = Builder.load_file("main.kv")

        screen.add_widget(self.help_str)
        users_tables = MDDataTable(
            pos_hint={
                'center_x': 0.5,
                'center_y': 0.5
            },
            size_hint=(1, 1),
            use_pagination=True,
            check=True,
            column_data=[
                ("Nom", dp(30)),
                ("Prenom", dp(30)),
                ("Code", dp(30)),
                ("Tel", dp(30)),
                ("Nombre d'étudiants", dp(30)),
            ],
            row_data=self.users,
        )

        users_tables.bind(on_check_press=self.user_check_press)
        users_tables.bind(on_row_press=self.row_press)

        students_tables = MDDataTable(pos_hint={
            'center_x': 0.5,
            'center_y': 0.5
        },
                                      size_hint=(1, 1),
                                      use_pagination=True,
                                      check=True,
                                      column_data=[
                                          ("Nom", dp(30)),
                                          ("Prenom", dp(30)),
                                          ("Code", dp(30)),
                                          ("Tel", dp(30)),
                                          ("code paraints", dp(30)),
                                      ],
                                      row_data=self.students)

        students_tables.bind(on_check_press=self.check_press)
        students_tables.bind(on_row_press=self.row_press)

        self.help_str.ids.screen_manager.get_screen(
            'manage_users').children[0].add_widget(users_tables)
        self.help_str.ids.screen_manager.get_screen(
            'manage_students').add_widget(students_tables)

        return screen

    def user_check_press(self, instance_table, current_row):
        self.help_str.ids.screen_manager.get_screen(
            'student_code').ids.box_layout.clear_widgets()
        conn = sqlite3.connect('icacard.db')
        cur = conn.cursor()
        code = current_row[2]
        cur.execute(
            "SELECT nom,prénom,code,tel FROM students WHERE code_affilié= ?",
            (code, ))
        stud_per_code = cur.fetchall()

        self.stud_code_tables = MDDataTable(
            pos_hint={
                'center_x': 0.5,
                'center_y': 0.5
            },
            size_hint=(1, 1),
            use_pagination=True,
            check=True,
            column_data=[
                ("Nom", dp(30)),
                ("Prenom", dp(30)),
                ("Code", dp(30)),
                ("Tel", dp(30)),
            ],
            row_data=stud_per_code,
        )

        self.stud_code_tables.bind(on_check_press=self.check_press)
        self.stud_code_tables.bind(on_row_press=self.row_press)

        self.help_str.ids.screen_manager.get_screen(
            'student_code').ids.stud_code_title.text = code
        u_code = code

        self.help_str.ids.screen_manager.get_screen(
            'student_code').ids.box_layout.add_widget(self.stud_code_tables)
        self.help_str.ids.screen_manager.current = "student_code"

    def check_press(self, instance_table, current_row):
        s_code = current_row[2]
        self.help_str.ids.screen_manager.get_screen(
            'student_profile').viewStudProfile()
        self.help_str.ids.screen_manager.current = "student_profile"

    def row_press(self, instance_table, current_row):
        pass

    conn.commit()
    conn.close()
Exemplo n.º 24
0
class sonarApp(MDApp):
    #Since we named class 'sonarApp', kivy auto-builds 'sonar.kv'.
    def build(self):
        self.theme_cls.primary_palette = 'DeepPurple'
    
    #Runs when user starts app.
    def on_start(self):
        self.conn = sqlite3.connect('database.db')
        #Ensure that results from sqlite queries are returned as dictionaries.
        self.conn.row_factory = database.dictFactory 
        self.cursor = self.conn.cursor()

        #Make all relevant tables if they do not yet exist.
        database.dbSetup(self.conn, self.cursor)
        
        #Get hosts on network from a single ARP broadcast.
        hostsOnNetwork = networking.surveyNetwork('255.255.255.0', 1)
        
        currentNetworkId = database.getNetworkId(hostsOnNetwork, self.conn, self.cursor)
        
        self.cursor.execute('SELECT * FROM networks WHERE id = ?', [currentNetworkId])
        currentNetwork = { currentNetworkId : self.cursor.fetchone() }
        
        self.cursor.execute('SELECT * FROM networks WHERE id != ?', [currentNetworkId])
        restOfNetworks = { network['id'] : network
            for network in self.cursor.fetchall() }
        
        #Ensure that currentNetwork is first in 'networks', and thus on GUI.
        networks = { **currentNetwork, **restOfNetworks }

        #Create list of networks, which give a table of hosts when clicked.
        for network in networks.values():
            columnWidth = (self.root.width * 0.69) / 5 / 5

            networkListItem = OneLineListItem(
                text = network['ssid'],
                on_press = (
                    lambda _, network = network, columnWidth = columnWidth:
                    self.networkTable(network, columnWidth) 
                )
            )

            self.root.ids['networksList'].add_widget(networkListItem)

        self.hosts = database.catalogNetwork(
            self.conn, self.cursor, hostsOnNetwork) 
        hostIdsOnNetwork = networking.getHostsOnNetwork(
            hostsOnNetwork, self.hosts)
        
        for hostId in self.hosts:
            onNetwork = (hostId in hostIdsOnNetwork)
            self.hosts[hostId]['onNetwork'] = onNetwork
        
        notifsQ = multiprocessing.Queue()
        hostsQ = multiprocessing.Queue()

        self.notifsProducerP = multiprocessing.Process(
            target = notifsProducer,
            args = (hostsOnNetwork, self.hosts, notifsQ, hostsQ,)
        )
        self.notifsProducerP.start()

        #Play ringtone for each notif-enabled host that entered network.
        #Update self.hosts data.
        def notifsConsumer(_):
            if not notifsQ.empty():
                for hostId in notifsQ.get_nowait():
                    MDDialog(
                        title = '%s has entered the network' % self.hosts[hostId]['macAddr']
                    ).open()
                    self.playRingtone(self.hosts[hostId]['tone'])
            
            #update host values.
            if not hostsQ.empty():
                currentHosts = hostsQ.get_nowait()
                
                for hostId, host in currentHosts.items():
                    self.hosts[hostId] = host


        #Check / react to contents of notifsQ every 5 seconds.
        self.notifChecker = Clock.schedule_interval(notifsConsumer, 5)

    #Plays ringtone no. given from file in 'ringtones'.
    #Needs to be method of app class so it can be called from '.kv' file.
    def playRingtone(self, ringtoneNo):
        if ringtoneNo not in range(1,10):
            return

        else:
            #kivy's audio module has issues on debian systems (inc. mine), so we use pygame.
            pygame.mixer.init()
            filepath = os.path.abspath(__file__)
            filedir = os.path.dirname(filepath)
            musicpath = os.path.join(filedir, "ringtones/%d.wav" % ringtoneNo)
            pygame.mixer.music.load(os.path.abspath(musicpath))
            pygame.mixer.music.play()
    
    #When user clicks a network row, display table showing its hosts.
    def networkTable(self, network, columnWidth):
        keysToShow = ['macAddr', 'ipAddr', 'manufacturer', 'notificationEnabled', 'onNetwork']

        hostsRowData = [
            list({
                    key:value 
                    for (key, value) in host.items()
                    if key in keysToShow
                }.values())
            for host in self.hosts.values()
        ]

        self.hostsTable = MDDataTable(
            column_data =  [
                ('MAC Address', columnWidth),
                ('IP Address', columnWidth),
                ('Manufacturer', columnWidth),
                ('Notifications Enabled', columnWidth),
                ('On Network', columnWidth)
            ],
            row_data = hostsRowData,
            size_hint = (0.7, 0.7)
        )

        self.hostsTable.bind(on_row_press = self.onHostPress)
        self.hostsTable.open()
    
    #If user clicks row corresponding for host in self.hostsTable, display dialog.
    #Dialog allows user to enable notifications / set notif tone for relevant host.
    def onHostPress(self, instanceTable, instanceRow):
        rowIndex = floor(instanceRow.index / 5)
        hostData = instanceTable.row_data[rowIndex]
        content = notificationSettings(enabled = hostData[3])
        hostId = list(self.hosts.values())[rowIndex]['id']

        self.hostDialog = MDDialog(
            title = 'Notifications for %s' % hostData[0],
            content_cls = content,
            type = 'custom',
            buttons = [
                ToggleButtonClass(
                    text = 'Cancel',
                    group = 'submit',
                    on_release = (lambda _: self.hostDialog.dismiss(force = 1))
                ),
                ToggleButtonClass(
                    text = 'OK',
                    group = 'submit',
                    on_release = (lambda _: self.hostDialogSubmit(hostId, rowIndex))
                )
            ]
        )
        
        #Nth value of checkbox bools indicate if checkbox n is selected.
        checkboxBools = [0] * 9
        
        if hostData[3]:
            checkboxBools[int(self.hosts[hostId]['tone']) - 1] = 1
        
        musicItems = [
            itemConfirmMusic(
                text = ('Ringtone %d' % num),
                active = (checkboxBools[num - 1]),
                index = num
            )
            for num in range(1,10)
        ]
        
        for item in musicItems:
            self.hostDialog.content_cls.ids['notifList'].add_widget(item)

        self.hostDialog.open()

    #When user submits host dialog, input info into db and update self.hosts.
    def hostDialogSubmit(self, hostId, hostIndex):
        #Get binary value of switch.
        notificationsEnabled = int(
            self.hostDialog.content_cls.ids['notificationsEnabled'].active)

        self.hosts[hostId]['notificationEnabled']  = notificationsEnabled

        if notificationsEnabled:
            selectedItem = None
            widgetList = list(enumerate(
                self.hostDialog.content_cls.ids['notifList'].children
            ))

            for index, widget in reversed(widgetList):
                if widget.ids['check'].active:
                    selectedIndex = widget.index

                    #update db;
                    self.cursor.execute(
                        'UPDATE hosts SET notificationEnabled = 1, tone = ? WHERE id = ?', 
                        [selectedIndex, hostId])
                    self.conn.commit()

                    self.hosts[hostId]['tone'] = selectedIndex
                    
                    #Close host's table and host dialog.
                    #MDDataTable can't be updated, so we need to close.
                    self.hostDialog.dismiss(force = 1)
                    self.hostsTable.dismiss(force = 1)
                    
                    return

            #Tell user to select a tone value, since none were selected.
            Snackbar(
                text = "Please select an option",
                padding = "20dp"
            ).open()

        else:
            self.hostsTable.table_data.row_data[hostIndex][3] = '1'
            self.cursor.execute('UPDATE hosts SET notificationEnabled = 0 WHERE id = ?',
                [hostId])
            self.conn.commit()
            self.hostDialog.dismiss(force = 1)
    
    #Callback to make "tone" checkboxes visible when user enables notifs.
    def selectNotifType(self):
        self.hostDialog.content_cls.ids['options'].opacity = 1
        self.hostDialog.update_height()   
Exemplo n.º 25
0
class RentCarEmpresa(MDApp):    
    def on_start(self):
        self.client()
        self.veicu()
        self.pedido()
        self.taxasrec()
        self.strng.get_screen("empre").ids.acti.text = "Não"
        
    def client(self):
        threading.Thread(target=self.client_load).start()

    def client_load(self):
        if TRIPS_SELECTED:
            for n_trip in TRIPS_SELECTED:
                dele = requests.delete(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Cliente/{n_trip}.json')
            toast("Cliente eliminado")

        resquest = requests.get(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Cliente.json')
        buscare = json.loads(resquest.content.decode())

        cols = ["ID"]
        values = []
        cont = 0

        for trip, data in buscare.items():
            lista = []
            lista.append(trip)

            for key, info in data.items():
                lista.append(info)

                if cont == 0:
                    cols.append(key)
            cont +=1
            values.append(lista)

        self.client_tabela(cols, values)

    def on_check_press(self, instance_table,current_row):
        if current_row[0] in TRIPS_SELECTED:
            TRIPS_SELECTED.remove(current_row[0])
        else:
            TRIPS_SELECTED.append(current_row[0])

    @mainthread
    def client_tabela(self, cols, values):
        self.strng.get_screen("empre").ids.card7.clear_widgets()
        self.cliente = MDDataTable(pos_hint={'center_x':0.5,'center_y':.50},
                            rows_num=300,
                            size_hint = (.99,0.90),
                            use_pagination=False,
                            column_data=[    
                                (col,dp(26)) for col in cols                                                             
                            ],
                            row_data = values,
                            check = True
                            )               
        self.cliente.bind(on_check_press=self.on_check_press)        
        self.strng.get_screen("empre").ids.card7.add_widget(self.cliente)

    def veicu(self):
        threading.Thread(target=self.veicu_load).start()

    def veicu_load(self):
        if TRIPS_SELECTED:
            for n_trip in TRIPS_SELECTED:
                dele = requests.delete(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Veiculos/{n_trip}.json')
            toast("Veiculo eliminado")

        request = requests.get(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Veiculos/.json')
        pegarr = json.loads(request.content.decode())

        cols = ["Modelo"]
        values = []
        cont = 0

        for trip, data in pegarr.items():
            lista=[]
            lista.append(trip)

            for key, info in data.items():
                lista.append(info)
                if cont == 0 :
                    cols.append(key)

            cont+=1
            values.append(lista)

        self.veicu_table(cols,values)

    def on_check_press(self, instance_table,current_row):
        if current_row[0] in TRIPS_SELECTED:
            TRIPS_SELECTED.remove(current_row[0])
        else:
            TRIPS_SELECTED.append(current_row[0])

    @mainthread
    def veicu_table(self, cols, values):
        self.strng.get_screen("empre").ids.card9.clear_widgets()
        self.veiculo = MDDataTable(pos_hint={'center_x':0.5,'center_y':.59},
                            rows_num=300,
                            size_hint = (.99,0.90),
                            use_pagination=False,
                            column_data=[    
                                (col,dp(27)) for col in cols                                                             
                            ],
                            row_data = values,
                            check = True
                            )    
        self.veiculo.bind(on_check_press=self.on_check_press)
        self.strng.get_screen("empre").ids.card9.add_widget(self.veiculo)

    def taxasrec(self):
        threading.Thread(target=self.taxas_lod).start()
    
    def taxas_lod(self):
        if TRIPS_SELECTED:
            for n_trip in TRIPS_SELECTED:
                post_rquests = requests.delete(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Taxas/{n_trip}.json')
            toast("Taxas eliminada") 

        bd = requests.get(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Taxas.json')
        buscar = json.loads(bd.content.decode())

        count = 0
        values = []
        cols = ["Modelo"]

        for trip, data in buscar.items():
            lista = []
            lista.append(trip)

            for key, info in data.items():
                lista.append(info)
                if count == 0:
                    cols.append(key) 
            count +=1
            values.append(lista)
        
        self.taxastable(cols, values)
    
    def on_check_press(self, instance_table,current_row):
        if current_row[0] in TRIPS_SELECTED:
            TRIPS_SELECTED.remove(current_row[0])
        else:
            TRIPS_SELECTED.append(current_row[0])

    @mainthread
    def taxastable(self, cols, values):
        layout = AnchorLayout()
        self.strng.get_screen("empre").ids.card10.clear_widgets()
        self.taxass = MDDataTable(pos_hint={'center_x':0.5,'center_y':.5},
                            rows_num=300,
                            size_hint = (.99,0.90),
                            use_pagination=False,
                            column_data=[    
                                (col,dp(28)) for col in cols                                                             
                            ],
                            row_data = values,
                            check = True
                            )    
        self.taxass.bind(on_check_press=self.on_check_press)
        self.strng.get_screen("empre").ids.card10.add_widget(self.taxass)
        return layout
        
    def pedido(self):
        threading.Thread(target=self.pedido_load).start()

    def pedido_load(self):
        if TRIPS_SELECTED:
            for n_trip in TRIPS_SELECTED:
                post_request = requests.delete(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Pedidos/{n_trip}.json')
            toast("Pedido excluído")
        buscar = requests.get(f'https://rent-car-banco-dados-default-rtdb.firebaseio.com/Pedidos.json')
        buscarorganizado = json.loads(buscar.content.decode())

        count = 0
        cols = ["ID"]
        values = []

        for trip, data in buscarorganizado.items():
            lista = []
            lista.append(trip)

            for key, info in data.items():
                lista.append(info)
                if count == 0:
                    cols.append(key)

            count +=1
            values.append(lista)

        self.actualizar(cols, values)

    def on_check_press(self, instance_table, current_row):
        if current_row [0] in TRIPS_SELECTED:
            TRIPS_SELECTED.remove(current_row [0])
        else:
            TRIPS_SELECTED.append(current_row[0])

    @mainthread
    def actualizar(self,cols,values): 
        self.strng.get_screen("empre").ids.card8.clear_widgets()
        self.pedido = MDDataTable(pos_hint={'center_x':0.5,'center_y':.40},
                            rows_num=300,
                            size_hint = (.99,0.80),
                            use_pagination=False,
                            column_data=[    
                                (col,dp(27)) for col in cols                                                             
                            ],
                            row_data = values,
                            check = True
                            )    
        self.pedido.bind(on_check_press = self.on_check_press)
        self.strng.get_screen("empre").ids.card8.add_widget(self.pedido)  

    def build(self):
        self.theme_cls.primary_palette = "Blue" 
        self.theme_cls.theme_style = 'Light'
        self.theme_cls.accent_palette = "Yellow"
        self.strng = Builder.load_string(janela)
        
        animka = Animation(text_color = (1,1,1,1)) + Animation(text_color = (1,1,1, .2))
        animka.repeat = True        
        animka.start(self.strng.get_screen("empre").ids.cad)

        an = Animation(text_color = (1,1,1,1)) + Animation(text_color = (1,1,1, .2))
        an.repeat = True         
        an.start(self.strng.get_screen("empre").ids.cd)

        animae = Animation(text_color = (1,1,1,1)) + Animation(text_color = (1,1,1, .2))
        animae.repeat = True        
        animae.start(self.strng.get_screen("login").ids.acessar)

        animaed = Animation(text_color = (1,1,1,1)) + Animation(text_color = (1,1,1, .2))
        animaed.repeat = True 
        animaed.start(self.strng.get_screen("login").ids.grav)

        animaal = Animation(text_color = ([71/200,73/200,82/200,2])) + Animation (text_color = (1,1,1,1))
        animaal.repeat=True       
        animaal.start(self.strng.get_screen("empre").ids.updd)

        aimaak = Animation(text_color = ([169/255,169/255,169/255,2])) + Animation (text_color = (128/255,128/255,128/255,1))
        aimaak.repeat=True
        aimaak.start(self.strng.get_screen("empre").ids.atc)

        animali = Animation(text_color = ([169/255,169/255,169/255,2])) + Animation (text_color = (128/255,128/255,128/255,1))
        animali.repeat=True       
        animali.start(self.strng.get_screen("empre").ids.ped) 
    
        animalid = Animation(text_color = ([169/255,169/255,169/255,2])) + Animation (text_color = (128/255,128/255,128/255,1))
        animalid.repeat=True       
        animalid.start(self.strng.get_screen("empre").ids.pede)     

        animalui = Animation(text_color = ([169/255,169/255,169/255,2])) + Animation (text_color = (128/255,128/255,128/255,1))
        animalui.repeat=True       
        animalui.start(self.strng.get_screen("empre").ids.peo)                                                     
    
        animaluiy = Animation(text_color = ([169/255,169/255,169/255,2])) + Animation (text_color = (128/255,128/255,128/255,1))
        animaluiy.repeat=True       
        animaluiy.start(self.strng.get_screen("empre").ids.pedu)  

        animaea = Animation(size_hint_y = (0.88),duration=1)
        animaea.start(self.strng.get_screen("login").ids.card37)  

        return self.strng  
    
    def gravar_veiculo(self):
        marc = self.strng.get_screen("empre").ids.hu.text
        mode = self.strng.get_screen("empre").ids.mdl.text
        anoo = self.strng.get_screen("empre").ids.an.text
        combu = self.strng.get_screen("empre").ids.conh.text
        tipos = self.strng.get_screen("empre").ids.tp.text
        cores = self.strng.get_screen("empre").ids.cr.text
        matr = self.strng.get_screen("empre").ids.matri.text
        mti = self.strng.get_screen("empre").ids.mt.text
        ar = self.strng.get_screen("empre").ids.acti.text

        if mode is "" or marc is "" or anoo is "" or combu is "" or tipos is "" or cores is "" or matr is "":
            toast("Por favor preencha todo o formulário")
        elif len(marc)>15 or len(marc)<2:
            toast("Marca do veiculo inválido")
        elif len(anoo)>4:
            toast("Ano do veiculo inválido")
        elif combu not in ("Gasolina","gasoleo","Gasoleo","gasolina"):
            toast("Tipo de Combustivél inválido")
        elif tipos not in ("Autómatico","manual","Automatico","automatico","automático","Manual","Automático"):
            toast("Tipo de veiculo inválido")            
        elif re. search ("[a-zA-Z]", mti):
            toast("O número do motor está inválido")
        elif ar not in ("Não","não","Sim","sim"):
            toast("Apenas sim ou não")
        else:
            closer = MDIconButton(icon="thumb-up",on_release=self.clos)
            self.dialog = MDDialog(title="Rent Car",text="Dados do veiculo "+marc+" cadastrado com sucesso",size_hint=(0.8,0.3),buttons=[closer])
            self.dialog.open()
            result = firebase.put('/Veiculos',mode,{"Alugado":ar,"Matricula":matr,"Marca":marc,"Ano":anoo,"Cor":cores,"Tipo de Veiculo":tipos,"Combusível":combu,"Nº do Motor":mti}) 
            marc = self.strng.get_screen("empre").ids.hu.text=""
            mode = self.strng.get_screen("empre").ids.mdl.text=""
            anoo = self.strng.get_screen("empre").ids.an.text=""
            combu = self.strng.get_screen("empre").ids.conh.text=""
            tipos = self.strng.get_screen("empre").ids.tp.text=""
            cores = self.strng.get_screen("empre").ids.cr.text=""
            matr = self.strng.get_screen("empre").ids.matri.text=""
            mti = self.strng.get_screen("empre").ids.mt.text=""
            ar = self.strng.get_screen("empre").ids.acti.text=""

    def actua(self):
            mode = self.strng.get_screen("empre").ids.mdl.text
            ar = self.strng.get_screen("empre").ids.acti.text
            marc = self.strng.get_screen("empre").ids.hu.text=""
            cores = self.strng.get_screen("empre").ids.cr.text=""
            if mode is "":
                toast("Preencha o modelo pretendio")   
            elif ar is "":
                toast("Preencha o estado aluguel")
            elif ar not in ("Não","não","Sim","sim"):
                toast("Apenas Sim ou Não")
            else:
                toast("Estado de alguel actualizado")
                signup_info = firebase.put('/Veiculos\"{mode}\"','Alugado',ar)
                print(signup_info)
           
    def gravar_taxas(self):
        valor1 = self.strng.get_screen("empre").ids.vd.text
        valor2  = self.strng.get_screen("empre").ids.vs.text
        valor3 = self.strng.get_screen("empre").ids.vm.text
        valor4 = self.strng.get_screen("empre").ids.vlf.text
        modeo = self.strng.get_screen("empre").ids.marca.text

        if modeo is "" or valor1 is "" or valor2 is "" or valor3 is "" or valor4 is "":
            toast("Preencha o formulário correctamente!")
        
        elif len(modeo)<3:
            toast("Modelo do veiculo inválido")
            
        elif len(valor1)<3 or len(valor2)<3 or len(valor3)<3 or len(valor4)<3:
            toast("Numeros dos valores inválido")

        elif  re. search ("[a-zA-Z]", valor1) or re. search ("[a-zA-Z]", valor2) or re. search ("[a-zA-Z]", valor3) or re. search ("[a-zA-Z]", valor4):
            toast("Valor do veículo inválido")

        else:            
            gravar = firebase.put('/Taxas',modeo,{"Valor Diário":valor1,"Valor Semanal":valor2,"Valor Mensal":valor3,"Fim de Semana":valor4})
            fecharr = MDIconButton(icon="thumb-up",on_release=self.clos)
            self.dialog = MDDialog(title="Rent Car",text="Taxas do veiculo "+modeo+" cadastrado com sucesso!",size_hint=(0.8,0.3),buttons=[fecharr])
            self.dialog.open()
            
    def actualiz(self):
        valor1 = self.strng.get_screen("empre").ids.vd.text
        valor2  = self.strng.get_screen("empre").ids.vs.text
        valor3 = self.strng.get_screen("empre").ids.vm.text
        valor4 = self.strng.get_screen("empre").ids.vlf.text
        modeo = self.strng.get_screen("empre").ids.marca.text

        if modeo is "" or valor1 is "" or valor2 is "" or valor3 is "" or valor4 is "":
            toast("Preencha o formulário correctamente!")
        
        elif len(modeo)<3:
            toast("Modelo do veiculo inválido")
            
        elif len(valor1)<3 or len(valor2)<3 or len(valor3)<3 or len(valor4)<3:
            toast("Numeros dos valores inválido")

        elif  re. search ("[a-zA-Z]", valor1) or re. search ("[a-zA-Z]", valor2) or re. search ("[a-zA-Z]", valor3) or re. search ("[a-zA-Z]", valor4):
            toast("Valor do veículo inválido")

        else:            
            gravar = firebase.put('/Taxas',modeo,{"Valor Diário":valor1,"Valor Semanal":valor2,"Valor Mensal":valor3,"Fim de Semana":valor4})
            toast("Taxas "+modeo+ " actualizadas")
                   
    def salvar(self):   
        nomr = self.strng.get_screen("login").ids.nom.text
        email = self.strng.get_screen("login").ids.ema.text
        password = self.strng.get_screen("login").ids.seusuario.text
        empresa = self.strng.get_screen("login").ids.sempresa.text

        if nomr is "" or email is "" or password is "" or empresa is "":
            toast("Preencha todos os campos")
            
        elif not re. match(r"[^@]+@[^@]+\.[^@]+", email):
            toast("Email incorrecto "+nomr)
                           
        elif empresa != "rentcar2021":
            toast("Senha da empresa incorrecta "+nomr)
                           
        else:            
            signup_info = str({f'\"{email}\":{{"Nome":\"{nomr}\","Senha":\"{password}\"}}'})
            signup_info = signup_info.replace(".","-")
            signup_info = signup_info.replace("\'","")
            to_database = json.loads(signup_info)
            print((to_database))
            requests.patch(url = urll,json = to_database)
            toast("Dados cadastrado com sucesso")

    auth =  'fVCTQKZdM93XfnRWQd2UEgqLeYEgzueEf5SllvfF'
    
    def login(self):
        emaill = self.strng.get_screen("login").ids.emai.text
        senha = self.strng.get_screen("login").ids.sen.text

        self.login_check = False
        request = requests.get(url+'?auth'+self.auth)
        data = request.json()
        emails = set()
        for key,value in data.items():
            emails.add(key)
        if emaill in emails and senha == data[emaill]['Senha']:
            self.login_check = True
            self.strng.get_screen('empre').manager.current = 'empre'           
        else:
            toast("Funcionário não cadastrado")
            senha = self.strng.get_screen("login").ids.sen.text = ""
    i = 1       
    def togglevisibility(self):
        self.i += 1
        if self.i%2 == 0:
            self.strng.get_screen("login").ids.sen.password =  False           
            self.strng.get_screen("login").ids.seusuario.password =  False          
            self.strng.get_screen("login").ids.lok.icon =  "eye"
            self.strng.get_screen("login").ids.loko.icon =  "eye"
        else:
           self.strng.get_screen("login").ids.sen.password =  True
           self.strng.get_screen("login").ids.seusuario.password =  True         
           self.strng.get_screen("login").ids.lok.icon =  "eye-off"
           self.strng.get_screen("login").ids.loko.icon =  "eye-off"
           
    def plo(self):
        self.i += 1
        if self.i%2 == 0:
            self.strng.get_screen("login").ids.sempresa.password =  False            
            self.strng.get_screen("login").ids.loki.icon =  "eye"
        else:
           self.strng.get_screen("login").ids.sempresa.password =  True  
           self.strng.get_screen("login").ids.loki.icon =  "eye-off"
           
    def check(self, checkbox, value):
        if value:
            self.theme_cls.theme_style = 'Dark'
            self.strng.get_screen("empre").ids.switch.thumb_color_down = [71/200,73/200,82/200,2] 
            self.strng.get_screen("empre").ids.car.text_color = 1,1,1,1 
            self.strng.get_screen("empre").ids.upd.text_color = 1,1,1,1
            self.strng.get_screen("empre").ids.updd.text_color = 1,1,1,1          
            self.strng.get_screen("empre").ids.hj.text_color = 1,1,1,1
        else:
            self.theme_cls.theme_style = 'Light'
            self.strng.get_screen("empre").ids.switch.thumb_color_down = 1,1,1,1
            self.strng.get_screen("empre").ids.car.text_color = [71/200,73/200,82/200,2] 
            self.strng.get_screen("empre").ids.upd.text_color = [71/200,73/200,82/200,2] 
            self.strng.get_screen("empre").ids.updd.text_color = [71/200,73/200,82/200,2]            
            self.strng.get_screen("empre").ids.hj.text_color = [71/200,73/200,82/200,2]
            
    def responder(self):
        self.dialog = MDDialog(
            type = "custom",
            content_cls = Content(),
        )
        self.dialog.open()

    def resp1(self):
        ema = self.dialog.content_cls.ids.cli.text
        if ema is "":
            toast("Preencha o email senhor")
            
        elif not re. match(r"[^@]+@[^@]+\.[^@]+", ema):
            toast("Email incorrecto senhor")            
        else:
            email_from = "*****@*****.**"
            email_to = ema
            senha = "rentcar2021"
            mensagem = "O seu pedido de alguel foi aceite com sucesso,esperamos que cumpra com as respectivas"
            outra = " normas e regras. \n\nObrigado pela preferencia!"
            titulo = "RentCar Luanda"

            smtp = "smtp.gmail.com"
            server = smtplib.SMTP(smtp, 587)
            server.starttls()
            server.login(email_from,senha)
            
            message = 'Subject: {}\n\n\n{}{}'.format(titulo,mensagem,outra)
            server.sendmail(email_from,email_to,message)

            toast("Notificação enviado com exito")
            
    def resp2(self):
        ema = self.dialog.content_cls.ids.cli.text

        if ema is "":
            toast("Preencha o email senhor!")
            
        elif not re.match(r"[^@]+@[^@]+\.[^@]+",ema):
            toast("Email incorrecto senhor")
        else:
            email_from = "*****@*****.**"
            email_to = ema
            senha = "rentcar2021"
            mensagem = "O seu pedido foi recusado, pois o veiculo not se encontra disponivel para ser alugado"
            mensa = " escolhe outro veiculo da sua escolha. \n\nObrigado pela preferencia!"
            titulo = "RentCar Luanda"

            server = smtplib.SMTP("smtp.gmail.com", 587)
            server.starttls()
            server.login(email_from,senha)

            messages = 'Subject: {}\n\n{}{}'.format(titulo,mensagem,mensa)
            server.sendmail(email_from,email_to,messages)

            toast("Notificação enviada com sucesso")

    def sair(self):
        sim = MDIconButton(icon="thumb-down",on_release=self.clos)
        nao = MDIconButton(icon="thumb-up",on_release=self.fech)
        self.dialog = MDDialog(title="Rent Car",text="Tens a certeza que queres sair?",size_hint=(0.7,0.5),buttons=[sim,nao])
        self.dialog.open()
        
    def closs(self):
        self.dialog.dismiss()
    def clos(self,obg):
        self.dialog.dismiss()
    def fech(self,obj):
        self.stop()
Exemplo n.º 26
0
class MainLayout(MDGridLayout):

    def __init__(self, **kwargs):
        super(MainLayout, self).__init__(**kwargs)
        self.data_tables = MDDataTable(
            padding=10,
            size_hint=(None, None),
            center_x=1,
            width=600,
            height=680,
            use_pagination=True,
            rows_num=10,
            column_data=[
                ("#", dp(5)),
                ("Name", dp(50)),
                ("Genre", dp(30)),
                ("Country", dp(20)),
            ],
            row_data=[
                [
                    i[0],
                    ("play", [39 / 256, 174 / 256, 96 / 256, 1], i[1]),
                    i[2],
                    i[3]
                ] for i in radio_list()]
        )
        self.radio_play_id = []
        self.record = False
        self.cols = 1
        self.topWindow = MDGridLayout(cols=1, adaptive_height=True)
        self.topWindow.add_widget(self.new_top())
        self.add_widget(self.topWindow)
        self.table()

    def table(self):
        self.add_widget(self.data_tables)
        self.data_tables.bind(on_row_press=self.play_radio)

    def new_top(self, color=None):
        if color is None:
            color = [131 / 255, 223 / 255, 25 / 255, .9]
        new_top = MDGridLayout(
            cols=4,
            size_hint=(None, None),
            center_x=1,
            width=600,
            height=70
        )
        new_top.md_bg_color = [200 / 255, 200 / 255, 200 / 255, .7]

        if len(self.radio_play_id) == 0:
            return new_top

        new_top.add_widget(AsyncImage(
            source=self.radio_play_id[5]
        ))

        new_top.add_widget(MDLabel(
            text="%s " % self.radio_play_id[1],
            theme_text_color="Custom",
            halign="right",
            text_color=[223 / 255, 102 / 255, 0, 1],
            font_style="H5",
        )
        )
        new_top.add_widget(MDIconButton(
            icon="record",
            user_font_size="48sp",
            theme_text_color="Custom",
            text_color=color,
            on_press=self.start_record)
        )
        new_top.add_widget(MDIconButton(
            icon="stop",
            user_font_size="48sp",
            theme_text_color="Custom",
            on_press=self.stop_record)
        )
        return new_top

    def play_radio(self, obj, obj2):

        if obj2.text in [i[1] for i in radio_list()]:
            self.radio_play_id = [i for i in radio_list() if i[1] == obj2.text][0]

            self.radio = Radio(self.radio_play_id[4], self.radio_play_id[1])
            try:
                self.radio.radio_start()
            except:
                return
            self.topWindow.clear_widgets()
            self.topWindow.add_widget(self.new_top())

    def start_record(self, obj):
        if len(self.radio_play_id) > 0:
            self.topWindow.clear_widgets()
            self.topWindow.add_widget(self.new_top([1, 0, 0, 1]))
            self.radio = Radio(self.radio_play_id[4], self.radio_play_id[1], record=True)
            self.radio.radio_start()
            self.record = True

    def stop_record(self, obj):
        if self.record:
            self.topWindow.clear_widgets()
            self.topWindow.add_widget(self.new_top())
            self.record = False
        self.radio.radio_stop()

    def close_popup(self, obj):
        self.popup.dismiss()

    def update_table(self):
        self.data_tables.clear_widgets()
        self.remove_widget(self.grid)
        self.table()
Exemplo n.º 27
0
class BuildApp(Screen):  #This class handles everything on screen
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        diffs = [{'text': 'Easy'}, {'text': 'Medium'}, {'text': 'Hard'}]

        self.drop = MDDropdownMenu(
            caller=self.ids.pushup_diff,
            items=diffs,
            width_mult=4,
        )
        self.drop.bind(on_release=self.diff_sel)

        self.drop1 = MDDropdownMenu(
            caller=self.ids.pullup_diff,
            items=diffs,
            width_mult=4,
        )
        self.drop1.bind(on_release=self.diff_sel)

        self.drop2 = MDDropdownMenu(
            caller=self.ids.legs_diff,
            items=diffs,
            width_mult=4,
        )
        self.drop2.bind(on_release=self.diff_sel)

        self.table = MDDataTable(
            check=True,
            column_data=[
                ("Plan", dp(30)),
                ("Push", dp(50)),
                ("Pull", dp(50)),
                ("Legs", dp(50)),
            ],
            row_data=[("Plan Name", "Push Exercises", "Pull Exercises",
                       "Leg Exercises"), ("", "", "", "")],
            pos_hint={
                "center_x": 0.5,
                "center_y": 0.35
            },
            size_hint=(0.75, 0.25),
        )
        self.add_widget(self.table)
        self.table.bind(on_check_press=self.selection)

    #Adding the data to the data table
    def add_data(self, *args):
        cur.execute("SELECT *FROM Plans;")
        rows = cur.fetchall()

        for row in rows:
            self.table.row_data = [(row), ("", "", "", "")]

    def selection(self, table, table_item):
        self.sel_plan = table_item[0]

    #Searching a Record
    def searching(self, *args):
        plan_name = str(self.ids.plan_name.text.strip())
        cur.execute("SELECT *FROM Plans WHERE Plan = ?", (plan_name, ))
        rows = cur.fetchall()

        for row in rows:
            self.table.row_data = [(row), ("", "", "", "")]
        print(plan_name)

    #Updating A Record
    def updation(self, *args):
        #Wasn't able to do it using self.push_str and stuff
        push_str = ", ".join([str(x) for x in push_list])
        pull_str = ", ".join([str(x) for x in pull_list])
        leg_str = ", ".join([str(x) for x in leg_list])

        record = [push_str, pull_str, leg_str, self.sel_plan]
        update = """UPDATE Plans SET Push = ?, Pull = ?, Leg = ? WHERE Plan = ?"""
        cur.execute(update, (record))

        con.commit()
        self.table.row_data = [(self.sel_plan, push_str, pull_str, leg_str),
                               ("", "", "", "")]

    #Deleting A Record
    def deletion(self, *args):
        cur.execute("DELETE FROM Plans WHERE Plan = ?", (self.sel_plan, ))
        con.commit()
        self.table.row_data = []

    #Inserting(Creating) A Record.
    def insertion(self):
        global push_list, pull_list, leg_list
        plan_name = self.ids.plan_name.text.strip()

        con = sql.connect("Workout.db")
        cur = con.cursor()

        push_str = ", ".join([str(x) for x in push_list])
        pull_str = ", ".join([str(x) for x in pull_list])
        leg_str = ", ".join([str(x) for x in leg_list])

        #record = [plan_name, self.push_str, self.pull_str, self.leg_str]
        record = [plan_name, push_str, pull_str, leg_str]

        cur.execute("INSERT INTO Plans(Plan, Push, Pull, Leg) VALUES(?,?,?,?)",
                    (record))
        cur.execute("SELECT *FROM Plans WHERE Plan = ?", (plan_name, ))
        rows = cur.fetchall()
        con.commit()
        con.close()
        self.add_data()
        print(rows)
        print("[RECORD INSERTED IN DATABASE SUCCESSFULLY]")

    #Fetch the Difficulty and Exercise Selection
    def diff_sel(self, menu, menu_item):
        global push, pull, leg
        print(menu.caller.text)  #menu.caller.text gives the text of the helper
        print(menu_item.text + "\n")

        if menu.caller.text == "Push":

            if menu_item.text == "Easy":
                #Clearing previous widgets
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in push[0] + push[1] + push[2]:
                            self.remove_widget(child)

                push_e = {}

                for ex, y in zip(push[0], np.arange(0.73, -1, -0.05)):
                    push_e[round(y, 2)] = ex

                for pos, ex in push_e.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.2,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_push,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

            elif menu_item.text == "Medium":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in push[0] + push[1] + push[2]:
                            self.remove_widget(child)

                push_m = {}

                for ex, y in zip(push[1], np.arange(0.73, -1, -0.05)):
                    push_m[round(y, 2)] = ex

                for pos, ex in push_m.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.2,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_push,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

            elif menu_item.text == "Hard":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in push[0] + push[1] + push[2]:
                            self.remove_widget(child)

                push_h = {}

                for ex, y in zip(push[2], np.arange(0.73, -1, -0.05)):
                    push_h[round(y, 2)] = ex

                for pos, ex in push_h.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.2,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_push,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

        if menu.caller.text == "Pull":
            if menu_item.text == "Easy":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in pull[0] + pull[1] + pull[2]:
                            self.remove_widget(child)

                pull_e = {}

                for ex, y in zip(pull[0], np.arange(0.73, -1, -0.05)):
                    pull_e[round(y, 2)] = ex

                for pos, ex in pull_e.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.505,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_pull,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

            elif menu_item.text == "Medium":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in pull[0] + pull[1] + pull[2]:
                            self.remove_widget(child)

                pull_m = {}

                for ex, y in zip(pull[1], np.arange(0.73, -1, -0.05)):
                    pull_m[round(y, 2)] = ex

                for pos, ex in pull_m.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.505,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_pull,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

            elif menu_item.text == "Hard":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in pull[0] + pull[1] + pull[2]:
                            self.remove_widget(child)

                pull_h = {}

                for ex, y in zip(pull[2], np.arange(0.73, -1, -0.05)):
                    pull_h[round(y, 2)] = ex

                for pos, ex in pull_h.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.505,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_pull,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

        if menu.caller.text == "Legs":
            if menu_item.text == "Easy":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(
                            child, MDChip
                    ):  #Checks if the widget exists or not. similar to type()
                        if child.text in leg[0] + leg[1] + leg[2]:
                            self.remove_widget(child)

                leg_e = {}

                for ex, y in zip(leg[0], np.arange(0.73, -1, -0.05)):
                    leg_e[round(y, 2)] = ex

                for pos, ex in leg_e.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.8,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_legs,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

            elif menu_item.text == "Medium":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in leg[0] + leg[1] + leg[2]:
                            self.remove_widget(child)

                leg_m = {}

                for ex, y in zip(leg[1], np.arange(0.73, -1, -0.05)):
                    leg_m[round(y, 2)] = ex

                for pos, ex in leg_m.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.8,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_legs,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

            elif menu_item.text == "Hard":
                #Clearing previous widgets.
                for child in self.children[:]:
                    if isinstance(child, MDChip):
                        if child.text in leg[0] + leg[1] + leg[2]:
                            self.remove_widget(child)

                leg_h = {}

                for ex, y in zip(leg[2], np.arange(0.73, -1, -0.05)):
                    leg_h[round(y, 2)] = ex

                for pos, ex in leg_h.items():
                    chip = MDChip(text=ex,
                                  pos_hint={
                                      'center_x': 0.8,
                                      'center_y': float(pos)
                                  },
                                  on_release=self.selected_legs,
                                  check=True)
                    chip.color = chip_color
                    chip.icon = "coffee"
                    self.add_widget(chip)

    #Creating a list of selected exercises.
    def selected_push(self, chip_widget):
        if chip_widget.color == chip_color:
            #self.root.remove_widget(chip_widget) #Root refers to the parent they are inside (Screen)
            chip_widget.color = selected_color
            if chip_widget.text not in push_list:
                push_list.append(chip_widget.text)
        else:
            chip_widget.color = chip_color
            push_list.remove(chip_widget.text)
        print(f"Push : {push_list}", chip_widget.pos_hint)

    def selected_pull(self, chip_widget):
        if chip_widget.color == chip_color:
            #self.root.remove_widget(chip_widget) #Root refers to the parent they are inside (Screen)
            chip_widget.color = selected_color
            if chip_widget.text not in pull_list:
                pull_list.append(chip_widget.text)
        else:
            chip_widget.color = chip_color
            pull_list.remove(chip_widget.text)
        print(f"Pull : {pull_list}")

    def selected_legs(self, chip_widget):
        if chip_widget.color == chip_color:
            #self.root.remove_widget(chip_widget) #Root refers to the parent they are inside (Screen)
            chip_widget.color = selected_color
            if chip_widget.text not in leg_list:
                leg_list.append(chip_widget.text)
        else:
            chip_widget.color = chip_color
            leg_list.remove(chip_widget.text)
        print(f"Legs : {leg_list}")

    def submit(self, obj):

        if self.ids.plan_name.text is "":
            dialog = "Please Enter a Plan Name"
            plan_name = "Error"
        else:
            dialog = f"You successfully created a plan named : {self.ids.plan_name.text}"
            plan_name = "Success"

        for child in self.children[:]:
            if isinstance(child, MDChip):
                self.remove_widget(child)
        push_list.clear()
        pull_list.clear()
        leg_list.clear()

        close_btn = MDRectangleFlatButton(text="Close",
                                          on_release=self.close_dial)
        self.dial = MDDialog(
            title=plan_name,
            text=dialog,
            buttons=[close_btn],
        )
        self.dial.open()

    def close_dial(self, obj):
        self.dial.dismiss()