Beispiel #1
0
class lockerstoreviewWindow(Screen):

    ini = ObjectProperty(None)
    intt = ObjectProperty(None)
    infirst = StringProperty('')
    insecond = StringProperty('')

    lockstore = JsonStore("lockerstore.json")

    def viewnotelocker(self):
        if self.intt.text == '':
            popFun()
        else:
            lockstore = JsonStore("lockerstore.json")
            if lockstore.exists(self.intt.text):
                h = self.intt.text
                k = lockstore.get(h)["items"]
                self.ini.text = k
            else:
                popFun()

    def closenotelocker(self):
        if self.intt.text == '':
            popFun()
        else:
            lockstore = JsonStore("lockerstore.json")
            if lockstore.exists(self.intt.text):
                self.intt.text = ''
                self.ini.text = ''
                sm.current = 'lockerstore'
            else:
                popFun()

    def copylocker(self):
        clipboard.copy(self.ini.text)
        b = clipboard.paste()

    def delnotelocker(self):
        if self.intt.text == '':
            popFun()
        else:
            lockstore = JsonStore("lockerstore.json")
            if lockstore.exists(self.intt.text):
                h1 = self.intt.text
                self.lockstore.delete(h1)
                sm.current = 'lockerstore'
            else:
                popFun()
Beispiel #2
0
    def __init__(self, **kwargs):
        super(HomePage, self).__init__(**kwargs)
#References the json file called local.json
        self.store = JsonStore('local.json')
        print("whether previous exist = " + repr(self.store.exists('numEntries')))
#Checks if there is a file. If there is not, initiate all 4 necessary parts
        if (not self.store.exists('numEntries')):
            print("enter")
            self.store.put("numEntries", value = 0)
            self.store.put("macDict", value = dict())
            self.store.put("recentTen", value = list())
            self.store.put("prevNetwork", value = dict())
        self.options = ObjectProperty(None)
#macClass variable is just used as a reference to be able to call the getMac class
        self.macClass = GetMacAdd()
        self.actualMac = self.macClass.getMac()
Beispiel #3
0
    def new_game(self):
        App.get_running_app().game_id = None
        self.manager.get_screen("rotor_screen").reset_rotors()
        self.manager.get_screen(
            "game_screen"
        ).ids.enigma_keyboard.ids.lamp_board.ids.board_output.text = ""
        self.manager.get_screen("plugboard_screen").clear_plugs()

        config_store = JsonStore(CONFIG_DIR)
        if (config_store.exists("auto_input")
                and config_store.get("auto_input")["value"] == 0):
            self.manager.get_screen("game_screen").current_time = "200"
        else:
            self.manager.get_screen("game_screen").current_time = "100"

        self.manager.current = "game_screen"
Beispiel #4
0
    def update_info(self):
        """
            Met à jour les informations dans l'onglet "Infos"
        """
        store = JsonStore('info.json')

        if store.exists('name'):
            self.ids["name"].secondary_text = store.get("name")["first_name"]
            self.ids["name"].tertiary_text = store.get("name")["family_name"]

        if store.exists('birthday'):
            self.ids["birthday"].secondary_text = datetime.strptime(
                store.get("birthday")["date"], '%Y:%m:%d').strftime('%d/%m/%Y')

        if store.exists('class'):
            self.ids["class"].secondary_text = store.get("class")["value"]
Beispiel #5
0
    def build(self):

        # store = JsonStore('{}.json'.format(self.subject.text.strip('\n').upper()))
        store = JsonStore('MATHEMATICS.json')
        count = 1
        box = GridLayout(cols=1, spacing=10, size_hint_y=None)
        box.bind(minimum_height=box.setter('height'))
        while count <= len(store):
            if store.exists(str(count)):
                for data in store.get(str(count)).values():
                    box.add_widget(
                        Label(text=str(data), size_hint_y=None, height=40))
            count = count + 1
        root = ScrollView(size_hint=(1, None), size=(400, 600))
        root.add_widget(box)
        return root
