Beispiel #1
0
    def init(self):

        ## Define ActionItems
        self.actionItems = {
            'spinner':
            ActionSpinner(id='ctx_1',
                          color=(.3, .3, .3, 1),
                          option_cls=new_option),
            'new':
            ActionButton(id='ctx_2',
                         icon='theme/action_new.png',
                         on_release=self.new_preset),
            'accept':
            ActionButton(id='ctx_3',
                         icon='theme/action_accept.png',
                         on_release=self.save,
                         disabled=True,
                         opacity=0,
                         width=1)
        }

        ## Set up the spinner
        self.current_preset = App.get_running_app().config.getdefault(
            'Audio', 'eq_preset', 'standard')
        store = JsonStore('eq_presets.json')

        self.actionItems['spinner'].bind(text=self.load_preset)
        for preset in store.keys():
            self.actionItems['spinner'].values.append(preset)
        self.actionItems['spinner'].text = self.current_preset

        ## Add Items to ActionBar
        for item in self.actionItems:
            App.get_running_app().root.bar.children[0].add_widget(
                self.actionItems[item])
Beispiel #2
0
 def render_widget(self, dt):
     self.watch_list_label.text = "站点列表"
     self.watch_list_label.font_name = new_font
     watch_stations = JsonStore("watchlist.json")                  # 重新获取json文件内容,否则新增站点不能即刻刷新出来
     with open("refresh_info.json", "r") as f:
         data = json.load(f)
     print(data)
     render_list = ["{0}{1}{2}".format(i, " "*4+"|"+" "*4, data[i]) for i in watch_stations.keys()]
     # render_list = watch_stations.keys()
     render_listbutton(self.station_watch_list, render_list)
Beispiel #3
0
 def on_enter(self, *args):
     feeds=JsonStore("UmutRss.json")
     if len(self.grid.children)>0:
         self.grid.clear_widgets()
     self.grid.bind(minimum_height=self.grid.setter("height"))
     for feed in feeds.keys():
         title=feeds.get(feed)["title"]
         url=feeds.get(feed)["url"]
         btn=MButton(text=title,height=65)
         btn.urls=url
         btn.bind(on_press=self.next_screen)
         self.grid.add_widget(btn)
Beispiel #4
0
 def build_screen(self):
     history = JsonStore(history_path)
     scrollview = ScrollView(do_scroll_x=False)
     md_list = MDList()
     scrollview.add_widget(md_list)
     for i in history.keys():
         item = HistoryItem(text=str(i))
         item.add_widget(
             AvatarSampleWidget(source="./assets/kivy-icon-128.png"))
         md_list.add_widget(item)
     print("building screen for history")
     self.add_widget(scrollview)
Beispiel #5
0
    def resetear(self):
        Store = JsonStore(
            os.path.join(App.get_running_app().data_folder, 'data.json'))

        keys = []

        for key in Store.keys():
            keys.append(key)

        for key in keys:
            if not key == 'Alumnos':
                Store.delete(key)
Beispiel #6
0
class Container(BoxLayout):
    
    stored_data = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        super(BoxLayout, self).__init__(*args, **kwargs)
        self.stored_data = JsonStore('data.json')
        for item_key in self.stored_data.keys():
            item = self.stored_data.get(item_key)
            self.addtodoClick(item['text'], item['done'])
        

    def addtodoClick(self, text, done=0):
        lab = ItemLabel(text="[ref=l]{}[/ref]".format(text))
        if done:
            lab.text = "[s]{}[/s]".format(lab.text)
            lab.color = (0.5, 0.5, 0.5, 1)
        lab.font_size = '40sp'
        
        lab.bind(on_ref_press=self.LabelClickHandler)
        lab.children[0].bind(on_touch_down=self.delClick)
        
        self.ids['todolist'].add_widget(lab)
    
    
    def delClick (self, image, touch):
        if image.collide_point(*touch.pos):
            #print(image.size)
            image.parent.parent.remove_widget(image.parent)
    

    def LabelClickHandler(self, *args):
        lab = args[0]
        text = lab.text
        if text.find('[s]')>=0:
            text = text.replace('[s]', '').replace('[/s]', '')
            lab.color = (1, 1, 1, 1)
        else:
            text = "[s]{}[/s]".format(text)
            lab.color = (0.5, 0.5, 0.5, 1)
        lab.text = text
        
             
    
    def clearTodos(self):
        #print(self.ids['todolist'].children)
        gl = self.ids['todolist']
        #for lab in gl.children:
        while gl.children:
            lab = gl.children[0]
            #print(lab.text)
            gl.remove_widget(lab)
Beispiel #7
0
    def update_notelist(self):
        """
            Met à jour la liste des notes dans l'onglet notes
        """
        store = JsonStore('notes.json')
        notelist = self.ids["notelist"]
        notelist.clear_widgets()
        self.notelist_items = {}

        for note in store.keys():
            widget = NoteListItem(text=str(store.get(note).get("text")))
            notelist.add_widget(widget)
            self.notelist_items[widget] = note
Beispiel #8
0
  def __init__(self, **kwargs):
      kwargs['cols'] = 2
      super(MainView, self).__init__(**kwargs)
 # def build(self):
     # global store
      project_store = JsonStore('projectlist.json')
      self.list_adapter = ListAdapter(data=[("Project " + r + ' ' + project_store[r]['profile']['projecttitle'])
                                            for r in project_store.keys()],
                                      cls=ListItemButton,
                                      sorted_keys=[])
      self.list_adapter.bind(on_selection_change=self.callback)
      list_view = ListView(adapter=self.list_adapter)
      self.add_widget(list_view)
Beispiel #9
0
    def load_note(self, *args):
        """
            Ouvre une note pour l'éditer
        """
        store = JsonStore('notes.json')
        notelist_items = app.root.get_widget_of_id(
            "notesscreen").notelist_items
        if args[0] in notelist_items.keys():
            note_to_load = notelist_items.get(args[0])
        else:
            note_to_load = ''.join(
                random.choice(string.ascii_lowercase) for i in range(32))
        if note_to_load in store.keys():
            self.ids["note_textfield"].text = store.get(note_to_load).get(
                "text")
        else:
            self.ids["note_textfield"].text = ""

        app.root.ids["screen_manager"].current = "editnote"
        self.current_note = note_to_load
