def prediccion(self, producto, cantidad, fecha): print("seccion prediccion") fechaN= datetime.datetime.strptime(fecha, '%Y-%m-%d').date() archivo_datos= open(producto+"_Tabla.txt", "r") #abrir el archivo renglones= archivo_datos.readlines() #se obtienen los renglones del txt archivo_datos.close() print(renglones) x_numero_elementos=[] y_dias=[] for i in renglones: largo_cadena= len(i) if(largo_cadena==4): numero=int(i[0]) dias=int(i[2]) x_numero_elementos.append(numero) y_dias.append(dias) elif(largo_cadena==5): if(i[1]==" "): numero=int(i[0]) dias=int(i[2:4]) x_numero_elementos.append(numero) y_dias.append(dias) elif(i[2]==" "): numero=int(i[0:2]) dias=int(i[3]) x_numero_elementos.append(numero) y_dias.append(dias) elif(largo_cadena==6): numero=int(i[0:2]) dias=int(i[3:5]) x_numero_elementos.append(numero) y_dias.append(dias) print(x_numero_elementos) print(y_dias) x= np.array(x_numero_elementos) print(x) y= np.array(y_dias) print(y) n=len(renglones) print(n) if(n==0 or n==1): print("No hay suficientes datos para generar la predicción") cadenaDialog="No hay suficientes datos para generar la predicción" else: sumx= sum(x) print(sumx) sumy= sum(y) print(sumy) sumx2= sum(x*x) print(sumx2) sumxy= sum(x*y) print(sumxy) promx= sumx/n print(promx) promy= sumy/n print(promy) m=((n*sumxy)-(sumx*sumy))/((n*sumx2)-(sumx*sumx)) b= promy-(m*promx) print(m, b) cant= int(cantidad) fx= int(m*cant+b) print("Tu producto pueden terminarse en ", fx," dias") pred= fechaN + datetime.timedelta(days=fx) print("La fecha prevista para que se termine tu producto es: ",pred) fechaPred=str(pred) cadenaDialog="La fecha prevista para que se termine tu producto es: "+fechaPred self.dialog= MDDialog(title = "Prediccion de faltantes", #CUADROD DE DIALOGO PARA OBTENER EL PERIODO DEL REPORTE DE GASTOS text = cadenaDialog, size_hint=[.9, .9], auto_dismiss=True, buttons=[ MDFlatButton( text="Cerrar", on_release=self.dialog_close) ] ) self.dialog.open() ###crear el txt con las fechas predichas archivo_fechasPred= open(producto+"_FechasPred.txt", "a") archivo_fechasPred.write(fechaPred+"\n") archivo_fechasPred.close() return
def select_to_rename(self): self.str_error = MDDialog( text="Select Something to Rename it", radius=[30, 30, 30, 30],) self.str_error.open()
class MainApp(MDApp): #Assign the data for the quick actions button data = { 'folder-plus': 'New Folder', 'rename-box': 'Rename', 'content-cut': 'Cut', 'content-copy': 'Copy', 'delete': 'Delete' } #The main app building process def build(self): Builder.load_file("file_explorer.kv") #Add the login screen and main screen to the screen manager sm.add_widget(LoginScreen(name='login_screen')) sm.add_widget(MainScreen(name='main_screen')) return sm # return our screen Manager #This function is called when you want to create a new folder def show_new_folder(self): self.folder_name = MDTextField( hint_text = "Enter A valid Folder name", required = True) self.dialog = MDDialog( title="New Folder", type="custom", content_cls=self.folder_name, radius = (30,30,30,30), buttons=[ MDFlatButton( text="Create",on_press=lambda a:MainApp.create_folder(self), ), ], ) self.dialog.open() return self.folder_name #Actually creates the new folder def create_folder(self): self.dialog.dismiss() MainScreenvar =sm.get_screen('main_screen') try: os.mkdir(os.path.join(MainScreenvar.ids.filechooser_icon.path, self.folder_name.text)) MainScreenvar.ids.filechooser_icon._update_files() except: Errors.folder_cannot_be_created(self) def show_rename_element(self): MainScreenvar = sm.get_screen('main_screen') self.element_name = MDTextField( hint_text = "Enter A valid new name", required = True) self.dialog = MDDialog( title="Rename", type="custom", content_cls=self.element_name, radius = (30,30,30,30), buttons=[ MDFlatButton( text="Rename",on_press=lambda a:MainApp.rename_element(self), ), ], ) if len(MainScreenvar.ids.filechooser_icon.selection) == 1: self.dialog.open() return self.element_name else: Errors.select_to_rename(self) #This function is called whenever an element needs to be renamed def rename_element(self): try: MainScreenvar = sm.get_screen('main_screen') self.dialog.dismiss() self.from_location = MainScreenvar.ids.filechooser_icon.selection[0] self.to_location = os.path.join(os.path.split(self.from_location)[0], self.element_name.text) self.to_location_with_ext = self.to_location + os.path.splitext(self.from_location)[1] os.rename(self.from_location, self.to_location_with_ext) MainScreenvar.ids.filechooser_icon._update_files() except: Errors().element_cannot_be_renamed(self)
def no_file_in_cart(self): self.nfinc_error = MDDialog( text="There are no files in the filecart, please select a file", radius=[30, 30, 30, 30], ) self.nfinc_error.open()
def no_undo_history(self): self.nuh_error = MDDialog( text="There is nothing left to undo", radius=[30, 30, 30, 30],) self.nuh_error.open()
class Errors(MDDialog): #This error message is displayed when no valid selection is selected but the copy or cut function has been called #Also called when a user selects a drive which is not a valid selection def passwd_not_crct(self): self.pnc_error = MDDialog( text="Hey you got the password or the userid wrong...try again", radius=[30, 30, 30, 30],) self.pnc_error.open() def file_not_selected(self): self.fns_error = MDDialog( text="Please Select a file or a folder to move to the filecart", radius=[30, 30, 30, 30],) self.fns_error.open() #This error message is displayed when a selection is already present in the filecart but user is attempting to add again def file_already_exists(self): self.fae_error = MDDialog( text="This file/Directory has already been added to the Filecart", radius=[30, 30, 30, 30], ) self.fae_error.open() #This error mesage is displayed when the paste function is called without any entries present in the filecart def no_file_in_cart(self): self.nfinc_error = MDDialog( text="There are no files in the filecart, please select a file", radius=[30, 30, 30, 30], ) self.nfinc_error.open() #This error is displayed if any internal error occurs where an unknown cvalueis read from the database def there_was_a_problem(self): self.twap_error = MDDialog( text="There is a problem. Please close and open the program again", radius=[30, 30, 30, 30],) self.twap_error.open() #This error is displayed when there is nothing left for the undo operation def no_undo_history(self): self.nuh_error = MDDialog( text="There is nothing left to undo", radius=[30, 30, 30, 30],) self.nuh_error.open() #This error is displayed when there is an error in the creation of a folder def folder_cannot_be_created(self): self.fcbc_error = MDDialog( text="The Folder Could Not Be Created", radius=[30, 30, 30, 30],) self.fcbc_error.open() #This error is displayed when a user must select something to rename def select_to_rename(self): self.str_error = MDDialog( text="Select Something to Rename it", radius=[30, 30, 30, 30],) self.str_error.open() #This error is displayed when the file cannot be renamed def element_cannot_be_renamed(self): self.ecbc_error = MDDialog( text="The selected item cannot be renamed", radius=[30, 30, 30, 30],) self.ecbc_error.open()
def file_not_selected(self): self.fns_error = MDDialog( text="Please Select a file or a folder to move to the filecart", radius=[30, 30, 30, 30],) self.fns_error.open()
def checkUpdates(self, ava=False, d=False): # print(ava) upCURL = 'https://raw.githubusercontent.com/biplobsd/proxySpeedTestApp/master/updates.json' # from json import load # with open('updates.json', 'r') as read: # updateinfo = load(read) # toast("Checking for any updates ...") try: updateinfo = get(upCURL).json() except: updateinfo = { "version": float(self.version), "messages": "", "changelogs": "", "force": "false", "release": { "win": "", "linux": "", "android": "", "macosx": "", "unknown": "", "kivy_build": "" } } # toast("Faild app update check!") if updateinfo: try: appLink = updateinfo["release"][platform] except KeyError: return title = f"App update v{updateinfo['version']}" msg = "You are already in latest version!" b1 = "CENCEL" force = False if updateinfo['version'] > float(self.version) and appLink != "": if updateinfo['messages']:title = updateinfo['messages'] msg = "" b2 = "DOWNLOAD" force = bool(updateinfo['force']) if force: b1 = "EXIT" ava = True else: b2 = "CHECK" self.updateDialog = MDDialog( title=title, text=msg+updateinfo['changelogs']+f"\n\n[size=15]Force update: {force}[/size]", auto_dismiss=False, buttons=[ MDFlatButton( text=b1, text_color=self.theme_cls.primary_color, on_release=lambda x: self.updateDialog.dismiss() if b1 == "CENCEL" else self.stop() ), MDRaisedButton( text=b2, on_release=lambda x:open_link(appLink) if b2 == "DOWNLOAD" else self.FCU(self.updateDialog), text_color=self.theme_cls.primary_color ), ], ) self.updateDialog.ids.title.theme_text_color = "Custom" self.updateDialog.ids.title.text_color = self.theme_cls.primary_light if ava:self.updateDialog.open()
class TestNavigationDrawer(MDApp): def close_dialog(self, obj): self.dialog.dismiss() def reset(self): self.root.ids.moisture.text = "" self.root.ids.nitrogen.text = "" self.root.ids.potassium.text = "" self.root.ids.phosphorus.text = "" def predict(self): if (self.root.ids.moisture.text == "" or self.root.ids.nitrogen.text == "" or self.root.ids.phosphorus.text == "" or self.root.ids.potassium.text == ""): alert1 = "Insufficient Data" close_button1 = MDFlatButton(text="Dismiss", on_release=self.close_dialog) self.dialog = MDDialog(title="Warning", text=alert1, radius=[20, 7, 20, 7], size_hint=(0.75, 0.8), buttons=[close_button1]) self.dialog.open() return num1 = np.asfarray(self.root.ids.moisture.text, float) num2 = np.asfarray(self.root.ids.nitrogen.text, float) num3 = np.asfarray(self.root.ids.phosphorus.text, float) num4 = np.asfarray(self.root.ids.potassium.text, float) result = Feedforward.output_results(num1, num2, num3, num4) # Display the result close_button2 = MDFlatButton(text="Dismiss", on_release=self.close_dialog) self.dialog = MDDialog(title="Crop Suggestions", type="simple", items=[ Item(text=result[0], source="wheat.png"), Item(text=result[1], source="wheat.png"), Item(text=result[2], source="wheat.png"), Item(text=result[3], source="wheat.png"), Item(text=result[4], source="wheat.png") ], radius=[20, 7, 20, 7], size_hint=(0.75, 0.8), buttons=[close_button2]) self.dialog.open() def build(self): self.theme_cls.primary_palette = "Green" return Builder.load_string(KV) def on_start(self): for crop in sorted(Feedforward.labels): card = MDCard(orientation='vertical', size_hint=(None, None), size=(self.root.width, 300)) imgr = Image(source="images/" + str(crop) + str(".jpg"), size_hint_y=0.8, allow_stretch="True", keep_ratio="False") lbl = MDLabel(text=str(crop), size_hint_y=0.2, halign='center', valign='center') card.add_widget(imgr) card.add_widget(lbl) self.root.ids.md_list.add_widget(card)
class KitchenSinkDialogs(ThemableBehavior, Screen): app = ObjectProperty() simple_dialog = None alert_dialog = None custom_dialog = None confirmation_dialog = None def show_example_confirmation_dialog(self): if not self.confirmation_dialog: self.confirmation_dialog = MDDialog( title="Phone ringtone", type="confirmation", items=[ KitchenSinkItemConfirm(text=i) for i in [ "Callisto", "Luna", "Night", "Solo", "Phobos", "Diamond", "Sirena", "Red music", "Allergio", "Magic", "Tic-tac", ] ], buttons=[ MDFlatButton( text="CANCEL", text_color=self.app.theme_cls.primary_color, ), MDFlatButton(text="OK", text_color=self.app.theme_cls.primary_color), ], ) self.confirmation_dialog.md_bg_color = self.theme_cls.bg_dark self.confirmation_dialog.open() def show_example_simple_dialog(self): if not self.simple_dialog: self.simple_dialog = MDDialog( title="Set backup account", type="simple", items=[ KitchenSinkOneLineLeftAvatarItem( text="*****@*****.**", source= f"{os.environ['KITCHEN_SINK_ASSETS']}heattheatr.png", ), KitchenSinkOneLineLeftAvatarItem( text="*****@*****.**", source= f"{os.environ['KITCHEN_SINK_ASSETS']}artemsbulgakov.png", ), KitchenSinkOneLineLeftAvatarItem( text="Add account", source= f"{os.environ['KITCHEN_SINK_ASSETS']}twitter-round.png", ), ], ) self.simple_dialog.md_bg_color = self.theme_cls.bg_dark self.simple_dialog.open() def show_example_custom_dialog(self): if not self.custom_dialog: self.custom_dialog = MDDialog( title="Address:", type="custom", content_cls=KitchenSinkDialogsCustomContent(), buttons=[ MDFlatButton( text="CANCEL", text_color=self.app.theme_cls.primary_color, ), MDFlatButton(text="OK", text_color=self.app.theme_cls.primary_color), ], ) self.custom_dialog.md_bg_color = self.theme_cls.bg_dark self.custom_dialog.open() def show_example_alert_dialog(self): if not self.alert_dialog: self.alert_dialog = MDDialog( title="Reset settings?", text= "This will reset your device to its default factory settings.", buttons=[ MDFlatButton( text="CANCEL", text_color=self.app.theme_cls.primary_color, ), MDFlatButton( text="ACCEPT", text_color=self.app.theme_cls.primary_color, ), ], ) self.alert_dialog.md_bg_color = self.theme_cls.bg_dark self.alert_dialog.open()
class ProxySpeedTestApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.icon = f"{environ['KITCHEN_SINK_ASSETS']}icon.png" self.version = __version__ self.theme_cls.primary_palette = "LightBlue" self.dialog_change_theme = None self.toolbar = None self.scaning = Queue() self.running = Queue() self.currentSpeed = Queue() self.pbar0 = Queue() self.pbar1 = Queue() self.pbar2 = Queue() self.totalpb = Queue() configs = dbRW.getAllConfigs() mirrors = dbRW.getAllMirrors() self.selLId = configs[0][2] if self.selLId: totalScan = dbRW.getProxysInxTS(self.selLId)[0] getips = dbRW.getAllCurrentProxys(self.selLId) protocol = getips[0][4] self.scan_list = [] if self.selLId: for l in getips: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6]}) self.theme_cls.theme_style = configs[0][0] miInx = configs[0][1] self.configs = { 'protocol': protocol if self.selLId else 'http', 'mirror': mirrors[miInx][0], 'timeout': int(configs[0][3]), 'fileSize': int(configs[0][4]), 'miInx': miInx, 'proxysInx': [], 'mirrors': mirrors, 'proxys': getips if self.selLId else[], 'totalScan': totalScan if self.selLId else 0 } # def on_resume(self): # self.ads.request_interstitial() def changeThemeMode(self, inst): self.theme_cls.theme_style = inst dbRW.updateThemeMode(inst) def checkUpdates(self, ava=False, d=False): # print(ava) upCURL = 'https://raw.githubusercontent.com/biplobsd/proxySpeedTestApp/master/updates.json' # from json import load # with open('updates.json', 'r') as read: # updateinfo = load(read) # toast("Checking for any updates ...") try: updateinfo = get(upCURL).json() except: updateinfo = { "version": float(self.version), "messages": "", "changelogs": "", "force": "false", "release": { "win": "", "linux": "", "android": "", "macosx": "", "unknown": "", "kivy_build": "" } } # toast("Faild app update check!") if updateinfo: try: appLink = updateinfo["release"][platform] except KeyError: return title = f"App update v{updateinfo['version']}" msg = "You are already in latest version!" b1 = "CENCEL" force = False if updateinfo['version'] > float(self.version) and appLink != "": if updateinfo['messages']:title = updateinfo['messages'] msg = "" b2 = "DOWNLOAD" force = bool(updateinfo['force']) if force: b1 = "EXIT" ava = True else: b2 = "CHECK" self.updateDialog = MDDialog( title=title, text=msg+updateinfo['changelogs']+f"\n\n[size=15]Force update: {force}[/size]", auto_dismiss=False, buttons=[ MDFlatButton( text=b1, text_color=self.theme_cls.primary_color, on_release=lambda x: self.updateDialog.dismiss() if b1 == "CENCEL" else self.stop() ), MDRaisedButton( text=b2, on_release=lambda x:open_link(appLink) if b2 == "DOWNLOAD" else self.FCU(self.updateDialog), text_color=self.theme_cls.primary_color ), ], ) self.updateDialog.ids.title.theme_text_color = "Custom" self.updateDialog.ids.title.text_color = self.theme_cls.primary_light if ava:self.updateDialog.open() def FCU(self, inst): inst.dismiss() Clock.schedule_once(partial(self.checkUpdates, True)) def on_pause(self): return True def save_UpdateDB(self, l=[]): dbRW = MyDb() if l:dbRW.updateScanList(l) def build(self): if platform == "android": self._statusBarColor() Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/list_items.kv" ) Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/dialog_change_theme.kv" ) return Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/start_screen.kv" ) @run_on_ui_thread def _statusBarColor(self, color="#03A9F4"): window = activity.getWindow() window.clearFlags(WindowManager.FLAG_TRANSLUCENT_STATUS) window.addFlags(WindowManager.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.setStatusBarColor(Color.parseColor(color)) window.setNavigationBarColor(Color.parseColor(color)) def show_dialog_change_theme(self): if not self.dialog_change_theme: self.dialog_change_theme = KitchenSinkDialogChangeTheme() self.dialog_change_theme.set_list_colors_themes() self.dialog_change_theme.open() def on_start(self): """Creates a list of items with examples on start screen.""" unsort = self.scan_list # print(unsort) if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.root.ids.Tproxys.text = f"proxys: {len(sort)}" self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" else: self.root.ids.Tscan.text = "scan: 0" self.root.ids.Tproxys.text = "proxys: 0" self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Smirror.text = f"Mirror: {parse.urlparse(self.configs['mirror']).netloc}".upper() # self.root.ids.backdrop._front_layer_open=True Logger.info(f"Platform: {platform}") # if platform == 'android': # self.ads = KivMob(adMobIds.APP) # self.ads.new_banner(adMobIds.BANNER, top_pos=False) # self.ads.request_banner() # self.ads.show_banner() # self.root.ids.adsShow.size = (self.root.ids.backdrop_front_layer.width, 110) self.mirrorPic() self.protPic() self.listPic() self.tap_target_list_view = MDTapTargetView( widget=self.root.ids.Slist, title_text="Pic a lists", description_text="I will remember your list later!", widget_position="right_top", # outer_radius=dp(320), cancelable=True, outer_circle_color=self.theme_cls.primary_color[:-1], outer_circle_alpha=0.9, ) Thread(target=self.checkUpdates).start() def listPic(self): proxysInx = dbRW.getProxysInx() self.selLId = dbRW.getConfig('proxysInx')[0] Logger.debug(self.selLId) self.configs['proxysInx'] = proxysInx if proxysInx: selLIdindxDict = {} self.ListItems = [] i = 0 for Inx in proxysInx: self.ListItems.append({"icon": "playlist-remove", "text": f'#{i} '+agoConv(Inx[0])}) selLIdindxDict[Inx[0]] = i i += 1 else: self.ListItems = [{"icon": "playlist-remove", "text": "None"}] if proxysInx: self.selLIdindx = selLIdindxDict[self.selLId] self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper() if proxysInx else "list :" self.listSel = MDDropdownMenu( caller=self.root.ids.Slist, items=self.ListItems, width_mult=3, opening_time=0.2, use_icon_item=False, position='auto', max_height=0, callback=self.set_list, ) def set_list(self, ins): import re self.selLIdindx = int(re.search(r'#(\d)\s', ins.text).group(1)) # withoutHash = re.search(r'#\d\s(.+)', ins.text).group(1) Logger.debug(self.selLIdindx) proxysInx = dbRW.getProxysInx() self.selLId = proxysInx[self.selLIdindx][0] proxys = dbRW.getAllCurrentProxys(self.selLId) protocol = proxys[0][4] dbRW.updateConfig("proxysInx", self.selLId) scan_list = proxys self.scan_list = [] if self.selLId: for l in scan_list: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6] }) unsort = self.scan_list if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.configs['proxys'] = proxys self.configs['protocol'] = protocol self.root.ids.Slist.text = f"list : {ins.text}".upper() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" # print(getips) toast(ins.text) # print(indx) self.listSel.dismiss() if self.tap_target_list_view.state == 'open': self.tap_target_list_view.stop() def protPic(self): items = [{"icon": "protocol", "text": protocol.upper()} for protocol in ['http', 'https', 'socks4', 'socks5']] self.protSel = MDDropdownMenu( caller=self.root.ids.Sprotocol, items=items, width_mult=2, opening_time=0.2, use_icon_item=False, position='auto', callback=self.set_protocol ) def set_protocol(self, ins): self.configs['protocol'] = ins.text.lower() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" toast(self.configs['protocol']) self.protSel.dismiss() def mirrorPic(self): mirrors = dbRW.getAllMirrors() self.configs['mirrors'] = mirrors items = [{"icon": "web", "text": parse.urlparse(mirror[0]).netloc} for mirror in mirrors] self.mirrSel = MDDropdownMenu( caller=self.root.ids.Smirror, items=items, width_mult=5, opening_time=0.2, use_icon_item=False, position='auto', max_height=0, callback=self.set_mirror, ) def set_mirror(self, ins): miInx = 0 for l in self.configs['mirrors']: if ins.text in l[0]: break miInx += 1 self.configs['mirror'] = self.configs['mirrors'][miInx][0] self.root.ids.Smirror.text = f"Mirror: {ins.text}".upper() dbRW.updateConfig("proxysInx", self.selLId) dbRW.updateConfig("miInx", self.configs['miInx']) toast(self.configs['mirror']) self.mirrSel.dismiss() def update_screen(self, dt): try: while not self.pbar0.empty(): sp = self.pbar0.get_nowait() if sp != 0: self.root.ids.progressBar1.value += sp else: self.root.ids.progressBar1.value = 0 except Empty: pass try: while not self.pbar1.empty(): sp = self.pbar1.get_nowait() if sp != 0: self.root.ids.progressBar2.value += sp else: self.root.ids.progressBar2.value = 0 except Empty: pass try: while not self.pbar2.empty(): sp = self.pbar2.get_nowait() if sp != 0: self.root.ids.progressBar3.value += sp else: self.root.ids.progressBar3.value = 0 except Empty: pass try: proxysL = len(self.configs['proxys']) while not self.totalpb.empty(): sp = self.totalpb.get_nowait() if sp != 0: self.root.ids.totalpb.value += sp comP = (self.root.ids.totalpb.value/proxysL)*100 self.root.ids.totalpbText.text = f"{round(comP)}%" else: self.root.ids.totalpb.max = proxysL self.root.ids.totalpb.value = 0 except Empty: pass self.speedcal() self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper() def start_scan(self, instance): # print("Clicked!!") if instance.text == "Start": self.mirrorPic() self.listPic() self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" if len(self.configs['proxys']) == 0: try: if self.configs['proxysInx']: self.tap_target_list_view.start() self.listSel.open() # toast("Pick that list!") return except: pass PSTDialogInput().open() toast("First input proxys ip:port list then start scan.") return instance.text = "Stop" color = "#f44336" instance.md_bg_color = get_color_from_hex(color) self.theme_cls.primary_palette = "Red" if platform == "android":self._statusBarColor(color) self.scaning.put_nowait(1) self.running.put_nowait(1) IndexTime = datetime.now() dbRW.updateConfig('proxysInx', IndexTime) dbRW.updateProxysInx(IndexTime, self.selLId) dbRW.updateProxys(IndexTime, self.selLId) configs = dbRW.getAllConfigs() self.configs['totalScan'] = dbRW.getProxysInxTS(IndexTime)[0] self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" # print(totalScan) self.configs['timeout'] = int(configs[0][3]) self.configs['fileSize'] = int(configs[0][4]) self.selLId = str(IndexTime) self.show_List() self.upScreen = Clock.schedule_interval(self.update_screen, 0.1) Thread(target=self.proxySpeedTest, args=( self.configs['proxys'], self.configs['protocol'], self.configs['mirror'], )).start() # self.proxySpeedTest('start') elif instance.text == "Stoping": toast(f"Waiting for finish {self.root.ids.currentIP.text[8:]}!") else: while not self.scaning.empty(): self.scaning.get_nowait() if not self.running.empty(): instance.text = "Stoping" # instance.text_color color = "#9E9E9E" self.theme_cls.primary_palette = "Gray" instance.md_bg_color = get_color_from_hex(color) if platform == "android":self._statusBarColor(color) def downloadChunk(self, idx, proxy_ip, filename, mirror, protocol): Logger.info(f'Scaning {idx} : Started') try: proxies = { 'http': f'{protocol}://{proxy_ip}', 'https': f'{protocol}://{proxy_ip}' } req = get( mirror, headers={ "Range": "bytes=%s-%s" % (0, self.configs['fileSize']), "user-agent": "Mozilla/5.0", }, stream=True, proxies=proxies, timeout=self.configs['timeout'] ) with(open(f'{filename}{idx}', 'ab')) as f: start = datetime.now() chunkSize = 0 # oldSpeed = 0 chunkSizeUp = 1024 for chunk in req.iter_content(chunk_size=chunkSizeUp): end = datetime.now() if 0.1 <= (end-start).seconds: delta = round(float((end - start).seconds) + float(str('0.' + str((end - start).microseconds))), 3) speed = round((chunkSize) / delta) # if oldSpeed < speed: # chunkSizeUp *= 3 # else: # chunkSizeUp = speed oldSpeed = speed start = datetime.now() self.currentSpeed.put_nowait(speed) chunkSize = 0 if chunk: chunkSize += sys.getsizeof(chunk) self.showupdate(idx) f.write(chunk) except ProxyError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except connError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except IndexError: self.showupdate(idx, 'd') Logger.info(f'Thread {idx} : You must provide a testing IP:PORT proxy') return False except ConnectTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ConnectTimeou for {proxy_ip}") return False except ReadTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ReadTimeout for {proxy_ip}") return False except RuntimeError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Set changed size during iteration. {proxy_ip}") return False except KeyboardInterrupt: self.showupdate(idx, 'd') Logger.info(f"Thread no {idx} : Exited by User.") self.showupdate(idx, 'd') def showupdate(self, idx, mode='u', error=True): if mode == 'u': if idx == 0: self.pbar0.put_nowait(1) elif idx == 1: self.pbar1.put_nowait(1) elif idx == 2: self.pbar2.put_nowait(1) elif mode == 'd': # color = "#f44336" if idx == 0: self.pbar0.put_nowait(0) elif idx == 1: self.pbar1.put_nowait(0) elif idx == 2: self.pbar2.put_nowait(0) self.root.ids.top_text.text = "0 KB/s" def proxySpeedTest(self, proxys, protocol, mirror): filename = 'chunk' unsort = list() sort = list() astTop3 = list() roundC = 0 self.totalpb.put(0) Logger.debug(proxys) for c, part in enumerate(proxys): if self.scaning.empty(): break proxy_ip = part[0].strip() self.root.ids.currentIP.text = f"CURRENT: {proxy_ip}" # Removing before test chunk file for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') # Starting chunk file downloading timeStart = datetime.now() downloaders = [ Thread( target=self.downloadChunk, args=(idx, proxy_ip, filename, mirror, protocol), ) for idx in range(3)] for _ in downloaders:_.start() for _ in downloaders:_.join() timeEnd = datetime.now() filesize = 0 for i in range(3): try: filesize = filesize + getsize(f'{filename}{i}') except FileNotFoundError: continue filesizeM = round(filesize / pow(1024, 2), 2) delta = round(float((timeEnd - timeStart).seconds) + float(str('0.' + str((timeEnd - timeStart).microseconds))), 3) speed = round(filesize) / delta for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') unsort.append( {'IP': proxy_ip, 'SIZE': filesizeM, 'TIME': delta, 'SPEED': int(speed), 'top3c': part[6]} ) sort = self.sort_Type(unsort, showL=False) sortLL = len(sort) if sortLL >= 3: for t in range(sortLL): if t < 3: if sort[t]['SPEED'] != 0: if not sort[t]['IP'] in astTop3: sort[t]['top3c'] += 1 astTop3.append(sort[t]['IP']) else: for i in range(len(astTop3)): if sort[t]['IP'] == astTop3[i]: # print(i) astTop3.pop(i) sort[t]['top3c'] -= 1 break self.show_List(sort) self.save_UpdateDB(sort) self.totalpb.put(1) roundC = c # return True self.save_UpdateDB(sort) # print(roundC) # print(self.root.ids.totalpb.value) roundC += 1 while True: if self.root.ids.totalpb.value == roundC: self.upScreen.cancel() break self.root.ids.start_stop.text = "Start" self.theme_cls.primary_palette = "LightBlue" self.root.ids.start_stop.md_bg_color = self.theme_cls.primary_color if platform == "android": self._statusBarColor() while not self.running.empty(): self.running.get_nowait() Logger.info("Scan : Finished!") def sort_Change(self, inst, ckid): if ckid and inst.active: self.sort_Type(self.data_lists, mode=inst.text, reverse=False) inst.active = False elif ckid and inst.active == False: self.sort_Type(self.data_lists, mode=inst.text, reverse=True) inst.active = True def sort_Type(self, unsort, mode='SPEED', reverse=True, showL=True): if mode == 'SERVER': mode = 'IP' if mode == 'TOP3-%':mode = 'top3c' sort = sorted(unsort, key=lambda x: x[mode], reverse=reverse) if showL: self.show_List(sort) return sort def show_List(self, data=[]): # if not self.root.ids.backdrop_front_layer.data: # print(data) # print(len(self.root.ids.backdrop_front_layer.data)) totalP = len(self.configs['proxys']) ddict = { "viewclass": "ProxyShowList", "text": "", "text1": "", "text2": "", "text3": "", "text4": "", "on_release": lambda: toast("empty!") } if not data: self.root.ids.backdrop_front_layer.data = [] for i in range(totalP): self.root.ids.backdrop_front_layer.data.append(ddict) else: for i in range(totalP): try: _ = data[i] self.root.ids.backdrop_front_layer.data[i] = { "viewclass": "ProxyShowList", "text": data[i]['IP'], "text1": f"{round((data[i]['top3c']/self.configs['totalScan'])*100)} %", "text2": f"{data[i]['SIZE']} MB", "text3": sec_to_mins(float(data[i]['TIME'])), "text4": f"{size(data[i]['SPEED'], system=alternative)}/s", "on_release": lambda x=data[i]['IP']: self.copy_proxyip(x), } except IndexError: self.root.ids.backdrop_front_layer.data[i] = ddict self.data_lists = data def copy_proxyip(self, data): toast(f"Copied: {data}") Clipboard.copy(data) def speedcal(self): speed = 0 try: while not self.currentSpeed.empty(): speed += self.currentSpeed.get_nowait() except Empty: pass if speed != 0: self.root.ids.top_text.text = f"{size(speed, system=alternative)}/s"
class HomeScreen(Screen): choose_dialog = None choice = None help_dialog = None def show_ChooseDialog(self): self.choose_dialog = MDDialog( title="Test zameraný pre:", type="confirmation", size_hint=[0.9, 0.5], auto_dismiss=False, items=[ ItemConfirm( text="osobné zlepšenie", on_release=self.next_page_me, on_press=self.close_choose_dialog, ), ItemConfirm( text="prácu v tíme", on_release=self.next_page_team, on_press=self.close_choose_dialog, ), ItemConfirm( text="osobné vzťahy", on_release=self.next_page_we, on_press=self.close_choose_dialog, ) ], ) self.choose_dialog.open() def close_choose_dialog(self, obj): self.choose_dialog.dismiss() print(self.choose_dialog.items) def next_page_me(self, obj): self.manager.current = "motivationme" def next_page_team(self, obj): self.manager.current = "motivationteam" def next_page_we(self, obj): self.manager.current = "motivationwe" def show_HelpDialog(self): ok_button = MDRectangleFlatButton(text="Rozummiem", on_release=self.close_help_dialog) self.help_dialog = MDDialog(title="O čo v teste ide?", text="obkec", size_hint=[0.8, 0.5], auto_dismiss=False, buttons=[ok_button]) self.help_dialog.open() def close_help_dialog(self, obj): self.help_dialog.dismiss() def main_navigate(self, button): if button.icon == "home": self.manager.current = "home" elif button.icon == "lightning-bolt": self.manager.current = "mygoals" elif button.icon == "notebook": self.manager.current = "history"
class GoalsScreen(Screen): model = ObjectProperty(None) panel_is_open = False ciel1 = ObjectProperty(None) def submit(self): if self.ids.model.text != "": file = open("package.txt", "w") file.write(self.ids.model.text) self.reset() def on_enter(self): self.ids.cards.clear_widgets() self.panel0 = MDExpansionPanel( icon="flash", content=AContent(), panel_cls=MDExpansionPanelOneLine(text="Definuj si ciele"), ) self.ids.cards.add_widget(self.panel0) self.panel0.bind(on_open=self.panel_open, on_close=self.panel_close) self.panel1 = MDExpansionPanel( icon="human-greeting", content=MeContent(), panel_cls=MDExpansionPanelOneLine(text="Ja"), ) self.ids.cards.add_widget(self.panel1) self.panel1.bind(on_open=self.panel_open, on_close=self.panel_close) self.panel2 = MDExpansionPanel( icon="human-capacity-increase", content=TeamContent(), panel_cls=MDExpansionPanelOneLine(text="Tím"), ) self.ids.cards.add_widget(self.panel2) self.panel2.bind(on_open=self.panel_open, on_close=self.panel_close) self.panel3 = MDExpansionPanel( icon="human-male-female", content=WeContent(), panel_cls=MDExpansionPanelOneLine(text="Vzťah"), ) self.ids.cards.add_widget(self.panel3) self.panel3.bind(on_open=self.panel_open, on_close=self.panel_close) def panel_open(self, *args): self.panel_is_open = True def panel_close(self, *args): self.panel_is_open = False def show_smart(self): self.smart_dialog = MDDialog( title="Technika SMART", text="Tvoj cieľ mousí byť: \n\n" "S- špecifický, pretože musíme vedieť čo\n" "M- merateľný, aby sme vedeli definovať pokrok\n" "A- akceptovaný, pre istotu, že všetic relevantí vedia a súhlasia\n" "R- realistický, aby bolo jasné, že stojíme nohami na zemi\n" "T– termínovaný, určený do kedy má byť splnený\n" "\n\n" "Mal by zodpovedať tieto otázky:\n\n" "- Čo potrebuje zmenu?\n" "- Aká zmena je potrebná?\n" "- Na koho je zmena zameraná?\n" "- Kde sa zmena uplatní?\n" "- Kedy sa zmena uplatní?\n", size_hint=[0.8, None], auto_dismiss=True, ) self.smart_dialog.open() def main_navigate(self, button): if button.icon == "home": self.manager.current = "home" elif button.icon == "lightning-bolt": self.manager.current = "mygoals" elif button.icon == "notebook": self.manager.current = "history"
class pantalla(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) self.app = MDApp.get_running_app() def voz_boton(self, texto): hoy = datetime.date.today() print(hoy) self.ids.txt_Fecha.text = str(hoy) r= sr.Recognizer() #leyenda= self.ids.btn_Producto.text print(texto) try: tts.speak("Ingrese "+texto) #print ("Escuchando") with sr.Microphone() as source: #r.adjust_for_ambient_noise(source) #print("Hable ahora...") audio = r.listen(source) entrada = r.recognize_google(audio, language='es-ES') if (texto=='Nombre'): self.ids.txt_Producto.text = entrada elif(texto=='Precio'): self.ids.txt_Precio.text = entrada elif(texto=='Cantidad'): self.ids.txt_Cantidad.text = entrada except NotImplementedError: popup = ErrorPopup() popup.open() except: print("No entendí o tardó demasiado") def accion(self): APP_PATH = os.getcwd() DB_PATH = APP_PATH+'/prueba.db' #SE DEBE CAMBIAR EL NOMBRE AL NOMBRE DE LA BD FINAL con = sqlite3.connect(DB_PATH) #CONEXION A LA BD cursor = con.cursor() #CURSOR PARA EJECUTAR QUERYS producto= self.ids.txt_Producto.text precio= self.ids.txt_Precio.text cantidad= self.ids.txt_Cantidad.text fecha= self.ids.txt_Fecha.text cursor.execute("""SELECT ID FROM PRODUCTOS""") id_mayor= max(cursor) num_id= id_mayor[0] id_nuevo= num_id+1 print("El proximo id es: ",id_nuevo) datos=[id_nuevo, producto, precio, cantidad, fecha] try: cursor.execute("""INSERT INTO PRODUCTOS VALUES(?, ?, ?, ?, ?)""", datos) con.commit() except Exception as e: print(e) for i in datos: print(i) con.close() ####CREAR TXT FECHA self.creatxtFechas(producto, fecha, cantidad) ####CREAR TXT TABLA self.creatxtTabla(producto) ####CREAR TXT PREDICCION self.prediccion(producto, cantidad, fecha) def creatxtFechas(self, producto, fecha, cantidad): print("Crea el txt e inserta las fechas y cantidad de productos") archivo_fechas= open(producto+"_Fechas.txt", "a") archivo_fechas.write(cantidad+" "+fecha+"\n") archivo_fechas.close() archivo_tablas=open(producto+"_Tabla.txt", "a") #lin= archivo_tablas.read() archivo_tablas.close() return def creatxtTabla(self, producto): archivo= open(producto+"_Fechas.txt", "r") #abrir el archivo-- el nombre no es estático lineas= archivo.readlines() #se obtienen las lineas del archivo print(lineas) archivo.close() #se cierra el archivo print(len(lineas)) if (len(lineas)>=2): #se verifica que haya más de una linea de información ultima= lineas[len(lineas)-1] print(len(ultima)) penultima =lineas[len(lineas)-2] print(len(penultima)) if(len(ultima)==14): #se ontienen las fechas dependiendo del largo de las cadenas ultimaF=ultima[3:13] elif(len(ultima)==13): ultimaF=ultima[2:12] if(len(penultima)==14): penultimaF=penultima[3:13] cantidad=penultima[0:2] elif(len(penultima)==13): penultimaF=penultima[2:12] cantidad=penultima[0] ultima_fecha= datetime.datetime.strptime(ultimaF, '%Y-%m-%d').date() #se pasa la fecha a tipo date print(ultima_fecha) penultima_fecha=datetime.datetime.strptime(penultimaF, '%Y-%m-%d').date() #se pasa la fecha a tipo date print(penultima_fecha) print("la cantidad de elementos es "+cantidad) dias= str((ultima_fecha - penultima_fecha).days) #se obtiene el numero de días entre las fechas print(dias) datos= cantidad+" "+dias #se crea la cadena que ingresa al nuevo txt print(datos) nuevo_archivo=open(producto+"_Tabla.txt", "a") nuevo_archivo.write(datos+"\n") nuevo_archivo.close() elif(len(lineas)==1): print("datos insuficientes para generar regresión lineal") return def prediccion(self, producto, cantidad, fecha): print("seccion prediccion") fechaN= datetime.datetime.strptime(fecha, '%Y-%m-%d').date() archivo_datos= open(producto+"_Tabla.txt", "r") #abrir el archivo renglones= archivo_datos.readlines() #se obtienen los renglones del txt archivo_datos.close() print(renglones) x_numero_elementos=[] y_dias=[] for i in renglones: largo_cadena= len(i) if(largo_cadena==4): numero=int(i[0]) dias=int(i[2]) x_numero_elementos.append(numero) y_dias.append(dias) elif(largo_cadena==5): if(i[1]==" "): numero=int(i[0]) dias=int(i[2:4]) x_numero_elementos.append(numero) y_dias.append(dias) elif(i[2]==" "): numero=int(i[0:2]) dias=int(i[3]) x_numero_elementos.append(numero) y_dias.append(dias) elif(largo_cadena==6): numero=int(i[0:2]) dias=int(i[3:5]) x_numero_elementos.append(numero) y_dias.append(dias) print(x_numero_elementos) print(y_dias) x= np.array(x_numero_elementos) print(x) y= np.array(y_dias) print(y) n=len(renglones) print(n) if(n==0 or n==1): print("No hay suficientes datos para generar la predicción") cadenaDialog="No hay suficientes datos para generar la predicción" else: sumx= sum(x) print(sumx) sumy= sum(y) print(sumy) sumx2= sum(x*x) print(sumx2) sumxy= sum(x*y) print(sumxy) promx= sumx/n print(promx) promy= sumy/n print(promy) m=((n*sumxy)-(sumx*sumy))/((n*sumx2)-(sumx*sumx)) b= promy-(m*promx) print(m, b) cant= int(cantidad) fx= int(m*cant+b) print("Tu producto pueden terminarse en ", fx," dias") pred= fechaN + datetime.timedelta(days=fx) print("La fecha prevista para que se termine tu producto es: ",pred) fechaPred=str(pred) cadenaDialog="La fecha prevista para que se termine tu producto es: "+fechaPred self.dialog= MDDialog(title = "Prediccion de faltantes", #CUADROD DE DIALOGO PARA OBTENER EL PERIODO DEL REPORTE DE GASTOS text = cadenaDialog, size_hint=[.9, .9], auto_dismiss=True, buttons=[ MDFlatButton( text="Cerrar", on_release=self.dialog_close) ] ) self.dialog.open() ###crear el txt con las fechas predichas archivo_fechasPred= open(producto+"_FechasPred.txt", "a") archivo_fechasPred.write(fechaPred+"\n") archivo_fechasPred.close() return def dialog_close(self, *args): # Cierra el dialog del boton ayuda #print("Cerrando Dialog") self.dialog.dismiss()
def fail_popup(retype: int) -> None: show = ERROR[retype] popup_win = MDDialog(title='Error', text=show, size=(.5, .5)) popup_win.open()
class Order(MDScreen): def __init__(self, **kw): super().__init__(**kw) self.add_request_dialog = None self.content = None # Data self.first_name = None self.place = None self.hour = None self.contact = int self.service = None def on_pre_enter(self, *args): self.add_request_button.bind(on_release=self.show_add_request_dialog) def show_add_request_dialog(self, instance_button): if not self.add_request_dialog: self.add_request_dialog = MDDialog( size_hint=(.8, .7), type="custom", content_cls=AddRequestDialog(hour_picker=self.show_time_picker, date_picker=self.show_date_picker), buttons=[ MDFlatButton( text="CANCELAR", text_color=APP.theme_cls.primary_color, on_release=self.close_dialog ), MDFlatButton( text="MARCAR", text_color=APP.theme_cls.primary_color, on_release=self.add_request ), ], ) self.content = self.add_request_dialog.ids.spacer_top_box.children[0] self.add_request_dialog.open() def show_date_picker(self): date_dialog = MDDatePicker(callback=self.get_date) date_dialog.open() def get_date(self, date): self.content.ids.date_label.color = APP.theme_cls.primary_color self.content.ids.date_label.text = date.strftime("%d/%m/%Y") def show_time_picker(self): """Open time picker dialog.""" time_dialog = MDTimePicker() time_dialog.bind(time=self.get_time) time_dialog.open() def get_time(self, instance, time): self.content.ids.hour_label.color = APP.theme_cls.primary_color self.content.ids.hour_label.text = time.strftime("%H:%M") def add_request(self, button): self.first_name = self.content.ids.first_name.text self.place = self.content.ids.place.text self.service = self.content.ids.service.text self.date = self.content.ids.date_label.text self.hour = self.content.ids.hour_label.text self.contact = self.content.ids.contact.text if (self.first_name and self.place and self.contact != "" and self.date != "Data" and self.hour != "Hora" and self.service != ""): DATABASE.add_order( self.first_name, self.place, self.date, self.hour, self.contact, self.service, ) self.close_dialog("") else: print("Deves completar todos os dados") def close_dialog(self, button): self.add_request_dialog.dismiss() self.add_request_dialog = None
def execute(self, current_path): #First we must check that there are selections in the selection table. If not display error popup mycursor.execute(exist_check) self.check_exists = mycursor.fetchone() if self.check_exists[0] == 0: return Errors().no_file_in_cart() else: #Go on with the normal execute function mycursor.execute("SELECT * FROM selection") self.execute_data = mycursor.fetchall()#get all of the recquired operations to be executed self.execute_data_length = len(self.execute_data) #along with the amount of operations to be executed MainScreenvar = sm.get_screen('main_screen') # Assign a variable that will call the main screen whenever the file browser view need to be updated #Here we are creating a list so that we can later append all the executed actions within a #single token to this list.. This list is then converted into a json string and inserted into the database list1 = [] #Initiate the loop that will execute all the recquired amount of operations for i in range(0, self.execute_data_length): if self.execute_data[i][3] == '1': #Check if it is a copy operation that must be executed if self.execute_data[i][2] == "File" : #Check if it is a file try:#We try to copy or else we raise an error message shutil.copy2(self.execute_data[i][1], current_path) MainScreenvar.ids.filechooser_icon._update_files()#Updates the file chooser view #Prepare a tuple for insertion into list pre_tuple = (1, "File", self.execute_data[i][1], os.path.join(current_path, str(self.execute_data[i][0]))) list1.append(pre_tuple)#Append the tuple to the list of all executed operations except shutil.SameFileError: #This error is raised if a file already exists with the same name dialog = MDDialog(text = self.execute_data[i][0]+ " was not coppied from " + self.execute_data[i][1] + ' to ' + current_path + ' as there exists a file already in that name ', radius = (30,30,30,30)) dialog.open() else:#If it is a folder self.dir_src = os.path.join(current_path, str(self.execute_data[i][0])) #Executed if it is a directory try: shutil.copytree(self.execute_data[i][1], self.dir_src) MainScreenvar.ids.filechooser_icon._update_files() pre_tuple = (1, "Directory", self.execute_data[i][1], self.dir_src) list1.append(pre_tuple) except shutil.SameFileError: dialog = MDDialog(text = self.execute_data[i][0]+ " was not copied from " + self.execute_data[i][1] + ' to ' + current_path + ' as there exists a folder already in that name ', radius = (30,30,30,30)) dialog.open() elif self.execute_data[i][3] == '2':#Executed if the operation is a cut operation #Here once again we check if it is a file or a directory. This is not necessary #as both files and directories have same move command but still we do it for sake of it. if self.execute_data[i][2] == 'File': try: # Try to move or else we raise and error shutil.move(self.execute_data[i][1], current_path) MainScreenvar.ids.filechooser_icon._update_files() pre_tuple = (2, "File", self.execute_data[i][1], os.path.join(current_path, str(self.execute_data[i][0]))) list1.append(pre_tuple) except: dialog = MDDialog(text = self.execute_data[i][0]+ " was not cut from " + self.execute_data[i][1] + ' to ' + current_path + ' as there exists a file already in that name ', radius = (30,30,30,30)) dialog.open() else: try: #Try to move or else raise and error shutil.move(self.execute_data[i][1], current_path) MainScreenvar.ids.filechooser_icon._update_files() pre_tuple = (2, "Directory", self.execute_data[i][1], os.path.join(current_path, str(self.execute_data[i][0]))) list1.append(pre_tuple) except: dialog = MDDialog(text = self.execute_data[i][0]+ " was not cut from " + self.execute_data[i][1] + ' to ' + current_path + ' as there exists a folder already in that name ', radius = (30,30,30,30)) dialog.open() else: #Executed if the operation is a delete operation try: shutil.move(self.execute_data[i][1],'C:\Recycle Bin' ) MainScreenvar.ids.filechooser_icon._update_files() pre_tuple = (3, "both", self.execute_data[i][1],os.path.join("C:\Recycle Bin", self.execute_data[i][0])) list1.append(pre_tuple) except: files = os.listdir('C:\Recycle Bin') #Get all files in recycle bin files.sort(reverse=True) # We sort the list in reverse order so we can extrapolate the correct number to be added key = 0 #Assign the key as simply zero for a in range(0,len(files)): #We then traverse across the list of files #Assign variables for the new element name and its extension newelement_name, newelement_ext= os.path.splitext(self.execute_data[i][0]) #Assign variables for the existing element name and its extension exisiting_name, exisiting_ext= os.path.splitext(files[a]) #Check to see if the new element and the old element have the same extension if newelement_ext == exisiting_ext: #If the name of the new element name is same as the old element we assign key as zero if newelement_name == exisiting_name: print("hello") key = -1 break #Else if the new elemenet is merely a substring of the old element we get the index of the highest element elif newelement_name in exisiting_name: key = files.index(files[a]) break print(key) if key == -1: new_number = 1 #We assign the new elements respective number else:# Or else we assign a number higher than the previous number existing_number = os.path.splitext(files[key])[0] existing_number = existing_number[-1] new_number = int(existing_number) + 1 #We then rename the element its new name and then move it to the recycle bin deleting_element = os.path.split(self.execute_data[i][1])[0] + "\\" + newelement_name + str(new_number) + newelement_ext os.rename(self.execute_data[i][1], deleting_element) shutil.move(deleting_element, 'C:/Recycle Bin') #Then the usual of updating the file viewer and also adding the tuple to user_Action table MainScreenvar.ids.filechooser_icon._update_files() pre_tuple = (3, "both", deleting_element,os.path.join("C:\Recycle Bin", newelement_name + str(new_number)+ newelement_ext)) list1.append(pre_tuple) #Resets the selection table for the next round mycursor.execute("DELETE FROM selection") mydb.commit() #First we take the list of all the executed function and then convert it into a JSON string #We then tak this string and then add to a tuple to be inserted into user action table if len(list1) > 0: json_list = json.dumps(list1) user_actions_data = (json_list,) mycursor.execute(user_actions, user_actions_data) mydb.commit() else: pass FileCart.FileCart_Update(self) #Update the fileCart view mycursor.execute("DELETE FROM undo_history") # Reset the undo history table to prevent collapsation
def pdf_dialog(pdfpath, cmds): """ Start dialog to ocr a pdf, start a pdf viewer or convert pdf to images""" # Called by image_glob.py def close_dialog(instance, *args): instance.parent.parent.parent.parent.dismiss() layout = MDList() try: pdfinfos = str( check_output([cmds["pdfimages"], "-list", pdfpath], universal_newlines=True)) pdfinfos = re.sub(r' +', ' ', pdfinfos) pdfinfos = pdfinfos.split("\n")[2:-1] pages = str(len(pdfinfos)) if pages != "0": dpis = [pdfinfo.split(" ")[-3] for pdfinfo in pdfinfos] from collections import Counter dpi = Counter(dpis).most_common(1)[0][0] else: pdfinfos = str( check_output([cmds["pdfinfo"], pdfpath], universal_newlines=True)) for info in pdfinfos.split("\n"): if "Pages:" in info[:7]: pages = info.split(": ")[-1].strip() dpi = 300 layout.add_widget( OneLineListItem(text=f'The detected resolution is: {dpi}')) layout.add_widget(OneLineListItem(text='First page')) # id first layout.add_widget( MDTextField(text="0", hint_text="First page", height=(get_app()._window.size[1]) // 2)) layout.add_widget(OneLineListItem(text='Last page')) # id last layout.add_widget( MDTextField(text=pages, hint_text="Last page", height=(get_app()._window.size[1]) // 2)) layout.add_widget( ThreeLineListItem( text='Fileformat output', secondary_text= 'Default: ppm (rendering), embedded format (extraction)', tertiary_text='Extraction with jpeg outputs ppm on win (bug)')) # id = "fileformat" boxlayout = MDBoxLayout(orientation="horizontal", adaptive_height=True) boxlayout.add_widget(MyToggleButton(text="jpeg", group="imageformat")) #boxlayout.add_widget(MyToggleButton(text="jp2", group="imageformat")) #defaulttoggle = MyToggleButton(text="ppm", group="imageformat") #boxlayout.add_widget(defaulttoggle) boxlayout.add_widget(MyToggleButton(text="png", group="imageformat")) boxlayout.add_widget(MyToggleButton(text="tiff", group="imageformat")) layout.add_widget(boxlayout) layout.add_widget( OneLineListItem(text='Process to convert PDF to images')) # id="converting", boxlayout = MDBoxLayout(orientation="horizontal", adaptive_height=True) defaulttoggle = MyToggleButton(text="rendering", group="converting") boxlayout.add_widget(defaulttoggle) boxlayout.add_widget( MyToggleButton(text="extraction", group="converting")) layout.add_widget(boxlayout) # id='include_pagenumber', pagenumbers = OneLineAvatarListItem( text='Include page numbers in output file names') # id = 'include_pagenumber_chk' pagenumbers.add_widget(SwitchListItem()) layout.add_widget(pagenumbers) dialog = MDDialog( title="Extract images from PDF", type='custom', auto_dismiss=False, text=pdfpath, content_cls=layout, buttons=[ MDFlatButton(text="OCR", on_release=partial(pdfimages_threading, pdfpath, cmds, ocr=True)), MDFlatButton(text="CREATE IMAGES", on_release=partial(pdfimages_threading, pdfpath, cmds)), MDFlatButton(text="VIEW PDF", on_release=partial(open_pdf, pdfpath)), MDFlatButton(text="DISCARD", on_release=close_dialog), ], ) defaulttoggle.state = 'down' if get_app()._platform not in ['win32', 'win64']: # TODO: Focus function seems buggy in win dialog.content_cls.focused = True dialog.open() except: logger.error(f"Error while reading information from {pdfpath}") toast(f"Error while reading information from {pdfpath}")
def passwd_not_crct(self): self.pnc_error = MDDialog( text="Hey you got the password or the userid wrong...try again", radius=[30, 30, 30, 30],) self.pnc_error.open()
class ServerReadingListsScreen(Screen): reading_list_title = StringProperty() page_number = NumericProperty() max_books_page = NumericProperty() dynamic_ids = DictProperty({}) # declare class attribute, dynamic_ids sync_bool = BooleanProperty(False) so = BooleanProperty() new_readinglist = ObjectProperty() def __init__(self, **kwargs): super(ServerReadingListsScreen, self).__init__(**kwargs) self.app = App.get_running_app() self.fetch_data = None self.readinglist_Id = StringProperty() self.readinglist_name = "" # self.bind_to_resize() self.bind(width=self.my_width_callback) self.m_grid = "" self.main_stack = "" self.prev_button = "" self.next_button = "" self.base_url = self.app.base_url self.api_url = self.app.api_url self.api_key = self.app.config.get("General", "api_key") self.list_count = "" self.paginator_obj = ObjectProperty() self.current_page = ObjectProperty() self.list_loaded = BooleanProperty() self.page_number = 1 self.list_loaded = False self.comic_thumb_height = 240 self.comic_thumb_width = 156 self.file_download = True self.num_file_done = 0 self.max_books_page = self.app.max_books_page self.please_wait_dialog = None self.dialog_load_comic_data = None def callback_for_menu_items(self, *args): pass def setup_screen(self): self.api_key = self.app.config.get("General", "api_key") self.api_url = self.app.api_url self.main_stack = self.ids["main_stack"] self.m_grid = self.ids["main_grid"] self.prev_button = self.ids["prev_button"] self.next_button = self.ids["next_button"] def on_pre_enter(self, *args): self.app.show_action_bar() return super().on_pre_enter(*args) def on_leave(self, *args): self.app.list_previous_screens.append(self.name) return super().on_leave(*args) def my_width_callback(self, obj, value): for key, val in self.ids.items(): if key == "main_grid": c = val c.cols = (Window.width - 10) // self.comic_thumb_width def page_turn(self, c_id, new_UserLastPageRead): grid = self.m_grid for child in grid.children: if child.comic_obj.Id == c_id: if new_UserLastPageRead == 0: child.percent_read = 0 else: child.percent_read = round( new_UserLastPageRead / (child.comic_obj.PageCount - 1) * 100) child.page_count_text = f"{child.percent_read}%" def file_sync_update(self, c_id, state): grid = self.m_grid for child in grid.children: if child.comic_obj.Id == c_id: child.has_localfile = state def collect_readinglist_data( self, readinglist_name="", readinglist_Id="", mode="From Server", current_page_num=1, *largs, ): async def collect_readinglist_data(): self.readinglist_name = readinglist_name self.app.set_screen(self.readinglist_name + " Page 1") self.reading_list_title = self.readinglist_name + " Page 1" self.readinglist_Id = readinglist_Id self.page_number = current_page_num self.mode = mode if self.mode == "From Server": self.fetch_data = ComicServerConn() lsit_count_url = "{}/Lists/{}/Comics/".format( self.api_url, readinglist_Id) # self.fetch_data.get_list_count(lsit_count_url,self) self.fetch_data.get_server_data(lsit_count_url, self) elif self.mode == "From DataBase": self.got_db_data() asynckivy.start(collect_readinglist_data()) def get_page(self, instance): page_num = instance.page_num self.app.set_screen(self.readinglist_name + f" Page {page_num}") self.reading_list_title = self.readinglist_name + f" Page {page_num}" page = self.paginator_obj.page(page_num) self.current_page = page if page.has_next(): self.next_button.opacity = 1 self.next_button.disabled = False self.next_button.page_num = page.next_page_number() else: self.next_button.opacity = 0 self.next_button.disabled = True self.next_button.page_num = "" if page.has_previous(): self.prev_button.opacity = 1 self.prev_button.disabled = False self.prev_button.page_num = page.previous_page_number() else: self.prev_button.opacity = 0 self.prev_button.disabled = True self.prev_button.page_num = "" self.build_page(page.object_list) def build_page(self, object_lsit): async def _build_page(): grid = self.m_grid grid.clear_widgets() for comic in object_lsit: await asynckivy.sleep(0) c = ReadingListComicImage(comic_obj=comic) c.lines = 2 c.readinglist_obj = self.new_readinglist c.paginator_obj = self.paginator_obj y = self.comic_thumb_height thumb_filename = f"{comic.Id}.jpg" id_folder = self.app.store_dir my_thumb_dir = os.path.join(id_folder, "comic_thumbs") t_file = os.path.join(my_thumb_dir, thumb_filename) if os.path.isfile(t_file): c_image_source = t_file else: part_url = f"/Comics/{comic.Id}/Pages/0?" part_api = "&apiKey={}&height={}".format( self.api_key, round(dp(y))) c_image_source = f"{self.api_url}{part_url}{part_api}" asynckivy.start(save_thumb(comic.Id, c_image_source)) c.source = c_image_source c.PageCount = comic.PageCount c.pag_pagenum = self.current_page.number grid.add_widget(c) grid.cols = (Window.width - 10) // self.comic_thumb_width self.dynamic_ids[id] = c self.ids.page_count.text = "Page #\n{} of {}".format( self.current_page.number, self.paginator_obj.num_pages()) self.loading_done = True asynckivy.start(_build_page()) def refresh_callback(self, *args): """A method that updates the state of reading list""" def __refresh_callback(interval): self.ids.main_grid.clear_widgets() self.collect_readinglist_data( self.readinglist_name, self.readinglist_Id, current_page_num=self.page_number, mode="From DataBase", ) # self.build_page(page.object_list) # self.ids.main_scroll.refresh_done() self.tick = 0 Clock.schedule_once(__refresh_callback, 1) def got_db_data(self): """ used if rl data is already stored in db. """ async def _do_readinglist(): self.new_readinglist = ComicReadingList( name=self.readinglist_name, data="db_data", slug=self.readinglist_Id, ) await asynckivy.sleep(0) self.so = self.new_readinglist.sw_syn_this_active self.setup_options() new_readinglist_reversed = self.new_readinglist.comics self.paginator_obj = Paginator(new_readinglist_reversed, self.max_books_page) page = self.paginator_obj.page(self.page_number) self.current_page = page if page.has_next(): self.next_button.opacity = 1 self.next_button.disabled = False self.next_button.page_num = page.next_page_number() else: self.next_button.opacity = 0 self.next_button.disabled = True self.next_button.page_num = "" if page.has_previous(): self.prev_button.opacity = 1 self.prev_button.disabled = False self.prev_button.page_num = page.previous_page_number() else: self.prev_button.opacity = 0 self.prev_button.disabled = True self.prev_button.page_num = "" self.build_page(page.object_list) self.list_loaded = True asynckivy.start(_do_readinglist()) def got_json(self, req, results): print("Start got_json") async def _got_json(): print("Start _got_json") self.new_readinglist = ComicReadingList( name=self.readinglist_name, data=results, slug=self.readinglist_Id, ) totalCount = self.new_readinglist.totalCount i = 1 for item in self.new_readinglist.comic_json: await asynckivy.sleep(0) str_name = "{} #{}".format(item["Series"], item["Number"]) self.dialog_load_comic_data.name_kv_file = str_name self.dialog_load_comic_data.percent = str(i * 100 // int(totalCount)) comic_index = self.new_readinglist.comic_json.index(item) new_comic = ComicBook( item, readlist_obj=self.new_readinglist, comic_index=comic_index, ) self.new_readinglist.add_comic(new_comic) i += 1 print("End for item in self.new_readinglist.comic_json:") self.setup_options() new_readinglist_reversed = self.new_readinglist.comics[::-1] self.paginator_obj = Paginator(new_readinglist_reversed, self.max_books_page) page = self.paginator_obj.page(self.page_number) self.current_page = page if page.has_next(): self.next_button.opacity = 1 self.next_button.disabled = False self.next_button.page_num = page.next_page_number() else: self.next_button.opacity = 0 self.next_button.disabled = True self.next_button.page_num = "" if page.has_previous(): self.prev_button.opacity = 1 self.prev_button.disabled = False self.prev_button.page_num = page.previous_page_number() else: self.prev_button.opacity = 0 self.prev_button.disabled = True self.prev_button.page_num = "" self.build_page(page.object_list) self.list_loaded = True self.dialog_load_comic_data.dismiss() self.dialog_load_comic_data = DialogLoadKvFiles() self.dialog_load_comic_data.open() asynckivy.start(_got_json()) def show_please_wait_dialog(self): def __callback_for_please_wait_dialog(*args): pass self.please_wait_dialog = MDDialog( title="No ReadingList loaded.", size_hint=(0.8, 0.4), text_button_ok="Ok", text=f"No ReadingList loaded.", events_callback=__callback_for_please_wait_dialog, ) self.please_wait_dialog.open() def setup_options(self): self.sync_options = SyncOptionsPopup( size_hint=(0.76, 0.76), cb_limit_active=self.new_readinglist.cb_limit_active, limit_num_text=str(self.new_readinglist.limit_num), cb_only_read_active=self.new_readinglist.cb_only_read_active, cb_purge_active=self.new_readinglist.cb_purge_active, # noqa cb_optimize_size_active=self.new_readinglist. cb_optimize_size_active, # noqa sw_syn_this_active=bool(self.new_readinglist.sw_syn_this_active), ) self.sync_options.ids.limit_num.bind( on_text_validate=self.sync_options.check_input, focus=self.sync_options.check_input, ) self.sync_options.title = self.new_readinglist.name def open_sync_options(self): if self.sync_options.ids.sw_syn_this.active is True: self.sync_options.ids.syn_on_off_label.text = f"" self.sync_options.ids.syn_on_off_label.theme_text_color = "Primary" self.sync_options.open() def sync_readinglist(self): if self.sync_options.ids.sw_syn_this.active is False: self.sync_options.ids.syn_on_off_label.text = f"Sync Not Turned On" self.open_sync_options() elif self.sync_options.ids.sw_syn_this.active is True: toast(f"Starting sync of {self.new_readinglist.name}") self.new_readinglist.do_sync()
def file_already_exists(self): self.fae_error = MDDialog( text="This file/Directory has already been added to the Filecart", radius=[30, 30, 30, 30], ) self.fae_error.open()
def get_voice(self, obj): close1_btn = MDFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Error', text='Function currently not available.', size_hint=(0.7, 1), buttons=[close1_btn]) self.dialog.open()
def there_was_a_problem(self): self.twap_error = MDDialog( text="There is a problem. Please close and open the program again", radius=[30, 30, 30, 30],) self.twap_error.open()
class Alerte_Anti_Arnaqueurs(MDApp): print(SERVER) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def build(self): #Build root widget, that is the core application or interface self.theme_cls.primary_palette = 'Green' screen = Screen() #Create a screen variable and add elements to the Screen to display them btn_num = MDRectangleFlatButton(text='Enter', pos_hint={'center_x': 0.5, 'center_y': 0.65}, on_release=self.get_data_num) screen.add_widget(btn_num) btn_sms = MDRectangleFlatButton(text='Enter', pos_hint={'center_x': 0.5, 'center_y': 0.45}, on_release=self.get_data_sms) screen.add_widget(btn_sms) icon_record = MDFloatingActionButton(icon='microphone', pos_hint={'center_x': 0.5, 'center_y': 0.25}, size_hint_x=None, on_press=self.get_voice) screen.add_widget(icon_record) self.num = Builder.load_string(num_helper) screen.add_widget(self.num) self.sms = Builder.load_string(sms_helper) screen.add_widget(self.sms) return screen #functions that activate on button release/ on button press def get_data_num(self, obj): if self.num.text == "": self.response = "Please enter a number" else: self.send(obj=(self.num.text + '1')) print(self.response, self.response[-4:]) if self.response[-4:]=="#123": self.response = self.response[:-4] close1_btn = MDFlatButton(text='Close', on_release=self.close_dialog) add_btn = MDRaisedButton(text='Mark as spam', on_release=self.add) self.dialog = MDDialog(title='Verification', text=self.response + '\n' + 'Do you want to mark this number as spam?', size_hint=(0.7, 1), buttons=[close1_btn, add_btn]) else: close1_btn = MDFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Verification', text=self.response, size_hint=(0.7, 1), buttons=[close1_btn]) self.dialog.open() def add(self, obj): self.send(obj=(self.num.text + 'A')) self.dialog.dismiss() def get_data_sms(self, obj): if self.sms.text == "": check_string = "Please enter the message" close_btn = MDFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Verification', text=check_string, size_hint=(0.7, 1), buttons=[close_btn]) else: self.send(obj=(self.sms.text + '2')) self.verdict = self.client.recv(HEADER).decode(FORMAT) self.list = self.response.split('-') self.showit = str(self.list[0]) + '\n' + str(self.list[1]) print(self.response, 'next', self.verdict) close_btn = MDFlatButton(text='Close', on_release=self.close_dialog) yes_btn = MDRaisedButton(text='Yes', on_release=self.yes) no_btn = MDRaisedButton(text='No', on_release=self.no) self.dialog = MDDialog(title='Verification', text=self.showit+'\n'+ 'Was the message correctly interpreted?', size_hint=(0.7, 1), buttons=[close_btn,yes_btn,no_btn]) self.dialog.open() def yes(self, obj): self.send(obj=(self.verdict + 'a')) self.send(obj=(self.sms.text)) self.dialog.dismiss() def no(self, obj): self.send(obj=(self.verdict + 'u')) self.send(obj=(self.sms.text)) self.dialog.dismiss() def get_voice(self, obj): close1_btn = MDFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Error', text='Function currently not available.', size_hint=(0.7, 1), buttons=[close1_btn]) self.dialog.open() def send(self, obj): message = obj.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - (len(send_length))) self.client.send(send_length) self.client.send(message) self.response = self.client.recv(HEADER).decode(FORMAT) return self.response def close_dialog(self, obj): self.dialog.dismiss()
def folder_cannot_be_created(self): self.fcbc_error = MDDialog( text="The Folder Could Not Be Created", radius=[30, 30, 30, 30],) self.fcbc_error.open()
class ForMap(MapView): gps_location = StringProperty() my_lat = NumericProperty() my_lon = NumericProperty() my_alt = NumericProperty() # ran_coord =[[NumericProperty]] def __init__(self, **kw): super().__init__(**kw) self.flag = False self.chck = 0 # self.random_points() try: from android.permissions import request_permissions, Permission def callback(permissions, results): if all([res for res in results]): print("callback. All permissions granted.") gps.configure(on_location=self.on_location, on_status=self.on_auth_status) gps.start(10, 0) else: print("callback. Some permissions refused.") request_permissions([ Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION, Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE ], callback) except: pass @mainthread def on_location(self, *args, **kwargs): global user_data self.my_lat = kwargs['lat'] self.my_lon = kwargs['lon'] self.my_alt = kwargs['altitude'] def on_auth_status(self, general_status, status_message): if general_status == 'provider-enabled': pass else: self.open_gps_access_popup() def open_gps_access_popup(self): dialog = MDDialog( title="GPS Error", text= "You need to enable GPS access for the app to function properly") dialog.size_hint = [.8, .8] dialog.pos_hint = {'center_x': .5, 'center_y': .5} dialog.open() # @mainthread def random_points(self): global marker_coord self.c = MapView.get_bbox(self) self.arr = np.array(self.c) # print(self.arr) self.lat_arr = np.random.uniform(low=self.arr[0], high=self.arr[2], size=(5)) self.lon_arr = np.random.uniform(low=self.arr[1], high=self.arr[3], size=(5)) marker_coord = (np.dstack((self.lat_arr, self.lon_arr))).reshape(-1, 2) # print(marker_coord) # print(len(marker_coord)) def show_points(self): global marker_coord self.marker = [] self.comp_logo = [] self.marker_image = [] # self.random_points() # print(marker_coord) for i in range(len(marker_coord)): # print("muji") self.marker.append(i) self.marker_image.append(i) self.marker[i] = MapMarker(lat=float(marker_coord[i][0]), lon=float(marker_coord[i][1]), source="gps_logo.png") self.add_widget(self.marker[i]) self.marker_image[i] = picture[random.randint(1, 3)] # self.distance_gps_random() def distance_gps_random(self): global marker_coord, gncn, nnpal self.vector = [] print('lat:', self.my_lat, "lon:", self.my_lon) if self.my_lat != 0: self.coord = Vector(self.my_lat, self.my_lon) else: self.coord = Vector(27.671585080600895, 85.36235332489015) # print(self.coord) # print(marker_coord) try: for i in range(len(marker_coord)): self.vector.append(i) self.vector[i] = (Vector(marker_coord[i].tolist())).distance( self.coord) * 10**5 print(self.vector, len(marker_coord)) if (self.vector[i]) < 100: self.distance_meet(i) marker_coord = np.delete(marker_coord, i, 0) self.dialog = MDDialog( text="Discard draft?", buttons=[ MDRaisedButton(text="CANCEL"), MDRaisedButton(text="DISCARD"), ], ) self.dialog.open() except IndexError as e: print(e) url = "https://treasure-hunt-f490f.firebaseio.com/Client_Location/" + ".json" #username=open(App.get_running_app().user_data_dir + "/username.txt","w").write(self.parent.root.ids.fls.ids.ctreate_account_screen.ids.username.text).close() #print(username) username = open(App.get_running_app().user_data_dir + "/user_file.txt", "r").read().split("\n")[0] json_code = dumps({username: {"lat": self.my_lat, "lon": self.my_lon}}) to_database = json.loads(json_code) requests.patch(url=url, json=(to_database)) def distance_meet(self, i): global marker_coord, gncn, nnpal self.comp_logo.append(i) self.remove_widget(self.marker[i]) self.marker[i] = MapMarkerPopup(lat=float(marker_coord[i][0]), lon=float(marker_coord[i][1]), source=self.marker_image[i]) print("kando!!!!!!") Clock.schedule_once(lambda dt: (self.add_widget(self.marker[i])), 2) if (self.marker_image[i] == "new_nepal.png"): # vibrator.vibrate(time=2) nnpal = nnpal + 1 cam = Camera(resolution=(320, 240), play=True) # self.add_widget(cam) # self.vector.pop(i) # marker_coord = np.delete(marker_coord, i, 0) elif (self.marker_image[i] == "greencoin.png"): # vibrator.vibrate(time=2) gncn = gncn + 1 cam = Camera(resolution=(320, 240), play=True) # self.add_widget(cam) # self.vector.pop(i) # marker_coord = np.delete(marker_coord, i, 0) # self.vector.pop(i) # marker_coord = np.delete(marker_coord, i, 0) def clear_points(self): self.chck += 1 if self.chck > 1: for i in range(len(self.marker)): print(len(self.marker)) self.remove_widget(self.marker[i]) for j in range(len(self.comp_logo)): print("greencoins" + str(len(self.comp_logo))) self.remove_widget(self.comp_logo[j]) def quit_start(self): self.ids.startgame.disabled = False def schedule(self): self.event = Clock.schedule_interval( lambda dt: self.distance_gps_random(), 5) self.event() def unschedule(self): try: self.event.cancel() except AttributeError as e: print(e)
def element_cannot_be_renamed(self): self.ecbc_error = MDDialog( text="The selected item cannot be renamed", radius=[30, 30, 30, 30],) self.ecbc_error.open()
class MainFrame(MDBoxLayout): """Main Frame of the application""" app = None export_dialog = prop.ObjectProperty() def __init__(self, **kwargs): super().__init__(**kwargs) ## Set up var to interact with main application \/ self.app = MDApp.get_running_app() ## Add standard widgets to main frame \/ self.ids.tree_frame.add_widget(self.app.pcd_tree) def switch_to_screen(self, screen, duration=0.2): """Switch to screen :param screen: str :param duration: float """ screen = self.ids.screen_manager.get_screen(screen) self.ids.screen_manager.switch_to(screen, duration=duration) def _export_csv(self, *args): """Callback for export dialog popup button""" try: ## try exporting data into .csv file self.export.export_data() except lib.utils.NotAbleToWriteFile: toast('Não foi possível criar o arquivo!') else: ## shows snackbar with path to new .csv file self.export_dialog.dismiss() snackbar = Snackbar( text=f'PCD exportado para {self.export.path_to_file}', duration=10 ) snackbar.show() def confirm_export_dialog(self): """Create and open export dialog popup""" btn_cancel = MDFlatButton( text = 'Cancelar', theme_text_color = 'Custom', text_color = self.app.theme_cls.primary_color ) btn_confirm = MDRaisedButton( text= 'Exportar .CSV', elevation= 11, on_release= self._export_csv ) self.export_dialog = MDDialog( title= 'Deseja exportar seu PCD?', text= f'O arquivo será salvo em\n{self.export.get_path()}', auto_dismiss= False, buttons= [btn_cancel,btn_confirm]) self.export_dialog.buttons[0].bind(on_release= self.export_dialog.dismiss) self.export_dialog.open() def open_export_dialog(self, *args): """Callback for Export button""" self.export = ExportCSV(name='PCD') ## Prepares for file export self.confirm_export_dialog() ## Opens dialog
class DefaultScreen(Screen): class NFCListener(CardListener): def __init__(self, default_screen: "DefaultScreen"): self.default_screen = default_screen def card_is_presented(self, uid=None) -> None: self.default_screen.nfc_card_presented(uid) def __init__(self, **kwargs): # Call to super (Screen class) super(DefaultScreen, self).__init__(**kwargs) self.nfc_listener = DefaultScreen.NFCListener(self) # Create a session to maintain cookie data for this instance self.event_loop: AbstractEventLoop = App.get_running_app().loop # Store the dialog that we use to select an active user self.user_select_dialog: MDDialog = None # Store a list of users we want to be able to select self.users_to_select = [] # Add extra information to footer text self.ids.copyright.text = self.ids.copyright.text.replace("%year%", str(datetime.datetime.now().year)) \ .replace("%date%", str(datetime.datetime.now().strftime("%Y/%m/%d @ %H:%M:%S"))) def register_card_listener(self, card_connection_manager: "CardConnectionManager"): card_connection_manager.register_listener(self.nfc_listener) # # restarts the card listener upon reentry of the screen # def on_enter(self, *args): # Reset active user, because we are back at this screen. App.get_running_app().active_user = None self.ids.spinner.active = False # Start loading user data. self.event_loop.call_soon_threadsafe(self.load_user_data) def to_credits(self): self.manager.transition = SlideTransition(direction='left') self.manager.current = Screens.CREDITS_SCREEN.value # # gets called when the 'NFC kaart vergeten button' is pressed # Shows a dialog to select a user. # def on_no_nfc(self): # Check if the dialog has been opened before (or whether the data has been loaded properly) if not self.user_select_dialog or len(self.user_select_dialog.items) < 1: # If not, create a dialog once. self.user_select_dialog = MDDialog( type="confirmation", items=self.users_to_select ) # Open the dialog once it's been created. self.user_select_dialog.open() def load_user_data(self, callback: Optional[Callable] = None): if len(App.get_running_app().user_mapping) > 0: Logger.debug("StellaPayUI: Not loading user data again") return user_data = App.get_running_app().session_manager.do_get_request(url=Connections.get_users()) Logger.debug("StellaPayUI: Loaded user data") App.get_running_app().user_mapping = {} if user_data and user_data.ok: # convert to json user_json = user_data.json() print(f"StellaPayUI: Loading user mapping on thread {threading.current_thread().name}") # append json to list and sort the list for user in user_json: # store all emails adressed in the sheet_menu App.get_running_app().user_mapping[user["name"]] = user["email"] # Sort items App.get_running_app().user_mapping = OrderedDict( sorted(App.get_running_app().user_mapping.items(), key=lambda x: x[0])) # Create dialog and its items on the main thread self.create_user_select_dialog(callback=callback) else: Logger.critical("StellaPayUI: Error: addresses could not be fetched from server") os._exit(1) @mainthread def create_user_select_dialog(self, callback: Optional[Callable] = None): # Load usernames into user select dialog if len(self.users_to_select) < 1: for user_name, user_email in App.get_running_app().user_mapping.items(): # store all users in a list of items that we will open with a dialog self.users_to_select.append( SelectUserItem(user_email=user_email, callback=self.selected_active_user, text=user_name)) # Add a callback so we know when a user has been selected # Create user dialog so we open it later. self.user_select_dialog = MDDialog( type="confirmation", items=self.users_to_select ) # If we have a callback, call it. if callback is not None: callback() # An active user is selected via the dialog def selected_active_user(self, item): # Close the user dialog self.user_select_dialog.dismiss() # Set member variables, these are required for making a purchase later user_name = item.text self.manager.transition = SlideTransition(direction='left') App.get_running_app().active_user = user_name # Go to the next screen self.manager.current = Screens.PRODUCT_SCREEN.value def on_leave(self, *args): # Hide the spinner self.ids.spinner.active = False # Dismiss the dialog if it was open if self.user_select_dialog: self.user_select_dialog.dismiss() def nfc_card_presented(self, uid: str): Logger.debug("StellaPayUI: Read NFC card with uid" + uid) # If we are currently making a transaction, ignore the card reading. if App.get_running_app().active_user is not None: Logger.debug("StellaPayUI: Ignoring NFC card as we are currently making a transaction.") return # Show the spinner self.ids.spinner.active = True # Request user info for the specific UID to validate person response = App.get_running_app().session_manager.do_get_request(url=Connections.request_user_info() + uid) # Check response code to validate whether this user existed already. If so, proceed # to the productScreen, else proceed to the registerUID screen if response and response.ok: # store result in JSON query_json = response.json() # Move to WelcomeScreen self.manager.transition = SlideTransition(direction='left') # store user-mail for payment confirmation later user_mail = query_json["owner"]["email"] user_name = query_json["owner"]["name"] App.get_running_app().active_user = user_name # Go to the product screen self.manager.current = Screens.PRODUCT_SCREEN.value else: # User was not found, proceed to registerUID file self.manager.get_screen(Screens.REGISTER_UID_SCREEN.value).nfc_id = uid self.manager.current = Screens.REGISTER_UID_SCREEN.value def on_select_guest(self): self.select_special_user("Gast Account") def on_select_beheer(self): self.select_special_user("Beheer Algemeen") def on_select_onderhoud(self): self.select_special_user("Beheer Onderhoud") def select_special_user(self, user: str): # Close the user dialog self.user_select_dialog.dismiss() self.manager.transition = SlideTransition(direction='left') App.get_running_app().active_user = user # Go to the next screen self.manager.current = Screens.PRODUCT_SCREEN.value
class sweApp(MDApp): def build(self): self.theme_cls.primary_palette = 'Red' self.theme_cls.theme_style = 'Dark' mainscreen1 = Builder.load_string(nav_widg) self.sensor_refresh = int( mainscreen1.ids.refr_rate_field.text ) #handle for this within the imu call and plotting functions self.psi = [] self.phi = [] self.theta = [] return mainscreen1 def connect_to_imu(self, obj): if self.root.ids.ipAddr.text is "": handle_ip_empty = "Please enter the Swe IP address" else: pass #self.imu = client_fx() # creates imu connection instance and code runs in background thread close_button = MDFlatButton(text='Ja', on_release=self.close_dialog) self.dialog = MDDialog(title='Connecting...', text='Connection with Swe Initializing...', size_hint=(0.7, 1), buttons=[close_button]) self.dialog.open() def close_dialog(self, obj): self.dialog.dismiss() def navigation_draw(self): print('navigation') def call_imu_data(self): ip_input = self.root.ids.ipAddr.text port_input = int(self.root.ids.portAddr.text) try: self.imu_instance = client_fx(1, ip_input, port_input) Snackbar( text=f'Attempting connection with {ip_input} : {port_input}' ).show() except: Snackbar( text= f'Cannot connect with {ip_input} : {port_input}... try again later' ).show() def updatePoints(self, *args): instant_imu = self.imu_instance.dq.get() self.c_time = instant_imu[0] - 1609477200 #epoch time since beg 2021 if len(self.psi) > 1000: self.psi.append([self.c_time, instant_imu[1]]) self.phi.append([self.c_time, instant_imu[2]]) self.theta.append([self.c_time, instant_imu[3]]) self.psi = self.psi[-1:-7 * self.sensor_refresh] self.phi = self.phi[-1:-7 * self.sensor_refresh] self.theta = self.theta[-1:-7 * self.sensor_refresh] else: self.psi.append([self.c_time, instant_imu[1]]) self.phi.append([self.c_time, instant_imu[2]]) self.theta.append([self.c_time, instant_imu[3]]) plot_psi = MeshLinePlot(color=[1, 0, 0, 1]) plot_phi = MeshLinePlot(color=[0, 1, 0, 1]) plot_theta = MeshLinePlot(color=[0, 0, 1, 1]) plot_psi.points = self.psi plot_phi.points = self.phi plot_theta.points = self.theta self.root.ids.graph01.add_plot(plot_psi) self.root.ids.graph01.add_plot(plot_phi) self.root.ids.graph01.add_plot(plot_theta) self.root.ids.testYawOut.text = f'{instant_imu[1]}-> yaw' #print(f'{instant_imu[0]}') def updateAxis(self, *args): new_time_min = self.c_time - 10 #define an epoch time in seconds that is 10 seconds in the past self.root.ids.graph01.xmin = round(new_time_min) self.root.ids.graph01.xmax = round(self.c_time) def livePlot(self, *args): self.graph_activate = True Clock.schedule_interval(self.updatePoints, 1 / self.sensor_refresh) Clock.schedule_interval(self.updateAxis, 1 / self.sensor_refresh) def cancelPlot(self, *args): Clock.unschedule(self.updatePoints) Clock.unschedule(self.updateAxis)