Beispiel #6
0
 def mostrar_lista(self):
     self.lista.rm_all_widgets()
     self.pedido.rm_all_widgets()
     listado = glob("../db/parking/*.json")
     for f in listado:
         db = JsonStore(f)
         pedido = db.get("db")
         btn = LabelClicable(bgColor="#444444",
                             font_size="16dp",
                             color="#ffffff")
         btn.tag = {"db": pedido, "fl": f}
         basename = os.path.basename(f).replace(".json","")
         texto = "{0: >25}  Total: {1:5.2f} €".format(basename, pedido['total'])
         btn.text = texto
         btn.bind(on_press=self.onPress)
         self.lista.add_linea(btn)
Beispiel #7
0
    def __init__(self, question_filename='question.json'):
        self.dict = {
            'q_in_page': [],
            'qu_title': "",
            'qu_description': "",
            'ques': {},
            'ans': {},
            'next_button': "",
            'prev_button': ""
        }
        store = JsonStore(question_filename,
                          encoding='utf-8').get('questionnaire')

        for key, value in store.items():
            if key in ['qu_title', 'next_button', 'prev_button', 'questions']:
                self.dict[key] = value[::-1]
            if key in ['qu_description', 'ques', 'ans']:
                self.dict[key] = {}
                for kqa, qa in value.items():
                    self.dict[key][kqa] = qa[::-1]
            if key in ['q_in_page']:
                self.dict[key] = int(value)

        self.dict['ques'] = collections.OrderedDict(
            sorted(self.dict['ques'].items()))
        self.dict['ans'] = collections.OrderedDict(
            sorted(self.dict['ans'].items()))

        k_page = 0
        k_page_ques = 0
        self.page_dict = []
        for k, v in self.dict['ques'].items():
            if k_page_ques == 0:
                page_questions = {}
            page_questions[k] = v
            k_page_ques += 1
            if k_page_ques == self.dict['q_in_page']:
                new_page = {}
                new_page['ques'] = page_questions
                new_page = collections.OrderedDict(sorted(new_page.items()))
                self.page_dict.append(new_page)
                k_page_ques = 0

        for pd in self.page_dict:
            for k, v in self.dict.items():
                if k != 'ques':
                    pd[k] = v
Beispiel #8
0
 def salvar_dados(self):
     store = JsonStore('4u.json')
     dados = {}
     i = 0
     while i < len(self.legenda):
         if self.dadopadrao[i].find(self.ids['db' + str(i + 1)].text) >= 0:
             dados[self.legenda[i]] = '-'
         else:
             dados[self.legenda[i]] = self.ids['db' + str(i + 1)].text
         i = i + 1
     #CRIA ID DE SALVAMENTO#
     idsalv = '#DB#' + dados['Dia'] + dados['Mes'] + dados['Hora']
     store[idsalv]=dados
     #todo implementar melhor a menssagem( colocar um try)
     popup = Popup(title='Aviso', content=Label(text='Dados Salvos'),
                   auto_dismiss=True, size_hint=(1, .5))
     popup.open()
    def __init__(self, **kwargs):
        super().__init__()
        self.store = JsonStore('Hi-Score.json')
        self.cols = 1
        self.padding = [0, 20]
        self.spacing = [0, 8]
        self.game_over = False

        self.hi_score = Label(
            text="[color=ffffff]High Score: [/color][color=724800]" +
            str(self.store.get('hi-score')['score']) + "[/color]",
            font_size='20sp',
            font_name=FONT_PATH.format('Pacifico-Regular.ttf'),
            markup=True,
            size_hint=[1, None],
            height=40)
        self.button_resume = Button(
            background_normal=IMAGES_PATH.format('btn.png'),
            background_down=IMAGES_PATH.format('btn_pressed.png'),
            text="Resume",
            size_hint=[1, None],
            font_name=FONT_PATH.format('Pacifico-Regular.ttf'),
            font_size='18sp',
            height=40)

        self.button_main_menu = Button(
            background_normal=IMAGES_PATH.format('btn.png'),
            background_down=IMAGES_PATH.format('btn_pressed.png'),
            text="Restart Game",
            size_hint=[1, None],
            font_name=FONT_PATH.format('Pacifico-Regular.ttf'),
            font_size='18sp',
            height=40)

        self.button_exit = Button(
            background_normal=IMAGES_PATH.format('btn_g.png'),
            background_down=IMAGES_PATH.format('btn_g_pressed.png'),
            text="Exit From Burning",
            size_hint=[1, None],
            font_name=FONT_PATH.format('Pacifico-Regular.ttf'),
            font_size='18sp',
            height=40)
        self.add_widget(self.hi_score)
        self.add_widget(self.button_resume)
        self.add_widget(self.button_main_menu)
        self.add_widget(self.button_exit)