Beispiel #10
0
class OctoOverlay(FloatLayout):
    octo = ObjectProperty(None)
    sb = ObjectProperty(None)
    settings_string = StringProperty(u'...')#Things I wanted: 
    
    data_dir = ''

    def settingsPressed(self):
        self.octo.size=(0,0)
        self.sb.size=(0,0)
        self.octo.size_hint=(0,0)

        self.oed = OctoEditServer()
        self.oed.doneButton.bind(on_press=self.settingsReturn)
        self.add_widget(self.oed)

    def settingsReturn(self,val):
        self.remove_widget(self.oed)
        self.sb.size=(45,45)
        self.octo.size_hint=(1,1)
        try:
            config = {}
            config['name'] = self.oed.ids['name'].text
            config['address'] = self.oed.ids['address'].text
            config['username'] = self.oed.ids['username'].text
            config['password'] = encrypt(self.oed.ids['password'].text)
            self.store.put(config['name'],
                           name=config['name'],
                           address=config['address'],
                           username=config['username'],
                           password=config['password'])
            self.octo.addServer(config)
        except:
            pass

    def loadServers(self):
        self.store = JsonStore(join(self.data_dir, 'hosts.json'))

        for key in self.store.keys():
            self.octo.addServer(self.store.get(key))
	def carregar_prova(self, modo, materia):
		container = self.ids.container
		container._index = 0
		
		bd = JsonStore(self.caminho, indent = 4, sort_keys = False)
		self.perguntas = {}

		container.clear_widgets()

		chaves = bd.keys()
		todas_materias = [bd.get(i) for i in chaves]
		p = dict()
		for i in range(len(chaves)):
			p[chaves[i]] = todas_materias[i]['perguntas']
		materia_atual = p[materia].copy()

		if modo == 'Tudo': self.tudo(container, materia_atual)
		elif modo == 'Padrão': self.padrao(container, materia_atual)
		elif modo == 'Alternativa': self.alternativa(container, materia_atual)
		elif modo == 'Dissertativa': self.dissertativa(container, materia_atual)
		elif modo == 'Aleatório': self.aleatorio(container, materia_atual)
		elif modo == 'Mais Erradas': self.mais_erradas(container, materia_atual)
Beispiel #12
0
class addStory(object):
    '''
    This class is used for adding story to the game

    Syntax for the story is a key based dictionary, these keys are hexadacimal numbers
    that will be used to track progress. Starting point is 1, so if scenario 1 had 3
    possible options then there would be 11, 12, and 13. If 13 had 2 options then it would
    be 131, and 132. This will continue until there is a string of 16 characters

    basic syntax: {key
    '''

    def __init__(self):
        self.File = raw_input("Which story would you like to edit?\n\n").lower()
        self.data = JsonStore(self.File + '.json')
        self.start = 1 #default start code
        if self.data.count(): #If file has been started
            print '\nLooking for where you left off...\n'
            keys = self.data.keys()
            leftOff = int(keys[len(keys) - 1])
            print ('It seems like you left off at event number'
                    ' %d, so let\'s move on to number %d.'
                    % (leftOff, leftOff + 1)
                    )
            self.start = leftOff
        self.addToDBLoop(self.start)

    def addToDBLoop(self, number):
        event = raw_input('What is event number %d?\n' % number).lower()
        optionsStr = raw_input(('What are the available options for player?\n'
            'If none just type \'none\'.\n')).lower().split()
        c = 0
        options = {}
        for o in optionsStr:
            c += 1
            options[o] = str(number) + str(c)
        self.data.put(str(number), event = event, options = options)
Beispiel #13
0
    def get_question(self):
        list_for_accord = []
        list_for_sub_item = []

        for i in list_of_subject:
            store = JsonStore('{}.json'.format(i.strip('').upper()))
            list_for_accord.append(i)
            accord_item = AccordionItem(title=i, orientation='horizontal')
            for key in store.keys():
                p = Popup(title=key, size_hint=(.5, .5), auto_dismiss=True)
                accord_sub_item = OneLineListItem(text=str(key))
                accord_sub_item.bind(on_press=p.open)
                accord_item.add_widget(accord_sub_item)

                grid = GridLayout(cols=1)
                l1 = Button(text=store[key]['question'])
                l2 = Button(text=store[key]['option1'])
                l3 = Button(text=store[key]['option2'])
                l4 = Button(text=store[key]['option3'])
                l5 = Button(text=store[key]['option4'])
                l7 = TextInput(text='')
                l6 = Button(text='see answer')
                l6.bind(on_release=lambda x: setattr(l7, 'text', store[p.title]
                                                     ['answer']))

                grid.add_widget(l1)
                grid.add_widget(l2)
                grid.add_widget(l3)
                grid.add_widget(l4)
                grid.add_widget(l5)
                grid.add_widget(l6)
                grid.add_widget(l7)

                p.add_widget(grid)
            self.accordion.add_widget(accord_item)
        self.add_widget(self.accordion)
Beispiel #14
0
screen_monitors = ScreenMonitors(name='screen_monitors')
screen_settings = ScreenSettings(name='screen_settings')
screen_edit_name = ScreenEditName(name='screen_edit_name')
screen_edit_sensor = ScreenEditSensor(name='screen_edit_sensor')
screen_monitor = ScreenMonitor(name='screen_monitor')
screen_list = ScreenList(name='screen_list')
screen_manager.add_widget(screen_monitors)
screen_manager.add_widget(screen_settings)
screen_manager.add_widget(screen_edit_name)
screen_manager.add_widget(screen_edit_sensor)
screen_manager.add_widget(screen_list)
screen_manager.add_widget(screen_monitor)
screen_manager.current = 'screen_monitors'

store = JsonStore('smartportbt.json')
for element in store.keys():
    config[element] = store[element]
    if 'type' in config[element]:
        if config[element]['type'] == 'monitor':
            button = Factory.ButtonList(text=config[element]['name'])
            button.uuid = element
            button.bind(on_long_press=screen_monitors.show_popup_monitors)
            button.bind(on_short_press=screen_monitors.show_screen_monitor)
            screen_monitors.ids.list_config.add_widget(button)

bluetooth_extended = BluetoothExtended()
bluetooth_extended.timeout = 0.003

event_voice = threading.Event()
thread_voice = threading.Thread(
    name='thread_voice', target=do_speak, args=(event_voice,), daemon=True)
