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)
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 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()
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()
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 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
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 startinfo(self, *args): store = JsonStore('archivio.json') if store.exists('startinfo'): if store.get('startinfo')['set'] == 'non_fatto': self.infapp() else: pass
class storageUnit(): def __init__(self): print("Before trying to find json file") self.store = JsonStore('local.json') print("Before test of jsonstore file") if (not self.store.exists("numEntries")): self.store.put("numEntries", value=0) self.store.put("macDict", value=dict()) self.store.put("recentTen", value=list()) self.store.put("prevNetwork", value=dict()) print("BEFORE PRINT ________") print(self.store.get("prevNetwork")["value"]) print("AFTER PRINT _________") def addEntry(self, macAddress, time): if macAddress in self.store.get("macDict")["value"]: self.store.get("macDict")["value"][macAddress] += [time] #HEREEE self.store.get("recentTen")["value"] = [[ time, macAddress ]] + self.store.get("recentTen")["value"][:9] #self.store.get("prevNetwork")["value"][macAddress] = 0 else: self.store.get("numEntries")["value"] += 1 self.store.get("macDict")["value"][macAddress] = [time] self.store.get("recentTen")["value"] = [[ time, macAddress ]] + self.store.get("recentTen")["value"][:9] #self.store.get("prevNetwork")["value"][macAddress] = 0 def isSamePrevNetwork(self, foreignSet): returnArr = [] for i in foreignSet: if i not in self.store.get("prevNetwork")["value"]: returnArr += [i] return returnArr
def loadobjectsize(self): store = JsonStore('Saved_variables.json') if store.exists('ballsize'): ballsize = store.get('ballsize')['ballsize'] else: ballsize = 6.6 return ballsize
class TestApp(App): def build(self): self.store_file = JsonStore(join(self.user_data_dir, 'user_data.txt')) if self.store_file.exists('data'): self.ud = self.store_file.get('data')['content'] else: self.ud = {'level': 0, 'level_xp': 100, 'xp': 0} self.btn = Button(text=str(self.ud)) self.btn.bind(on_press=self.mark_item) return self.btn def mark_item(self, event): self.add_xp(10) def add_xp(self, xp): new_xp = (self.ud['xp'] + xp) if new_xp >= self.ud['level_xp']: # level up self.ud['level'] += 1 # find remainder xp after level up self.ud['xp'] = new_xp - self.ud['level_xp'] # set new level_xp self.ud['level_xp'] *= 1.5 else: self.ud['xp'] = new_xp self.btn.text = str(self.ud) def on_stop(self): self.store_file.put('data', content=self.ud)
def getBank(self, *args): store = JsonStore('db.json') if store.exists('p1'): return str(store['p1']['bank']) else: store['p1'] = {'bank':'0'} return '0'
class GrupoApp(App): def build(self): self.screen_manager = ScreenManager() import os if 'MANTENCIONES_VERBOSE' in os.environ: verbose=1 else: verbose=0 if 'DEVELOPMENT_SERVER' in os.environ: # domain_url='http://192.168.43.150:5000' domain_url='http://192.168.1.39:5000' else: domain_url='http://kheitmann.webfactional.com' from webserver import WebServer from kivy.storage.jsonstore import JsonStore self.ws = WebServer(domain_url, verbose) self.store = JsonStore('base_de_datos.json') if self.store.exists('session'): session = self.store.get('session') if session['auth_token'] is None: print("AUTH TOKEN ES NONE") return None else: self.ws.set_auth_token(session['auth_token']) else: print("NO HAY BASE DE DATOS") return None self.screen_manager.add_widget(Grupo(name='grupo')) self.screen_manager.add_widget(Informe(name='informe')) return self.screen_manager
class Factors(): def __init__(self): self.datastore = JsonStore('data.json') def add_new_factor(self, secret_2FA, label_2FA): mac = hmac.new(bytes.fromhex(secret_2FA), "id_2FA".encode('utf-8'), sha1) id_2FA_20b = mac.hexdigest() id_2FA = sha256(mac.digest()).hexdigest() mac = hmac.new(bytes.fromhex(secret_2FA), "key_2FA".encode('utf-8'), sha1) key_2FA = mac.hexdigest()[0:32] # keep first 16 bytes out of 20 idreply_2FA = sha256(id_2FA.encode('utf-8')).hexdigest() self.datastore.put(id_2FA, secret_2FA=secret_2FA, key_2FA=key_2FA, label_2FA=label_2FA, idreply_2FA=idreply_2FA, id_2FA_20b=id_2FA_20b) Logger.info("Satochip: \nAdded new factor on " + str(datetime.now()) + "\n" + "label: " + label_2FA + "\n" + "id_2FA: " + id_2FA + "\n" + "idreply_2FA: " + idreply_2FA) #Logger.debug("Satochip: secret_2FA"+ secret_2FA) #Logger.debug("Satochip: key_2FA: "+ key_2FA) def remove_factor(self, id): if self.datastore.exists(id): self.datastore.delete(id)
def send_message(self): """send message""" if self.ids['ti_message'].text is None: return else: msg = create_message(user_card_screen.user_name, self.contact_name, self.ids['ti_message'].text) self.msg_height += msg.height self.ids['msg_list'].height = max(self.msg_height, self.height / 10 * 7) self.ids['msg_list'].add_widget(msg) # send to server data = json.loads(msg.serialize()) data['hash'] = msg.hash() params = parse.urlencode(data) url = user_card_screen.ids[ 'ti_url'].text + 'post.php' + '?' + params # print(url) req = UrlRequest(url=url, on_success=self.send_success, on_failure=self.send_failure, on_error=self.send_failure) # store in local 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()} except Exception as e: print(str(e))
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 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)
class MainApp(App): #create the application screens def build(self): data_dir = getattr( self, 'user_data_dir') #get a writable path to save our score self.store = JsonStore(join( data_dir, 'score.json')) # create a JsonScore file in the available location if (not self.store.exists('score') ): # if there is no file, we need to save the best score as 1 self.store.put('score', best=1) if platform( ) == 'android': # if we are on Android, we can initialize the ADs service revmob.start_session('54c247f420e1fb71091ad44a') self.screens = {} # list of app screens self.screens['menu'] = MenuScreen( self ) #self the MainApp instance, so others objects can change the screen self.screens['game'] = GameScreen(self) self.root = FloatLayout() self.open_screen('menu') self.sound = SoundLoader.load( 'res/background.mp3') # open the background music # kivy support music loop, but it was not working on Android. I coded in a different way to fix it # but if fixed, we can just set the loop to True and call the play(), so it'll auto repeat # self.sound.loop = True It # was not working on android, so I wrote the following code: self.sound.play() # play the sound Clock.schedule_interval(self.check_sound, 1) #every second force the music to be playing return self.root # play the sound def check_sound(self, dt=None): self.sound.play() # when the app is minimized on Android def on_pause(self): self.sound.stop() # the stop the sound Clock.unschedule(self.check_sound) if platform() == 'android': #if on android, we load an ADs and show it revmob.show_popup() return True # when the app is resumed def on_resume(self): self.sound.play() # we start the music again Clock.schedule_interval(self.check_sound, 1) # show a new screen. def open_screen(self, name): self.root.clear_widgets() #remove the current screen self.root.add_widget(self.screens[name]) # add a new one self.screens[name].run() # call the run method from the desired screen
def __init__(self, store_file_path, *args, **kwargs): store = JsonStore(store_file_path) if not store.exists('admin'): store.put('admin', username='******', password='******') self.__store = store
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"]
def on_enter(self): pathstore = JsonStore("pathstore.json") if pathstore.exists("path"): print pathstore["path"] self.imagepath = pathstore["path"]["path"][0] print self.imagepath self.populateCarousel()
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 build(self): co_lang.set_language("EN") store = JsonStore("co_T.json") if store.exists("co-lang"): lng = store.get("co-lang")["name"] co_lang.set_language(lng) return Builder.load_file("main.kv")
def __init__(self, **kwargs): super().__init__(**kwargs) config_store = JsonStore(CONFIG_DIR) self.music = SoundLoader.load("misc/SneakySnooper.mp3") self.music.loop = True if config_store.exists("background_volume"): self.music.volume = config_store.get("background_volume")["value"] self.music.play()
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 build(self): print(Window.size) print(type(Window.size)) store = JsonStore('local.json') if (not store.exists("numEntries")): store.put("numEntries", value=0) store.put("macDict", value=dict()) store.put("recentTen", value=list()) return kv
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 login(self, *args): if self.accesscode.text != "": librarian = JsonStore("jsondb/librarian.json") if librarian.exists(self.accesscode.text): app.root.current = "librarian" else: Dialog().no_display_user( "the user with accesscode %s" % self.accesscode.text, "does not exist")
def delete(self, *args): if self.user == "Pat": User = JsonStore("jsondb/patron.json") else: User = JsonStore("jsondb/librarian.json") if self.accesscode.text != "": if User.exists(self.accesscode.text): User.delete(self.accesscode.text) Dialog().display_user(self.accesscode, "deleted")
def delete(self, *args): mat = JsonStore("jsondb/material.json") if self.mat_id.text != "": if mat.exists(self.mat_id.text): mat.delete(self.mat_id.text) Dialog().display_mat("Material", self.mat_id.text, "deleted") else: Dialog().no_display_user( "the material with the id %s" % self.mat_id.text, "does not exist")
def login(self, *args): admin = JsonStore("jsondb/admin.json") if (self.username.text != "" and self.password.text != ""): if admin.exists(self.username.text): if self.password.text == admin.get( self.username.text)["password"]: app.root.current = "admin" else: Dialog().no_display_user("admin username and password", "does not exist")
class AccountStorage: def __init__(self): self.store = JsonStore('ownphotos.json') if not self.store.exists('accounts'): self.store.put('accounts', data=[]) if not self.store.exists('accounts_selected'): self.store.put('accounts_selected', selected=None) def get_data(self): return self.store.get('accounts')["data"] def get_selected(self): print(self.store.get('accounts_selected')) return self.store.get('accounts_selected')["selected"] def set_selected(self, account_id): self.store.put("accounts_selected", selected=account_id) def add_account(self, url, username, password): accounts = self.get_data() accounts.append({ "url": url, "username": username, "password": password }) self.store.put("accounts", data=accounts) if self.get_selected() is None: self.set_selected(len(accounts) - 1) def get_account(self, account_id): a = self.get_data() if int(account_id) > len(a) - 1: return return a[int(account_id)] def get_selected_account(self): a = self.get_selected() if a is None: return print("urrrr") return self.get_account(a)
def build(self): # For testing #store = JsonStore ('D:/Git/Kivy_Apps/First28/profile.json') store = JsonStore ('profile.json') sm = First28ScreenManager() if store.exists('main_profile'): sm.current = 'Menu' else: sm.current = 'NewProfile' return sm
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
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 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()
class MainApp(App): #create the application screens def build(self): data_dir = getattr(self, 'user_data_dir') #get a writable path to save our score self.store = JsonStore(join(data_dir, 'score.json')) # create a JsonScore file in the available location if(not self.store.exists('score')): # if there is no file, we need to save the best score as 1 self.store.put('score', best=1) if platform() == 'android': # if we are on Android, we can initialize the ADs service revmob.start_session('54c247f420e1fb71091ad44a') self.screens = {} # list of app screens self.screens['menu'] = MenuScreen(self) #self the MainApp instance, so others objects can change the screen self.screens['game'] = GameScreen(self) self.root = FloatLayout() self.open_screen('menu') self.sound = SoundLoader.load('res/background.mp3') # open the background music # kivy support music loop, but it was not working on Android. I coded in a different way to fix it # but if fixed, we can just set the loop to True and call the play(), so it'll auto repeat # self.sound.loop = True It # was not working on android, so I wrote the following code: self.sound.play() # play the sound Clock.schedule_interval(self.check_sound, 1) #every second force the music to be playing return self.root # play the sound def check_sound(self, dt = None): self.sound.play() # when the app is minimized on Android def on_pause(self): self.sound.stop() # the stop the sound Clock.unschedule(self.check_sound) if platform() == 'android': #if on android, we load an ADs and show it revmob.show_popup() return True # when the app is resumed def on_resume(self): self.sound.play() # we start the music again Clock.schedule_interval(self.check_sound, 1) # show a new screen. def open_screen(self, name): self.root.clear_widgets() #remove the current screen self.root.add_widget(self.screens[name]) # add a new one self.screens[name].run() # call the run method from the desired screen
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 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 FindBWidget(BoxLayout): level=NumericProperty(1) bfound = NumericProperty(0) bnumber = NumericProperty(0) def __init__(self,**kwargs): super(FindBWidget,self).__init__(**kwargs) self.BBoxList=[] self.store = JsonStore("findb.json") self.gridSize_height = 0 self.gridSize_width = 0 self.bnumber = 0 self.badded = 0 self.bfound = 0 self.mute=True self.gameover = False self.custimize = False self.custimize_height = 0 self.custimize_width = 0 self.custimize_brate = 0.2 self.sounds = {'bomb':SoundLoader.load('bomb.wav'), 'state':SoundLoader.load('state.wav'), 'upgrade':SoundLoader.load('upgrade.mp3')} self.start_clock = clock() self.config = None def on_bfound(self,instance,value): self.status_bar.label_left_bomb.text = '{}'.format(self.bnumber - self.bfound) self.CheckSucceed() def on_bnumber(self,instance,value): self.status_bar.label_left_bomb.text = '{}'.format(self.bnumber - self.bfound) def Restart(self): self.custimize,self.custimize_height,self.custimize_width,self.custimize_brate = self.get_customize_info() self.level,self.levels_info = self.get_level_info() self.mute = self.get_mute_info() self.BBoxList = [] if self.custimize == True: self.status_bar.label_level.text = 'L:C' self.gridSize_height = self.custimize_height self.gridSize_width = self.custimize_width if self.gridSize_height < 5: self.gridSize_height = 5 if self.gridSize_width < 5: self.gridSize_width = 5 if self.gridSize_height > 50: self.gridSize_height = 50 if self.gridSize_width > 50: self.gridSize_width = 50 else: self.status_bar.label_level.text = 'L:{}'.format(self.level) self.gridSize_width = self.level + Rows_For_First_Level self.gridSize_height = self.level + Rows_For_First_Level self.bnumber = 0 self.badded = 0 self.bfound = 0 self.start_clock = clock() self.gameover = False self.play_area.clear_widgets() self.play_area.cols = self.gridSize_width self.play_area.rows = self.gridSize_height for i in range(0,self.gridSize_height): for j in range(0,self.gridSize_width): b = BBox(root=self) b.row=i b.col=j self.BBoxList.append(b) self.play_area.add_widget(b) self._calculate_bombs() self.status_bar.toggle_mark.disable = False self.status_bar.toggle_mark.state = "normal" self.status_bar.button_reset.image.source='smile.png' def _calculate_bombs(self): if self.custimize: self.brate = self.custimize_brate/100.0 if self.brate < 0.05: self.brate = 0.05 if self.brate > 0.8: self.brate = 0.8 elif self.level < 6: self.brate = 0.11 elif self.level < 11: self.brate = 0.13 elif self.level < 20: self.brate = 0.15 elif self.level < 30: self.brate = 0.18 else: self.brate = 0.2 self.bnumber = int(self.brate * self.gridSize_width * self.gridSize_height) self.badded = 0 while True: if self._add_bomb(): self.badded += 1 if self.badded >= self.bnumber: break def _add_bomb(self): if len(self.BBoxList) <=0: return i = Random().randint(0,len(self.BBoxList) - 1) if self.BBoxList[i].isBomb: return False else: self.BBoxList[i].isBomb = True #set bomb number of the around boxes row = self.BBoxList[i].row col = self.BBoxList[i].col self._add_bomb_number(row - 1,col - 1) self._add_bomb_number(row - 1,col) self._add_bomb_number(row - 1,col + 1) self._add_bomb_number(row,col - 1) self._add_bomb_number(row,col + 1) self._add_bomb_number(row + 1,col - 1) self._add_bomb_number(row + 1,col) self._add_bomb_number(row + 1,col + 1) return True def _add_bomb_number(self,row,col): if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height: return index = row*self.gridSize_width + col if index < 0 or index >= len(self.BBoxList): return self.BBoxList[index].BNumber += 1 def Clear(self,row,col): if row < 0 or row >= self.gridSize_width or col < 0 or col >= self.gridSize_height: return index = row*self.gridSize_width + col if index < 0 or index >= len(self.BBoxList): return self.BBoxList[index].MarkNumberOrEmpty() def ShowAll(self): self.status_bar.toggle_mark.state='normal' for i in range(0,len(self.BBoxList)): if self.BBoxList[i].isBomb: self.BBoxList[i].bbutton.MarkB() else: self.BBoxList[i].Clear() def CheckSucceed(self): if self.bfound > 0 and self.bfound == self.bnumber: for i in range(0,len(self.BBoxList)): if self.BBoxList[i].state == 0: return False #upgrade level if self.mute == False: self.sounds['upgrade'].play() if self.custimize == False: duration = round((clock() - self.start_clock),2) if self.levels_info.has_key(self.level) and self.levels_info[self.level] > 0: if self.levels_info[self.level] > duration: self.levels_info[self.level] = duration else: self.levels_info[self.level] = duration if self.level < Max_Level: self.level += 1 self.store_user_data(self.level,self.levels_info) self.Restart() return True else: return False def get_level_info(self): if self.store.exists("UserData") == False: self.store.put("UserData",CurrentLevel=1,Levels={}) return self.store.get("UserData")["CurrentLevel"],self.store.get("UserData")["Levels"] def get_mute_info(self): return self.config.get('Sounds','Mute') == '1' def get_customize_info(self): return self.config.get('Customization','Enable') == '1',self.config.getint('Customization','C_Height'),self.config.getint('Customization','C_Width'),self.config.getint('Customization','Rate') def store_user_data(self,currentLevel,levels): self.store.put("UserData",CurrentLevel=currentLevel,Levels=levels) def GameOver(self): self.status_bar.toggle_mark.disable = True self.status_bar.button_reset.image.source='gameover.png' self.gameover = True
class DescargarApp(App): # Desactiva el cuadro de configuración genérico de Kivy use_kivy_settings = False # Para que no se cierre al cambiar de aplicación en Android def on_pause(self): return True def build(self): self.download_thread = None self.store = JsonStore("descargar-aragontv.json") if not self.store.exists("target_folder"): if self.get_platform_name()=="android": from jnius import autoclass Environment = autoclass('android.os.Environment') download_folder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) self.store.put("target_folder",value=download_folder.getAbsolutePath() ) else: self.store.put("target_folder",value=os.path.expanduser("~") ) if not self.store.exists("source_url"): self.store.put("source_url",value="http://alacarta.aragontelevision.es/programas/chino-chano/por-la-sierra-de-armantes-28022016-1452") self.screen_manager = ScreenManager(transition=FadeTransition()) self.paso1 = Paso1(name='Paso 1') self.paso1.ids.target_folder.text = self.store.get("target_folder")["value"] self.paso1.ids.page_url.text = self.store.get("source_url")["value"] self.paso2 = Paso2(name='Paso 2') self.paso3 = Paso3(name='Paso 3') self.screen_manager.add_widget(self.paso1) self.screen_manager.add_widget(self.paso2) self.screen_manager.add_widget(self.paso3) return self.screen_manager def dismiss_popup(self): self._popup.dismiss() def target_selected(self, path, filename): self._popup.dismiss() self.paso1.ids.target_folder.text = path self.store.put("target_folder",value=self.paso1.ids.target_folder.text) def target_selection(self): content = LoadDialog(load=self.target_selected, cancel=self.dismiss_popup) content.ids.filechooser.path = self.paso1.ids.target_folder.text self._popup = Popup(title="Elige destino", content=content, size_hint=(0.9, 0.9)) self._popup.open() def message(self,title,body): content = MessageDialog() content.ids.message_body.text = body self._popup = Popup(title=title, content=content, size_hint=(0.8, 0.8)) self._popup.open() def url_ready(self,page_url): print "url_ready" print self.paso1.ids.page_url.text if not self.paso1.ids.page_url.text.startswith("http://") and not self.paso1.ids.page_url.text.startswith("https://"): self.message("Hay un problema...","La URL que has introducido no es válida") return self.store.put("target_folder",value=self.paso1.ids.target_folder.text) self.store.put("source_url",value=self.paso1.ids.page_url.text) from core.item import Item item = Item(url=self.paso1.ids.page_url.text) from channels import aragontv item = aragontv.detalle_episodio(item) self.video_title = item.title self.media_url = item.media_url if self.media_url=="": self.message("Hay un problema...","No se puede encontrar un vídeo en esa URL") return self.screen_manager.current = self.screen_manager.next() self.paso2.ids.description.text = "[b]"+item.title+"[/b]\n\n"+item.plot def start_download(self): print "start_download" self.paso3.resultado = "Descargando "+self.media_url+"\n\n" self.screen_manager.current = self.screen_manager.next() # Start download in background from core import downloadtools clean_file_name = downloadtools.limpia_nombre_caracteres_especiales(self.video_title.decode("utf-8"))+".flv" #print "clean_file_name="+clean_file_name self.target_file = os.path.join( self.paso1.ids.target_folder.text , clean_file_name ) #print "target_file="+self.target_file if self.get_platform_name()=="win": self.target_file = self.target_file.encode("utf-8") # get_platform_name es: win, linux, android, macosx, ios or unknown folder_platform = os.path.join( os.getcwd() , "rtmpdump" , self.get_platform_name() ) print "folder_platform="+folder_platform if self.get_platform_name()=="win": rtmpdump = os.path.join(folder_platform,"rtmpdump.exe") elif self.get_platform_name()=="linux": rtmpdump = "rtmpdump" else: rtmpdump = os.path.join(folder_platform,"rtmpdump") # En Android hay que darle antes expresamente permisos de ejecución al binario de rtmpdump if self.get_platform_name()=="android": subprocess.Popen(["chmod","0755",rtmpdump], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) exe = [rtmpdump] exe.append("-r") exe.extend(self.media_url.replace("app=","--app ").replace("playpath=","--playpath ").split(" ")) #exe.append("--live") exe.append("-o") exe.append(self.target_file) self.paso3.ids.cargando.opacity=1 self.download_thread = DownloadThread(exe,self.paso3) self.download_thread.start() Clock.schedule_interval(self.check_output_size, 0.5) def abort_download(self): print "abort_download" self.download_thread.abort() self.screen_manager.current = self.screen_manager.previous() def check_output_size(self,value): #print "check_output_size" if os.path.exists(self.target_file): statinfo = os.stat(self.target_file) self.paso3.tamanyo = human_size(statinfo.st_size) def on_stop(self): print "on_stop!" if self.download_thread is not None: self.download_thread.abort() def get_platform_name(self): from kivy import platform platform_name = str(platform) print "platform_name="+platform_name return platform_name
class WeatherRoot(BoxLayout): current_weather = ObjectProperty() locations = ObjectProperty() forecast = 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 = CurrentWeather(location=location) adapter_data = self.locations.locations_list.adapter.data if location not in adapter_data: adapter_data.append(location) self.locations.locations_list._trigger_reset_populate() self.store.put("locations", locations=list(adapter_data), current_location=location) 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 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) @staticmethod def format_location(location): return "{} ({})".format(*location)
class KivyBirdApp(App): pipes = [] playing = False score = 0 scored = False highscore = StringProperty("0") #legg til her def build(self): self.highscorestore = JsonStore("highscore.json") if self.highscorestore.exists("highscore"): print self.highscorestore.get("highscore")["score"] self.highscore = self.highscorestore.get("highscore")["score"] return KivyBirdRoot() # Når ting går over til ScreenManager, må du huske å bytte root.ids til screenen sin ID # Dette gjøres gjennom root.ids.kivybird_screen_manager.get_screen("game_screen") def on_start(self): self.spacing = 0.5 * self.root.width self.background = self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.background self.score_label = ScoreLabel() self.bird = self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.bird Clock.schedule_interval(self.update, 1.0/60.0) Window.bind(on_key_down=self.on_key_down) self.background.on_touch_down = self.user_action sfx_start.play() self.background.update(1.0 / 60.0) def on_key_down(self, window, key, *args): if key == Keyboard.keycodes['spacebar']: self.user_action() def user_action(self, *args): if not self.playing: sfx_start.play() self.bird.gravity_on(self.root.height) self.spawn_pipes() self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.score_label.text = "0" self.score = 0 self.playing = True sfx_flap.play() self.bird.bump() def update(self, nap): if not self.playing: return self.background.update(nap) self.bird.update(nap) for p in self.pipes: p.x -= 96 * nap if p.x <= -64: p.x += 4 * self.spacing p.ratio = random.uniform(0.25, 0.75) p.scored = False if self.test_game_over(): current_score = self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.score_label.text #self.highscorestore["highscore"] = {"score": current_score} if int(current_score) > int(self.highscore): self.highscore = current_score self.highscorestore.put("highscore", score=current_score) sfx_die.play() self.playing = False def test_game_over(self): screen_height = self.root.height if self.bird.y < 90 or self.bird.y > screen_height - 50: return True for p in self.pipes: if not p.collide_widget(self.bird): continue if (self.bird.y < p.lower_len + 116 or self.bird.y > screen_height - (p.upper_len + 75)): return True if not p.scored and p.x < self.bird.x: p.scored = True sfx_score.play() self.score += 1 self.root.ids.kivybird_screen_manager.get_screen("game_screen").ids.score_label.text = str(self.score) return False def spawn_pipes(self): for p in self.pipes: self.root.remove_widget(p) self.pipes = [] for i in range(4): p = Pipe(x=self.root.width + (self.spacing * i)) p.ratio = random.uniform(0.25, 0.75) self.root.add_widget(p) self.pipes.append(p)
serverTime = datetime.datetime.utcnow().replace(microsecond=0) # Client Time reported locally. localTime = datetime.datetime.now().replace(microsecond=0) # Cache Files jobCache = JsonStore('jobs.json') pilotCache = JsonStore('pilots.json') statusCache = JsonStore('server.json') # Server connection objects can be reused for each connection point # to the api as each one may have a different cache timer. # Server(serverName, serverAddress, serverStatus, serverPlayers, datetime.datetime(cacheExpire), serverPing) if statusCache.exists('server'): print('Server Status Already Exists:', statusCache.get('server')) # This possibly needs moving/redesign (Into preferences dialog) if (statusCache.get('server')['name']) == 'Tranquility': apiURL = 'https://api.eveonline.com/' elif (statusCache.get('server')['name']) == 'Singularity': apiURL = 'https://api.testeveonline.com/' else: apiURL = '' serverConn = Server(statusCache.get('server')['name'], apiURL, statusCache.get('server')['status'], statusCache.get('server')['players'], datetime.datetime(*(time.strptime((statusCache.get('server')['cacheExpires']), '%Y-%m-%d %H:%M:%S')[0:6])), statusCache.get('server')['ping']) else: # Provide a default here.
class _2048Controller: def __init__(self): self.width = 4 self.height = 4 self.store = JsonStore('data.json') self.best_score = 0 if self.store.exists('score'): self.best_score = self.store.get('score')['best_score'] self.initGame() def initGame(self): self.score = 0 self.undo_left = 2 self.undo_game_array = [] self.game_array = self.generateGameArray() #self.game_array = [[0, 0, 8, 16], [32, 64, 128, 256], [512, 1024, 2048, 4096], [8192, 16384, 32768, 65536]] self.end_game = False self.new_number_array = [] # list of new number is generated self.undo_game_array = [] # #### for i in range(2): self.generateNumber() # generate 2 new numbers def checkExists(self, x, y): return self.game_array[y][x] != 0 def generateGameArray(self): game_board = [] for y in range(self.height): rows = [] for x in range(self.width): rows.append(0) game_board.append(rows) return game_board def generateNumber(self): while True: # loop until the position is valid x = random.randint(0, self.width - 1) y = random.randint(0, self.height - 1) if not self.checkExists(x, y): number = 2 if random.randint(1, 100) > 80: number = 4 self.game_array[y][x] = number break self.new_number_array.append((x, y)) def slideUp(self, game_board=None): if not game_board: game_board = self.game_array moved = False score = 0 animation_way = [] for x in range(self.width): notCombineList = [] for y in range(self.height): if game_board[y][x] == 0: continue for stop_y in range(y - 1, -1, -1): if game_board[stop_y][x] != 0: if game_board[stop_y][x] == game_board[y][x] and stop_y not in notCombineList: game_board[stop_y][x] *= 2 game_board[y][x] = 0 moved = True score += game_board[stop_y][x] notCombineList.append(stop_y) animation_way.append([(x, y), (x, stop_y)]) else: game_board[stop_y + 1][x], game_board[y][x] = game_board[y][x], game_board[stop_y + 1][x] if y != stop_y + 1: animation_way.append([(x, y), (x, stop_y + 1)]) moved = True break if stop_y == 0 and game_board[0][x] == 0 and game_board[y][x] != game_board[0][x]: game_board[0][x], game_board[y][x] = game_board[y][x], game_board[0][x] moved = True animation_way.append([(x, y), (x, stop_y)]) return [moved, score, animation_way] def slideDown(self, game_board=None): if not game_board: game_board = self.game_array moved = False score = 0 animation_way = [] for x in range(self.width): notCombineList = [] for y in range(self.width - 1, -1, -1): if game_board[y][x] == 0: continue for stop_y in range(y + 1, self.height): if game_board[stop_y][x] != 0: if game_board[stop_y][x] == game_board[y][x] and stop_y not in notCombineList: game_board[stop_y][x] *= 2 game_board[y][x] = 0 moved = True score += game_board[stop_y][x] notCombineList.append(stop_y) animation_way.append([(x, y), (x, stop_y)]) else: game_board[stop_y - 1][x], game_board[y][x] = game_board[y][x], game_board[stop_y - 1][x] if y != stop_y - 1: animation_way.append([(x, y), (x, stop_y - 1)]) moved = True break if stop_y == (self.height - 1) and game_board[self.height - 1][x] == 0 and \ game_board[y][x] != game_board[self.height - 1][x]: game_board[self.height - 1][x], game_board[y][x] = game_board[y][x], game_board[self.height - 1][x] moved = True animation_way.append([(x, y), (x, stop_y)]) return [moved, score, animation_way] def slideLeft(self, game_board=None): if not game_board: game_board = self.game_array moved = False score = 0 animation_way = [] for y in range(self.height): notCombineList = [] for x in range(1, self.width): if game_board[y][x] == 0: continue for stop_x in range(x - 1, -1, -1): if game_board[y][stop_x] != 0: if game_board[y][stop_x] == game_board[y][x] and stop_x not in notCombineList: game_board[y][stop_x] *= 2 game_board[y][x] = 0 moved = True score += game_board[y][stop_x] notCombineList.append(stop_x) animation_way.append([(x, y), (stop_x, y)]) else: game_board[y][stop_x + 1], game_board[y][x] = game_board[y][x], game_board[y][stop_x + 1] if x != stop_x + 1: animation_way.append([(x, y), (stop_x + 1, y)]) moved = True break if stop_x == 0 and game_board[y][0] == 0 and game_board[y][x] != game_board[y][0]: game_board[y][0], game_board[y][x] = game_board[y][x], game_board[y][0] moved = True animation_way.append([(x, y), (stop_x, y)]) return [moved, score, animation_way] def slideRight(self, game_board=None): if not game_board: game_board = self.game_array moved = False score = 0 animation_way = [] for y in range(self.height): notCombineList = [] for x in range(self.width - 2, -1, -1): if game_board[y][x] == 0: continue for stop_x in range(x + 1, self.width): if game_board[y][stop_x] != 0: if game_board[y][stop_x] == game_board[y][x] and stop_x not in notCombineList: game_board[y][stop_x] *= 2 game_board[y][x] = 0 moved = True score += game_board[y][stop_x] notCombineList.append(stop_x) animation_way.append([(x, y), (stop_x, y)]) else: game_board[y][stop_x - 1], game_board[y][x] = game_board[y][x], game_board[y][stop_x - 1] if x != stop_x - 1: animation_way.append([(x, y), (stop_x - 1, y)]) moved = True break if stop_x == (self.width - 1) and game_board[y][self.width - 1] == 0 and\ game_board[y][x] != game_board[y][self.width - 1]: game_board[y][self.width - 1], game_board[y][x] = game_board[y][x], game_board[y][self.width - 1] moved = True animation_way.append([(x, y), (stop_x, y)]) return [moved, score, animation_way] def checkForWin(self): for y in range(len(self.game_array)): for x in range(len(self.game_array[0])): if self.game_array[y][x] == 2048: return True else: return False def checkForBestScore(self): if self.score > self.best_score: self.best_score = self.score def saveData(self): self.store.put('score', best_score=self.best_score) def up(self): tmp_game_array = copy.deepcopy(self.game_array) tmp_score = self.score moved, score, animation_way = self.slideUp() self.score += score self.checkForBestScore() if not self.existsMove() and self.undo_left == 0: self.end_game = True elif moved: self.undo_game_array.append([tmp_game_array, tmp_score]) self.generateNumber() return animation_way def down(self): tmp_game_array = copy.deepcopy(self.game_array) tmp_score = self.score moved, score, animation_way = self.slideDown() self.score += score self.checkForBestScore() if not self.existsMove() and self.undo_left == 0: self.end_game = True elif moved: self.undo_game_array.append([tmp_game_array, tmp_score]) self.generateNumber() return animation_way def left(self): tmp_game_array = copy.deepcopy(self.game_array) tmp_score = self.score moved, score, animation_way = self.slideLeft() self.score += score self.checkForBestScore() if not self.existsMove() and self.undo_left == 0: self.end_game = True elif moved: self.undo_game_array.append([tmp_game_array, tmp_score]) self.generateNumber() return animation_way def right(self): tmp_game_array = copy.deepcopy(self.game_array) tmp_score = self.score moved, score, animation_way = self.slideRight() self.score += score self.checkForBestScore() if not self.existsMove() and self.undo_left == 0: self.end_game = True elif moved: self.undo_game_array.append([tmp_game_array, tmp_score]) self.generateNumber() return animation_way def existsMove(self): exists = False #if self.slideUp(game_array_clone)[0] or self.slideDown(game_array_clone)[0] or \ # self.slideLeft(game_array_clone)[0] or self.slideRight(game_array_clone)[0]: # exists = True for test in (self.slideLeft, self.slideRight, self.slideUp, self.slideDown): game_array_clone = copy.deepcopy(self.game_array) # clone the game array to check if test(game_array_clone)[0]: exists = True return exists def undo(self): if self.undo_left == 0 or len(self.undo_game_array) == 0: # if start game or out of undo left, not do undo return self.undo_left -= 1 temp_array, temp_score = self.undo_game_array.pop() # pop the undo data (array and score) for y in range(len(temp_array)): # dont do this : self.game_array = temp.array for x in range(len(temp_array[0])): # because it reference to new list, not a current list, it wont work self.game_array[y][x] = temp_array[y][x] self.score = temp_score
class Controller(EventDispatcher): """ Controls the playing of audio and coordinates the updating of the playlist and screen displays """ volume = NumericProperty(1.0) advance = True # This flag indicates whether to advance to the next track # once the currently playing one had ended sm = None # THe ScreenManager pos = 0 def __init__(self, **kwargs): """ Initialize the screens and the screen manager """ self._store = JsonStore(join(self._get_settings_folder(), "zenplayer.json")) self.playlist = PlayList(self._store) self.sm = ScreenManager() self.playing = PlayingScreen(self, name="main") self.sm.add_widget(self.playing) self.sm.current = "main" if platform not in ['ios', 'android']: self.kb_listener = ZenKeyboardListener(self.on_key_down, self.playing) Sound.add_state_callback(self.playing.on_sound_state) Sound.add_state_callback(self._on_sound_state) super(Controller, self).__init__(**kwargs) if self._store.exists('state'): state = self._store.get("state") if "volume" in state.keys(): self.volume = state["volume"] @staticmethod def _get_settings_folder(): """ Return the folder when the setting file is stored. """ path = expanduser("~/.zencode") if not exists(path): mkdir(path) return path def _on_sound_state(self, state): """ The sound state has changed. If the track played to the end, move to the next track.""" if state == "finished" and self.advance: self.play_next() def get_current_art(self): return self.playlist.get_current_art() def get_current_info(self): return self.playlist.get_current_info() def get_current_file(self): return self.playlist.get_current_file() @staticmethod def get_pos_length(): return Sound.get_pos_length() def on_key_down(self, keyboard, keycode, text, modifiers): """ React to the keypress event """ key_name = keycode[1] if key_name == "up" or text == "+": self.volume += 0.025 elif key_name == "down" or text == "-": self.volume -= 0.025 elif key_name == "x": self.play_pause() elif key_name == "z": self.play_previous() elif key_name == "v": self.stop() elif key_name == "b": self.play_next() elif key_name == "a": self.show_filebrowser() elif key_name == "p": self.show_playlist() elif key_name == "s": self.show_main() return True def on_volume(self, widget, value): """ Set the volume of the currently playing sound """ if 0.0 > value: self.volume = 0.0 elif value > 1.0: self.volume = 1.0 else: Sound.set_volume(value) self.playing.volume_slider.value = value def play_index(self, index): """ Play the track with the specified playlist index """ Sound.stop() self.playlist.current = index self.play_pause() def play_pause(self): """ Play or pause the currently playing track """ self.advance = True if Sound.state == "playing": self.pos, x = Sound.get_pos_length() Sound.stop() else: audio_file = self.get_current_file() if audio_file: Sound.play(audio_file, self.volume) if self.pos > 0: def set_pos(dt): Sound.seek(self.pos) self.pos = 0 Clock.schedule_once(set_pos, 0.1) def play_next(self): """ Play the next track in the playlist. """ Sound.stop() self.playlist.move_next() self.play_pause() def play_previous(self): """ Play the previous track in the playlist. """ Sound.stop() self.playlist.move_previous() self.play_pause() @staticmethod def set_position(value): """ Set the playing position to the specified value. """ Sound.set_position(value) def save(self): """ Save the state of the the playlist and volume. """ self.playlist.save(self._store) self._store.put("state", volume=self.volume) if "filebrowser" in self.sm.screen_names: self.sm.get_screen("filebrowser").save(self._store) def show_filebrowser(self): """ Switch to the file browser screen """ if "filebrowser" not in self.sm.screen_names: self.sm.add_widget(ZenFileBrowser(self, self.playlist, self._store, name="filebrowser")) self.sm.current = "filebrowser" def show_playlist(self): """ Switch to the playlist screen """ if "playlist" not in self.sm.screen_names: self.sm.add_widget(PlayListScreen(self.sm, self, self.playlist, name="playlist")) self.sm.current = "playlist" def show_main(self): """ Switch to the main playing screen""" self.sm.current = "main" def stop(self): """ Stop any playing audio """ self.advance = False Sound.stop()
class RobRehabGUI( Widget ): connection = None currentServerAddress = None UPDATE_INTERVAL = 0.02 setpointsUpdated = True isCalibrating = False isSampling = False isOperating = False samplingEvent = None operationEvent = None JOINT = 0 AXIS = 1 deviceIDs = ( [], [] ) currentDeviceIndexes = [ None for i in range( len(deviceIDs) ) ] NULL_ID = '<Select>' axisMeasures = [ 0.0 for var in range( DOF_VARS_NUMBER ) ] setpoints = [ 0.0 for var in range( DOF_VARS_NUMBER ) ] jointMeasures = [ 0.0 for var in range( DOF_VARS_NUMBER ) ] class DataPlot: def __init__( self, handle, values, source, offset ): self.handle = handle self.values = values self.source = source self.offset = offset dataPlots = [] INITIAL_VALUES = [ 0.0 for value in range( 101 ) ] def __init__( self, **kwargs ): super( RobRehabGUI, self ).__init__( **kwargs ) self.configStorage = JsonStore( 'config.json' ) if self.configStorage.exists( 'server' ): self.ids[ 'address_input' ].text = self.configStorage.get( 'server' )[ 'address' ] if self.configStorage.exists( 'user' ): self.ids[ 'user_name_input' ].text = self.configStorage.get( 'user' )[ 'name' ] self.deviceSelectors = ( self.ids[ 'joint_selector' ], self.ids[ 'axis_selector' ] ) self.deviceEntries = [ DropDown() for selector in self.deviceSelectors ] for index in range( len(self.deviceEntries) ): def SelectEntry( instance, name, index=index ): self.SetDevice( index, name ) self.deviceEntries[ index ].bind( on_select=SelectEntry ) self.deviceSelectors[ index ].bind( on_release=self.deviceEntries[ index ].open ) dataGraph = self.ids[ 'data_graph' ] measure_range = self.ids[ 'measure_slider' ].range GRAPH_PROPERTIES = { 'xlabel':'Last Samples', 'x_ticks_minor':5, 'x_ticks_major':25, 'y_ticks_major':0.25, 'y_grid_label':True, 'x_grid_label':True, 'padding':5, 'x_grid':True, 'y_grid':True, 'xmin':0, 'xmax':len(self.INITIAL_VALUES) - 1, 'ymin':measure_range[ 0 ], 'ymax':measure_range[ 1 ], 'background_color':[ 1, 1, 1, 1 ], 'tick_color':[ 0, 0, 0, 1 ], 'border_color':[ 0, 0, 0, 1 ], 'label_options':{ 'color': [ 0, 0, 0, 1 ], 'bold':True } } axisPositionGraph = Graph( ylabel='Position', **GRAPH_PROPERTIES ) axisPositionPlot = SmoothLinePlot( color=[ 0, 0, 1, 1 ] ) axisPositionGraph.add_plot( axisPositionPlot ) self.dataPlots.append( RobRehabGUI.DataPlot( axisPositionPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_POSITION ) ) axisVelocityPlot = SmoothLinePlot( color=[ 0, 1, 0, 1 ] ) axisPositionGraph.add_plot( axisVelocityPlot ) self.dataPlots.append( RobRehabGUI.DataPlot( axisVelocityPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_VELOCITY ) ) refPositionPlot = SmoothLinePlot( color=[ 0, 0, 0.5, 1 ] ) axisPositionGraph.add_plot( refPositionPlot ) self.dataPlots.append( RobRehabGUI.DataPlot( refPositionPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_POSITION ) ) refVelocityPlot = SmoothLinePlot( color=[ 0, 0.5, 0, 1 ] ) axisPositionGraph.add_plot( refVelocityPlot ) self.dataPlots.append( RobRehabGUI.DataPlot( refVelocityPlot, self.INITIAL_VALUES[:], self.setpoints, DOF_VELOCITY ) ) axisAccelerationPlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] ) axisPositionGraph.add_plot( axisAccelerationPlot ) self.dataPlots.append( RobRehabGUI.DataPlot( axisAccelerationPlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_ACCELERATION ) ) dataGraph.add_widget( axisPositionGraph ) dataGraph.add_widget( Label( size_hint_y=0.05 ) ) axisForceGraph = Graph( ylabel='Torque', **GRAPH_PROPERTIES ) axisForcePlot = SmoothLinePlot( color=[ 1, 0, 0, 1 ] ) axisForceGraph.add_plot( axisForcePlot ) self.dataPlots.append( RobRehabGUI.DataPlot( axisForcePlot, self.INITIAL_VALUES[:], self.axisMeasures, DOF_FORCE ) ) dataGraph.add_widget( axisForceGraph ) Clock.schedule_interval( self.NetworkUpdate, self.UPDATE_INTERVAL / 2 ) Clock.schedule_interval( self.GraphUpdate, self.UPDATE_INTERVAL * 2 ) Clock.schedule_interval( self.SliderUpdate, self.UPDATE_INTERVAL ) def ConnectClient( self, serverAddress ): self.connection = None self.robotID = '' self.deviceIDs = ( [], [] ) serverType, serverHost = serverAddress.split( '://' ) print( 'acquired %s server host: %s' % ( serverType, serverHost ) ) if serverType == 'ip': self.connection = ipclient.Connection() if self.connection is not None: self.configStorage.put( 'server', address=serverAddress ) self.connection.Connect( serverHost ) self.robotID, self.deviceIDs = self.connection.RefreshInfo() self.ids[ 'robot_id_display' ].text = self.robotID def UpdateSelectorEntries( selector, entriesList, entryNames ): entriesList.clear_widgets() for name in entryNames: entryButton = Button( text=name, size_hint_y=None ) entryButton.height = entryButton.font_size * 2 entryButton.bind( on_release=lambda button: entriesList.select( button.text ) ) entriesList.add_widget( entryButton ) for deviceType in range( len(self.deviceIDs) ): UpdateSelectorEntries( self.deviceSelectors[ deviceType ], self.deviceEntries[ deviceType ], self.deviceIDs[ deviceType ] ) self.SetDevice( deviceType, self.deviceIDs[ deviceType ][ 0 ] if len(self.deviceIDs[ deviceType ]) > 0 else self.NULL_ID ) def GraphUpdate( self, dt ): for plot in self.dataPlots: if len(plot.values) >= len(self.INITIAL_VALUES): plot.handle.points = [ ( sample, plot.values[ sample ] ) for sample in range( len(self.INITIAL_VALUES) ) ] plot.values = [] plot.values.append( plot.source[ plot.offset ] ) def SliderUpdate( self, dt ): self.ids[ 'measure_slider' ].value = self.axisMeasures[ DOF_POSITION ] #* 180 / math.pi def NetworkUpdate( self, dt ): currentAxisIndex = self.currentDeviceIndexes[ self.AXIS ] currentJointIndex = self.currentDeviceIndexes[ self.JOINT ] if self.connection is not None and currentAxisIndex is not None: if self.setpointsUpdated: self.connection.SendAxisSetpoints( currentAxisIndex, self.setpoints ) self.setpointsUpdated = False self.connection.ReceiveAxisMeasures( currentAxisIndex, self.axisMeasures ) #print( 'NetworkUpdate: received axis measures: ' + str( self.axisMeasures ) ) #self.connection.ReceiveJointMeasures( currentJointIndex, self.jointMeasures ) def SetUserName( self, name ): if self.connection is not None: self.connection.SetUser( name ) self.configStorage.put( 'user', name=name ) def SetDevice( self, type, name ): self.deviceSelectors[ type ].text = name deviceIDs = self.deviceIDs[ type ] self.currentDeviceIndexes[ type ] = deviceIDs.index( name ) if ( name in deviceIDs ) else None def SetSetpoints( self ): if not self.isSampling: self.setpoints[ DOF_POSITION ] = self.ids[ 'setpoint_slider' ].value #* math.pi / 180 self.setpoints[ DOF_STIFFNESS ] = self.ids[ 'stiffness_slider' ].value self.setpoints[ DOF_DAMPING ] = self.ids[ 'damping_slider' ].value self.setpointsUpdated = True def _SendCommand( self, commandKey ): self.connection.SendCommand( commandKey ) def SetEnable( self, enabled ): offsetToggle = self.ids[ 'offset_button' ] if enabled: self._SendCommand( ENABLE ) offsetToggle.state = 'down' else: self._SendCommand( DISABLE ) offsetToggle.state = 'normal' def SetOffset( self, enabled ): if enabled: self._SendCommand( OFFSET ) else: self._SendCommand( OPERATE if self.isOperating else PASSIVATE ) self.ids[ 'setpoint_slider' ].value = 0 self.SetSetpoints() def SetCalibration( self, enabled ): self.isCalibrating = enabled calibrationLED = self.ids[ 'indication_led' ] def TurnLedOn( *args ): calibrationLED.color = [ 0, 1, 0, 1 ] Clock.schedule_once( TurnLedOff, 5.0 ) def TurnLedOff( *args ): calibrationLED.color = [ 1, 0, 0, 1 ] if self.isCalibrating: Clock.schedule_once( TurnLedOn, 3.0 ) if enabled: self._SendCommand( CALIBRATE ) TurnLedOn() else: self._SendCommand( OPERATE if self.isOperating else PASSIVATE ) TurnLedOff() def SetOptimization( self, enabled ): PHASE_CYCLES_NUMBER = 5 PHASE_CYCLE_INTERVAL = 8.0 SETPOINT_AMPLITUDE = math.pi / 4 #SETPOINT_AMPLITUDE_ANGLE = SETPOINT_AMPLITUDE * 180 / math.pi PHASE_INTERVAL = PHASE_CYCLES_NUMBER * PHASE_CYCLE_INTERVAL PHASES_STIFFNESS_LIST = [ 0, 30, 60, 60, 30, 0, 0, 10 ] PHASES_DIRECTION_LIST = [ 1, 1, 1, 1, 1, 1, -1, -1 ] PHASES_ACTIVE_LIST = [ False, False, False, True, True, True, True, True ] TOTAL_SAMPLING_INTERVAL = len(PHASES_STIFFNESS_LIST) * PHASE_INTERVAL self.isSampling = enabled self.samplingTime = 0.0 setpointSlider = self.ids[ 'setpoint_slider' ] stiffnessSlider = self.ids[ 'stiffness_slider' ] dampingSlider = self.ids[ 'damping_slider' ] activeLED = self.ids[ 'indication_led' ] def UpdateSetpoint( delta ): phaseIndex = int( self.samplingTime / PHASE_INTERVAL ) if phaseIndex >= len(PHASES_STIFFNESS_LIST): self.ids[ 'sampling_button' ].state = 'normal' return False self.samplingTime += delta setpointDirection = PHASES_DIRECTION_LIST[ phaseIndex ] activeLED.color = [ 0, 1, 0, 1 ] if PHASES_ACTIVE_LIST[ phaseIndex ] else [ 1, 0, 0, 1 ] setpoint = math.sin( 2 * math.pi * self.samplingTime / PHASE_CYCLE_INTERVAL ) setpointSlider.value = setpoint * SETPOINT_AMPLITUDE #SETPOINT_AMPLITUDE_ANGLE #- SETPOINT_AMPLITUDE_ANGLE self.setpoints[ DOF_POSITION ] = setpoint * SETPOINT_AMPLITUDE * setpointDirection - SETPOINT_AMPLITUDE targetStiffness = PHASES_STIFFNESS_LIST[ phaseIndex ] stiffnessSlider.value = stiffnessSlider.value * 0.9 + targetStiffness * 0.1 self.setpoints[ DOF_STIFFNESS ] = stiffnessSlider.value dampingSlider.value = 0.0 if enabled: self._SendCommand( PREPROCESS ) self.samplingEvent = Clock.schedule_interval( UpdateSetpoint, self.UPDATE_INTERVAL * 2 ) else: self.samplingTime = TOTAL_SAMPLING_INTERVAL setpointSlider.value = 0.0 stiffnessSlider.value = 0.0 dampingSlider.value = 0.0 activeLED.color = [ 1, 0, 0, 1 ] self._SendCommand( OPERATE if self.isOperating else PASSIVATE ) self.samplingEvent.cancel() def SetOperation( self, enabled ): PHASE_CYCLE_INTERVAL = 8.0 SETPOINT_AMPLITUDE = math.pi / 4 #SETPOINT_AMPLITUDE_ANGLE = SETPOINT_AMPLITUDE * 180 / math.pi self.isOperating = enabled self.operationTime = 0.0 import numpy from scipy import signal self.trajectory = numpy.loadtxt( 'positionknee.txt' ) self.trajectory = numpy.reshape( self.trajectory, numpy.size( self.trajectory ) ) self.trajectory = signal.resample( self.trajectory, int(len(self.trajectory) / 2) ) print( self.trajectory ) self.curveStep = 0 self.setpoints[ DOF_STIFFNESS ] = 0 #self.hasStarted = False setpointSlider = self.ids[ 'setpoint_slider' ] stiffnessSlider = self.ids[ 'stiffness_slider' ] dampingSlider = self.ids[ 'damping_slider' ] activeLED = self.ids[ 'indication_led' ] def UpdateSetpoint( delta ): #cyclesCount = int( self.operationTime / PHASE_CYCLE_INTERVAL ) #self.operationTime += delta #setpoint = math.sin( 2 * math.pi * self.operationTime / PHASE_CYCLE_INTERVAL ) #if self.hasStarted: setpoint = - float( self.trajectory[ self.curveStep % len(self.trajectory) ] ) self.curveStep += 1 setpointSlider.value = setpoint * SETPOINT_AMPLITUDE #SETPOINT_AMPLITUDE_ANGLE #- SETPOINT_AMPLITUDE_ANGLE #elif self.setpoints[ DOF_STIFFNESS ] > 0: # if( abs( self.setpoints[ DOF_POSITION ] - self.axisMeasures[ DOF_POSITION ] ) ) < 0.0001: # self.hasStarted = True #stiffnessSlider.value = self.axisMeasures[ DOF_STIFFNESS ] #if cyclesCount < 20: self.setpoints[ DOF_STIFFNESS ] = 60 #else: self.setpoints[ DOF_STIFFNESS ] = 0 #self.setpoints[ DOF_STIFFNESS ] = 60 if enabled: self._SendCommand( OPERATE ) activeLED.color = [ 0, 1, 0, 1 ] self.operationEvent = Clock.schedule_interval( UpdateSetpoint, self.UPDATE_INTERVAL * 2 ) else: setpointSlider.value = 0.0 stiffnessSlider.value = 0.0 dampingSlider.value = 0.0 activeLED.color = [ 1, 0, 0, 1 ] self._SendCommand( PASSIVATE ) self.operationEvent.cancel()
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()
class EbolaCAREApp(App): 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 def on_pause(self): # Here you can save data if needed return True def on_resume(self): # Here you can check if any data needs replacing (usually nothing) pass def set_var_value(self, name, value): if value in self.categories: value = self.categories[value] values[name] = value print name, value def set_var_unit(self, name, unit): units[name] = unit self.store.put(name, unit=unit) print name, unit def restart(self): values = {} for scr in in_scr: scr.clear_widgets() sm.transition = FallOutTransition() sm.current = 'input 1' def go_screen(self, scr): curr_scr = int(sm.current.split()[1]) if curr_scr < scr: sm.transition = SlideTransition(direction='left') else: sm.transition = SlideTransition(direction='right') sm.current = 'input ' + str(scr) def calc_risk(self): if "AGE" in values and values["AGE"]: age = 30 try: age = float(values["AGE"]) except ValueError: pass except TypeError: pass if age < 10 or 50 < age: res_scr.curr_risk_color = [153.0/255, 93.0/255, 77.0/255, 1] res_scr.curr_risk_label = 'HIGH RISK' res_scr.curr_risk_level = 1 sm.current = 'result' return # Find highest ranking model that contained in the provided variables model_dir = None model_vars = None vv = set([]) for k in values: if values[k]: vv.add(k) print vv for info in models_info: v = set(info[1]) res = v.issubset(vv) #print res, info[1] if res: model_dir = info[0] model_vars = info[1] break if not model_dir or not models_info: res_scr.curr_risk_color = [0.5, 0.5, 0.5, 1] res_scr.curr_risk_label = 'INSUFFICIENT DATA' res_scr.curr_risk_level = 0 sm.transition = RiseInTransition() sm.current = 'result' return print "FOUND MODEL !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" print model_dir print model_vars predictor = gen_predictor(os.path.join(model_dir, 'nnet-params')) N = len(model_vars) model_min = [] model_max = [] with open(os.path.join(model_dir, 'bounds.txt')) as bfile: lines = bfile.readlines() for line in lines: line = line.strip() parts = line.split() model_min.append(float(parts[1])) model_max.append(float(parts[2])) print model_min print model_max v = [None] * (N + 1) v[0] = 1 for i in range(N): var = model_vars[i] if var in values: try: v[i + 1] = float(values[var]) if var in units and units[var] != var_def_unit[var]: # Need to convert units c, f = var_unit_conv[var] print "convert",var,v[i + 1],"->",f*(v[i + 1] + c) v[i + 1] = f * (v[i + 1] + c) except ValueError: pass except TypeError: pass if None in v: res_scr.curr_risk_color = [0.5, 0.5, 0.5, 1] res_scr.curr_risk_label = 'INSUFFICIENT DATA' res_scr.curr_risk_level = 0 sm.current = 'result' return for i in range(N): f = (v[i + 1] - model_min[i]) / (model_max[i] - model_min[i]) if f < 0: v[i + 1] = 0 elif 1 < f: v[i + 1] = 1 else: v[i + 1] = f print values print v X = np.array([v]) probs = predictor(X) pred = probs[0] print "------------->",pred,type(pred) res_scr.curr_risk_level = float(pred) if pred < 0.5: res_scr.curr_risk_color = [121.0/255, 192.0/255, 119.0/255, 1] res_scr.curr_risk_label = 'LOW RISK' else: level = float((pred - 0.5) / 0.5) res_scr.curr_risk_color = [153.0/255, 93.0/255, 77.0/255, 1] res_scr.curr_risk_label = 'HIGH RISK' sm.transition = RiseInTransition() #sm.transition = SlideTransition(direction='left') sm.current = 'result'