Beispiel #10
0
def save_header(info_slot, name, gender, domain, symbol, rank, varenth,
                chars_collected, quest_count, lowest_floor, total_score,
                perks_unlocked):
    info = JsonStore(info_slot)
    info['game_version'] = GAME_VERSION
    info['last_save_time'] = strftime('%d/%m/%y %I:%M %p', localtime(time()))
    info['save_name'] = name
    info['gender'] = gender
    info['domain'] = domain
    info['symbol'] = symbol
    info['rank'] = rank
    info['varenth'] = varenth
    info['chars_collected'] = chars_collected
    info['quests'] = quest_count
    info['lowest_floor'] = lowest_floor
    info['total_character_score'] = total_score
    info['skill_level'] = perks_unlocked
Beispiel #11
0
 def handle_timer(self, dt):
     """
     Handle timer during game
     Init timer handled in gameselector and setup_new_game_settings
     """
     game_id = App.get_running_app().game_id
     store = JsonStore(DATA_DIR)
     current_state = store.get(str(game_id))["current_state"]
     # Timer logic
     if int(self.current_time) == 0:
         self.timer_clock.cancel()
         Factory.TimesUp().open()
     else:
         self.current_time = str(int(self.current_time) - 1)
         # Save timer in data
         current_state["timer"] = self.current_time
         store_put(current_state=current_state)
Beispiel #12
0
 def load_keys(self, u_name=None, u_path=None):
     """加载用户密钥"""
     if u_name and u_path:
         self.user_path = u_path
         self.user_name = u_name
     try:
         store = JsonStore(self.user_path)
         self.address = store.get(self.user_name)['address']
         self.__rsa_prikey = store.get(self.user_name)['rsa_prikey']
         self.rsa_pubkey = store.get(self.user_name)['rsa_pubkey']
         self.__ecc_prikey = store.get(self.user_name)['ecc_prikey']
         self.ecc_pubkey = store.get(self.user_name)['ecc_pubkey']
         self.__aes_key = store.get(self.user_name)['aes_key']
         self.__aes_iv = store.get(self.user_name)['aes_iv']
         return True
     except Exception as e:
         return False, str(e)
	def loadhsv(self):
		store = JsonStore('Saved_variables.json')
		if store.exists('variables'):
			h_min = store.get('variables')['h_min']
			s_min = store.get('variables')['s_min']
			v_min = store.get('variables')['v_min']
			h_max = store.get('variables')['h_max']
			s_max = store.get('variables')['s_max']
			v_max = store.get('variables')['v_max']
		else:
			h_min = 0
			s_min = 0
			v_min = 0
			h_max = 255
			s_max = 255
			v_max = 255
		return np.array([h_min,s_min,v_min,h_max,s_max,v_max])