Beispiel #15
0
class DataBase:
    url = 'https://ospapp-53708.firebaseio.com/.json?auth='
    admin_passwd = ''

    def __init__(self, path, heroes_path, passwd_path):
        self.path = path
        self.store = JsonStore(path)
        with open("secret", 'r') as file:
            data = file.read().split("\n")
            self.url = self.url + data[0]
        self.firebase_patch_all()
        try:
            string = str(requests.get(self.url).json()['heroes'])
            if string:
                with open(heroes_path, 'w') as file:
                    file.write(string)
        except Exception as e:
            print(str(e))
        try:
            with open(heroes_path, 'r') as file:
                self.heroes = json.loads(str(file.read()).replace("'", '"'))
        except Exception as e:
            print(str(e))
            self.heroes = ["brak strażaków w bazie"]
        try:
            string = str(requests.get(self.url).json()['passwd'])
            if string:
                with open(passwd_path, 'w') as file:
                    file.write(string)
        except Exception as e:
            print(str(e))
        try:
            with open(passwd_path, 'r') as file:
                global admin_passwd
                admin_passwd = file.readline()
        except Exception as e:
            print(str(e))

    def put_report(self, uuid_num, id_number, dep_date, dep_time, spot_time,
                   location, type_of_action, section_com, action_com, driver,
                   perpetrator, victim, section, details, return_date,
                   end_time, home_time, stan_licznika, km_location, completed):
        if uuid_num == "":
            uuid_num = str(uuid.uuid1())
        if section_com == "Dowódca sekcji":
            section_com = ""
        if action_com == "Dowódca akcji":
            action_com = ""
        if driver == "Kierowca":
            driver = ""
        self.store.put(uuid_num,
                       innerID=id_number,
                       depDate=dep_date,
                       depTime=dep_time,
                       spotTime=spot_time,
                       location=location,
                       type=type_of_action,
                       sectionCom=section_com,
                       actionCom=action_com,
                       driver=driver,
                       perpetrator=perpetrator,
                       victim=victim,
                       section=section,
                       details=details,
                       returnDate=return_date,
                       endTime=end_time,
                       homeTime=home_time,
                       stanLicznika=stan_licznika,
                       KM=km_location,
                       modDate=self.get_date(),
                       ready=completed)
        try:
            string = "{'" + uuid_num + "': " + str(
                self.store.get(uuid_num)) + "}"
            to_database = json.loads(string.replace("'", '"'))
            requests.patch(url=self.url, json=to_database)
        except Exception as e:
            print(str(e))

    def delete_report(self, uuid_num):
        if self.store.exists(uuid_num):
            try:
                # requests.delete(url=self.url[:-5] + id_number + ".json")
                string = '{"deleted-' + uuid_num + '": "true"}'
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
            except Exception as e:
                Factory.deletePopout().open()
                print(str(e))
            else:
                self.store.delete(uuid_num)
        else:
            return -1

    def get_heroes(self):
        return self.heroes

    def firebase_patch_all(self):
        try:
            with open(self.path, 'r') as file:
                data = file.read()
                to_database = json.loads(data)
                requests.patch(url=self.url, json=to_database)
        except Exception as e:
            print(str(e))

    def delete_all(self):
        string_all = ""
        try:
            for key in self.store.keys():
                # requests.delete(url=self.url[:-5] + key + ".json")
                string = '{"deleted-' + key + '": "true"}'
                string_all = string_all + string
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
        except Exception as e:
            Factory.deletePopout().open()
            print(str(e))
        else:
            self.store.clear()

    def get_report(self, id_number):
        for item in self.store.find(innerID=id_number):
            dane = self.store.get(item[0])
            id_number = dane['innerID']
            dep_date = dane['depDate']
            dep_time = dane['depTime']
            spot_time = dane['spotTime']
            location = dane['location']
            type_of_action = dane['type']
            section_com = dane['sectionCom']
            action_com = dane['actionCom']
            driver = dane['driver']
            perpetrator = dane['perpetrator']
            victim = dane['victim']
            section = dane['section']
            details = dane['details']
            return_date = dane['returnDate']
            end_time = dane['endTime']
            home_time = dane['homeTime']
            stan_licznika = dane['stanLicznika']
            km_location = dane['KM']
            date = dane['modDate']
            completed = dane['ready']
            return [
                item[0], id_number, dep_date, dep_time, spot_time, location,
                type_of_action, section_com, action_com, driver, perpetrator,
                victim, section, details, return_date, end_time, home_time,
                stan_licznika, km_location, date, completed
            ]
        else:
            return -1

    def get_all_friendly(self):
        result = []
        for item in self.store.keys():
            data = self.store.get(item)
            result.append(data["innerID"] + " " + data["location"])
        return result

    def find_inner_id(self, id_number):
        for _ in self.store.find(innerID=id_number):
            return True
        return False

    @staticmethod
    def get_date():
        return str(datetime.datetime.now()).split(".")[0]

    def get_passwd(self):
        global admin_passwd
        return admin_passwd
    def carregar_conteudo(self):
        container = self.ids.container
        container.clear_widgets()

        titulo1 = Builder.load_string(f'''
LabelPergunta:
	text: 'Modo de Estudo'
	size_hint: 1, None
	height: dp('50')
''')
        container.add_widget(titulo1)

        for nome_modo in self.modos:
            modo = Builder.load_string(f'''
ToggleCheckBox:
	text: '{nome_modo}'
	group: 'modo'
	size_hint: 1, None
	height: dp('50')
	cor_fundo_pressionado: [0.95,0.61,0.07,1]
	on_release:
		app.root.get_screen('estudar').modo = '{nome_modo}'
''')
            container.add_widget(modo)
        titulo2 = Builder.load_string(f'''
LabelPergunta:
	text: 'Selecionar Matéria'
	size_hint: 1, None
	height: dp('50')
''')
        container.add_widget(titulo2)
        bd = JsonStore(self.caminho, indent=4, sort_keys=False)
        chaves = bd.keys()
        chaves1 = [bd.get(i) for i in chaves]
        chaves2 = [i for i in chaves]
        p = dict()
        for i in range(len(chaves)):
            p[chaves2[i]] = chaves1[i]['perguntas']
        materias = p.copy()
        for nome_materia in materias.keys():
            materia = Builder.load_string(f'''
ToggleCheckBox:
	text: "{nome_materia}"
	group: 'materia'
	size_hint: 1, None
	height: dp('50')
	cor_fundo_pressionado: [0.95,0.61,0.07,1]
	on_release:
		app.root.get_screen('estudar').materia = self.text
''')
            container.add_widget(materia)

        bt_final = Builder.load_string(f'''
Botao:
	text: "Iniciar Prova"
	size_hint: 1, None
	height: dp('50')
	cor_fundo: app.color_button_pressed
	cor_fundo_pressionado: app.color_button
	on_release:
		app.root.get_screen('estudar').iniciar_prova()
''')
        container.add_widget(bt_final)
