def populate(self): store = JsonStore(DATA_DIR) latest_game_id = store.get("latest_game_id")["id"] if latest_game_id is not None: for x in range(int(latest_game_id) + 1): game = store.get(str(x)) title = game["game_title"] DATE_FORMAT = "%b %d %Y %H:%M:%S" created = datetime.fromisoformat(str(game["created_date"])) created = created.strftime(DATE_FORMAT) try: last_saved = datetime.fromisoformat( str(game["last_saved_date"])) last_saved = last_saved.strftime(DATE_FORMAT) except ValueError: # Since last_saved_time is None to begin with last_saved = str(game["last_saved_date"]) or "None" self.rv.data.append({ "text": f"{title}\n" f"Created: {created}\n" f"Last Saved: {last_saved}" }) else: self.rv.data = [{"text": self.no_saved_games}]
def es_st_alr(self): st_sys = JsonStore('json/status.json') if st_sys.get('alrm')['st'] == 1: command_line = 'A0PR' write_data = self.ser.write(command_line) elif (st_sys.get('alrm')['st'] == 2 or st_sys.get('alrm')['st'] == 3): pass
def load_contacts(self, u_name, c_path): """显示除自己外的所有测试用户信息""" self.user_name = u_name self.contact_path = c_path self.contacts.clear() layout = GridLayout(cols=1, spacing=10, size_hint_y=None) layout.bind(minimum_height=layout.setter('height')) self.clear_widgets() try: store = JsonStore(self.contact_path) for name in demo_user_names: if name == self.user_name: continue address = store.get(name)['address'] pubkey = store.get(name)['rsa_pubkey'] c = ContactLayout(u_name=name, u_address=address, u_pubkey=pubkey) self.contacts[address] = {'name': name, 'pubkey': pubkey, 'control': c} # (name, pubkey, c) c.update() layout.add_widget(c) except Exception as e: print(str(e)) self.size_hint = (1, 1) self.add_widget(layout)
class SeeDataPage(Screen): def __init__(self, **kwargs): super(SeeDataPage, self).__init__(**kwargs) print("ENTER SEEDATAPAGE INIT") self.store = JsonStore('local.json') #Used for future reference and changing the data in the table self.data = [0] * 20 #Stores the recentTen aspect of the json file self.recentTen = self.store.get("recentTen")["value"] #Creates the grid used to display the information self.table = GridLayout() self.table.cols = 2 print("BEFORE ASSIGN VALUES") #Initiates the table by first creating a label into the self.data array, and #then adding them to the grid for i in range(len(self.recentTen)): self.data[2 * i] = Label(text = self.recentTen[i][1]) self.data[2 * i + 1] = Label(text = self.recentTen[i][0]) self.table.add_widget(self.data[2 * i]) self.table.add_widget(self.data[2 * i + 1]) self.add_widget(self.table) #This method changes the self.data so that it reflects the new recentTen def renewRecentTen(self): print("renew clicked") self.recentTen = self.store.get("recentTen")["value"] for i in range(len(self.recentTen)): self.data[2 * i].text = self.recentTen[i][1] self.data[2 * i + 1].text = self.recentTen[i][0] pass
def timer(self, i): store = JsonStore('config.json') tmp_1 = self.count tmp_2 = time.gmtime(tmp_1) self.ids.count.text = time.strftime('%M:%S', tmp_2) for key, entry in store.find(active_questions=True): len_questions = store.get(key).get('number') if self.count == 0: self.pass_q += 1 self.ids.text_button.text = '{}/{}'.format(self.pass_q, len_questions) try: self.questions.pop(0) Clock.schedule_once(self.sound_play, 1) store = JsonStore('config.json') for key, entry in store.find(active_seconds=True): self.count = store.get(key).get('number') self.question = self.questions[0].get('name') # self.sound_play(self) except IndexError as err: print('IndexError: ', err) self.even_2.cancel() self.manager.current = 'done' self.count -= 1
def play_effect_sound(self, sound): sound_names = { "pop", "plug_in", "keyboard_click", "paper", "button_1", "swoosh", "button_2", "rotor", } if sound not in sound_names: return settings = JsonStore(CONFIG_DIR) volume = 1.0 if settings.exists("effects_volume"): if settings.get("effects_volume")["value"] == 0: return else: volume = settings.get("effects_volume")["value"] sound = SoundLoader.load("misc/" + sound + (".wav" if sound != "swoosh" else ".mp3")) sound.volume = volume sound.play() if platform.system() in {"Linux", "Darwin"}: Clock.schedule_once(lambda dt: sound.unload(), sound.length)
def create_message(sender, receiver, content): """create message""" "" try: store = JsonStore(default_path) sender_address = store.get(sender)['address'] sender_ecc_prikey = store.get(sender)['ecc_prikey'] sender_ecc_pubkey = store.get(sender)['ecc_pubkey'] receiver_address = store.get(receiver)['address'] receiver_rsa_pubkey = store.get(receiver)['rsa_pubkey'] # use receiver's rsa pubkey encrypt content h = SHA.new(content.encode('utf-8')) key = RSA.importKey(receiver_rsa_pubkey) cipher = PKCS1_v1_5.new(key) encrypt = cipher.encrypt(content.encode('utf-8') + h.digest()) encrypted_content = binascii.hexlify(encrypt).decode('utf-8') # sign message use sender's ecc prikey ecc_prikey = PrivateKey(bytes(bytearray.fromhex(sender_ecc_prikey))) sign = ecc_prikey.ecdsa_sign(encrypt) msg_sing = binascii.hexlify( ecc_prikey.ecdsa_serialize(sign)).decode('utf-8') return MessageLayout(sender=sender_address, receiver=receiver_address, content=encrypted_content, sign=msg_sing, pubkey=sender_ecc_pubkey, t=str(time.asctime(time.localtime(time.time())))) except Exception as e: print(str(e))
class WeatherRoot(BoxLayout): carousel = ObjectProperty() current_weather = ObjectProperty() forecast = ObjectProperty() locations = ObjectProperty() add_location_form = ObjectProperty() def __init__(self, **kwargs): super(WeatherRoot, self).__init__(**kwargs) self.store = JsonStore("weather_store.json") if self.store.exists('locations'): current_location = self.store.get("locations")["current_location"] self.show_current_weather(current_location) def show_current_weather(self, location=None): self.clear_widgets() if self.current_weather is None: self.current_weather = CurrentWeather() if self.locations is None: self.locations = Factory.Locations() if (self.store.exists('locations')): locations = self.store.get("locations")['locations'] self.locations.locations_list.adapter.data.extend(locations) if location is not None: self.current_weather.location = location if location not in self.locations.locations_list.adapter.data: self.locations.locations_list.adapter.data.append(location) self.locations.locations_list._trigger_reset_populate() self.store.put("locations", locations=list( self.locations.locations_list.adapter.data), current_location=location) self.current_weather.update_weather() self.add_widget(self.current_weather) def show_forecast(self, location=None): self.clear_widgets() if self.forecast is None: self.forecast = Factory.Forecast() if location is not None: self.forecast.location = location self.forecast.update_weather() self.add_widget(self.forecast) # BEGIN SHOW_MODAL_VIEW def show_add_location_form(self): self.add_location_form = AddLocationForm() self.add_location_form.open() # END SHOW_MODAL_VIEW def show_locations(self): self.clear_widgets() self.add_widget(self.locations)
def auto_input_processor(char: str) -> str: """ Processes the next handled letter for auto-inputting if directed by user from settings """ config_store = JsonStore(CONFIG_DIR) try: if config_store.get("auto_input")["value"] == 1: game_id = App.get_running_app().game_id store = JsonStore(DATA_DIR) game = store.get(str(game_id)) current_output_text = game["current_output_text"] ciphered_text = game["ciphered_text"] output = str(ciphered_text)[len(current_output_text)] return output else: return char except KeyError: # If setting not found, start again and re-process config_store.put("auto_input", value=1) return auto_input_processor(char) except IndexError: # Game won or messed up and passed len(ciphertext). # Nothing else to auto-input. return char
def load_plugs(self): if self.all_plugged: self.clear_plugs() # Prepare data store = JsonStore(DATA_DIR) plugs = store.get(str( App.get_running_app().game_id))["current_state"]["plugs"] # Assumes the data plugs are even. If game goes well # If not, we pop the last one. if len("".join(i for i in plugs)) % 2 != 0: new_plugs = [] for x in plugs: new_plugs.append(str(x)[0]) new_plugs.append(str(x)[1]) # save_plugs(new_plugs) # Reset plugs to be the new even numbered length plugs = store.get(str( App.get_running_app().game_id))["current_state"]["plugs"] """ Begin creation of plugs We have to use get_plug method. We have to find all PlugHole instances """ plugholes_instances = self.ids.plug_board.ids # Plugs prepared. Select instances. Adding in. for x in plugs: instance1 = plugholes_instances[str(x)[0]] instance2 = plugholes_instances[str(x)[1]] self.handle_plug_release(instance1) self.handle_plug_release(instance2)
class WeatherRoot(BoxLayout): carousel = ObjectProperty() current_weather = ObjectProperty() forecast = ObjectProperty() locations = ObjectProperty() add_location_form = ObjectProperty() def __init__(self, **kwargs): super(WeatherRoot, self).__init__(**kwargs) self.store = JsonStore("weather_store.json") if self.store.exists('locations'): current_location = self.store.get("locations")["current_location"] self.show_current_weather(current_location) def show_current_weather(self, location=None): self.clear_widgets() if self.current_weather is None: self.current_weather = CurrentWeather() if self.locations is None: self.locations = Factory.Locations() if (self.store.exists('locations')): locations = self.store.get("locations")['locations'] self.locations.locations_list.adapter.data.extend(locations) if location is not None: self.current_weather.location = location if location not in self.locations.locations_list.adapter.data: self.locations.locations_list.adapter.data.append(location) self.locations.locations_list._trigger_reset_populate() self.store.put("locations", locations=list(self.locations.locations_list.adapter.data), current_location=location) self.current_weather.update_weather() self.add_widget(self.current_weather) def show_forecast(self, location=None): self.clear_widgets() if self.forecast is None: self.forecast = Factory.Forecast() if location is not None: self.forecast.location = location self.forecast.update_weather() self.add_widget(self.forecast) # BEGIN SHOW_MODAL_VIEW def show_add_location_form(self): self.add_location_form = AddLocationForm() self.add_location_form.open() # END SHOW_MODAL_VIEW def show_locations(self): self.clear_widgets() self.add_widget(self.locations)
def check_backup(self, _): if not (os.path.isfile(BACKUP)): self.info_popup( "Er is geen backup gevonden.\nJe bestelling is verzonden en aangekomen." ) return #probeer de backup in te laden try: store = JsonStore(BACKUP) info = store.get("backup").get( "info") #gebruiken voor popup met info data = store.get("backup").get("data") DATA.load_data(data) except Exception as e: print("JSON load error", str(e)) self.info_popup("Er ging iets mis bij het inladen van de backup.") return #maak popup met info over de klant/status popup = Popup(title="Klantinfo") layout = GridLayout(cols=1) layout.add_widget( Label(text="ID: {}".format(info["id"]), font_size=30)) layout.add_widget( Label(text="Naam: {}".format(info["naam"]), font_size=28)) layout.add_widget( Label(text="Tafel: {}".format(info["tafel"]), font_size=30)) layout.add_widget( Label(text="Verzonden: {}".format("Ja" if ( info["verzonden"]) else "Nee"), font_size=30)) layout.add_widget( Label(text="Bevestigd: {}".format("Ja" if ( info["bevestigd"]) else "Nee"), font_size=30)) info_label = Label( text= "[color=#ffff00]Indien je bestelling reeds verzonden is zullen veranderingen niet worden toegelaten![/color]", font_size=30, markup=True) info_label.bind(width=self._update_text_width) layout.add_widget(info_label) knop = Button(text="sluit", width=Window.size[0] * .75) knop.bind(on_press=popup.dismiss) layout.add_widget(knop) popup.add_widget(layout) popup.open() #herlaad het bestellingscherm m_app.prod_pagina.klik(Label(text=""), True) m_app.prod_pagina.reset() m_app.screen_manager.current = "bestelling"
def __init__(self, i, *args, **kwargs): js = JsonStore('names.json') super(MyItem, self).__init__(*args) state = js.get(i)['state'] self.text = js.get(i)['name'] self.secondary_text = js.get(i)['state'] self._no_ripple_effect = True self.image = ImageLeftWidget(source=f"images/{state}.jpg") self.add_widget(self.image)
def tem(self, *args): store = JsonStore('archivio.json') if store.exists('tema'): if store.get('tema')['set'] == 'scuro': self.theme_cls.theme_style = "Dark" if store.get('tema')['set'] == 'chiaro': self.theme_cls.theme_style = "Light" else: pass
def clkLogin(self, obj): global db global cursor global loggedUser global sftp global store global screenCounter global taskCounter sql = "SELECT * FROM USERS \ WHERE USER = '******' AND PW = '%s'" % (self.userinput.text, self.passinput.text) cursor.execute(sql) db.commit() results = cursor.fetchall() if not results: popup = Popup( title='Login mismatch', content=Label( text= 'Your password may be incorrect or the account may not exist. Please try again or else create an account.' ), size_hint=(.8, .5)) popup.open() else: loggedUser = self.userinput.text popup = Popup( title='Login successful', content=Label(text='You have logged in successfully'), size_hint=(.5, .5)) popup.open() #check if there exists a file named 'loggedUser.json' with sftp.cd('/home/public/taskapp/'): exists = sftp.isfile('%s.json' % loggedUser) #if there does not, store = loggedUser.json. This will be an empty file for a new user. if not exists: store = JsonStore('%s.json' % loggedUser) screenCounter = 0 taskCounter = 0 #if there is, get that file and then set store equal to it. else: sftp.get('/home/public/taskapp/%s.json' % loggedUser) store = JsonStore('%s.json' % loggedUser) if store.exists('screenCounter'): screenCounter = store.get('screenCounter')['val'] else: screenCounter = 0 if store.exists('taskCounter'): taskCounter = store.get('taskCounter')['val'] else: taskCounter = 0 screen = TasksWindow(True, 'No Parent', [], -1, True) screen.name = 'Screen 0' Clock.schedule_interval(screen.preupdate, 1.0 / 2.0) sm.add_widget(screen) sm.current = 'Screen 0' screen.loadData()
def on_enter(self): """ The filebrowser screen is being opened """ if not self.initailized: self.initailized = True store = JsonStore("zenplayer.json") if store.exists("filebrowser"): if "path" in store.get("filebrowser").keys(): file_path = store.get("filebrowser")["path"] if exists(file_path): self.filechooser.path = file_path
class WeatherRoot(BoxLayout): add_location_form = ObjectProperty() carousel = ObjectProperty current_weather = ObjectProperty() forecast = ObjectProperty locations = ObjectProperty 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()) def show_add_location_form(self): self.add_location_form = AddLocationForm() self.add_location_form.open() def show_current_weather(self, location=None): config = WeatherApp.get_running_app().config if config.get("App", "save_search_history"): if not self.store.exists('locations'): self.store.put('locations') locations = self.store.get('locations') if 'location_history' not in locations: locations['location_history'] = {} location_history = locations['location_history'] if str(location[2] ) not in location_history: # JSON keys are string location_history[str(location[2])] = location self.store.put('locations', location_history=location_history, current_location=location) self.current_weather.location = location self.current_weather.update_weather() self.forecast.location = location self.forecast.update_weather() self.carousel.load_slide(self.current_weather) if self.add_location_form is not None: self.add_location_form.dismiss()
def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) self.workers[0].start() self.workers[1].start() self.workers[2].start() self.workers[3].start() Clock.schedule_interval(self.checkisrunning, 0.1) Clock.schedule_interval(self.getblockinfo, 1) Clock.schedule_interval(self.checkbalance, 1) Clock.schedule_interval(self.checkname, 0.1) # load data if it exists if isfile('forms.json'): try: store = JsonStore('forms.json') self.input_name.text = store.get('forms')['walletname'] self.input_address.text = store.get('forms')['sendtoaddress'] self.input_amount.text = store.get('forms')['amount'] self.input_mixin.text = store.get('forms')['mixin'] self.input_paymentid.text = store.get('forms')['paymentid'] self.minerurl_input.text = store.get('forms')['mineraddress'] self.mineruser_input.text = store.get('forms')['mineruser'] self.minerpw_input.text = store.get('forms')['minerpw'] self.minerthreads_input.text = store.get('forms')[ 'minerthreads'] except: pass
def __init__(self, **kwargs): super(RootWidget, self).__init__(**kwargs) self.workers[0].start() self.workers[1].start() self.workers[2].start() self.workers[3].start() Clock.schedule_interval(self.checkisrunning, 0.1) Clock.schedule_interval(self.getblockinfo, 1) Clock.schedule_interval(self.checkbalance, 1) Clock.schedule_interval(self.checkname, 0.1) # load data if it exists if isfile('forms.json'): try: store = JsonStore('forms.json') self.input_name.text = store.get('forms')['walletname'] self.input_address.text = store.get('forms')['sendtoaddress'] self.input_amount.text = store.get('forms')['amount'] self.input_mixin.text = store.get('forms')['mixin'] self.input_paymentid.text = store.get('forms')['paymentid'] self.minerurl_input.text = store.get('forms')['mineraddress'] self.mineruser_input.text = store.get('forms')['mineruser'] self.minerpw_input.text = store.get('forms')['minerpw'] self.minerthreads_input.text = store.get( 'forms')['minerthreads'] except: pass
def LoadSettings(self): store = JsonStore("data.json") if store.exists("lower_num") or store.exists("high_num"): low = store.get("lower_num")["value"] high = store.get("upper_num")["value"] if store.exists("lower_num"): if low < high: self.math_screen.min_num = low if store.exists("upper_num"): self.math_screen.max_num = high
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)
def save_values(self,value1,value2,rsvalue): store = JsonStore('result.json') store['first'] = {'first': value1} store['second'] = {'second': value2} store['result'] = {'result': rsvalue} store['f1'] = {'f1': rsvalue + int(random()*20) + 1} store['f2'] = {'f2': rsvalue - int(random()*20) - 1} store['f3'] = {'f3': rsvalue * int(random()*20) + 20} store['f4'] = {'f4': rsvalue - int(random()*25) - 1} print(store.get('first')) print(store.get('second')) print(store.get('result'))
class ScoreBar(BoxLayout): score = NumericProperty() hi_score = NumericProperty() game_id = StringProperty() players = NumericProperty() active_player = NumericProperty() def __init__(self,**kwargs): super(ScoreBar,self).__init__(**kwargs) self.store = JsonStore(os.path.join(get_user_path(),'scores.json')) self.bind(score = self.score_changed) self.set_game_id() def set_game_id(self, game_id = 'default', multiplayer = False): self.players = int(multiplayer) + 1 self.active_player = 1 self.game_id = game_id if self.players == 1: if self.store.exists(game_id): data = self.store.get(game_id) self.hi_score = data['high_score'] else: self.hi_score = 0 def score_changed(self, *args): if self.players == 2: return if self.game_id != 'default': date = uspac.fromutc(datetime.datetime.utcnow()) game_id = 'd%i%i%i'%(date.year, date.month, date.day) if self.game_id != game_id: #daily challenge has finished, the game reverts to default type so we only update the default high score table self.set_game_id() else: #store the high score in the default table as well as in the daily table hi_score = 0 if self.store.exists('default'): data = self.store.get('default') hi_score = data['high_score'] if self.score > hi_score: self.store.put('default',high_score=int(self.score)) if self.score > self.hi_score: self.hi_score = self.score self.store.put(self.game_id,high_score=int(self.score)) if platform == 'android' and self.players == 1: if self.score > 600: App.get_running_app().gs_achieve('achievement_score_of_600') if self.score > 800: App.get_running_app().gs_achieve('achievement_score_of_800') if self.score > 1000: App.get_running_app().gs_achieve('achievement_score_of_1000') if self.score > 1200: App.get_running_app().gs_achieve('achievement_score_of_1200')
def build(self): storage = JsonStore('storage_file.json') try: storage.get('highscore') except KeyError: storage.put('highscore', level=0, name='no highscores yet') game = Game() game.storage = storage game.highscore = storage.get('highscore')['level'] game.name = storage.get('highscore')['name'] self.game = game return game
class UrbanRoot(BoxLayout): urbansearch = ObjectProperty() urbandict = ObjectProperty() def __init__(self, **kwargs): super(UrbanRoot, self).__init__(**kwargs) self.store = JsonStore("dictionary.json") self.update_urbandict() def add_to_dictionary(self, word, definition, example): current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else [] d = { 'word' : word.encode('utf-8'), 'definition' : definition.encode('utf-8'), 'example' : example.encode('utf-8') } if d not in current: current.append(d) self.store.put('dictionary', dictionary = list(current)) self.update_urbandict() Popup(size_hint=(0.8,0.2),title='Success', content = Label(text = 'Word has been added into dictionary')).open() def update_urbandict(self): current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else [] self.urbandict.urbandictcontainer.clear_widgets() for d in current: item = Factory.UrbanItemDict() item.word = d['word'].encode('utf-8') item.definition = d['definition'].replace('\r','').replace('\t','').encode('utf-8') item.example = d['example'].replace('\r','').replace('\t','').encode('utf-8') self.urbandict.urbandictcontainer.add_widget(item) def remove_from_dict(self, word, definition, example): current = self.store.get('dictionary')['dictionary'] if self.store.exists('dictionary') else [] d = { 'word' : word.encode('utf-8'), 'definition' : definition.encode('utf-8'), 'example' : example.encode('utf-8') } if d in current: current.remove(d) self.store.put('dictionary', dictionary = list(current)) print 'removed' self.update_urbandict()
def load_checklists_screen_main(self): store = JsonStore("dataChecklist.json") self.list_name = store.get('UserInfo')['name'] criado_por = store.get('UserInfo')['data'] criado_em = store.get('UserInfo')['responsavel'] self.list_name = ThreeLineIconListItem( text=self.list_name, secondary_text='Responsável: ' + criado_por, tertiary_text='Data de emissão: ' + criado_em, on_release=self.change_screen) self.list_name.add_widget(IconLeftWidget(icon='check-box-outline')) self.strng.get_screen('screen2').ids.my_checklists.add_widget(self.list_name) self.strng.get_screen('screen1').manager.current = 'screen1'
def loadcalibration(self): cameracalibration = JsonStore('Saved_calibration.json') if cameracalibration.exists('calibration_var'): mtx = cameracalibration.get('calibration_var')['mtx'] dist = cameracalibration.get('calibration_var')['dist'] mtx = np.array(mtx) dist = np.array(dist) needscalibration = False else: dist = None mtx = None needscalibration = True return dist,mtx,needscalibration
def show_all_demo_users(): """show all demo user keys""" try: store = JsonStore('../demo_users.json') for name in demo_user_names: print('User ' + name) print('Address:= ' + store.get(name)['address']) print(store.get(name)['rsa_prikey']) print(store.get(name)['rsa_pubkey']) print('ECC Private Key:= ' + store.get(name)['ecc_prikey']) print('ECC Public Key := ' + store.get(name)['ecc_pubkey']) print('AES Key:= ' + store.get(name)['aes_key']) print('AES IV := ' + store.get(name)['aes_iv']) except Exception as e: print(str(e))
def loadData(self, ext): cant = 0 letters = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') if len(ext) == 0: return None if ext[0] == ".": ext = ext.split(".")[1] if ext[0] in letters: file_path = './data/' + ext[0] + '.json' else: file_path = './data/1.json' data = JsonStore(file_path) if data.exists(ext): platforms = str(data.get(ext)[2]) platform_list = platforms.split(',') programs = str(data.get(ext)[3]) programs_list = programs.split('][') body = "[b][color=3333ff]How to open:[/color][/b] \n\n" if len(platform_list) <= len(programs_list): cant = len(platform_list) else: cant = len(programs_list) for i in range(cant): for ch in ['[', ']']: if ch in programs_list[i]: programs_list[i] = programs_list[i].replace(ch, "") body += ("[color=3333ff]" + platform_list[i] + ":[/color] " + programs_list[i] + "\n\n") description = ("[color=3333ff]Name:[/color] " + str(data.get(ext)[0]) + "\n\n" + "[color=3333ff]Description:[/color] " + str(data.get(ext)[1]) + "\n\n" + body) self.show_dialog(ext, description) else: extError = ext + " not found" notFound = "Make sure that the file has a correct name" self.show_dialog(extError, notFound)
def change_solution_text(self,value): store = JsonStore('result.json') value = store.get(value).values().pop() #print value result = self.set_solution_value(value) self.btn_text = str(result) return self.btn_text
def input_data(self): store = JsonStore(DATA_DIR) game_id = str(App.get_running_app().game_id) if game_id == "None": return [ {"text": "[b]Plugboard:[/b]"}, {"text": "[b]Rotors:[/b]"}, {"text": "[b]Rotor settings:[/b]"}, {"text": "[b]Ciphertext:[/b]"}, ] game = store.get(game_id) cipher_text = game["ciphered_text"] encrypted_state = game["encrypted_state"] plugs = encrypted_state["plugs"] plug_settings = " ".join(x for x in plugs) rotor_settings = "I II III" rotors = "" for i, x in enumerate(encrypted_state["rotors"]): if x is None: continue rotors += x input_data = [ {"text": "[b]Plugboard:[/b]"}, {"text": plug_settings + "\n"}, {"text": "[b]Rotors:[/b]"}, {"text": rotors + "\n"}, {"text": "[b]Rotor settings:[/b]"}, {"text": rotor_settings + "\n"}, {"text": "[b]Ciphertext:[/b]"}, {"text": cipher_text}, ] return input_data
def __init__(self): super(QuestionsForm, self).__init__() with self.canvas.before: #Color(0, 1, 0, 1) # green; colors range from 0-1 instead of 0-255 self.rect = Rectangle(source='back2.png') self.bind(size=self._update_rect, pos=self._update_rect) dict = { 'q_in_page': [], 'qu_title': "", 'qu_description': "", 'ques': {}, 'ans': {}, 'next_button': "", 'prev_button': "" } #f = open('try.py', 'r', encoding='utf-8') self.answers = {} # txt = f.read() txt = "קרן" store = JsonStore('hello.json') self.add_widget(Label(text=txt[::-1], font_name="DejaVuSans.ttf")) self.add_widget( Label(text=store.get("questionnaire")["qu_title"][::-1], font_name="DejaVuSans.ttf"))
def setUrls(self): if self.urls.__len__()>0: if hasattr(self,"side"): self.side.container.clear_widgets() self.remove_widget(self.side) del self.side title=JsonStore("titles.json") titles=title.get("titles") self.side = LeftSide() for k in self.urls: all=titles["all"] if all[k]: lbl = MToggleButton(text=all[k], size_hint=(1, None), height=100) lbl.urlToShow = self.urls[k] lbl.ac=self.container lbl.gndmLabel=self.gndmLabel if all[k]==u"Gündem": lbl.state="down" self.gndmLabel.text=self.title+u" Gündem" lbl.reqData() self.side.container.add_widget(lbl) self.add_widget(self.side) self.side.x=-self.side.width-self.manager.width*0.2 self.side.y=0 self.side.container.height=100*(len(self.side.container.children))
def loadobjectsize(self): store = JsonStore('Saved_variables.json') if store.exists('ballsize'): ballsize = store.get('ballsize')['ballsize'] else: ballsize = 6.6 return ballsize
class Form1App(App): def build(self): self.icon = 'cropped_lumpy2.png' Config.set("input", "mouse", "mouse, disable_multitouch") root = RootHome() self.title = 'hello' self.store = JsonStore('projectlist.json') from kivy.core.window import Window # Window.borderless = True return root def on_start(self): time.sleep(.5) def g_store(self): w = self.store return w def spit_store(self, text,DR_F, DRR_F, DRIS_F, DRISR_F): # store = JsonStore('projectlist.json') print text print PROJECT g = self.store.get(PROJECT) print g if text == lisp[0][0]: print DR_F print type(DRR_F) print DRIS_F print DRISR_F g['content']['designrequirements'][lisp[0][1]] = {"drisr": DRISR_F, "drr": DRR_F, "dr": DR_F, "dris": DRIS_F} print g print g['content'] # store[PROJECT]= {"content":{'designrequirements':{ lisp[0][1] : { 'drisr':DRISR_F, # 'drr':DRR_F, # 'dr':DR_F, # 'dris':DRIS_F}}}} print lisp[0][1] elif text == lisp[1][0]: print lisp[1][1] store[PROJECT]['content']['designrequirements'][lisp[1][1]] = {"drisr": DRISR_F, "drr": DRR_F, "dr": DR_F, "dris": DRIS_F} print store[PROJECT]['content'] elif text == lisp[2][0]: print lisp[2][1] store[PROJECT]['content']['designrequirements'][lisp[2][1]] = {"drisr": DRISR_F, "drr": DRR_F, "dr": DR_F, "dris": DRIS_F} elif text == lisp[3][0]: print lisp[3][1] elif text == lisp[4][0]: print lisp[4][1] elif text == lisp[5][0]: print lisp[5][1] else: pass return store
def send_message(self): """发送消息 生成一侧对话信息,并存储在本地 """ content = self.ids['ti_message'].text if content is None: return message = self.user.create_chat_message(self.contact['address'], self.contact['pubkey'], content) if message is not None: # print(message.serialize()) # 将信息写入本地 try: # 读取本地信息列表 store = JsonStore(self.message_path) block_height = store.get('block')['height'] if not store.exists( message.hash()): # store message if not exist store[block_height] = {'hash': message.hash()} block_height += 1 store['block'] = {'height': block_height} store[message.hash()] = {'message': message.serialize()} except Exception as e: print(str(e))
def load_history(self): """加载聊天历史""" self.ids['history_list'].clear_widgets() try: # 读取本地信息列表 store = JsonStore(self.message_path) b_height = store.get('block')['height'] while b_height > 0: msg_hash = store[str(b_height - 1)]['hash'] msg_data = json.loads(store[msg_hash]['message']) message = MMMessage(msg_data) # 接受的信息 if message.receiver == self.user.address and message.sender == self.contact[ 'address']: content = self.user.decode_message(message) msg_text = "{0}:<{1}>@[{2}]".format( self.contact['name'], content, msg_data['time']) msg = ChatMessageRecv(text=msg_text) self.ids['history_list'].add_widget(msg) # 发送的信息 if message.receiver == self.contact[ 'address'] and message.sender == self.user.address: content = self.user.decode_message(message) msg_text = "{0}:<{1}>@[{2}]".format( self.user.user_name, content, msg_data['time']) msg = ChatMessageSend(text=msg_text) self.ids['history_list'].add_widget(msg) b_height -= 1 except Exception as e: print(str(e))
def on_enter(self, *args): store = JsonStore('config.json') id_topic = self.ids.id_topic.text url = domain + '/app/detail/' + id_topic r = requests.get(url) try: r.raise_for_status() data = r.json() # get some random questions from JSON for key, entry in store.find(active_questions=True): count_questions = store.get(key).get('number') try: questions = random.sample(data, count_questions) except ValueError as err: questions = data TalkingScreen.questions = questions # pass Objects to TalkingScreen class i = 1 for x in questions: q = str(i) + '. ' + x.get('name') + ' ?' label = MDLabel(text=q) self.ids.box.add_widget(label) i += 1 btn = MDRaisedButton(text='Start', pos_hint={'center_x': 0.5}) self.ids.my_btn.add_widget(btn) btn.bind(on_press=self.go_to_talking) except requests.exceptions.HTTPError as err: print('Http error: ', err)
def favorite(self, id, topic): store = JsonStore('favorite.json') for x in store: self.s.append(store.get(x).get('id')) if id in self.s: try: store.delete(topic) self.iconButton.text_color = rgba('#000000') print('Removed') if len(store) == 0: os.remove('favorite.json') MDApp.get_running_app( ).root.ids.main.ids.main_star.text_color = 0, 0, 0, 0 print('<<<< File was removed >>>') except KeyError as keyerr: print('>>>>> Error <<<<<: ', keyerr) store.put(topic, id=id) self.iconButton.text_color = rgba('#E91E63') MDApp.get_running_app( ).root.ids.main.ids.main_star.text_color = 1, 1, 1, 1 except FileNotFoundError as fileerr: print('<<< Error>>> : ', fileerr) else: store.put(topic, id=id) self.iconButton.text_color = rgba('#E91E63') print('Added to favorite') if len(store) == 1: MDApp.get_running_app( ).root.ids.main.ids.main_star.text_color = 1, 1, 1, 1 self.s = []
def load_chat_messsages(self, user, u_contact, m_path): """显示除自己外的所有测试用户信息""" self.user = user self.message_path = m_path self.contacts = u_contact layout = GridLayout(cols=1, spacing=10, size_hint_y=None) layout.bind(minimum_height=layout.setter('height')) self.clear_widgets() try: # 读取本地信息列表 store = JsonStore(self.message_path) b_height = store.get('block')['height'] while b_height > 0: msg_hash = store[str(b_height - 1)]['hash'] msg_data = json.loads(store[msg_hash]['message']) message = MMMessage(msg_data) # 验证接收地址是自己的信息 if self.user.is_mine(message) and verify_message(message): if message.sender in self.contacts: s_name = self.contacts[message.sender]['name'] elif message.sender == self.user.address: s_name = self.user.user_name else: s_name = None s_address = message.sender s_content = self.user.decode_message(message) msg_widget = MessageWidget(s_name, s_address, s_content) msg_widget.update() layout.add_widget(msg_widget) b_height -= 1 self.size_hint = (1, 1) self.add_widget(layout) except Exception as e: print('Error: ', str(e))
class WeatherRoot(BoxLayout): current_weather = ObjectProperty() locations = ObjectProperty() # BEGIN LOAD_CURRENT def __init__(self, **kwargs): super(WeatherRoot, self).__init__(**kwargs) self.store = JsonStore("weather_store.json") if self.store.exists('locations'): current_location = self.store.get("locations")["current_location"] self.show_current_weather(current_location) # END LOAD_CURRENT def show_current_weather(self, location=None): self.clear_widgets() if self.current_weather is None: self.current_weather = CurrentWeather() if self.locations is None: self.locations = Factory.Locations() if (self.store.exists('locations')): locations = self.store.get("locations")['locations'] self.locations.locations_list.adapter.data.extend(locations) # BEGIN PUT_CURRENT if location is not None: self.current_weather.location = location if location not in self.locations.locations_list.adapter.data: self.locations.locations_list.adapter.data.append(location) self.locations.locations_list._trigger_reset_populate() self.store.put("locations", locations=list(self.locations.locations_list.adapter.data), current_location=location) # END PUT_CURRENT self.current_weather.update_weather() self.add_widget(self.current_weather) def show_add_location_form(self): self.clear_widgets() self.add_widget(AddLocationForm()) def show_locations(self): self.clear_widgets() self.add_widget(self.locations)
def __int__(self, **kwargs): super().__init__(**kwargs) store = JsonStore('hello.json') #put some values store.put('tito', name='Mathieu', org='kivy') store.put('tshirtman', name='Gabriel', age=27) store.put('tito', name='Mathieu', age=30) print('tito is', store.get('tito')['age'])
def check_password(self, un, pw): general_store = JsonStore('general.json') key = '%s' % (un) p = general_store.get("users") list = json.dumps(p.keys()) print list if key in p: matching_pw = json.dumps(general_store.get("users")[key]) print("\nmatching_pw = " + matching_pw) print '%s' % (pw) if '"%s"' % (pw) == matching_pw: return True else: return False else: warning = 'username not found' return warning
class MbtMergeManager(object): """ Keeps track mbtiles merging state (merged vs not merged) and handles merging. """ def __init__(self): json_store_path = App.get_running_app().json_store_path self.store = JsonStore(json_store_path) def merge_not_merged(self): """ Merges not merged files. """ mbtmerge = MbtMerge() sources = self.not_merged() destination = App.get_running_app().main_mbtiles_path mbtmerge.merge(sources, destination) for source in sources: self.add_to_merged(source) def not_merged(self): """ Returns the list of not merged files. """ merged_list = self.merged() not_merged_list = App.get_running_app().mbtiles_paths for merged in merged_list: not_merged_list.remove(merged) return not_merged_list def merged(self): """ Returns the list of merged files. """ try: merged = self.store.get('merged_mbtiles')['list'] except KeyError: merged = [] return merged def add_to_merged(self, mbtiles_path): """ Adds the mbtiles to the merged list. """ merged = self.merged() merged.append(mbtiles_path) self.store.put('merged_mbtiles', list=merged) def remove_from_merged(self, mbtiles_path): """ Removes the mbtiles from the merged list. """ merged = self.merged() merged.remove(mbtiles_path) self.store.put('merged_mbtiles', list=merged)
def check_user_exists(self, username): general_store = JsonStore('general.json') un = username key = '%s' % (un) p = general_store.get("users") list = json.dumps(p.keys()) if key in p: return True else: False
class EntryStackLayout(StackLayout): def __init__(self, **kwargs): super(EntryStackLayout, self).__init__(**kwargs) ''' Build a list of entries to be displayed on the app ''' self.id = 'entry_stack_layout' self.name = 'entry_stack_layout' self.size_hint = (1,1) self.entry_widgets = [] self.screen_manager = App.get_running_app().sm self.build_list() for i in self.entry_widgets: self.add_widget(i) def build_list(self): self.data_store = JsonStore('./dat.json') entries = json.loads(self.data_store.get('feeds')['entries']) entries_count = len(entries) card_contents = StackLayout(size_hint = [1, 0.0225]) for entry in entries: self.size_hint[1] += 0.35 card_contents.add_widget(Image(source = './assets/images/talkpython-nowrds.png', size_hint = [0.15,0.4])) card_contents.add_widget(Label(text=entry['title'], valign='top', size_hint=[0.85, 0.4], text_size= [Window.width * 0.35, None])) card_contents.add_widget(MyAudioPlayer(source="./assets/audio/043_monitoring_high_performance_python_apps_at_opbeat.mp3", thumbnail= './assets/images/talkpython.png', size_hint = [1,0.4], allow_fullscreen= False )) #card_contents.add_widget(VideoPlayer(source="./assets/videos/hst_1.mpg", size_hint = [1,0.8])) self.entry_widgets.append(card_contents) card_contents = StackLayout(size_hint = [1, 0.0225]) def test_bind(self): print('test bind EntryStackLayout', self.test_data_store)
def __init__(self, *args, **kwargs): super(RootBox, self).__init__(*args, **kwargs) self.chat_client = None self.receive_queue = Queue() # create the confirm box for quitting self.quit_confirm = ConfirmPopup(title='Quit?', confirm_text='Quit') self.quit_confirm.bind(on_confirm=self.quit_pushed) self.quit_confirm.bind(on_cancel=self.cancel_pushed) # there is some sort of instantiation order problem where you can't # directly refer to custom classes as children in the kv language, so # everywhere were we want custom classes there is a BoxLayout which we # will now put the custom classes inside self.menu = Menu() self.menu.hide_item('Chats') self.menu.bind(text=self.menu_action) self.ids.menu_container.add_widget(self.menu) self.chat_box = ChatBox() self.ids.chat_box_container.add_widget(self.chat_box) # don't add friend_box just yet, it has the connection status label in # it self.friend_box = FriendBox(self) store = JsonStore('storage.json') try: userid = store.get('account')['userid'] password = store.get('account')['password'] host = store.get('server')['host'] port = store.get('server')['port'] except KeyError: self.ids.connection_label.text = 'No Username Set' else: # create the chat client and start processing on separate thread self.chat_client = ChatClient(self, userid, password) self.chat_client.connect((host, port)) self.chat_client.process(block=False)
def check_btn_solution(self,value): store = JsonStore('result.json') jsonvalue = store.get('result').values().pop() value = int(value) #print ('value=',type(value), type(jsonvalue)) if value == jsonvalue: #print 'its correct! change text and need to update score! +2' self.update_score(2) self.change_text() #else: #print 'here is something wrong' return self.btn_text
class LoginScreen(Screen): store='' username='' def __init__(self,**kwargs): super(LoginScreen, self).__init__(**kwargs) Clock.schedule_once(self.update_layout,1/60) def update_layout(self,btn): data_dir= App.get_running_app().user_data_dir+'/' self.store = JsonStore(join(data_dir, 'storage.json')) try: self.username=self.store.get('credentials')['username'] exp_data.set_username(self.username) self.parent.current = 'ExperimentSelectScreen' except KeyError: box=BoxLayout(orientation= 'vertical',padding=(100,100,100,100)) #l=Label(size_hint_y=0.25) #box.add_widget(l) box.add_widget(Label(text="Enter email",font_size= sp(30),size_hint_y=.5)) self.t=TextInput(font_size= sp(30),size_hint_y=0.5) box.add_widget(self.t) box.add_widget(Button(text="Okay",on_press=self.change_screen,font_size=sp(25),size_hint_y=.25)) #box.add_widget(l) self.add_widget(box) # #AppScreen.store.put('credentials', username=username, password=password) def change_screen(self,btn): if len(self.t.text) == 0: #deal with exception here of not selecting a single experiment error_popup=Popup(title='Error',content=Label(text="Email cannot be left blank")\ ,size_hint=(.75,.75),auto_dismiss=True) error_popup.open() Clock.schedule_interval(error_popup.dismiss, 3) else: self.store.put('credentials', username=self.t.text) self.username=self.store.get('credentials')['username'] exp_data.set_username(self.username) self.parent.current = 'ExperimentSelectScreen'
def get_grade(self,filename, root): descript = JsonStore('data_descript.json') cwd = str(descript.get(filename)['desc']) speech = root.ids['input_speech'].text cwd_list = str.split(cwd) speech_list = str.split(speech) correct = set(cwd_list).intersection(speech_list) correct_number = len(correct) if correct_number <= 10: marks = correct_number * correct_number else: marks = correct_number * 10 return marks
def on_enter(self, *args): super(PanelScreen,self).on_enter(*args) self.entered=True self.selectedCat=None js=JsonStore("titles.json") titles=js.get("titles") drop=DropDown() for t in titles["all"]: btn=MiButton(text=titles["all"][t],size_hint_y=None,height=50,key=t) btn.bind(on_release=lambda btn:drop.select(btn)) drop.add_widget(btn) def set_select(inst,btn): self.drp.text=btn.text self.selectedCat=btn.key drop.bind(on_select=set_select) self.drp.bind(on_release=drop.open)
def __init__(self): super(QuestionsForm, self).__init__() with self.canvas.before: #Color(0, 1, 0, 1) # green; colors range from 0-1 instead of 0-255 self.rect = Rectangle(source='back2.png') self.bind(size=self._update_rect, pos=self._update_rect) dict = {'q_in_page':[], 'qu_title': "", 'qu_description': "", 'ques': {}, 'ans': {}, 'next_button': "", 'prev_button': ""} #f = open('try.py', 'r', encoding='utf-8') self.answers={} # txt = f.read() txt = "קרן" store = JsonStore('hello.json') self.add_widget(Label(text=txt[::-1], font_name="DejaVuSans.ttf")) self.add_widget(Label(text=store.get("questionnaire")["qu_title"][::-1], font_name="DejaVuSans.ttf"))
def __init__(self, parent_app): self.the_app = parent_app self.the_widget = CuriosityWidget() # initialize items items_path = 'items/' items_json = JsonStore(items_path + 'items.json') items_list = items_json.get('list') for name, value in items_list.items(): self.items[name] = Item(do_rotation=False, do_scale=False) self.items[name].name = name if 'label' in value: self.items[name].item_lbl.text = value['label'] if 'pos' in value: self.items[name].pos = (int(value['pos']['x']), int(value['pos']['y'])) self.items[name].img = {} if 'img' in value: for ki, i in value['img'].items(): self.items[name].img[ki] = items_path + i self.items[name].change_img('1') self.items[name].info = {} if 'text' in value: for kt, t in value['text'].items(): self.items[name].info[int(kt)] = {'text': t['text']} try: self.items[name].info[int(kt)]['audio'] = SoundLoader.load(items_path + t['audio']) self.items[name].info[int(kt)]['audio'].bind( on_play=partial(self.on_play, name)) self.items[name].info[int(kt)]['audio'].bind( on_stop=partial(self.on_stop, name)) except: Logger.info('audio: cant find ' + items_path + t['audio']) # set widgets for key, value in self.items.items(): self.the_widget.add_widget(value) # set the timer of the game Clock.schedule_once(self.end_game, 60)
def callback_set_color(self, in_data, frame_count, time_info, status): data = self.wf.readframes(frame_count) descript = JsonStore('data_descript.json') cwd = str(descript.get(self.kwargs['filename'])['desc']) self.kwargs['root'].ids['cw_desc'].text = '[color=000000] ' + cwd + '[/color]' cwd_list = str.split(cwd) progress = int(round(float(self.wf.tell())/float(self.wf.getnframes()),2)*cwd_list.__len__()) cwd_list.insert(0, '[color=ff3333]') cwd_list.insert(progress+1, '[/color]') cwd_markup = '' for i in range(cwd_list.__len__()): cwd_markup = cwd_markup + cwd_list[i] + ' ' self.kwargs['root'].ids['cw_desc'].text = cwd_markup #print progress if self.Playstate is True: return (data,pyaudio.paContinue) else: return (data,pyaudio.paComplete)
class WeatherRoot(BoxLayout): carousel = ObjectProperty() current_weather = ObjectProperty() forecast = ObjectProperty() locations = ObjectProperty() add_location_form = ObjectProperty() # BEGIN INIT def __init__(self, **kwargs): super(WeatherRoot, self).__init__(**kwargs) self.store = JsonStore("weather_store.json") if self.store.exists('locations'): locations = self.store.get('locations') self.locations.locations_list.adapter.data.extend(locations['locations']) current_location = locations["current_location"] self.show_current_weather(current_location) else: Clock.schedule_once(lambda dt: self.show_add_location_form()) # END INIT # BEGIN SHOW_CURRENT_WEATHER def show_current_weather(self, location): if location not in self.locations.locations_list.adapter.data: self.locations.locations_list.adapter.data.append(location) self.locations.locations_list._trigger_reset_populate() self.store.put("locations", locations=list(self.locations.locations_list.adapter.data), current_location=location) self.current_weather.location = location self.forecast.location = location self.current_weather.update_weather() self.forecast.update_weather() self.carousel.load_slide(self.current_weather) if self.add_location_form is not None: self.add_location_form.dismiss() # END SHOW_CURRENT_WEATHER def show_add_location_form(self): self.add_location_form = AddLocationForm() self.add_location_form.open()
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))
class ReGalData(object): servertypes = [ import_module('regallery.servers.piwigo').ReGalServerPiwigo ] @staticmethod def get_servertypes(): '''Returns a list with all valids server types''' return [cls.name for cls in ReGalData.servertypes] @staticmethod def get_sever(_type, url, user, pw): ''' Get new instance of a server _type - type from get_servertypes() url - base url for server user - username pw - password ''' for cls in ReGalData.servertypes: if cls.name == _type: return cls(url, user, pw) raise LookupError() def __init__(self): self._app = App.get_running_app() serverconfig = os.path.join(self._app.user_data_dir, 'servers.json') self._servers = JsonStore(serverconfig) def add_server(self, url, name, username, password): self._servers.put(name, url=url, username=username, password=password) def get_servers(self): servers = {} for name in self._servers: servers[name] = self._servers.get(name) return servers
class ClockApp(App): clearcolor = (0,0,0,1) def __init__(self,**kwargs): super(ClockApp,self).__init__(**kwargs) from os.path import join self.store = JsonStore(join(self.user_data_dir,"clockalarm.json")) def build(self): root = ClockWidget() root.init_alarms() self.root=root return self.root def on_pause(self): return True def on_resume(self): pass def get_alarm_from_store(self,id): if self.store.exists("alarms"): try: return self.store.get("alarms")["a{}".format(id)] except: return None def set_alarm_to_store(self,id,alarm): allAlarms = {} for i in range(1,5): if i == int(id): allAlarms["{}".format(i)]=alarm else: allAlarms["{}".format(i)]=app.get_alarm_from_store("{}".format(i)) self.store.put("alarms",a1=allAlarms["1"],a2=allAlarms["2"],a3=allAlarms["3"],a4=allAlarms["4"])
class Settings(object): MIN_TOASTING_TIME = 10 MAX_TOASTING_TIME = 600 FILENAME = 'sofatech_toaster_storage' SETTINGS_KEY = 'settings' def __init__(self): self._ip = '127.0.0.1' self._port = 50007 self._store = JsonStore(Settings.FILENAME) @property def ip(self): return self._ip @ip.setter def ip(self, value): self._ip = value @property def port(self): return self._port @port.setter def port(self, value): self._port = value def load(self): if self._store.exists(Settings.SETTINGS_KEY): settings_dict = self._store.get(Settings.SETTINGS_KEY) self._ip = settings_dict['ip'] self._port = settings_dict['port'] def save(self): self._store.put(Settings.SETTINGS_KEY, ip=self._ip, port=self._port)
class PonumiPerformer(App): osc_ip_address = StringProperty(_default_osc_ip_address) osc_port = StringProperty(_default_osc_port) auto_generate_rhythm = BooleanProperty(_default_auto_generate_rhythm) osc_indicator = ObjectProperty(None) input_focus = ObjectProperty(None) poem_position = NumericProperty(0) rhythm_position = NumericProperty(0) def __init__(self, **kwargs): super(PonumiPerformer, self).__init__(**kwargs) data_dir = getattr(self, 'user_data_dir') self.config_store = JsonStore(join(data_dir, 'ponumiperformer.json')) self.rhythm = _default_rhythm self.initialise_osc() def initialise_osc(self): oscAPI.init() oscid = oscAPI.listen(ipAddr='127.0.0.1', port=osc_listen_port) oscAPI.bind(oscid, self.poem_position_changed, osc_poem_position) oscAPI.bind(oscid, self.rhythm_position_changed, osc_rhythm_position) self.osc_poll = Clock.schedule_interval(lambda *x: oscAPI.readQueue(oscid), 0.01) send_osc_message('/osc/respond_to', [osc_listen_port]) send_osc_message(osc_poem_position, [0.0001], typehint=1.0) send_osc_message(osc_rhythm_position, [0.0001], typehint=1.0) def shutdown_osc(self): self.osc_poll.cancel() oscAPI.dontListen() def poem_position_changed(self, msg, *args): self.poem_position = int(msg[2]) def rhythm_position_changed(self, msg, *args): self.rhythm_position = int(msg[2]) def build(self): self.load_config() rootscreen = RootScreen() navbar = NavBar() self.osc_indicator = navbar.osc_indicator rootscreen.add_widget(navbar) self.screen_manager = PonumiPerformerScreenManager() rootscreen.add_widget(self.screen_manager) return rootscreen def save_config(self): self.config_store.put('config', osc_ip_address=self.osc_ip_address, osc_port=self.osc_port) def load_config(self): if self.config_store.exists('config'): config = self.config_store.get('config') if 'osc_ip_address' in config: self.osc_ip_address = config['osc_ip_address'] if 'osc_port' in config: self.osc_port = config['osc_port'] def load_default_config(self): self.osc_ip_address = _default_osc_ip_address self.osc_port = _default_osc_port def on_stop(self): self.shutdown_osc()