Beispiel #14
0
    def create(self):
        self.store = JsonStore("streak.json")
        obj = self.root.get_screen('one')  # get info from ScreenOne
        self.streak = Streak(obj.ids.action_entry.text,
                             obj.ids.delay_entry.text, obj.ids.day_entry.text,
                             obj.ids.hour_entry.text,
                             obj.ids.minute_entry.text)

        empty_error = "Make sure to fill out all boxes!"  # not in use yet

        popup = Popup(title="Not filled",
                      content=Label(text=empty_error),
                      size_hint=(None, None),
                      size=(300, 100))

        # error handling and calculating total seconds
        parsed = False
        try:
            total = (
                (int(self.streak.day) * 86400) +
                (int(self.streak.hour) * 3600) + (int(self.streak.minute) * 60)
            )  # convert into seconds

            self.current_time = time.time()
            self.count = self.current_time + total
            grace = (int(self.streak.delay) * 60) + self.count  # aka delay
            grace_sec = (int(self.streak.delay) * 60) + total

            parsed = True

            # delete later just used to test
            print("[seconds:", total, ']', "[action:", self.streak.action, ']',
                  "[grace:", grace, ']')

            # store streak attributes inside "streak.json"
            self.store.put(self.streak.action,
                           action=self.streak.action,
                           delay=grace,
                           seconds=total,
                           score=1,
                           delta=self.count,
                           grace_sec=grace_sec)

            self.change_screen(self)
        except ValueError as error:
            popup.open()
 def on_show(self):
     self.ids['msg_list'].clear_widgets()
     self.msg_height = 0
     try:
         store = JsonStore(message_path)
         b_height = store.get('block')['height']
         while b_height > 0:
             msg_hash = store[str(b_height - 1)]['hash']
             msg_data = store[msg_hash]['message']
             msg = MessageLayout(data=json.loads(msg_data))
             self.msg_height += msg.height
             self.ids['msg_list'].height = max(self.msg_height,
                                               self.height / 5 * 4)
             self.ids['msg_list'].add_widget(msg)
             b_height -= 1
     except Exception as e:
         print(str(e))
 def load_local_messages(self, m_path):
     """加载本地信息"""
     self.message_path = m_path
     self.message_hash.clear()
     self.block_height = 0
     try:
         message_store = JsonStore(self.message_path)
         if not message_store.exists('block'):  # initialize block info
             message_store.put('block', height=0)
         else:
             self.block_height = message_store.get('block')['height']
             for i in range(0, self.block_height):
                 msg_hash = message_store[str(i)]['hash']
                 self.message_hash.add(msg_hash)
                 # print(i, msg_hash)
     except Exception as e:
         print(str(e))
Beispiel #17
0
    async def set_refresh(self):
        await asynckivy.sleep(1)

        try:
            self.store = JsonStore("userProfile.json")
            nome = self.store.get("UserInfo")["name"]
            email = self.store.get("UserInfo")["email"]

            await asynckivy.sleep(1)
            self.strng.get_screen(
                "profile").ids.name_perfil_toolbar.text = nome
            self.strng.get_screen(
                "profile").ids.email_perfil_toolbar.text = email

            self.strng.get_screen(
                "screen1").ids.name_perfil_toolbar.text = nome
            self.strng.get_screen(
                "screen1").ids.email_perfil_toolbar.text = email

            self.strng.get_screen(
                "screen2").ids.name_perfil_toolbar.text = nome
            self.strng.get_screen(
                "screen2").ids.email_perfil_toolbar.text = email

            self.strng.get_screen(
                "screen3").ids.name_perfil_toolbar.text = nome
            self.strng.get_screen(
                "screen3").ids.email_perfil_toolbar.text = email

            self.strng.get_screen(
                "screen5").ids.name_perfil_toolbar.text = nome
            self.strng.get_screen(
                "screen5").ids.email_perfil_toolbar.text = email

            self.strng.get_screen(
                "checklistName").ids.name_perfil_toolbar.text = nome
            self.strng.get_screen(
                "checklistName").ids.email_perfil_toolbar.text = email

            self.strng.get_screen("profile").ids.profile_name_input.text = nome
            self.strng.get_screen(
                "profile").ids.profile_email_input.text = email
            self.s

        except Exception:
            pass
Beispiel #18
0
    def load_game(self, game_index):
        App.get_running_app().game_id = int(game_index)
        self.manager.get_screen("rotor_screen").load_rotors()
        self.manager.get_screen("plugboard_screen").load_plugs()
        self.manager.get_screen("game_screen").load_output_text()

        # Setting up timer
        store = JsonStore(DATA_DIR)
        game_id = App.get_running_app().game_id
        current_timer = store.get(str(game_id))["current_state"]["timer"]
        self.manager.get_screen("game_screen").current_time = (
            str(current_timer) or "200")
        if self.manager.get_screen("game_screen").timer_clock:
            self.manager.get_screen("game_screen").timer_clock()

        # Switching to game screen with current config
        self.manager.current = "game_screen"
Beispiel #19
0
class Storage(EventDispatcher):

    store = ListProperty()
    json_store = JsonStore('storage.json')

    instants = ['Drink', 'Flush', 'Washing Clothes', 'Other']

    quantity_based = [
        'Washing Dishes', 'Washing Clothes (manually)', 'Watering Plants'
    ]

    time_based = ['Showering']

    def __init__(self):
        for key in self.json_store.keys():
            entity = self.json_store.get(key)
            self.store.append(entity)