Beispiel #17
0
    def __init__(self, **kwargs):
        super(MainBox, self).__init__(**kwargs)
        data_json = JsonStore(os.path.join("data/rogue_trader_data.json"))
        for key in data_json.keys():
            self.data[key] = data_json[key]
        global data
        data = self.data
        user_dir = pathlib.Path(App.get_running_app().user_data_dir)

        # Load config
        global config
        config = JsonStore(user_dir / "config.json")
        if not config.exists("config"):
            config.put("config", **default_config)

        dos_algorithm = DoSAlgorithm(config.get("config")["dos_algorithm"])
        if dos_algorithm == DoSAlgorithm.ROGUE_TRADER:
            self.ids["dos_rt"].state = "down"
        elif dos_algorithm == DoSAlgorithm.MIXED:
            self.ids["dos_mixed"].state = "down"
        else:
            self.ids["dos_dh2"].state = "down"

        self.ids["dos_rt"].algorithm = DoSAlgorithm.ROGUE_TRADER
        self.ids["dos_mixed"].algorithm = DoSAlgorithm.MIXED
        self.ids["dos_dh2"].algorithm = DoSAlgorithm.DARK_HERESY_2

        # load character
        global CHARACTER
        CHARACTER = JsonStore(user_dir / "character.json")
        if not CHARACTER.exists("character"):
            CHARACTER.put("character", **default_character)
        # CHARACTER.put("character", **default_character)
        self.character = CHARACTER.get("character")
        start_layout = StartLayout(self.data)
        self.ids["all_talents"].add_widget(start_layout)

        # set characteristics
        for key in characteristics.keys():
            self.ids[key].set_text(self.character["characteristics"][key])
            self.ids[key].key = self.data["characteristics"][key]["name"]
            self.ids[key].value = self.character["characteristics"][key][0]
            self.ids[key].bind(
                on_press=lambda inst: TestPopup(inst.key, inst.value))

        # add skills to the charakter screen
        self.ids["skill_box"].height = 0
        bg = True
        self.skill_box_dict = {}
        for key, skill in self.data["skills"].items():
            if skill["skill_group"]:
                skill_group_box_dict = {}
                if key in self.character["skills"]:
                    for skill_group, status in self.character["skills"][
                            key].items():
                        box = SkillBox(
                            skill,
                            self.data["characteristics"][
                                skill["characteristic"]]["short"],
                            self.character["characteristics"][
                                skill["characteristic"]][0],
                            status,
                            bg,
                            name="{} ({})".format(skill["name"], skill_group),
                        )
                        bg = not bg
                        self.ids["skill_box"].height += box.height
                        self.ids["skill_box"].add_widget(box)
                        skill_group_box_dict[skill_group] = box
                else:
                    box = SkillBox(
                        skill,
                        self.data["characteristics"][skill["characteristic"]]
                        ["short"],
                        self.character["characteristics"][
                            skill["characteristic"]][0],
                        None,
                        bg,
                        name="{} ()".format(skill["name"]),
                    )
                    bg = not bg
                    self.ids["skill_box"].height += box.height
                    self.ids["skill_box"].add_widget(box)
                self.skill_box_dict[key] = skill_group_box_dict
            else:
                box = SkillBox(
                    skill,
                    self.data["characteristics"][
                        skill["characteristic"]]["short"],
                    self.character["characteristics"][skill["characteristic"]]
                    [0],
                    self.character["skills"][key]
                    if key in self.character["skills"].keys() else None,
                    bg,
                )
                bg = not bg
                self.ids["skill_box"].height += box.height
                self.ids["skill_box"].add_widget(box)
                self.skill_box_dict[key] = box

        # add talents to the character screen
        for talent in self.character["talents"]:
            if type(talent) == list:
                key = talent[0]
                groups = talent[1:]
            else:
                key = talent
                groups = []
            button = TalentButton(
                key=key,
                text=f'{self.data["talents"][key]["name"]}'
                if len(groups) == 0 else
                f'{self.data["talents"][key]["name"]} ({", ".join(groups)})',
            )
            button.bind(on_press=lambda b: TalentInfoPopup(self.data["talents"]
                                                           [b.key]))
            self.ids["talents_box"].add_widget(button)
            self.ids["talents_box"].height += button.height

            # handle talented
            if key == "talented":
                for skill in groups:
                    for skill_key, skill_data in self.data["skills"].items():
                        if skill_data["name"] == skill:
                            break
                    self.skill_box_dict[skill_key].skill_value += 10
                    self.skill_box_dict[skill_key].modifier_list.append({
                        "name":
                        f"Talented ({skill})",
                        "bonus":
                        10,
                        "type":
                        "talent",
                        "on":
                        True,
                    })
        self.ids["talents_box"].children.sort()

        # add implants to the character srceen
        self.ids["implants_box"].height = 0
        for implant in self.character["implants"]:
            modifier_list = []
            for modifier in self.data["implants"][implant["key"]]["bonus"]:
                modifier_list.append(
                    [self.skill_box_dict[modifier[0]], modifier[1]])
            implant_box = ImplantBox(
                self.data["implants"][implant["key"]],
                implant["on"],
                implant["quality"],
                modifier_list,
            )
            self.ids["implants_box"].add_widget(implant_box)
            self.ids["implants_box"].height += implant_box.height

        # add weapons to the battle screen
        for weapon in self.character["weapons"]:
            weapon_box = WeaponBox(
                weapon,
                self.character["characteristics"]["ws"][0],
                self.character["characteristics"]["bs"][0],
                self.character["characteristics"]["s"][0],
                self.skill_box_dict["dodge"].skill_value,
            )
            self.ids["weapon_box"].add_widget(weapon_box)
            self.ids["weapon_box"].height += weapon_box.height

        # set wounds
        self.ids["wounds_max"].text = str(
            self.character["status"]["wounds"]["max"])
        self.ids["wounds_current"].text = str(
            self.character["status"]["wounds"]["current"])
        self.ids["wounds_critical"].text = str(
            self.character["status"]["wounds"]["critical"])
        self.ids["button_take_damage"].bind(
            on_press=lambda _: TakeDamagePopup(self))
        self.ids["button_heal"].bind(on_press=lambda _: HealDamagePopup(self))

        # set fatigue
        self.ids["fatigue_current"].text = str(
            self.character["status"]["fatigue"])
        self.ids["fatigue_max"].text = str(
            self.character["characteristics"]["t"][0] // 10)

        # set fate points
        self.ids["fate_max"].text = str(
            self.character["status"]["fate"]["max"])
        self.ids["fate_current"].text = str(
            self.character["status"]["fate"]["current"])
 def load_data(self):
     Logger.info("Data: Loading data...")
     store = JsonStore(os.path.join(data_dir, 'data.json'))
     for k in store.keys():
         self.data[k] = store.get(k)['val']
     Logger.info("Data: Loading data done {:s}".format(str(self.data)))
Beispiel #19
0
class DataBase:
    base_url = 'https://osptest-3ddc5.firebaseio.com/'
    url = ''
    secret = ''
    admin_password = ''

    def __init__(self, path, heroes_path, password_path, trucks_path, version):
        self.version = version
        self.heroes_path = heroes_path
        self.password_path = password_path
        self.trucks_path = trucks_path
        self.path = path
        self.store = JsonStore(path)
        with open("login_data/login", 'r') as file:
            self.user = file.read().split("\n")[0]
        with open("login_data/secret", 'r') as file:
            self.secret = file.read().split("\n")[0]
        self.url = self.base_url + self.user + self.secret

        self.firebase_patch_all()
        self.update_osp_data()

    def update_osp_data(self):
        try:
            string = str(requests.get(self.url).json()['heroes'])
            if string:
                with open(self.heroes_path, 'w') as file:
                    file.write(string)
        except Exception as connection_error:
            Logger.exception(str(connection_error))
        try:
            with open(self.heroes_path, 'r') as file:
                self.heroes = json.loads(str(file.read()).replace("'", '"'))
        except Exception as no_heroes_in_db:
            Logger.exception(str(no_heroes_in_db))
            self.heroes = ["brak strażaków w bazie"]
        try:
            string = str(requests.get(self.url).json()['trucks'])
            if string:
                with open(self.trucks_path, 'w') as file:
                    file.write(string)
        except Exception as connection_error:
            Logger.exception(str(connection_error))
        try:
            with open(self.trucks_path, 'r') as file:
                self.trucks = json.loads(str(file.read()).replace("'", '"'))
        except Exception as no_trucks_in_db:
            Logger.exception(str(no_trucks_in_db))
            self.trucks = ["brak zastepów w bazie"]
        try:
            string = str(requests.get(self.url).json()['passwd'])
            if string:
                with open(self.password_path, 'w') as file:
                    file.write(string)
        except Exception as no_password_in_db:
            Logger.exception(str(no_password_in_db))
        try:
            with open(self.password_path, 'r') as file:
                self.admin_password = file.readline()
        except Exception as no_password_file:
            Logger.exception(str(no_password_file))

    def update_reports_data(self):
        result = self.firebase_patch_all()
        if result == -1:
            Factory.connectionPopout().open()
        else:
            self.update_osp_data()
            Factory.updateOK().open()

    def put_report(self, uuid_num, id_number, dep_date, dep_time, spot_time,
                   location, type_of_action, section_com, action_com, driver,
                   perpetrator, victim, section, details, return_date,
                   end_time, home_time, meter_reading, km_location, completed,
                   truck_num):
        if uuid_num == "":
            uuid_num = str(uuid.uuid1())
        if section_com == "Dowódca sekcji":
            section_com = ""
        if action_com == "Dowódca akcji":
            action_com = ""
        if driver == "Kierowca":
            driver = ""
        if truck_num == "Zastęp":
            truck_num = ""
        self.store.put(uuid_num,
                       innerID=id_number,
                       depDate=dep_date,
                       depTime=dep_time,
                       spotTime=spot_time,
                       location=location,
                       type=type_of_action,
                       sectionCom=section_com,
                       actionCom=action_com,
                       driver=driver,
                       perpetrator=perpetrator,
                       victim=victim,
                       section=section,
                       details=details,
                       returnDate=return_date,
                       endTime=end_time,
                       homeTime=home_time,
                       stanLicznika=meter_reading,
                       KM=km_location,
                       modDate=self.get_date(),
                       ready=completed,
                       truck=truck_num)
        try:
            string = "{'" + uuid_num + "': " + str(
                self.store.get(uuid_num)) + "}"
            to_database = json.loads(string.replace("'", '"'))
            requests.patch(url=self.url, json=to_database)
            return 0
        except Exception as connection_error:
            Logger.exception(str(connection_error))
            return -1

    def delete_report(self, uuid_num):
        if self.store.exists(uuid_num):
            try:
                # requests.delete(url=self.url[:-5] + id_number + ".json")
                string = '{"deleted-' + uuid_num + '": "true"}'
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
                self.store.delete(uuid_num)
            except Exception as connection_error:
                Factory.deletePopout().open()
                Logger.exception(str(connection_error))
        else:
            return -1

    def get_heroes(self):
        return self.heroes.get("all")

    def get_driver(self):
        return self.heroes.get("driver")

    def get_section_comm(self):
        return self.heroes.get("section")

    def get_action_comm(self):
        return self.heroes.get("action")

    def get_trucks(self):
        return self.trucks

    def firebase_patch_all(self):
        try:
            with open(self.path, 'r') as file:
                data = file.read()
                to_database = json.loads(data)
                requests.patch(url=self.url, json=to_database)
            to_database = json.loads('{"' + self.user + '": "' + self.version +
                                     '"}')
            requests.patch(url=self.base_url + "mobileVersion/" + self.secret,
                           json=to_database)
            return 0
        except Exception as connection_error:
            Logger.exception(str(connection_error))
            return -1

    def delete_all(self):
        string_all = ""
        try:
            for key in self.store.keys():
                # requests.delete(url=self.url[:-5] + key + ".json")
                string = '{"deleted-' + key + '": "true"}'
                string_all = string_all + string
                to_database = json.loads(string)
                requests.patch(url=self.url, json=to_database)
                self.store.clear()
        except Exception as connection_error:
            Factory.deletePopout().open()
            Logger.exception(str(connection_error))

    def get_report(self, id_number):
        for item in self.store.find(innerID=id_number):
            dane = self.store.get(item[0])
            id_number = dane['innerID']
            dep_date = dane['depDate']
            dep_time = dane['depTime']
            spot_time = dane['spotTime']
            location = dane['location']
            type_of_action = dane['type']
            section_com = dane['sectionCom']
            action_com = dane['actionCom']
            driver = dane['driver']
            perpetrator = dane['perpetrator']
            victim = dane['victim']
            section = dane['section']
            details = dane['details']
            return_date = dane['returnDate']
            end_time = dane['endTime']
            home_time = dane['homeTime']
            meter_reading = dane['stanLicznika']
            km_location = dane['KM']
            date = dane['modDate']
            completed = dane['ready']
            truck_num = dane['truck']
            return [
                item[0], id_number, dep_date, dep_time, spot_time, location,
                type_of_action, section_com, action_com, driver, perpetrator,
                victim, section, details, return_date, end_time, home_time,
                meter_reading, km_location, date, completed, truck_num
            ]
        else:
            return -1

    def get_all_friendly(self):
        result = []
        for item in self.store.keys():
            data = self.store.get(item)
            result.append(data["innerID"] + " " + data["location"])
        return result

    def find_inner_id(self, id_number):
        for _ in self.store.find(innerID=id_number):
            return True
        return False

    @staticmethod
    def get_date():
        return str(datetime.datetime.now()).split(".")[0]

    def get_user(self):
        return self.user

    def get_password(self):
        return self.admin_password

    def change_osp(self, user, password):
        with open("login_data/login", 'r') as file:
            old_user = file.read().split("\n")[0]
        if user != old_user:
            try:
                user_password = str(
                    requests.get(self.base_url + "passwd/" + user +
                                 self.secret).json())
                to_database = json.loads('{"' + user + '": "' + self.version +
                                         '"}')
                requests.patch(url=self.base_url + "mobileVersion/" +
                               self.secret,
                               json=to_database)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
                return -2  # no connection
            if user_password == "UPDATE":
                return -3  # update neeeded
            if user_password == "None" or password != user_password:
                return -1  # wrong password

            self.url = self.base_url + user + self.secret
            try:
                string = str(requests.get(self.url).json()['heroes'])
                with open(self.heroes_path, 'w') as file:
                    file.write(string)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
                with open(self.heroes_path, 'w') as file:
                    file.write("")
            try:
                with open(self.heroes_path, 'r') as file:
                    self.heroes = json.loads(
                        str(file.read()).replace("'", '"'))
            except Exception as no_heroes_in_db:
                Logger.exception(str(no_heroes_in_db))
                self.heroes = ["brak strażaków w bazie"]
            try:
                string = str(requests.get(self.url).json()['trucks'])
                with open(self.trucks_path, 'w') as file:
                    file.write(string)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
            try:
                with open(self.trucks_path, 'r') as file:
                    self.trucks = json.loads(
                        str(file.read()).replace("'", '"'))
            except Exception as no_trucks_in_db:
                Logger.exception(str(no_trucks_in_db))
                self.trucks = ["brak zastepów w bazie"]
            try:
                string = str(requests.get(self.url).json()['passwd'])
                with open(self.password_path, 'w') as file:
                    file.write(string)
            except Exception as connection_error:
                Logger.exception(str(connection_error))
                self.url = self.base_url + self.user + self.secret
                return -2
            try:
                with open(self.password_path, 'r') as file:
                    self.admin_password = file.readline()
            except Exception as no_password:
                Logger.exception(str(no_password))
            self.store.clear()
            self.user = user
            with open("login_data/login", 'w') as file:
                file.write(user)
        return 0
Beispiel #20
0
class Question(ToolbarScreen):
    quest = ObjectProperty(None)
    optA = ObjectProperty(None)
    optB = ObjectProperty(None)
    optC = ObjectProperty(None)
    optD = ObjectProperty(None)
    exp = ObjectProperty(None)
    questNum = ObjectProperty(None)
    questStatus = ObjectProperty(None)

    def __init__(self, **opt):
        super(Question, self).__init__(**opt)

    def choice(self, widget):
        if widget.state == "down":
            #print(widget.value,"is picked")
            val_select = widget.value
            #storing the selected ans
            #print("previous",self.choosedAns)
            self.choosedAns[self.index - 1] = val_select
            correct_ans = self.correctAns[self.index - 1]
            #print("current",self.choosedAns)
            #print(val_select.lower())
            if correct_ans != val_select.lower():
                self.exp.text = "Explanation: \n" + self.store.get(
                    self.all_questions[self.index - 1])["explanation"]
                #print(type(self.ids["stateB"].icon
                #print(val_select)
                self.questStatus.text = "Wrong"
                self.questStatus.secondary_text = "The correct Answer is {}".format(
                    correct_ans.upper())
                self.questStatus.children[0].children[0].icon = "close"
                self.questStatus.children[0].children[0].text_color = [
                    1, 0, 0, 1
                ]
            else:
                self.exp.text = "Explanation: \n" + self.store.get(
                    self.all_questions[self.index - 1])["explanation"]
                self.questStatus.text = "Correct"
                self.questStatus.secondary_text = "..."
                self.questStatus.children[0].children[0].icon = "check"
                self.questStatus.children[0].children[0].text_color = [
                    0, 1, 0, 1
                ]

    def load_quest(self):
        self.store = JsonStore("question.json")
        ids = self.store.keys()

        self.all_questions = sample(ids, 20)

        #refreshing the checkbuttons
        self.exp.text = ""
        self.questStatus.text = ""
        self.questStatus.secondary_text = ""
        self.questStatus.children[0].children[0].text_color = get_color(
            "#fce4ec")
        self.clearOpts()
        self.index = 1
        self.correctAns = [
            self.store.get(i)['answer'].replace("\r", "")
            for i in self.all_questions
        ]
        self.choosedAns = ["" for i in range(len(self.all_questions))]
        #self.quest1=self.store.get(self.all_questions[self.index-1])["quest"]
        self.questNum.text = str(self.index) + "/" + str(
            len(self.all_questions))
        self.quest.text = str(self.index) + ". " + self.store.get(
            self.all_questions[self.index - 1])["quest"]
        self.optA.text = self.store.get(self.all_questions[self.index -
                                                           1])["a"]
        self.optB.text = self.store.get(self.all_questions[self.index -
                                                           1])["b"]
        self.optC.text = self.store.get(self.all_questions[self.index -
                                                           1])["c"]
        self.optD.text = self.store.get(self.all_questions[self.index -
                                                           1])["d"]

    # print(self.store.get(self.all_questions[self.index-1]))
    def next_quest(self, *args):
        if self.index < len(self.all_questions):
            self.index += 1
            #self.quest1=self.all_questions[self.index-1]
            self.questNum.text = str(self.index) + "/" + str(
                len(self.all_questions))
            self.quest.text = str(self.index) + ". " + self.store.get(
                self.all_questions[self.index - 1])["quest"]
            self.optA.text = self.store.get(self.all_questions[self.index -
                                                               1])["a"]
            self.optB.text = self.store.get(self.all_questions[self.index -
                                                               1])["b"]
            self.optC.text = self.store.get(self.all_questions[self.index -
                                                               1])["c"]
            self.optD.text = self.store.get(self.all_questions[self.index -
                                                               1])["d"]
            self.clearOpts()
            #print(self.choosedAns)
            #print(self.correctAns)
            #refreshing the checkbuttons
            #refreshing the checkbuttons
            if self.choosedAns[self.index - 1] != "":
                print("previously answered")
                choice = "check" + self.choosedAns[self.index - 1]
                self.ids[choice].active = True
            else:
                self.exp.text = ""
                self.questStatus.text = ""
                self.questStatus.secondary_text = ""
                self.questStatus.children[0].children[
                    0].text_color = get_color("#fce4ec")

    def submit(self):
        score = 0
        counter = 0
        for i in self.choosedAns:
            if i.lower() == self.correctAns[counter].lower():
                score += 1
            counter += 1
        return (counter, score)

    def prev_quest(self, *args):

        if self.index > 1:
            self.clearOpts()
            self.index -= 1
            self.questNum.text = str(self.index) + "/" + str(
                len(self.all_questions))
            self.quest.text = str(self.index) + ". " + self.store.get(
                self.all_questions[self.index - 1])["quest"]
            self.optA.text = self.store.get(self.all_questions[self.index -
                                                               1])["a"]
            self.optB.text = self.store.get(self.all_questions[self.index -
                                                               1])["b"]
            self.optC.text = self.store.get(self.all_questions[self.index -
                                                               1])["c"]
            self.optD.text = self.store.get(self.all_questions[self.index -
                                                               1])["d"]
            if self.choosedAns[self.index - 1] != "":
                #print("previously answered")
                choice = "check" + self.choosedAns[self.index - 1]
                self.ids[choice].active = True
        #print(self.index)
    def clearOpts(self):

        checkButs = ["checkA", "checkB", "checkC", "checkD"]
        for checkbut in checkButs:
            self.ids[checkbut].active = False
__author__ = 'karinamarie'
from kivy.storage.jsonstore import JsonStore
from kivy.event import EventDispatcher
import json
import csv
import wx
import wx.grid as gridlib

storej = JsonStore('projectlist.json')

p = []
for key in storej.keys():
    p.append(key)
print p
# Write CSV Header
# f.writerow(["pk", "model", "codename", "name", "content_type"])

def make_csv(project):
    # define & clear lists for each project number
    list = []
    profilelist = []
    contentlist = []

    print project + ' project'

    file = ('%s.csv' % (project))
    f = csv.writer(open(file, "wb+"))

    for key in storej.get((project)):
        list.append(key)
    print list  # [profile, content]
Beispiel #22
0
# verificanco se existe
if store.exists('tito'):
    print('tite exists:', store.get('tito'))

# deletando valor
store.delete('tito')

# trz todas ocorrencia em que nome é igual Gabriel
for item in store.find(name='Gabriel'):
    print('tshirtmans index key is', item[0])
    print('his key value pairs are', str(item[1]))

entries = list(
    store.find(name='Mathieu'))  #pode ser usado convertido em uma lista

store.clear()  # Limpe todo o armazenamento.
store.count()  # Retorna o número de entradas armazenadas.
store.keys()  #Retorna uma lista com todas as chaves armazenadas.

# ==========================================================
# ASSINCRONA
# se definir o callback a funcao torna se assincrona


def my_callback(store, key, result):
    print('the key', key, 'has a value of', result)


mystore.get('plop', callback=my_callback)
Beispiel #23
0
class MainApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "Teal"

        self.storage = JsonStore('../store.json')
        self.emails = JsonStore('../emails.json')

        self.view_stock_widgets = []
        self.manage_items_widgets = []
        self.add_remove_stock_widgets = []
        self.edit_item_widgets = []
        self.send_data_widgets = []
        self.low_stock_widgets = []

    def add_item(self, name, stock_type, stock_level, stock_units,
                 low_threshold, pop_weighting):
        inputs = [
            name, stock_type, stock_level, stock_units, low_threshold,
            pop_weighting
        ]
        if '' not in inputs:
            self.storage.put(name,
                             name=name,
                             stock_type=stock_type,
                             stock_level=int(stock_level),
                             stock_units=stock_units,
                             low_threshold=int(low_threshold),
                             pop_weighting=int(pop_weighting))
        else:
            toast('Some fields were left blank...')

    def remove_item(self, name):
        self.storage.delete(name)

    def remove_email(self, email):
        self.emails.delete(email)

    def update_stock_level(self, name, stock_level_change):
        item = self.storage.get(name)
        item['stock_level'] += stock_level_change
        if item['stock_level'] < 0:
            item['stock_level'] = 0
        self.storage.put(name,
                         name=name,
                         stock_type=item['stock_type'],
                         stock_level=item['stock_level'],
                         stock_units=item['stock_units'],
                         low_threshold=item['low_threshold'],
                         pop_weighting=item['pop_weighting'])

    def apply_stock_changes(self):
        for widget in self.add_remove_stock_widgets:
            try:
                if widget.ids.plus_minus.active == True:
                    sign = '+'
                else:
                    sign = '-'
            except AttributeError:
                continue
            if len(widget.ids.stock.text) > 0:
                stock_change = sign + widget.ids.stock.text
                self.update_stock_level(widget.ids.name.text,
                                        int(stock_change))
                widget.ids.stock.text = ''
        self.load_add_remove_stock_screen()
        self.load_low_stock_screen()
        toast('Update Successful')

    def apply_edit_changes(self, name, stock_type, stock_level, stock_units,
                           low_threshold, pop_weighting):
        self.storage.delete(self.editing_item)
        self.storage.put(name,
                         name=name,
                         stock_type=stock_type,
                         stock_level=int(stock_level),
                         stock_units=stock_units,
                         low_threshold=int(low_threshold),
                         pop_weighting=int(pop_weighting))
        self.load_manage_items_screen()
        self.load_view_stock_screen()
        self.load_add_remove_stock_screen()
        self.load_low_stock_screen()
        self.editing_item = None
        toast('Changes Applied')

    def delete_item(self, item):
        screen = self.root.ids.screen_manager.current
        if screen == 'manage_items':
            self.remove_item(item)
            self.root.ids.screen_manager.current = 'manage_items'
            self.load_manage_items_screen()
            self.load_view_stock_screen()
            self.load_add_remove_stock_screen()
            self.load_low_stock_screen()
        elif screen == 'send_data':
            self.remove_email(item)
            self.root.ids.screen_manager.current = 'send_data'
            self.load_send_data_screen()
        toast('Deleted')

    def load_manage_items_screen(self):
        for widget in self.manage_items_widgets:
            self.root.ids.manage_items_list.remove_widget(widget)
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.manage_items_list.add_widget(widget)
            self.manage_items_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    name = item['name']
                    widget = Manage_Items_Swipe_Card(name)
                    self.root.ids.manage_items_list.add_widget(widget)
                    self.manage_items_widgets.append(widget)

    def load_view_stock_screen(self):
        for widget in self.view_stock_widgets:
            self.root.ids.view_stock_list.remove_widget(widget)
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.view_stock_list.add_widget(widget)
            self.view_stock_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    name = item['name']
                    stock_level = item['stock_level']
                    units = item['stock_units']
                    low_threshold = item['low_threshold']
                    if stock_level <= low_threshold:
                        low = True
                    else:
                        low = False
                    stock_level_string = str(stock_level) + ' ' + str(units)
                    widget = View_Stock_Card(name, stock_level_string, low)
                    self.root.ids.view_stock_list.add_widget(widget)
                    self.view_stock_widgets.append(widget)

    def load_add_remove_stock_screen(self):
        for widget in self.add_remove_stock_widgets:
            self.root.ids.add_remove_stock_list.remove_widget(widget)
        self.add_remove_stock_widgets = []
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.add_remove_stock_list.add_widget(widget)
            self.add_remove_stock_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    name = item['name']
                    widget = Add_Remove_Stock_Card(name)
                    self.root.ids.add_remove_stock_list.add_widget(widget)
                    self.add_remove_stock_widgets.append(widget)
        widget = MDCard(size_hint_y=None, height='50dp')
        self.root.ids.add_remove_stock_list.add_widget(widget)
        self.add_remove_stock_widgets.append(widget)

    def load_edit_item_screen(self, key):
        for widget in self.edit_item_widgets:
            self.root.ids.edit_item_layout.remove_widget(widget)
        self.edit_item_widgets = []
        item = self.storage.get(key)
        widget = Edit_Item_Dialog_Content()
        widget.ids.item_name.text = str(item['name'])
        widget.ids.item_type.text = str(item['stock_type'])
        widget.ids.stock_level.text = str(item['stock_level'])
        widget.ids.stock_units.text = str(item['stock_units'])
        widget.ids.low_threshold.text = str(item['low_threshold'])
        widget.ids.pop_weighting.text = str(item['pop_weighting'])
        self.root.ids.edit_item_layout.add_widget(widget)
        self.edit_item_widgets.append(widget)
        self.editing_item = item['name']

    def load_send_data_screen(self):
        for widget in self.send_data_widgets:
            self.root.ids.emails_list.remove_widget(widget)
        self.send_data_widgets = []
        keys = sorted(self.emails.keys())
        for key in keys:
            email = self.emails.get(key)
            widget = Email_Contact_Card(email['email'])
            self.root.ids.emails_list.add_widget(widget)
            self.send_data_widgets.append(widget)

    def load_low_stock_screen(self):
        for widget in self.low_stock_widgets:
            self.root.ids.low_stock_layout.remove_widget(widget)
        self.low_stock_widgets = []
        keys = sorted(self.storage.keys())
        stock_types = []
        for key in self.storage:
            item = self.storage.get(key)
            if item['stock_type'] not in stock_types:
                stock_types.append(item['stock_type'])
        stock_types.sort()
        for stock_type in stock_types:
            widget = Subtitle_Widget(stock_type)
            self.root.ids.low_stock_layout.add_widget(widget)
            self.low_stock_widgets.append(widget)
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type and item[
                        'stock_level'] <= item['low_threshold']:
                    widget = Low_Stock_Item_Card(item['name'])
                    self.root.ids.low_stock_layout.add_widget(widget)
                    self.low_stock_widgets.append(widget)

    def open_add_item_popup(self):
        content = Add_Item_Dialog_Content()
        self.popup = MDDialog(
            type='custom',
            content_cls=content,
            auto_dismiss=False,
        )
        self.popup.open()

    def confirm_delete_dialog(self, item):
        content = Confirm_Delete_Dialog_Content(item)
        self.popup = MDDialog(
            type='custom',
            content_cls=content,
            auto_dismiss=False,
        )
        self.popup.open()

    def open_add_email_popup(self):
        content = Add_Email_Content()
        self.popup = MDDialog(
            type='custom',
            content_cls=content,
            auto_dismiss=False,
        )
        self.popup.open()

    def add_contact(self, email):
        self.emails.put(email, email=email, sent=False)
        self.load_send_data_screen()

    def send_email(self, email):

        address = self.emails.get(email)
        self.emails.put(email, email=email, sent=True)

        #customise frm and password to send emails from your account for testing purposes.
        frm = '*****@*****.**'
        password = ''
        to = email
        subject = 'Stock Level Data'

        server = smtplib.SMTP(host='smtp.gmail.com', port=587)
        server.starttls()
        server.login(frm, password)

        msg = MIMEMultipart()
        msg['From'] = frm
        msg['to'] = to
        msg['subject'] = subject

        body = ""

        keys = self.storage.keys()
        keys.sort()

        stock_types = []
        for key in keys:
            stock_type = self.storage.get(key)['stock_type']
            if stock_type not in stock_types:
                stock_types.append(stock_type)
        for stock_type in stock_types:
            body += '%s\n' % stock_type.upper()
            for key in keys:
                item = self.storage.get(key)
                if item['stock_type'] == stock_type:
                    body += '%s: %s %s\n' % (item['name'], item['stock_level'],
                                             item['stock_units'])
            body += '\n'

        msg.attach(MIMEText(body, 'plain'))

        server.sendmail(frm, to, msg.as_string())

        toast('Sent to: %s' % email)

    def set_screen(self, screen):
        self.root.ids.screen_manager.current = screen

    def build(self):
        self.title = 'WTF Stock Take'
        return MainLayout()

    def on_start(self):
        self.load_manage_items_screen()
        self.load_view_stock_screen()
        self.load_add_remove_stock_screen()
        self.load_send_data_screen()
        self.load_low_stock_screen()