def __init__(self, the_app): super(FinalForm, self).__init__() self.the_app = the_app self.statements = {} store = JsonStore('final_statements.json').get('final_statements') for key, value in store.items(): self.statements[key] = {} for k,v in value.items(): self.statements[key][k] = v title_txt = u"כל הכבוד!" self.title.text = title_txt[::-1] statement_layout = BoxLayout(orientation="vertical") self.statement_label = [] statement_layout.add_widget(BoxLayout(size_hint_y=0.3)) for k in range(0,4): self.statement_label.append(Label(font_size=40, font_name="fonts/the_font.ttf", halign='center', size_hint_y=0.4, color=[0,0,0, 1])) statement_layout.add_widget(self.statement_label[-1]) self.add_widget(statement_layout) end_text = u"סיום" self.end_button.text = end_text[::-1] self.end_button.bind(on_press=self.next)
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 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 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()
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 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 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
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'))
def storeformdata(self): store = JsonStore('forms.json') store.put('forms', walletname=self.input_name.text, sendtoaddress=self.input_address.text, amount=self.input_amount.text, mixin=self.input_mixin.text, paymentid=self.input_paymentid.text, mineraddress=self.minerurl_input.text, mineruser=self.mineruser_input.text, minerpw=self.minerpw_input.text, minerthreads=self.minerthreads_input.text)
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 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
def __init__(self, **kwargs): kwargs['cols'] = 2 super(MainView, self).__init__(**kwargs) # def build(self): # global store project_store = JsonStore('projectlist.json') self.list_adapter = ListAdapter(data=[("Project " + r + ' ' + project_store[r]['profile']['projecttitle']) for r in project_store.keys()], cls=ListItemButton, sorted_keys=[]) self.list_adapter.bind(on_selection_change=self.callback) list_view = ListView(adapter=self.list_adapter) self.add_widget(list_view)
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 get_public_key(): if DataMode.communication in KivyLogger.base_mode: # get from communication pub_pem = KivyLogger.socket.recv(1024) else: private_key = RSA.generate(2048, e=65537) prv_pem = private_key.exportKey("PEM") store = JsonStore(KivyLogger.filename + '.enc') store.put('private_key', pem=prv_pem) pub_pem = private_key.publickey().exportKey("PEM") KivyLogger.public_key = RSA.importKey(pub_pem) pass
def on_pre_leave(self, *args): if len(self.haberadi.text)<3 and len(self.takmaadi.text)<3: return js=JsonStore("UmutRss.json") fst=True url_str="{" for k,v in self.urls.items(): if fst: url_str +=k+":"+v fst=False else: url_str += ","+k + ":" + v url_str +="}" js.put(self.haberadi.text,title=self.takmaadi.text,url=url_str)
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 __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 __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 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 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
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 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 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 __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 __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): 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 __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)
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
class HiQontrolApp(App): __version__ = '0.0.3' datastore = JsonStore('settings.json') store_needs_update = False device = None try: device = hiqnet.device.Device( datastore.get('device_name')['value'], datastore.get('device_address')['value']) except KeyError: Logger.warning(APPNAME + ': Settings not found, will use sane defaults') device_name = APPNAME device = hiqnet.device.Device(device_name) datastore.put('device_name', value=device.name) datastore.put('device_address', value=device.hiqnet_address) except TypeError: if on_rtd: pass control = None screen = None udp_transport = None tcp_transport = None def build(self): reactor.listenTCP(hiqnet.service.ip.PORT, hiqnet.service.ip.Factory(self)) reactor.listenUDP(hiqnet.service.ip.PORT, hiqnet.service.ip.UDPProtocol(self)) reactor.listenUDP(soundcraft.ip.VUMETER_IP_PORT, soundcraft.ip.VuMeterUDPPRotocol(self)) self.title = APPNAME self.icon = 'assets/icon.png' self.screen = HiQontrol(list=self.populate()) return self.screen def on_start(self): """Initialize device and network communications.""" self.control = Control(self.device, self.udp_transport, self.tcp_transport) def on_pause(self): """Enable pause mode.""" return True def store_needs_udate(self): self.store_needs_update = True def store_update(self, name, address): if self.store_needs_update: Logger.info(APPNAME + ": Updating store") self.datastore.put('device_name', value=name) self.datastore.put('device_address', value=int(address)) Logger.info(APPNAME + ": Store updated, reloading device") self.device = hiqnet.device.Device( self.datastore.get('device_name')['value'], self.datastore.get('device_address')['value']) self.control = Control(self.device, self.udp_transport, self.tcp_transport) self.store_needs_update = False def get_model(self): # FIXME: placeholder return "Si Compact 16" def get_name(self): # FIXME: placeholder return "Si Compact 16" def get_hiqnet_address(self): # FIXME: placeholder return str(SI_COMPACT_16_DEVICE_ADDRESS) def get_ip_address(self): # FIXME: placeholder return SI_COMPACT_16_IP def get_local_name(self): return self.device.manager.name_string def get_local_hiqnet_address(self): return str(self.device._hiqnet_address) def get_local_mac_address(self): return self.device.network_info.mac_address def get_local_dhcp_status(self): return self.device.network_info.dhcp def get_local_ip_address(self): return self.device.network_info.ip_address def get_local_subnet_mask(self): return self.device.network_info.subnet_mask def get_local_gateway(self): return self.device.network_info.gateway_address def locate_toggle(self, hiqnet_dest, ip_dest, serial_dest): self.control.locate_toggle(hiqnet_dest, ip_dest, serial_dest) def populate(self): # FIXME: This should be dynamically detected from the network or manually added/removed item_strings = ['0', '1'] integers_dict = { '0': { 'text': 'Si Compact 16', 'ip_address': SI_COMPACT_16_IP, 'hiqnet_address': SI_COMPACT_16_DEVICE_ADDRESS, 'is_selected': False }, '1': { 'text': 'Lool', 'ip_address': '192.168.1.3', 'hiqnet_address': 9999, 'is_selected': False } } args_converter = \ lambda row_index, rec: \ {'text': rec['text'], 'size_hint_y': None, 'height': 50, 'cls_dicts': [{'cls': ListItemButton, 'kwargs': {'text': rec['text'], 'is_representing_cls': True}}, {'cls': ListInfoButton, 'kwargs': {'text': 'i', # TODO: replace by a nice icon 'size_hint_x': None}}, {'cls': ListLocateButton, 'kwargs': {'text': 'L', # TODO: replace by a nice icon 'size_hint_x': None, 'hiqnet_address': rec['hiqnet_address'], 'ip_address': rec['ip_address'], 'serial_number': SI_COMPACT_16_SERIAL}}, # FIXME {'cls': ListMixButton, 'kwargs': {'text': '>', # TODO: replace by a nice icon 'size_hint_x': None}}]} dict_adapter = DictAdapter(sorted_keys=item_strings, data=integers_dict, args_converter=args_converter, selection_mode='single', allow_empty_selection=False, cls=CompositeListItem) return dict_adapter def handle_message(self, message, host, protocol): """Handle messages received from twisted servers. Only display it on screen for debugging right now :param message: HiQnet message :type message: hiqnet.protocol.Command :param: host: IPv4 host address :param protocol: Protocol that received :type protocol: str :return: """ self.screen.debug.text = protocol + '(' + str( host) + ')' + binascii.hexlify(bytes(message))
from kivy.config import Config import subprocess, os, sys from kivy.uix.filechooser import FileChooserIconView # outclass var = subprocess.check_output("pwd", shell=True) var = var.decode("utf-8") var = var.split("/") var.pop() var = "/".join(var) os.chdir(var) Window.size = (1920, 1080) data_storage = JsonStore("data_store.json") # vars version = None file_path = None check5 = False check4 = False check3 = False check2 = False check1 = False check = False now = None customer_name = None customer_numberz = len(data_storage)
class WeatherRoot(BoxLayout): carousel = ObjectProperty() current_weather = ObjectProperty() forecast = ObjectProperty() locations = 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() # Doesn't seem to work, no children though current_weather is present. #for c2 in list(self.children): # if isinstance(c2,CurrentWeather): # self.remove(c2) # TODO; figure out how to not have duplicate widgets here! # It's present in the .kv: "current_weather: current_weather" if self.current_weather: pass #self.remove_widget(self.current_weather) #self.remove_widget(self.children[0]) # IndexError: list index out of range #self.remove_widget(self.children[0]) # IndexError: list index out of range #self.remove_widget(self.current_weather) #self.current_weather = None # ValueError: None is not allowed for WeatherRoot.current_weather #del self.current_weather # NotImplementedError: __delete__ else: self.add_widget(self.current_weather) #for c2 in list(self.children): # if isinstance(c2,CurrentWeather): self.remove(c2) 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) 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)
class RoundsScreen(BaseScreen): POSITIONS_X = {0: 328 / 2048.0, 1: 1228 / 2048.0} POSITIONS_Y = {0: (1536. - 1400) / 1536.0} SIZES = {0: (730 / 2048.0, (1536 - 1340) / 1536.0)} def __init__(self, sm, **kwargs): """Init start screen.""" super(RoundsScreen, self).__init__(**kwargs) self.sm = sm self.name = kwargs['name'] self.menu_screen = kwargs['menu'] self.back_button = self.ids['Back'] self.back_button.late_init( **{ 'name': 'Back', 'image': 'assets/settings/btn_back_active.png' }) self.back_button.bind(on_press=self.pressed_back) self.back_button.pos_hint = { 'x': self.POSITIONS_X[0], 'y': self.POSITIONS_Y[0] } self.back_button.size_hint = self.SIZES[0] self.back_button.render() self.back_button.show() self.play_button = self.ids['Play'] self.play_button.late_init(**{'name': 'Play'}) self.play_button.bind(on_press=self.pressed_play) self.play_button.pos_hint = { 'x': self.POSITIONS_X[1], 'y': self.POSITIONS_Y[0] } self.play_button.size_hint = self.SIZES[0] self.game = None self.bot_name = None self.store = JsonStore(join(STORE_DIR, 'user.dat')) #{round_id: bool} self.rounds_stats = self.ids['rounds_stats'] states_db = [] dist_cnt = {} dist_won_cnt = {} won_states = [] with open(states_csv) as states_file: reader = csv.DictReader(states_file) for row in reader: row_ = {k: v for k, v in row.iteritems()} states_db.append(row_) if row_['state'] in dist_cnt.keys(): dist_cnt[row_['state']] += 1 else: dist_cnt[row_['state']] = 1 if self.store.exists(str(int(row_['id']) - 1)): if row_['state'] in dist_won_cnt.keys(): dist_won_cnt[row_['state']] += 1 else: dist_won_cnt[row_['state']] = 1 for state in dist_won_cnt.keys(): if dist_cnt[state] == dist_won_cnt[state]: won_states.append(state) self.rounds_stats.late_init(self.store, won_states) self.states_scroll = self.ids['StatesScroll'] self.dist_scroll = self.ids['DistrictsScroll'] self.descr_scroll = self.ids['DescriptionScroll'] self.descr_scroll.late_init( size_hint=(((2048.0 - 340) / 3) / 2048.0, 880 / 2048.0), pos_hint={ 'x': (138 + 2 * ((2048.0 - 400) / 3) + 120) / 2048.0, 'y': 400.0 / 1536.0 }, states_db=states_db) self.dist_scroll.late_init( self.descr_scroll, self.store, size_hint=(((2048.0 - 440) / 3) / 2048.0, 880 / 2048.0), pos_hint={ 'x': (138 + ((2048.0 - 340) / 3) + 60) / 2048.0, 'y': 400.0 / 1536.0 }, states_db=states_db) self.states_scroll.late_init(self.dist_scroll, won_states, size_hint=(((2048.0 - 370) / 3) / 2048.0, 880 / 2048.0), pos_hint={ 'x': 138 / 2048.0, 'y': 400.0 / 1536.0 }, states_db=states_db) self.set_new_game() def pressed_back(self, *args): self.sm.current = 'startscreen' def set_new_game(self): self.game = elections_game.ElectionsGame(self.sm, name="electionsgame") self.game.set_start_screen(self.menu_screen) def set_bot(self, bot_name): self.bot_name = bot_name print('reounds:set_bot: ', bot_name, self.bot_name) # if self.game: # self.game.set_bot(self.bot_name) def pressed_play(self, *args): state = self.states_scroll.state_selected area = self.dist_scroll.area_selected round_id = self.dist_scroll.round_selected print('pressed_play: ', self.bot_name) self.game.set_bot(self.bot_name) self.game.set_store(self.store) self.game.set_round(round_id, state, area) self.sm.switch_to(self.game)
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 ) # TODO; Error kivy.uix.widget.WidgetException: # Cannot add <__main__.CurrentWeather object at 0x7f4c3e63f320>, # it already has a parent <kivy.uix.relativelayout.RelativeLayout object at 0x7f4c3e5bea08> 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)
import os import hashlib from EncryptionModule.symmetric import generate_scrypt_key, aes_encrypt ##THe documentation for this function which were copied are present at https://kivy.org/docs/api-kivy.uix.filechooser.html import os import sys from Crypto.Cipher import AES from Crypto.Protocol.KDF import scrypt def str_to_class(str): return getattr(sys.modules[__name__], str) store = JsonStore('config.json') class UserRegistration(Screen): loadfile = ObjectProperty(None) savefile = ObjectProperty(None) text_input = ObjectProperty(None) mnemonic = StringProperty() address = StringProperty() file = 'enter zip path or select it' def open(self, textfield_id): self.popup = Popup(title='Test popup', content=self.explorer(), size_hint=(None, None), size=(600, 600))
def __init__(self, sm, **kwargs): """Init start screen.""" super(RoundsScreen, self).__init__(**kwargs) self.sm = sm self.name = kwargs['name'] self.menu_screen = kwargs['menu'] self.back_button = self.ids['Back'] self.back_button.late_init( **{ 'name': 'Back', 'image': 'assets/settings/btn_back_active.png' }) self.back_button.bind(on_press=self.pressed_back) self.back_button.pos_hint = { 'x': self.POSITIONS_X[0], 'y': self.POSITIONS_Y[0] } self.back_button.size_hint = self.SIZES[0] self.back_button.render() self.back_button.show() self.play_button = self.ids['Play'] self.play_button.late_init(**{'name': 'Play'}) self.play_button.bind(on_press=self.pressed_play) self.play_button.pos_hint = { 'x': self.POSITIONS_X[1], 'y': self.POSITIONS_Y[0] } self.play_button.size_hint = self.SIZES[0] self.game = None self.bot_name = None self.store = JsonStore(join(STORE_DIR, 'user.dat')) #{round_id: bool} self.rounds_stats = self.ids['rounds_stats'] states_db = [] dist_cnt = {} dist_won_cnt = {} won_states = [] with open(states_csv) as states_file: reader = csv.DictReader(states_file) for row in reader: row_ = {k: v for k, v in row.iteritems()} states_db.append(row_) if row_['state'] in dist_cnt.keys(): dist_cnt[row_['state']] += 1 else: dist_cnt[row_['state']] = 1 if self.store.exists(str(int(row_['id']) - 1)): if row_['state'] in dist_won_cnt.keys(): dist_won_cnt[row_['state']] += 1 else: dist_won_cnt[row_['state']] = 1 for state in dist_won_cnt.keys(): if dist_cnt[state] == dist_won_cnt[state]: won_states.append(state) self.rounds_stats.late_init(self.store, won_states) self.states_scroll = self.ids['StatesScroll'] self.dist_scroll = self.ids['DistrictsScroll'] self.descr_scroll = self.ids['DescriptionScroll'] self.descr_scroll.late_init( size_hint=(((2048.0 - 340) / 3) / 2048.0, 880 / 2048.0), pos_hint={ 'x': (138 + 2 * ((2048.0 - 400) / 3) + 120) / 2048.0, 'y': 400.0 / 1536.0 }, states_db=states_db) self.dist_scroll.late_init( self.descr_scroll, self.store, size_hint=(((2048.0 - 440) / 3) / 2048.0, 880 / 2048.0), pos_hint={ 'x': (138 + ((2048.0 - 340) / 3) + 60) / 2048.0, 'y': 400.0 / 1536.0 }, states_db=states_db) self.states_scroll.late_init(self.dist_scroll, won_states, size_hint=(((2048.0 - 370) / 3) / 2048.0, 880 / 2048.0), pos_hint={ 'x': 138 / 2048.0, 'y': 400.0 / 1536.0 }, states_db=states_db) self.set_new_game()
from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.graphics.vertex_instructions import RoundedRectangle from kivy.uix.checkbox import CheckBox from kivy.uix.dropdown import DropDown from kivy.uix.textinput import TextInput from kivy.storage.jsonstore import JsonStore from functools import partial import re import newspaper from newspaper import Article, Source, Config from time import sleep kivy.require("1.9.1") owm = pyowm.OWM('f8ad5034578b3193450b67823d91f5bf') store = JsonStore('settings.json') smart_sleep = 0 weather_stat = 0 news_stat = 0 news_article_num = 1 alarm_hour = 0 alarm_minute = 0 alarm_changed = 0 wait_next_minute = 0 smart_sleep_count = 0 alarm_pid = 999999999999 sub_process = 0 weather_zip = '06106' paper_name = 'NPR' npr_paper = newspaper.build('http://npr.org/sections/technology', memoize_articles=False)
class KaTrainBase: USER_CONFIG_FILE = os.path.expanduser("~/.katrain/config.json") PACKAGE_CONFIG_FILE = "katrain/config.json" """Settings, logging, and players functionality, so other classes like bots who need a katrain instance can be used without a GUI""" def __init__(self, force_package_config=False, debug_level=None, **kwargs): self.debug_level = debug_level or 0 self.game = None self.logger = lambda message, level=OUTPUT_INFO: self.log( message, level) self.config_file = self._load_config( force_package_config=force_package_config) self.debug_level = self.config( "general/debug_level", OUTPUT_INFO) if debug_level is None else debug_level Config.set("kivy", "log_level", "warning") if self.debug_level >= OUTPUT_DEBUG: Config.set("kivy", "log_enable", 1) Config.set("kivy", "log_level", "debug") # if self.debug_level >= OUTPUT_EXTRA_DEBUG: # Config.set("kivy", "log_level", "trace") self.players_info = {"B": Player("B"), "W": Player("W")} self.reset_players() def log(self, message, level=OUTPUT_INFO): if level == OUTPUT_ERROR: print(f"ERROR: {message}") elif self.debug_level >= level: print(message) def _load_config(self, force_package_config): if len(sys.argv) > 1 and sys.argv[1].endswith("config.json"): config_file = os.path.abspath(sys.argv[1]) self.log(f"Using command line config file {config_file}", OUTPUT_INFO) else: user_config_file = find_package_resource(self.USER_CONFIG_FILE) package_config_file = find_package_resource( self.PACKAGE_CONFIG_FILE) if force_package_config: config_file = package_config_file else: try: if not os.path.exists(user_config_file): os.makedirs(os.path.split(user_config_file)[0], exist_ok=True) shutil.copyfile(package_config_file, user_config_file) config_file = user_config_file self.log( f"Copied package config to local file {config_file}", OUTPUT_INFO) else: # user file exists try: version = JsonStore(user_config_file).get( "general")["version"] except Exception: # broken file etc version = "0.0.0" if version < CONFIG_MIN_VERSION: backup = user_config_file + f".{version}.backup" shutil.copyfile(user_config_file, backup) shutil.copyfile(package_config_file, user_config_file) self.log( f"Copied package config file to {user_config_file} as user file is outdated or broken ({version}<{CONFIG_MIN_VERSION}). Old version stored as {backup}", OUTPUT_INFO, ) config_file = user_config_file self.log(f"Using user config file {config_file}", OUTPUT_INFO) except Exception as e: config_file = package_config_file self.log( f"Using package config file {config_file} (exception {e} occurred when finding or creating user config)", OUTPUT_INFO, ) try: self._config_store = JsonStore(config_file, indent=4) except Exception as e: self.log(f"Failed to load config {config_file}: {e}", OUTPUT_ERROR) sys.exit(1) self._config = dict(self._config_store) return config_file def save_config(self, key=None): if key is None: for k, v in self._config.items(): self._config_store.put(k, **v) else: self._config_store.put(key, **self._config[key]) def config(self, setting, default=None): try: if "/" in setting: cat, key = setting.split("/") return self._config.get(cat, {}).get(key, default) else: return self._config[setting] except KeyError: self.log(f"Missing configuration option {setting}", OUTPUT_ERROR) def update_player(self, bw, **kwargs): self.players_info[bw].update(**kwargs) self.update_calculated_ranks() def update_calculated_ranks(self): for bw, player_info in self.players_info.items(): if player_info.player_type == PLAYER_AI: settings = self.config(f"ai/{player_info.strategy}") player_info.calculated_rank = ai_rank_estimation( player_info.player_subtype, settings) def reset_players(self): self.update_player("B") self.update_player("W") for v in self.players_info.values(): v.periods_used = 0 @property def last_player_info(self) -> Player: return self.players_info[self.game.current_node.player] @property def next_player_info(self) -> Player: return self.players_info[self.game.current_node.next_player]
def __init__(self, the_app): super(DetailsFormPersonal, self).__init__() self.the_app = the_app with self.canvas.before: self.rect = Rectangle(source='back3.png') self.bind(size=self._update_rect, pos=self._update_rect) dict = {} self.answers = {} store = JsonStore('details.json').get('details') for key, value in store.items(): if key in [ 'FirstName', 'LastName', 'Email', 'end_button', 'details_title', 'Age' ]: dict[key] = value[::-1] if key in ['Gender']: dict[key] = {} for kqa, qa in value.items(): if kqa == 'text': dict[key][kqa] = qa[::-1] elif kqa == 'default': dict[key][kqa] = qa[::-1] elif kqa != 'ages': dict[key][kqa] = [] for k, v in value[kqa].items(): dict[key][kqa].append(v[::-1]) else: dict[key][kqa] = [] age = 10 while age < 100: dict[key][kqa].append(str(age)) age += 1 # definitions of all the GUI y_size = 0.2 self.age_text = LoggedTextInput(size_hint_x=0.5, font_size=40, input_filter='int', size_hint_y=y_size) self.age_text.bind(text=self.age_text.on_text_change) self.age_text.name = 'age' self.email_text = LoggedTextInput(size_hint_x=2, font_size=32, size_hint_y=y_size) self.email_text.bind(text=self.email_text.on_text_change) self.email_text.name = 'email' self.gender_default = dict['Gender']['default'] print(dict['Gender']['Genders']) self.gender_spinner = LoggedSpinner(text=dict['Gender']['default'], values=dict['Gender']['Genders'], size=(50, 50), font_name="fonts/the_font.ttf", font_size=40, size_hint_y=y_size, option_cls=MySpinnerOption) self.gender_spinner.name = 'gender' self.gender_spinner.bind(text=self.gender_spinner.on_spinner_text) end_button = Button(background_color=[0, 0.71, 1, 1], background_normal="", text=dict['end_button'], font_size=30, font_name="fonts/the_font.ttf", halign='right', on_press=self.next) end_button.bind(on_press=self.save) # layout of the GUI layoutup = BoxLayout(orientation='vertical') layoutup.add_widget(BoxLayout(size_hint_y=y_size)) layoutup.add_widget( Label(text=dict['details_title'], font_size=50, font_name="fonts/the_font.ttf", halign='right', size_hint_y=y_size, color=[0, 0, 0, 1])) layout = GridLayout(cols=8, rows=6) # === first line === layout.add_widget(end_button) layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=y_size)) if 'age' in self.what_to_include: layout.add_widget(self.age_text) layout.add_widget( Label(text=dict['Age'], font_size=30, font_name="fonts/the_font.ttf", halign='right', size_hint_y=y_size, color=[0, 0, 0, 1])) else: layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout()) if 'email' in self.what_to_include: layout.add_widget(self.email_text) # layout.add_widget(BoxLayout(size_hint_x=1, size_hint_y=1)) layout.add_widget( Label(text=dict['Email'], font_size=30, font_name="fonts/the_font.ttf", halign='right', size_hint_y=y_size, color=[0, 0, 0, 1])) else: layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout()) if 'gender' in self.what_to_include: layout.add_widget(self.gender_spinner) layout.add_widget( Label(text=dict['Gender']['text'], font_size=30, font_name="fonts/the_font.ttf", halign='right', size_hint_y=y_size, color=[0, 0, 0, 1])) else: layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout(size_hint_y=y_size)) # === second line === layout.add_widget(BoxLayout(size_hint_y=y_size)) layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=y_size)) layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout(size_hint_y=y_size)) layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout(size_hint_x=1.5)) layout.add_widget(BoxLayout(size_hint_x=1.5)) # === space lines === for lines in range(2): for space_line in range(8): layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=1)) # layout.add_widget(BoxLayout(size_hint_y=1)) # === last line === layout.add_widget(BoxLayout(size_hint_x=0.2)) layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=y_size)) layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout(size_hint_x=0.2)) layout.add_widget( Label(text="ךתופתתשה לע הדות", font_size=36, color=[0, 0, 0, 1], font_name="fonts/the_font.ttf", halign='right', size_hint_x=1.5)) layout.add_widget(BoxLayout()) layout.add_widget(BoxLayout()) # === space lines === for lines in range(1): for space_line in range(7): layout.add_widget(BoxLayout(size_hint_x=0.1, size_hint_y=1)) # layout.add_widget(BoxLayout(size_hint_y=1)) # ======= end ======= layoutup.add_widget(layout) self.add_widget(layoutup) self.start()
def get_question_result_grid(user_answers, width): """ Here we create the question grid. Each question has the question itself and the three categories of answers: The answers the user gave The answers the user would have given if they had a perfect memory The true answer in the graph. """ user_answers = user_answers question_result_grid = GridLayout(rows=len(user_answers)) store = JsonStore("Json/answers.json", encoding='utf-8') for item in user_answers: new_question = GridLayout(rows=4, cols=1) new_question.add_widget( Label(text=item.question_string, text_size=(width, None), font_name="fonts/Alef-Regular.ttf", halign='right')) keys = GridLayout(rows=1, cols=3) keys.add_widget( Label(text=store['answers']['answer_graph_type']['user_answer'] [::-1], font_name="fonts/Alef-Regular.ttf", halign='right')) keys.add_widget( Label(text=store['answers']['answer_graph_type'] ['discovered_graph_answer'][::-1], font_name="fonts/Alef-Regular.ttf", halign='right')) keys.add_widget( Label(text=store['answers']['answer_graph_type'] ['full_graph_answer'][::-1], font_name="fonts/Alef-Regular.ttf", halign='right')) new_question.add_widget(keys) answers = GridLayout(rows=1, cols=3) answers.add_widget( Label(text=translate_answers(item.user_answer), font_name="fonts/Alef-Regular.ttf", halign='right')) answers.add_widget( Label(text=translate_answers(item.user_graph_answer), font_name="fonts/Alef-Regular.ttf", halign='right')) answers.add_widget( Label(text=translate_answers(item.real_answer), font_name="fonts/Alef-Regular.ttf", halign='right')) new_question.add_widget(answers) new_question.add_widget(MyLabel(size_hint_y=0.005)) KL.log.insert( action=LogAction.data, comment='results_question_%s_user_%s_discovered_%s_true_%s' % (item.question_string, str(item.user_answer), str(item.user_graph_answer), str(item.real_answer))) question_result_grid.add_widget(new_question) return question_result_grid
PROJECT_PATH = PATH_SEPERATOR.join( path.realpath(__file__).split(PATH_SEPERATOR)[:-1]) if PATH_SEPERATOR == '/': cmd = "echo $HOME" else: cmd = "echo %USERPROFILE%" out, err = run_syscall(cmd) DATAFILE = "%(out)s%(ps)s.kivydeployapp%(ps)sdeployapp" % { 'out': out.rstrip(), 'ps': PATH_SEPERATOR } KIVY_VERSION = __version__ DB = JsonStore(DATAFILE) directory = path.dirname(DATAFILE) if not path.exists(directory): makedirs(directory) DB.store_put('servers', []) DB.store_put('username', "") DB.store_put('password', "") DB.store_sync() if not DB.store_exists('servers'): DB.store_put('servers', []) DB.store_sync() if not DB.store_exists('username'): DB.store_put('username', "") DB.store_sync() if not DB.store_exists('password'): DB.store_put('password', "")
class MarkerInitialScreen(Screen): PATH_DATA = '/home/sol2/Datasets' # loadfile = ObjectProperty(None) # savefile = ObjectProperty(None) text_input = ObjectProperty(None) listOfDatasets_CheckBoxs_Ids = {} listOfDatasets_Boxs_Ids = {} username = '' hostname = '' password = '' connected = False datasets_list = [] imagesHomePath = '' ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) data_dir = App().user_data_dir store = JsonStore(join(data_dir, 'storage.json')) sftp_client = '' files = [] configFilePath = '' initialLabels = [] lastCredential = "" login = "" fileName = '' def __init__(self, **kwa): super(MarkerInitialScreen, self).__init__(**kwa) self.pathText = [] self.progressBarTime = 0 self.progressLen = 0 self.box = BoxLayout() self.box.add_widget( kIm.Image(source='kvFiles/appImages/gifs/heimdall_OMG.gif')) self.popup = Popup(title='Por Odin!', content=self.box, size_hint=(0.4, 0.40)) self.textinputtext = StringProperty() try: self.lastCredential = MarkerInitialScreen.store.get('credentials') print(self.lastCredential) except KeyError: print('Failed Login') MarkerInitialScreen.store.put('credentials', hostname='', username='', password='') self.lastCredential = MarkerInitialScreen.store.get('credentials') username = "" # self.popup.bind(on_open=self.puopen) def textInputActivate(self): if (os.path.isdir(self.ids.text_input.text)): self.ids.boxLayoutFineTuningScreenSelectId.disabled = False self.ids.boxLayoutFineTuningScreenRunId.disabled = False self.ids.boxLayoutSCM.disabled = True self.ids.checkbox_HU.disabled = True self.ids.checkbox_GLCM.disabled = True self.ids.checkbox_LBP.disabled = True else: self.ids.text_input.text = 'Invalid Folder' self.ids.boxLayoutFineTuningScreenSelectId.disabled = True self.ids.boxLayoutFineTuningScreenRunId.disabled = True def disable_input(self, checkbox1, checked): self.ids.text_input.disabled = not checked def read_and_login(self): temp = TextInput(text=self.ids.text_input_username_hostname.text).text try: temp = temp.split('@') except: print('Invalid adrress') try: self.username = temp[0] self.hostname = temp[1] self.password = TextInput( text=self.ids.text_input_password.text).text del temp self.ssh_client.connect(hostname=self.hostname, username=self.username, password=self.password, port=2203) self.connected = True self.ids.boxLayoutConnectionStatus.text = 'Status de conexção SSH: Conectado' self.ids.boxLayoutViewerDatasetsId.disabled = False self.ids.boxLayoutAvailablesDatasetsId.disabled = False # Apesar de ser obvio ( Flag logo acima dizendo True, essa parte abaixo foi extraida de uma função e portanto deixada intacta) if self.connected: MarkerInitialScreen.store.put('credentials', hostname=self.hostname, username=self.username, password=self.password) #self.PATH_DATA = '/media/'+self.username+'/Dados/Datasets' self.PATH_DATA = config.PATH_DATASET # self.PATH_DATA = '/home/' + self.username + '/Datasets' self.sftp_client = self.ssh_client.open_sftp() self.datatasets_list = self.sftp_client.listdir(self.PATH_DATA) self.datatasets_list.sort() self.n_files = len(self.sftp_client.listdir(self.PATH_DATA)) for idxRM, wgtRM in self.listOfDatasets_Boxs_Ids.items(): self.ids.boxLayoutAvailablesDatasetsId.remove_widget(wgtRM) for datasetName in self.datatasets_list: if '_temp' not in datasetName: stdin_F, stdout_F, stderr_F = self.ssh_client.exec_command( "find " + self.PATH_DATA + '/' + datasetName + '/bruto' + " -type f") n_files = len([ file for file in stdout_F.readlines() if any(ext in file for ext in ('.jpg', '.png', '.JPG', '.PNG')) ]) newBox = BoxLayout() newLabel = Label() newCheckBox = CheckBox() self.listOfDatasets_CheckBoxs_Ids[ "CheckBox_" + str(datasetName)] = newCheckBox self.listOfDatasets_Boxs_Ids["Box_" + str(datasetName)] = newBox newLabel.text = datasetName + ' (' + str(n_files) + ')' newCheckBox.group = 'AvailableCheckbox' newCheckBox.color = (1, 1, 1, 1) newBox.size_hint = (1, None) newBox.add_widget(newLabel) newBox.add_widget(newCheckBox) self.ids.boxLayoutAvailablesDatasetsId.add_widget( newBox) # print(self.datatasets_list) else: self.ids.boxLayoutConnectionStatus.text = 'Status de conexção SSH: Favor, conectar para acessar os datasets' except Exception as e: print(e) # self.ids.boxLayoutViewerDatasetsId.disable = True self.ids.boxLayoutConnectionStatus.text = 'Status de conexão SSH: Inválidado' self.ids.boxLayoutViewerDatasetsId.disabled = True self.ids.boxLayoutAvailablesDatasetsId.disabled = True def get_dataset(self): for idx, wgt in self.listOfDatasets_CheckBoxs_Ids.items(): if wgt.active: self.imagesHomePath = os.path.join( self.PATH_DATA, idx.replace("CheckBox_", "")) # print("Image Path ", self.imagesHomePath) self.manager.get_screen('markerLabelScreenName').setImagesPath( self.imagesHomePath) self.sftp_client = self.ssh_client.open_sftp() self.datatasets_list = self.sftp_client.listdir( self.imagesHomePath) for fileName in self.datatasets_list: if ".config" in fileName: self.configFilePath = os.path.join( self.imagesHomePath, fileName) break with self.sftp_client.open(self.configFilePath) as f: for k in f.readlines(): self.initialLabels.append(k.replace("\n", "")) self.manager.get_screen('markerLabelScreenName').setLabels( self.initialLabels) self.initialLabels = [] self.manager.get_screen('markerLabelScreenName').get_labels() self.manager.current = 'markerLabelScreenName' def waitTime(self): time.sleep(3) self.popup.dismiss() def next(self, dt): if self.progress_bar.value >= 100: return False self.progress_bar.value = self.progressLen def puopen(self, instance): Clock.schedule_interval(self.next, 1 / 25)
import re, time # import kivy from kivy.app import App from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.clock import Clock from kivy.storage.jsonstore import JsonStore # from os.path import join # data_dir = getattr(self, 'user_data_dir') #get a writable path to save the file # store = JsonStore(join(data_dir, 'user.json')) db = JsonStore('M97.json') # db.put('about',about=TITLE) class NumInput(TextInput): re_num = re.compile(r'[0-9.]+') def insert_text(self, substring, from_undo=False): if self.re_num.match(substring) and len(self.text) < 4: return super(self.__class__, self).insert_text(substring, from_undo=from_undo) else: return super(self.__class__, self).insert_text('', from_undo=from_undo)
from kivy.storage.jsonstore import JsonStore store = JsonStore('hello.json') # put some values store.put('tito', name='Mathieu', org='kivy') store.put('tshirtman', name='Gabriel', age=27) # using the same index key erases all previously added key-value pairs store.put('tito', name='Mathieu', age=30) # get a value using a index key and key print('tito is', store.get('tito')['age']) # or guess the key/entry for a part of the key for item in store.find(name='Gabriel'): print('tshirtmans index key is', item[0]) print('his key value pairs are', str(item[1]))
def carregar_conteudo(self): container = self.ids.container container.clear_widgets() titulo1 = Builder.load_string(f''' LabelPergunta: text: 'Modo de Estudo' size_hint: 1, None height: dp('50') ''') container.add_widget(titulo1) for nome_modo in self.modos: modo = Builder.load_string(f''' ToggleCheckBox: text: '{nome_modo}' group: 'modo' size_hint: 1, None height: dp('50') cor_fundo_pressionado: [0.95,0.61,0.07,1] on_release: app.root.get_screen('estudar').modo = '{nome_modo}' ''') container.add_widget(modo) titulo2 = Builder.load_string(f''' LabelPergunta: text: 'Selecionar Matéria' size_hint: 1, None height: dp('50') ''') container.add_widget(titulo2) bd = JsonStore(self.caminho, indent=4, sort_keys=False) chaves = bd.keys() chaves1 = [bd.get(i) for i in chaves] chaves2 = [i for i in chaves] p = dict() for i in range(len(chaves)): p[chaves2[i]] = chaves1[i]['perguntas'] materias = p.copy() for nome_materia in materias.keys(): materia = Builder.load_string(f''' ToggleCheckBox: text: "{nome_materia}" group: 'materia' size_hint: 1, None height: dp('50') cor_fundo_pressionado: [0.95,0.61,0.07,1] on_release: app.root.get_screen('estudar').materia = self.text ''') container.add_widget(materia) bt_final = Builder.load_string(f''' Botao: text: "Iniciar Prova" size_hint: 1, None height: dp('50') cor_fundo: app.color_button_pressed cor_fundo_pressionado: app.color_button on_release: app.root.get_screen('estudar').iniciar_prova() ''') container.add_widget(bt_final)
def __init__(self, **k): super(KivyStudio, self).__init__(**k) self.user_settings = JsonStore( os.path.join(self.user_data_dir, 'user_settings.json')) if not self.user_settings.exists('file-settings'): self.fill_config_settiigs()
class MenuScreen(Screen): price = [] stored_data = ObjectProperty(None) def __init__(self, **kwargs): super().__init__(**kwargs) self.stored_data = JsonStore('info.json') if self.stored_data.exists('mydata'): self.price = self.stored_data.get('mydata')['text'] self.price = [float(i) for i in self.price] else: temp = ['400', '600', '25', '80', '200', '220'] self.stored_data.put('mydata', text=temp) self.price = [float(i) for i in temp] def clear(self): self.choice_type.text = 'Вид плёнки' self.adress.text = '' self.square_meters.text = '0' self.perimeter.text = '0' self.add_corners.text = '0' self.lamp.text = '0' self.soffit.text = '0' self.output.text = 'Информация' self.output.font_size = '36sp' def calculate(self): result = 0.0 try: if self.choice_type.text == 'Фактурная': type_skin = self.price[1] elif self.choice_type.text == 'Глянец, мат, сатин': type_skin = self.price[0] if float(self.square_meters.text) < 0: raise Exception() elif float(self.square_meters.text) < 15: result += ((15 - float(self.square_meters.text)) * 10 + type_skin) * float(self.square_meters.text) else: result += float(self.square_meters.text) * type_skin if float(self.perimeter.text) < 0 or float(self.lamp.text) < 0 \ or float(self.soffit.text) < 0 or float(self.add_corners.text) < 0: raise Exception() result += float(self.perimeter.text) * self.price[2] result += float(self.add_corners.text) * self.price[3] result += float(self.lamp.text) * self.price[4] result += float(self.soffit.text) * self.price[5] if result.is_integer(): result = int(result) self.output.text = "Итого:\n" + str(round(result, 2)) + " руб" self.output.font_size = '36sp' except: self.output.text = "Неверный ввод данных"
def on_enter(self): col_width = kivy.core.window.Window.size[0] / 2 height_spacing = self.score_label_height + self.submit_button_height + self.graph_spacing + \ (2 * self.graph_title_size) height = (kivy.core.window.Window.size[1] - height_spacing) / 2 # First part of the result screen is split in two - questions and graphs layout = GridLayout(rows=len(self.main_app.user_answers) * 2, cols=3) # !/usr/bin/python # -*- coding: utf-8 -*- layout.add_widget( self.get_question_result_grid( user_answers=self.main_app.user_answers, width=col_width)) layout.add_widget(MyLabel(size_hint_x=0.0005)) store = JsonStore("Json/answers.json", encoding='utf-8') map_grid = GridLayout(rows=7, cols=1) map_grid.add_widget( Label(text=store['answers']['graphs_types']['discovered_graph'] [::-1], font_name="fonts/Alef-Regular.ttf", halign='right', size_hint_y=None, height=self.graph_title_size)) map_grid.add_widget(MyLabel(size_hint_y=0.002)) graph_discovered = GraphDisplay(graph=self.main_app.discovered_graph, font_name="fonts/Alef-Regular.ttf", halign='right', dim=(col_width, height)) map_grid.add_widget(graph_discovered) map_grid.add_widget( Label(text=store['answers']['graphs_types']['real_graph'][::-1], font_name="fonts/Alef-Regular.ttf", halign='right', size_hint_y=None, height=self.graph_title_size)) map_grid.add_widget(MyLabel(size_hint_y=0.002)) graph_true = GraphDisplay(graph=self.main_app.current_graph, dim=(col_width, height)) map_grid.add_widget(graph_true) map_grid.add_widget(MyLabel(size_hint_y=0.002)) layout.add_widget(map_grid) self.add_widget(layout) self.res = self.calculate_percentage(self.main_app.user_answers) self.add_widget( Label(text=" {}%;".format(self.res['user_score']) + store['answers']['scores']['subject_score'][::-1] + " {}%;".format(self.res['possible_score']) + store['answers']['scores']['discovered_graph_score'][::-1] + " {}%".format( self.game_grade(self.main_app.discovered_graph, self.main_app.current_graph)) + store['answers']['scores']['nodes_discovered'][::-1], size_hint_y=None, height=self.score_label_height, font_name="fonts/Alef-Regular.ttf", halign='right')) self.submit_button = Button(text=store['answers']['next_button'][::-1], size_hint_y=None, font_name="fonts/Alef-Regular.ttf", halign='right', height=self.submit_button_height) self.submit_button.bind(on_press=self.stop_me) self.add_widget(self.submit_button) self.log_answers()
from kivy.network.urlrequest import UrlRequest from functools import wraps from kivy.storage.jsonstore import JsonStore cache_global = JsonStore('swr_cache.json') def RemoteData(url, memory_only=False, *global_args, **global_kwargs): def swr(func): if memory_only: cache = dict() else: cache = cache_global @wraps(func) def memoized_func(*args, **kw): def callback(): params = func.__code__.co_varnames if isinstance(cache[url], dict): desided_keys = dict( filter(lambda e: e[0] in params, cache[url].items())) func(*args, **kw, **desided_keys) else: raise ValueError( 'Only JSON dict object {} are accepted in swr remote_data.' ) def save_cache(req, res):
def __init__(self, **kwargs): super(WeatherRoot, self).__init__(**kwargs) # <1> self.store = JsonStore("weather_store.json")
def criar_abrir_arquivo(caminho): bd = JsonStore(caminho, indent=4, sort_keys=False) return bd
class MasterDateApp(App): todo_list = None def __init__(self, **kwargs): super(MasterDateApp, self).__init__(**kwargs) self.fb = FireBase(self) self.db = DataBase(self) self.date_keyboard = DateKeyboard() # user num for database entries self.store_file = JsonStore(join(self.user_data_dir, 'store_file.txt')) try: self.storage = self.store_file.get('data')['content'] self.user = self.storage['user_data'] self.user_num = self.user['num'] except KeyError: self.storage = {} self.user = { 'num': str(random.randint(1000000000, 9999999999)), 'level': 1, 'skip_tutorial': 0 } self.storage['user_data'] = self.user self.user_num = self.user['num'] self.save() def save(self): self.store_file.put('data', content=self.storage) def on_stop(self): self.save() def build(self): print('user_num', self.user_num) # Loader.loading_image = 'images/loading.gif' try: filename = join(self.user_data_dir, "refresh_token.txt") with open(filename, 'r') as f: refresh_token = f.read() except FileNotFoundError: # Open login page sm.add_widget(Login(name='login')) return sm else: # if refresh_token and data req = self.fb.exchange_refresh_token(refresh_token) if req['success']: self.id_token = req['id_token'] self.local_id = req['local_id'] self.login_attempts = 0 return self.login() else: # return login login_screen = Login(name='login') login_screen.error_msg.text = 'Expired Token(Login or try again)' login_screen.add_widget(login_screen.try_btn) sm.add_widget(login_screen) return sm def login(self, *args): # return main req = self.fb.get_data() print('app.login') if args and req['success']: # if args, login was called from the login screen sm.add_widget(DepSelect(name='dep_select')) sm.current = 'dep_select' elif req['success']: sm.add_widget(DepSelect(name='dep_select')) return sm else: if req['error'] == 'call_todo': req = self.db.call_todo(self.id_token, self.local_id) if req['success']: print('todo was success') if args: return self.login(1) else: return self.login() # remove this elif self.login_attempts <= 3: print('trying login again') self.login_attempts += 1 if args: return self.login(1) else: return self.login() else: # return a blank screen, open trouble popup, with try again # as partial(self.login, 1) raise Exception('connection') # remove this elif req['error'] == 'request' and self.login_attempts <= 3: print('trying login again') self.login_attempts += 1 if args: return self.login(1) else: return self.login() else: # return a blank screen, open trouble popup, with try again # as partial(self.login, 1) raise Exception('connection') def on_start(self): from kivy.base import EventLoop EventLoop.window.bind(on_keyboard=self.hook_keyboard) def hook_keyboard(self, window, key, *largs): if key == 27: sm.current_screen.back_pressed() # self.stop() return True def on_pause(self): self.save() return True def on_resume(self): # Check connection to DB return True
PROJECT_PATH = PATH_SEPERATOR.join( os.path.realpath(__file__).split(PATH_SEPERATOR)[:-1]) if PATH_SEPERATOR == '/': cmd = "echo $HOME" else: cmd = "echo %USERPROFILE%" out = run_syscall(cmd) DEF_USER = out.split('%s' % PATH_SEPERATOR)[-1] REPOFILE = "%(out)s%(ps)s.kivy-mines%(ps)smines" % { 'out': out.rstrip(), 'ps': PATH_SEPERATOR } DB = JsonStore(REPOFILE) directory = os.path.dirname(REPOFILE) if not os.path.exists(directory): os.makedirs(directory) DB.store_sync() KIVY_VERSION = VERSION HOVER = get_color_from_hex('ACACAC') NORMAL = get_color_from_hex('E2DDD5') RED = get_color_from_hex('990000') COLOR_PALETTE = { 1: "ff0000", 2: "ff8000", 3: "ffff00", 4: "80ff00",
class Timer(BoxLayout): nap_time = ObjectProperty nap = StringProperty nap_button = StringProperty recommend = StringProperty cd_seconds = 0 start = False sound1 = SoundLoader.load('sounds/annoying_alarm.wav') sound1.volume = 1.0 store = JsonStore('store.json') num_of_rec = JsonStore( 'amount_storage.json' ) #used for adding keys into the store variable e.g. {0: time}, {1:time} if num_of_rec.exists('amount'): rec_number = num_of_rec.get('amount')['times'] print rec_number else: num_of_rec.put('amount', times=0) rec_number = 0 def store_recommendation(self, rating): self.store.put(self.rec_number, time=self.cd_seconds / 60, rating=rating) self.rec_number += 1 self.num_of_rec.put('amount', times=self.rec_number) def rating_popup(self): """rating popup asks user how their nap was using a popup""" layout = BoxLayout(orientation='vertical', padding=20, spacing=20) btn1 = Button(text='bad') btn2 = Button(text='good') btn3 = Button(text='great') layout.add_widget(btn1) layout.add_widget(btn2) layout.add_widget(btn3) popup = Popup(title='How did you sleep?', content=layout, size_hint=(None, None), size=(400, 400)) def bad_rating(): self.store_recommendation(0) popup.dismiss() def good_rating(): self.store_recommendation(1) popup.dismiss() def great_rating(): self.store_recommendation(2) popup.dismiss() btn1.bind(on_press=lambda x: bad_rating()) btn2.bind(on_press=lambda x: good_rating()) btn3.bind(on_press=lambda x: great_rating()) popup.open() def create_recommendation(self): listz = [ self.store.get(i[1])['time'] for i in enumerate(self.store.keys()) if self.store.get(i[1])['rating'] > 1 ] rec_num = clt.Counter(listz) return rec_num.most_common()[0][0] def start_var(self): """used to change the global start variable""" self.start = True def stop_var(self): """used to change the global start variable""" self.start = False def countdown_time(self, nap): if self.cd_seconds <= 1: if self.sound1: self.sound1.play() self.stop_var() self.rating_popup() self.clock(self.start) if self.start: self.cd_seconds -= nap minutes, seconds = divmod(self.cd_seconds, 60) self.ids.nap_label.text = ('%02d:%02d' % (int(minutes), int(seconds))) def track_time(self): """This functions initializes the time to seconds from minutes""" cd_seconds = int(self.ids.nap_minutes.text) * 60 return cd_seconds def recommend_time(self): """this function displays the created recommendation to the screen""" rec_num = self.create_recommendation() self.ids.nap_minutes.text = str(rec_num) def reset(self): """resets the look of the screen back""" self.cd_seconds = self.track_time() minutes, seconds = divmod(self.cd_seconds, 60) self.ids.nap_label.text = ('%02d:%02d' % (int(minutes), int(seconds))) def clock(self, stop_start): """this resets kivy's clock function and changes the nap button""" event = Clock.schedule_interval(self.countdown_time, 0) if stop_start or self.cd_seconds <= 0: self.set_alarm() Clock.unschedule(self.countdown_time) self.nap_button.text = "I woke up early" event() else: Clock.unschedule(self.countdown_time) self.nap_button.text = "Time For A Nap" self.reset() def start_countdown(self): "this function starts the other functions" self.cd_seconds = 0 #makes the app countdown from the user sets on the first try try: self.cd_seconds = self.track_time() except: print("You f*****g broke something!") return if self.start: self.stop_var() else: self.start_var() self.clock(self.start) def set_alarm( self ): #this function sets the sound1 variable to whatever is in the naptimer.ini config = NapTimerApp.get_running_app().config sound = config.getdefault("Sound", "Alarms", "Annoying Alarm") if sound == "Annoying Alarm": self.sound1 = SoundLoader.load('sounds/annoying_alarm.wav') elif sound == "Sunday Mass": self.sound1 = SoundLoader.load('sounds/sunday_church.wav') elif sound == "Dulcet Tones": self.sound1 = SoundLoader.load('sounds/Dulcet Tones.m4a')
from kivy.storage.jsonstore import JsonStore from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.floatlayout import FloatLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.image import Image from kivy.uix.label import Label from kivy.uix.popup import Popup from kivy.uix.screenmanager import Screen, ScreenManager from kivy.uix.textinput import TextInput #uix lib #uix lib from kivy.uix.togglebutton import ToggleButton, ToggleButtonBehavior from numpy import ndarray store = JsonStore('storage.json') #from pylint import message kivy.require('1.11.1') #other file #dictionaries #kv filepath Window.size = (800, 800)
class Ml(FloatLayout): dict_children = DictProperty({}) paho = paho server = StringProperty("192.168.xxx") mqtt_state = StringProperty("not connect") client = None read_thread = None storage = JsonStore("data_server.json") storage_widget = JsonStore("widget.json") storage_mqtt_state = JsonStore("mqtt_state.json") child = ListProperty([]) tutup = False rc = 1000 def __init__(self, **kwargs): super(Ml, self).__init__(**kwargs) self.load() self.ids["pc"].on_pilih_widget = self.on_pilih_widget self.client = self.paho.Client( uniqueid.id) #(str(random.randint(1,2000))) self.client.on_connect = self.connecting self.client.on_message = self.on_message Window.bind(on_keyboard=self.back) if self.mqtt_state == "connected": self.connect() def load(self): try: li = [i for i in self.storage_widget] li.reverse() for i in li: if self.storage_widget.get(i)["score"][0] == "saklar": print(i) self.ids["root_widget"].add_widget( Saklar( device_name=self.storage_widget.get(i)["score"][1], topic=self.storage_widget.get(i)["score"][2], status=self.storage_widget.get(i)["score"][3], message1=self.storage_widget.get(i)["score"][4], message2=self.storage_widget.get(i)["score"][5], state=self.storage_widget.get(i)["score"][6], status_color=self.storage_widget.get( i)["score"][7])) if self.storage_widget.get(i)["score"][0] == "slider": print(i) self.ids["root_widget"].add_widget( Pwm(device_name=self.storage_widget.get(i)["score"][1], topic=self.storage_widget.get(i)["score"][2], status=self.storage_widget.get(i)["score"][3], message1=self.storage_widget.get(i)["score"][4], message2=self.storage_widget.get(i)["score"][5], state=self.storage_widget.get(i)["score"][6], status_color=self.storage_widget.get(i)["score"] [7])) if self.storage_widget.get(i)["score"][0] == "monitor": print(i) self.ids["root_widget"].add_widget( Monitor( device_name=self.storage_widget.get(i)["score"][1], topic=self.storage_widget.get(i)["score"][2], status=self.storage_widget.get(i)["score"][3], message1=self.storage_widget.get(i)["score"][4], message2=self.storage_widget.get(i)["score"][5], state=self.storage_widget.get(i)["score"][6], status_color=self.storage_widget.get( i)["score"][7])) self.server = self.storage.get("han")["score"] self.mqtt_state = self.storage_mqtt_state.get("state")["score"] except: pass def start_connect(self, data, state): if state == False: self.server = data self.save(self.server) if self.client: try: print("connecting...") self.connect() except: pass def connect(self): print("connect") if platform == "android": PythonActivity = autoclass('org.kivy.android.PythonActivity') PythonActivity.toastError("connecting...") try: if platform == "android": PythonActivity = autoclass('org.kivy.android.PythonActivity') PythonActivity.toastError("connected") self.mqtt_state = "connected" self.storage_mqtt_state.put("state", score=self.mqtt_state) self.client.connect(self.server, keepalive=5) self.client.loop_start() except: if platform == "android": PythonActivity = autoclass('org.kivy.android.PythonActivity') PythonActivity.toastError("failed to connect to server") self.mqtt_state = "not connect" self.storage_mqtt_state.put("state", score=self.mqtt_state) def connecting(self, client, userdata, flags, rc): self.rc = rc if self.client: self.client.subscribe("#") def disconnecting(self, client, userdata, rc, properties): print(rc) def on_message(self, client, userdata, message): self.mqtt_masuk = str(message.payload.decode("utf-8")) print(self.mqtt_masuk) tpc = message.topic for i in self.ids["root_widget"].children: if i.topic == tpc: i.status = self.mqtt_masuk def save(self, server): self.storage.put("han", score=server) def on_pilih_widget(self, data): if data == "saklar": self.ids["root_widget"].add_widget(Saklar()) if data == "slider": self.ids["root_widget"].add_widget(Pwm()) if data == "monitor": self.ids["root_widget"].add_widget(Monitor()) self.ids["pc"].posisi = 2 def back(self, window, key, *largs): if key == 27: self.save_widget() def save_widget(self): self.storage_widget.clear() for i in self.ids["root_widget"].children: self.storage_widget.put(str(i), score=[ i.tittle, i.device_name, i.topic, i.status, i.message1, i.message2, i.state, i.status_color ])
# @Last modified time: 21-Feb-2018 # @License: Apache license vesion 2.0 import config from valle_libs.valleorm.qson import * from models.db import * from datetime import datetime from kivy.storage.jsonstore import JsonStore import time import json import os path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) url_db = os.path.join(path, "db", "sync.json") db = JsonStore(url_db) class SyncVentasSender(QSonSender): db_name = "ventas" url = config.URL_SERVER + "/simpleapi/" class SyncClasesSender(QSonSender): db_name = "clases" url = config.URL_SERVER + "/simpleapi/" def on_success(obj, result): if result["success"] == True: text_hora = str(datetime.now())
class Locations(MDApp): def build(self): if platform == 'android': perms = ["android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.CAMERA", "android.permission.ACCESS_FINE_LOCATION"] haveperms = utils.acquire_permissions(perms) self.gps = plyer.gps self.gps.configure(self.gps_onlocation, self.gps_onstatus) import my_camera self.camera = my_camera.MyAndroidCamera() Window.bind(on_keyboard=self.popScreen) os.makedirs(utils.getDataDir() + "/images", exist_ok=True) self.markerMap = {} self.settings_cls = SettingsWithSidebar self.curMarker = None self.relocated = 0 self.dialog = None self.baseConfig = config.Config() self.error = self.baseConfig.getErrors() if self.error: Clock.schedule_once(self.show_error, 2) self.store = JsonStore("base.json") self.root = Page() try: base = self.store.get("base")["base"] self.baseConfig.getBase(self.base) except: base = self.baseConfig.getNames()[0] print("base", base) print("----------- /data/user/0/de.adfcmuenchen.abstellanlagen") utils.walk("/data/user/0/de.adfcmuenchen.abstellanlagen") # print("----------- cwd", os.getcwd()) # utils.walk(".") # print("------------getDataDir", utils.getDataDir()) # utils.walk(utils.getDataDir()) # print("------------getExternalFilesDir", utils.getExternalFilesDir()) # utils.walk(utils.getExternalFilesDir()) self.executor = ThreadPoolExecutor(max_workers=1) self.future = None laststored = self.getConfigValue("gespeichert") if not laststored: self.setConfigValue("gespeichert", time.strftime("%Y.%m.%d %H:%M:%S")) self.useGoogle = bool(self.getConfigValue("useGoogle")) self.setup(base) return self.root def setup(self, base): self.selected_base = base self.root.toolbar.title = self.selected_base self.root.datenbtn.text = self.selected_base self.store.put("base", base=self.selected_base) self.baseJS = self.baseConfig.getBase(self.selected_base) self.stellen = self.baseJS.get("gps").get("nachkommastellen") # self.root.sm.clear_widgets() does not work !? sm_screens = self.root.sm.screens[:] self.root.sm.clear_widgets(sm_screens) sm_screens = None self.karte = Karte(name="Karte") self.root.sm.add_widget(self.karte) self.mapview = self.karte.ids.mapview self.mapview.map_source = "osm-de" self.mapview.map_source.min_zoom = self.baseConfig.getMinZoom(self.selected_base) self.mapview.map_source.max_zoom = 19 self.mapview.map_source.bounds = self.baseConfig.getGPSArea(self.selected_base) # Hack, trying to fix random zoom bug # self.mapview._scatter.scale_min = 0.5 # MUH was 0.2 # self.mapview._scatter.scale_max: 2.0 # MUH was 3!? self.images = Images(self, name="Images") self.root.sm.add_widget(self.images) self.single = Single(self, name="Single") self.root.sm.add_widget(self.single) self.kamera = Kamera(self) self.account = Account(name="Account") self.root.sm.add_widget(self.account) self.daten = Daten(self, name="Daten") self.root.sm.add_widget(self.daten) self.zusatz = Zusatz(self, name="Zusatz") self.root.sm.add_widget(self.zusatz) self.pushScreen("Karte") if self.future is not None: self.future.result() self.future = self.executor.submit(self.setup2) def setup2(self): try: self.dbinst = db.DB.instance() self.dbinst.initDB(self) except Exception as e: self.message("Kann DB nicht öffnen:" + str(e)) raise (e) if self.useGoogle: try: self.message("Mit Google Sheets verbinden") self.gsheet = gsheets.GSheet(self) except Exception as e: self.message("Kann Google Sheets nicht erreichen:" + str(e)) raise (e) try: userInfo = self.gsheet.get_user_info(self.gsheet.getCreds()) self.message("Mit Google Photos verbinden als " + userInfo["name"]) self.gphoto = gphotos.GPhoto(self) except Exception as e: self.message("Kann Google Photos nicht erreichen:" + str(e)) raise (e) else: self.serverIntf = serverintf.ServerIntf(self) self.loadSheet(False) def show_markers(self, fromSheets, *args): with Spinner(): clat = self.mapview.centerlat clon = self.mapview.centerlon # roughly a square on the map delta = float(self.getConfigValue("delta", "5")) / 1000.0 minlat = clat - delta maxlat = clat + delta minlon = clon - 2 * delta maxlon = clon + 2 * delta for k in list(self.markerMap.keys()): # lat, lon = k.split(":") # lat = float(lat) # lon = float(lon) # if not (minlat < lat < maxlat and minlon < lon < maxlon): # markerOld = self.markerMap.get(k) # self.mapview.remove_marker(markerOld) # del self.markerMap[k] markerOld = self.markerMap.get(k) self.mapview.remove_marker(markerOld) del self.markerMap[k] if fromSheets: if self.useGoogle: self.message("Lade Daten von Google Sheets") try: sheetValues = self.gsheet.getValuesWithin(minlat, maxlat, minlon, maxlon) self.dbinst.fillWithSheetValues(sheetValues) except Exception as e: self.message("Konnte Daten nicht von Google Sheets laden: " + str(e)) raise (e) else: self.message("Lade Daten vom LocationsServer") try: dbValues = self.serverIntf.getValuesWithin(minlat, maxlat, minlon, maxlon) self.dbinst.fillWithDBValues(dbValues) except Exception as e: utils.printEx("Konnte Daten nicht vom LocationsServer laden", e) self.message("Konnte Daten nicht vom LocationsServer laden: " + str(e)) raise (e) self.message("Lade Map Marker") markers = self.dbinst.getMarkerLocs(minlat, maxlat, minlon, maxlon) self.show_markers2(markers) @mainthread def show_markers2(self, markers): for marker in markers: self.add_marker(marker[0], marker[1]) def show_account(self, *args): self.pushScreen("Account") def clear(self, *args): cur_screen = self.root.sm.current_screen if cur_screen.name == "Karte": return if cur_screen.name == "Daten": self.daten.clear() lat, lon = self.centerLatLon() self.add_marker(round(lat, self.stellen), round(lon, self.stellen)) return if cur_screen.name == "Zusatz": self.zusatz.clear() return if cur_screen.name == "Images": self.msgDialog("Auswahl", "Bitte ein Bild auswählen") return if cur_screen.name == "Single": src = cur_screen.im.source os.remove(src) src = os.path.basename(src) lat, lon = self.centerLatLon() self.dbinst.delete_images(lat, lon, src) self.add_marker(round(lat, self.stellen), round(lon, self.stellen)) self.show_daten(False) @mainthread def msgDialog(self, titel, text): if self.dialog is not None: self.dialog_dismiss() self.dialog = MDDialog(size_hint=(.8, .4), title=titel, text=text, buttons=[ MDFlatButton( text="Weiter", text_color=self.theme_cls.primary_color, on_press=self.dialog_dismiss )]) self.dialog.auto_dismiss = False self.dialog.open() def dialog_dismiss(self, *args): self.dialog.dismiss(animation=False, force=True) self.dialog = None def loadSheet(self, newCenter): if newCenter and self.future.running(): return if newCenter: lat = self.mapview.lat lon = self.mapview.lon self.store.put("latlon", lat=lat, lon=lon) else: try: lat = self.store.get("latlon")["lat"] lon = self.store.get("latlon")["lon"] except: lat = lon = 0 if lat == 0 or lon == 0: gps = self.baseJS.get("gps") lat = gps.get("center_lat") lon = gps.get("center_lon") self.center_on(lat, lon) if newCenter: # called from UI self.future = self.executor.submit(self.show_markers, True) else: self.show_markers(False) def storeImages(self, newImgs): # tuples to list, skip if image_url=row[7] is already set unsavedImgs = [list(row) for row in newImgs if not row[7].startswith("http")] # don't store already saved images again in gphoto: savedImgs = [list(row) for row in newImgs if row[7].startswith("http")] photo_objs = [{"filepath": utils.getDataDir() + "/images/" + row[6], "desc": row[6][0:row[6].index(".jpg")]} for row in unsavedImgs] # if len(photo_objs) > 0: # self.gphoto.upload_photos(photo_objs) pcnt = len(photo_objs) for i, photo_obj in enumerate(photo_objs): self.message(f"Speichere Bild {i + 1} von {pcnt}") if self.useGoogle: self.gphoto.upload_photos([photo_obj]) else: self.serverIntf.upload_photos([photo_obj]) for i, row in enumerate(unsavedImgs): old_image_path = row[6] new_image_path = photo_objs[i]["id"] new_image_url = photo_objs[i]["url"] self.dbinst.update_imagepath(old_image_path, new_image_path, new_image_url, row[4], row[5]) row[6] = new_image_path row[7] = new_image_url # store all of them in gsheets (duplicates removed by gsheet script) # or in Locationsserver DB unsavedImgs.extend(savedImgs) return unsavedImgs, photo_objs def storeSheet(self): if self.checkAlias(): if self.future.running(): self.msgDialog("Läuft noch", "Ein früherer Speichervorgang läuft noch!") return self.future = self.executor.submit(self.storeSheet2) def storeSheet2(self, *args): with Spinner(): try: laststored = self.getConfigValue("gespeichert") newvals = self.dbinst.getNewOrChanged(laststored) # special case images, store them first in gphotos newImgs = newvals[self.baseJS["db_tabellenname"] + "_images"] newImgs, photo_objs = self.storeImages(newImgs) imgCnt = len(newImgs) newvals[self.baseJS["db_tabellenname"] + "_images"] = newImgs recCnt = 0 self.message("Speichere Daten") for sheet_name in newvals.keys(): vals = newvals[sheet_name] if len(vals) > 0: recCnt += len(vals) if self.useGoogle: self.gsheet.appendValues(sheet_name, vals) else: self.serverIntf.appendValues(sheet_name, vals) self.setConfigValue("gespeichert", time.strftime("%Y.%m.%d %H:%M:%S")) for obj in photo_objs: os.remove(obj["filepath"]) self.msgDialog("Gespeichert", f"Es wurden {imgCnt} Fotos und {recCnt} neue oder geänderte Datensätze gespeichert") self.dbinst.deleteAll() except Exception as e: self.message("Konnte nicht in Google Drive oder Photos speichern:" + str(e)) raise (e) self.show_markers(True) def center_on(self, lat, lon): self.mapview.set_zoom_at(17, 0, 0, 2.0) self.mapview.center_on(lat, lon) self.mapview.centerlat = lat self.mapview.centerlon = lon self.relocated = 0 def map_relocated(self): self.relocated += 1 def centerLatLon(self): # if self.relocated == 1, the map has not moved since the last center_on if self.relocated == 1: return (self.mapview.centerlat, self.mapview.centerlon) return (self.mapview.lat, self.mapview.lon) def gps_onlocation(self, **kwargs): lat = kwargs["lat"] lon = kwargs["lon"] self.center_on(float(lat), float(lon)) self.gps.stop() def gps_onstatus(self, **kwargs): print("onsta", kwargs) def gps_fix(self, btn): # cannot get a continuous update to work, onlocation is called not more often than every 20 seconds # so update GPS loc once per button press if platform != 'android': return self.gps.start(minTime=10, minDistance=0) def show_images(self, *args): self.pushScreen("Images") self.images.show_images() def show_daten(self, delay): if self.checkAlias(): self.daten.setDaten() self.center_on(self.daten.lat, self.daten.lon) if delay and self.root.sm.current_screen.name == "Karte": Clock.schedule_once(self.show_daten2, 1) else: self.pushScreen("Daten") def show_daten2(self, *args): self.pushScreen("Daten") def on_pause(self): print("on_pause") # lat, lon = self.centerLatLon() # self.store.put("latlon", lat=lat, lon=lon) return True def on_stop(self): print("on_stop") return self.on_pause() def on_resume(self): print("on_resume") # base = self.store.get("base")["base"] # self.setup(base) return True def change_base(self, *args): self.dialog_dismiss() items = self.items for item in items: if item.ids.check.active: t = item.text if t != self.selected_base: self.setup(t) return def show_bases(self, *args): basen = list(self.baseConfig.getNames()) items = [ItemConfirm(text=base) for base in basen] x = basen.index(self.selected_base) for i, item in enumerate(items): items[i].ids.check.active = i == x self.items = items buttons = [MDFlatButton(text="OK", text_color=self.theme_cls.primary_color, on_press=self.change_base)] if self.dialog is not None: self.dialog_dismiss() self.dialog = MDDialog(size_hint=(.8, .4), type="confirmation", title="Auswahl der Datenbasis", text="Bitte Datenbasis auswählen", items=items, buttons=buttons) self.dialog.auto_dismiss = False # this line costed me two hours! Without, change_base is not called! self.dialog.open() def set_icon(self, instance_check, x): instance_check.active = True check_list = instance_check.get_widgets(instance_check.group) for check in check_list: if check != instance_check: check.active = False def createMarker(self, lat, lon): img = self.dbinst.existsImage(lat, lon) if self.baseJS.get("name") == "Abstellanlagen": col = self.dbinst.getRedYellowGreen(lat, lon) elif self.dbinst.existsDatenOrZusatz(lat, lon): col = "red" else: col = None if not img and col is None: return None if col is None: col = "red" if img: src = col + "_plus48.png" else: src = col + "48.png" mm = MyMapMarker(lat=lat, lon=lon, source=utils.getCurDir() + "/icons/" + src) return mm def add_marker(self, lat, lon): lat_round = round(lat, self.stellen) lon_round = round(lon, self.stellen) markerMapKey = str(lat_round) + ":" + str(lon_round) markerOld = self.markerMap.get(markerMapKey, None) markerNew = self.createMarker(lat_round, lon_round) if markerOld is not None: self.mapview.remove_marker(markerOld) if markerNew is None: del self.markerMap[markerMapKey] else: self.mapview.add_marker(markerNew) self.markerMap[markerMapKey] = markerNew def clickMarker(self, marker): self.curMarker = marker self.center_on(marker.lat, marker.lon) self.show_daten(True) def do_capture(self, *args): if self.checkAlias(): # and self.root.sm.current_screen.name == "Daten": self.daten.setDaten() self.kamera.do_capture(self.daten.lat, self.daten.lon) def checkAlias(self): if not self.account.ids.aliasname.text: self.msgDialog("Account", "Bitte den Aliasnamen ausfüllen") self.pushScreen("Account") return False self.dbinst.aliasname = self.account.ids.aliasname.text return True def show_error(self, *args): self.msgDialog("Konfigurationsfehler", self.error) def pushScreen(self, nextScreen): self.lastScreen = self.root.sm.current_screen.name self.root.sm.current = nextScreen def popScreen(self, window, key, *largs): if key != 27: return True if self.lastScreen is None: if self.dialog is not None: self.dialog_dismiss() self.dialog = MDDialog(size_hint=(.8, .4), title="Beenden?", text="Möchten Sie die App beenden?", buttons=[ MDFlatButton( text="Ja", text_color=self.theme_cls.primary_color, on_press=self.stopApp), MDFlatButton( text="Nein", text_color=self.theme_cls.primary_color, on_press=self.dialog_dismiss), ]) self.dialog.auto_dismiss = False # !!! self.dialog.open() else: self.root.sm.current = self.lastScreen self.lastScreen = None return True configDefaults = { # 'boolexample': True, # 'numericexample': 10, # 'stringexample': 'somestring', # 'optionsexample': 'options2', # 'pathexample': 'c:/temp', 'gespeichert': '', 'maxdim': 1024, 'thumbnaildim': 200, 'useGoogle': False, 'delta': 5, 'serverName': "raspberrylan.1qgrvqjevtodmryr.myfritz.net", 'serverPort': 80, 'restoreDefaults': False, } # see https://www.youtube.com/watch?v=oQdGWeN51EE def build_config(self, config): config.setdefaults('Locations', self.configDefaults) def build_settings(self, settings): settings_json = json.dumps([ {'type': 'title', 'title': 'Einstellungen'}, {'type': 'string', 'title': 'Gespeichert', 'desc': 'Datum des letzten Speicherns', 'section': 'Locations', 'key': 'gespeichert'}, {'type': 'numeric', 'title': 'Max Dim', 'desc': 'Max Größe der Photos vom LocationsServer oder Goggle Photos', 'section': 'Locations', 'key': 'maxdim'}, {'type': 'numeric', 'title': 'Vorschaubilder Dim', 'desc': 'Größe der Vorschaubilder', 'section': 'Locations', 'key': 'thumbnaildim'}, {'type': 'bool', 'title': 'Speichern mit Google', 'desc': 'On: Gsheets, GPhotos, Off: LocationsServer', 'section': 'Locations', 'key': 'useGoogle'}, {'type': 'numeric', 'title': 'Größe der MapMarker-Region', 'desc': 'Bestimmt die Größe der Kartenfläche, die mit MapMarkern gefüllt ist', 'section': 'Locations', 'key': 'delta'}, {'type': 'string', 'title': 'Server URL', 'desc': 'Name des LocationsServer', 'section': 'Locations', 'key': 'serverName'}, {'type': 'numeric', 'title': 'Server Portnummer', 'desc': 'Portnummer des LocationsServer', 'section': 'Locations', 'key': 'serverPort'}, {'type': 'bool', 'title': 'Default-Werte wiederherstellen', 'desc': 'Hier sichtbar leider nur nach Neustart, aber schon wirksam!', 'section': 'Locations', 'key': 'restoreDefaults'}, # {'type': 'bool', # 'title': 'A boolean setting', # 'desc': 'Boolean description text', # 'section': 'Locations', # 'key': 'boolexample'}, # {'type': 'numeric', # 'title': 'A numeric setting', # 'desc': 'Numeric description text', # 'section': 'Locations', # 'key': 'numericexample'}, # {'type': 'options', # 'title': 'An options setting', # 'desc': 'Options description text', # 'section': 'Locations', # 'key': 'optionsexample', # 'options': ['option1', 'option2', 'option3']}, # {'type': 'path', # 'title': 'A path setting', # 'desc': 'Path description text', # 'section': 'Locations', # 'key': 'pathexample'} ]) settings.add_json_panel('Locations', self.config, data=settings_json) def on_config_change(self, config, section, key, value): print(config, section, key, value) if section != "Locations": return if key == "useGoogle": self.useGoogle = bool(int(value)) # value is "0" or "1" !?! self.dbinst.deleteAll() self.gsheet = None self.gphoto = None self.serverIntf = None self.setup(self.selected_base) if key == "restoreDefaults": defaults = self.configDefaults.copy() del defaults["gespeichert"] self.config.setall(section, defaults) self.config.write() def getConfigValue(self, param, fallback=""): if param == "useGoogle": return self.config.getboolean("Locations", param) return self.config.get("Locations", param, fallback=fallback) def setConfigValue(self, param, value): self.config.set("Locations", param, value) self.config.write() def stopApp(self, *args): if self.future is not None and not self.future.done(): self.msgDialog("Bitte warten", "Das Speichern ist noch nicht beendet!") return self.stop() @mainthread def message(self, m): # toast(m, duration=5.0) t = Toast(duration=5) t.toast(m)