Beispiel #20
0
    def show_files_extensions(self, file_type):
        ''' Loads the files extension settings from the assets/file_extension.json
            it is called when either 'Document, Video, Image or Audoi' List items is pressed.
            After loading, it is shown in a dialog

            :parameters:
                file_type --> extension key in the json_file e.g 'document_extensions

            :return:
                opens a dialog
         '''

        files_extension = JsonStore('assets/files_extension.json')
        dialog_content = MDList()
        self.dialog = None

        for extension in files_extension.get(file_type):
            # trim '.' from the file extension e.g. '.pdf', and add doc_ext_
            # to itso it becomes 'doc_ext_pdf' and use it as the widget id.
            icon_right_sample_widget = IconRightSampleWidget(id="doc_ext_" +
                                                             extension[1:])

            if files_extension.get(file_type)[extension]:
                icon_right_sample_widget.active = True

            # trim '.'from the file extension e.g. '.pdf', and
            # convert it to uppercase
            # so it comes 'PDF'
            list_item = OneLineAvatarIconListItem(text=extension[1:].upper())
            list_item.add_widget(icon_right_sample_widget)
            dialog_content.add_widget(list_item)

        self.dialog = MDDialog(
            title="Select file extensions to include in search",
            content=dialog_content,
            size_hint=(.8, None),
            height=self.root.height - dp((self.root.height / 2) / 8),
            auto_dismiss=False)

        self.dialog.add_action_button("DONE",
                                      action=lambda *x: self.dialog.dismiss())

        # bind the dialog to self.save_extensions method when it is closed
        self.dialog.bind(on_dismiss=partial(self.save_extensions, file_type))
        self.dialog.open()
 def on_show(self):
     """update user card"""
     self.ids['l_user_name'].text = self.user_name
     try:
         store = JsonStore(default_path)
         self.ids['ti_address'].text = store.get(self.user_name)['address']
         self.ids['ti_rsa_prikey'].text = store.get(
             self.user_name)['rsa_prikey']
         self.ids['ti_pubkey'].text = store.get(
             self.user_name)['rsa_pubkey']
         self.ids['ti_ecc_prikey'].text = store.get(
             self.user_name)['ecc_prikey']
         self.ids['ti_ecc_pubkey'].text = store.get(
             self.user_name)['ecc_pubkey']
         self.ids['ti_aes_key'].text = store.get(self.user_name)['aes_key']
         self.ids['ti_aes_iv'].text = store.get(self.user_name)['aes_iv']
     except Exception as e:
         print(str(e))
def add_new_message(req, values):
    """get new message"""
    dat = (json.loads(values))

    msg = MessageLayout(data=json.loads(dat))

    if msg is not None:
        try:
            store = JsonStore(message_path)
            if not store.exists(msg.hash()):  # store message if not exist
                global block_height
                store[block_height] = {'hash': msg.hash()}
                block_height += 1
                store['block'] = {'height': block_height}
                store[msg.hash()] = {'message': msg.serialize()}
            message_hash.add(msg.hash())
        except Exception as e:
            print(str(e))
    def test_post(self):
        """test post"""
        try:
            store = JsonStore(message_path)
            msg_hash = store['2']['hash']
            msg_data = store[msg_hash]['message']

            data = json.loads(msg_data)
            data['hash'] = msg_hash
            params = parse.urlencode(data)
            url = self.ids['ti_url'].text + 'post.php' + '?' + params
            # print(url)
            req = UrlRequest(url=url,
                             on_success=self.request_success,
                             on_failure=self.request_failure,
                             on_error=self.request_failure)
        except Exception as e:
            print(str(e))
 def __init__(self, parent_screen, main_app):
     """
     :param main_app: The main app that runs the program. We use it to pass on the question list and the user answers
     """
     super(QuestionnaireWidget, self).__init__(rows=2 * len(main_app.question_list) + 1, cols=1)
     self.parent_screen = parent_screen
     self.main_app = main_app
     self.question_list = self.main_app.question_list
     self.questionsArray = []
     self.main_app.user_answers = []
     self.set_questions(self.question_list)
     store = JsonStore("Json/questions.json", encoding='utf-8')
     self.submit_button = LoggedButton(text=store['questionnaire']['next_button'][::-1],
                                       font_name="fonts/Alef-Regular.ttf", halign='right')
     # print (store['questionnaire']['next_button'][::-1]) # DEBUG
     self.submit_button.name = 'questionnaire submit'
     self.submit_button.bind(on_press=self.submit_action)
     self.add_widget(self.submit_button)
Beispiel #25
0
def translate_answers(answers_list):
    try:

        int(str(answers_list[0]))

        return str(answers_list[0])
    except (TypeError, ValueError) as e:
        store = JsonStore("Json/questions.json", encoding='utf-8')
        translated_list = [
            store['questionnaire']['get_answers'][str(answer)][::-1]
            for answer in answers_list
        ]
    if (len(answers_list)) == 1:

        return str(translated_list[0])
    else:

        return str(', '.join(translated_list))
Beispiel #26
0
class MyApp(MDApp):
	store=JsonStore('Parametr.json')
	def build(self):
		if lang=="zh":
			Builder.load_string(Labl)
		print(Labl)
		#self.icon_folder=
		try:
			request_permissions([Permission.CAMERA,Permission.WRITE_EXTERNAL_STORAGE,Permission.READ_EXTERNAL_STORAGE])
		except:
			print('Error_permissions')
		
		Sm=sm()
		print('Hi')
		Sm.on_pre_enter=Sm.Enter_()
		return Sm
	def first(self):
		App.root.current="first"
Beispiel #27
0
    def show_birthday_date_picker(self):
        """
            Ouvre la popup pour choisir la date d'anniversaire
        """
        try:
            init_date = datetime.strptime(
                JsonStore('info.json').get("birthday")["date"], '%Y:%m:%d')
        except KeyError:
            init_date = datetime.strptime("2000:01:01", '%Y:%m:%d').date()

        date_dialog = MDDatePicker(
            callback=self.set_birthday,
            year=init_date.year,
            month=init_date.month,
            day=init_date.day,
            min_date=datetime.strptime("1990:01:01", '%Y:%m:%d').date(),
            max_date=datetime.strptime("2010:01:01", '%Y:%m:%d').date())
        date_dialog.open()
Beispiel #28
0
    def __init__(self, **kwargs):
        super(WeatherRoot, self).__init__(**kwargs)

        config = WeatherApp.get_running_app().config
        if len(config.get("App", "weather_api_key")) <= 0:
            print("No API key provided")
            exit()
        self.store = JsonStore("weather_store.json", indent=4, sort_keys=True)
        if self.store.exists("locations"):
            locations = self.store.get('locations')
            if 'current_location' in locations:
                current_location = tuple(
                    locations['current_location'])  # List in JSON
                self.show_current_weather(current_location)
            else:
                Clock.schedule_once(lambda dt: self.show_add_location_form())
        else:
            Clock.schedule_once(lambda dt: self.show_add_location_form())
Beispiel #29
0
    def on_enter(self, *args):
        store = JsonStore('favorite.json')
        list_id = []
        for x in store:
            list_id.append(str(store.get(x).get('id')))
        ids = ','.join(list_id)
        data = {'data': ids}
        url = domain + '/app/favorite/'
        r = requests.get(url, data=data)

        try:
            r.raise_for_status()
            topics = r.json()
            for x in topics:
                card = TopicCard(id=x.get('id'), topic=x.get('topic'))
                self.ids.box.add_widget(card)

        except requests.exceptions.HTTPError as err:
            print('Error: ', err)
Beispiel #30
0
 def build(self):
     self.categories = {
         "Unknown": "",
         "Yes": "1",
         "No": "0",
         "Female": "1",
         "Male": "0"
     }
     data_dir = getattr(
         self, 'user_data_dir')  #get a writable path to save the file
     self.store = JsonStore(join(data_dir, 'units.json'))
     print "DATA DIR", data_dir
     # Load last used units
     for var in units:
         if self.store.exists(var):
             units[var] = self.store.get(var)['unit']
     for scr in in_scr:
         scr.set_units()
     return sm