def get_positions(self): view = View() positions = Position.select_many_where("WHERE accounts_pk = ?", (self.pk, )) for position in positions: view.positions(self, position) return positions
def __init__(self): self._app = QtWidgets.QApplication(sys.argv) self._model = Model() self._view = View() self.add_thread = AddThread() self.timer_thread = TimerThread() self.init()
class Main(object): def __init__(self): self.views = View(cherrypy.Application.currentDir) @cherrypy.expose def index(self): return self.views.create("index.mako") @cherrypy.expose def rutaMaiz(self): return self.views.create("rutaMaiz.mako") @cherrypy.expose def flora(self): consulta = con.query('SELECT ?sub WHERE {?sub ?pred wo:TaxonName.}') valores = [] titulo = "" for sujeto in consulta: objetos = con.query('SELECT ?obj WHERE {<'+ sujeto['sub']['value'] +'> ?pred ?obj.}') valores.append(objetos) return self.views.create("flora.mako", valores, titulo) @cherrypy.expose def empresas(self): consulta = con.query('SELECT ?sub WHERE {?sub ?pred GR:BusinessEntity.}') return self.views.create("empresas.mako", consulta) #/** # * Permite obtener todas las tripletas del repositorio # */ @cherrypy.expose def verTodo(self): todos = con.query('SELECT ?sub ?pred ?obj WHERE { ?sub ?pred ?obj.}') for res in todos: return res['sub']['value'] #/** # * Permite obtener los datos desde SESAME # * id, criterio de consulta # */ @cherrypy.expose def view(self, id): nombre = id.title().encode('utf-8')#La primera en mayuscula, el resto en minuscula sa = con.query('SELECT ?sub WHERE {?sub ?pred ?obj . FILTER (regex(?obj, "'+ nombre +'")).}') valores = [] for sujeto in sa: objetos = con.query('SELECT ?obj WHERE {<'+ sujeto['sub']['value'] +'> ?pred ?obj.}') valores.append(objetos) nom = "" return self.views.create("resultados.mako", valores, nom)
class Main(object): def __init__(self): self.views = View(cherrypy.Application.currentDir) @cherrypy.expose def index(self): return self.views.create("index.mako") @cherrypy.expose def rutaMaiz(self): return self.views.create("rutaMaiz.mako") @cherrypy.expose def flora(self): consulta = con.query('SELECT ?sub WHERE {?sub ?pred wo:TaxonName.}') valores = [] titulo = "" for sujeto in consulta: objetos = con.query('SELECT ?obj WHERE {<' + sujeto['sub']['value'] + '> ?pred ?obj.}') valores.append(objetos) return self.views.create("flora.mako", valores, titulo) @cherrypy.expose def empresas(self): consulta = con.query( 'SELECT ?sub WHERE {?sub ?pred GR:BusinessEntity.}') return self.views.create("empresas.mako", consulta) #/** # * Permite obtener todas las tripletas del repositorio # */ @cherrypy.expose def verTodo(self): todos = con.query('SELECT ?sub ?pred ?obj WHERE { ?sub ?pred ?obj.}') for res in todos: return res['sub']['value'] #/** # * Permite obtener los datos desde SESAME # * id, criterio de consulta # */ @cherrypy.expose def view(self, id): nombre = id.title().encode( 'utf-8') #La primera en mayuscula, el resto en minuscula sa = con.query( 'SELECT ?sub WHERE {?sub ?pred ?obj . FILTER (regex(?obj, "' + nombre + '")).}') valores = [] for sujeto in sa: objetos = con.query('SELECT ?obj WHERE {<' + sujeto['sub']['value'] + '> ?pred ?obj.}') valores.append(objetos) nom = "" return self.views.create("resultados.mako", valores, nom)
class Controller: def __init__(self): self._app = QtWidgets.QApplication(sys.argv) # self._model = Model() self._view = View() def run(self): self._view.show() return self._app.exec_()
def __init__(self, loop): self.__loop = loop self.__dao = None self.__updater = Updater( config.telegram.token, defaults=Defaults(parse_mode=ParseMode.MARKDOWN)) self.__view = View(self.__updater, self.__handler) self.__modal = Modal(config.meross, config.solaredge, config.sun) self.__loop.run_until_complete(self.__modal.async_init())
def __init__(self): self.__root = Tk() self.__root.protocol('WM_DELETE_WINDOW', self._on_closing_window) self.__view = View(self.__root) self.__view.filepath_button.config( command=lambda: self._get_directory(self.__view.string)) self.__view.paste_button.config( command=lambda: self._paste(self.__view.url_entry)) self.__view.download_button.config(command=self._start) # Variables self.__thread = None threading.Thread(target=self._check_update).start() self.__root.mainloop()
class App: def __init__(self, loop): self.__loop = loop self.__dao = None self.__updater = Updater( config.telegram.token, defaults=Defaults(parse_mode=ParseMode.MARKDOWN)) self.__view = View(self.__updater, self.__handler) self.__modal = Modal(config.meross, config.solaredge, config.sun) self.__loop.run_until_complete(self.__modal.async_init()) def __handler(self, update: Update, _: CallbackContext) -> None: if self.__dao is not None: self.__dao.close() self.__dao = DAO() user = update.effective_user search = self.__dao.search_user(user.id) if search is None: if update.message: update.message.reply_text('You cannot use this bot.') return if update.message: message = update.message logger.info('%s %s %s', 'chat', user.id, message.text) if '/start' in message.text: text = self.__view.welcome(user.first_name) message.reply_text(text) devices = self.__dao.get_all_devices() text, inline_keyboard = self.__view.menu(devices) message.reply_text( text, reply_markup=InlineKeyboardMarkup(inline_keyboard)) else: message.reply_text('Command not found') elif update.callback_query: query = update.callback_query logger.info('%s %s %s', 'callback_query', user.id, query.data) action = query.data.split('|')[0] data = query.data.split('|')[1:] if 'menu' == action: devices = self.__dao.get_all_devices() text, inline_keyboard = self.__view.menu(devices) query.edit_message_text( text, reply_markup=InlineKeyboardMarkup(inline_keyboard)) elif 'device' == action: """ 0: device_id 1: day """ self.__device(query, data[0], int(data[1])) elif 'lock' == action: """ 0: device_id 1: delay before unlock (optional) """ if len(data) == 1: text, inline_keyboard = self.__view.choose_delay(data[0]) query.edit_message_text( text, reply_markup=InlineKeyboardMarkup(inline_keyboard)) elif len(data) == 2: self.__modal.lock_device(data[0], int(data[1])) self.__device(query, data[0], 0) query.answer('Dispositivo bloccato') elif 'unlock' == action: """ 0: device_id """ self.__modal.unlock_device(data[0]) self.__device(query, data[0], 0) query.answer('Dispositivo sbloccato') else: query.answer('Command not found', show_alert=True) query.answer() def __device(self, query, device_id, day=0): date = datetime.today() + timedelta(days=day) _type = 'local' device = self.__modal.get_device(device_id) if device is None: # get from DB if not exist _type = 'db' device = self.__dao.get_device(device_id) powers_on = self.__dao.get_device_powers_on(device_id, date.strftime('%Y-%m-%d')) attributes = self.__dao.get_device_attributes(device_id) if device is not None: text, inline_keyboard = self.__view.device(_type, device, powers_on, attributes, day) query.edit_message_text( text, reply_markup=InlineKeyboardMarkup(inline_keyboard)) else: query.answer('Device not found', show_alert=True) def close(self): self.__updater.stop() self.__loop.run_until_complete(self.__modal.async_close())
def __init__(self): self.views = View(cherrypy.Application.currentDir)
current = DefaultInteract() if view.interaction is not None and view.interaction.open(): current = view.interaction else: time.sleep(2) if __name__ == "__main__": DefaultInteract.SIMULATION = False device = Device(data.actuators_8()) # Initialising view with networks, interactions and mouse tracking view = View(device, networks=data.all_networks(), interacts=data.all_interactions(), mouse_tracking=False, default_network='default', default_interact='default') # Setting tracking and interacting threadq tracker_thrd = threading.Thread(target=tracker, args=(device, )) interaction_thrd = threading.Thread(target=interact, args=(view, )) # Starting threads tracker_thrd.start() interaction_thrd.start() view.loop() # runs the view, forever
class Controller: """ Class that orchestrates the interactions between model(data) and view(user) """ def __init__(self): self.model = Model() self.view = View() def run(self) -> None: """ Method is the main method that orchestrates all the methods in the model, view, and controller """ run = self.view.display( ) # if the user selects to procede, then with the main program if run == True: self.storeCredentials( ) # gets the credentials from the user and store in class methods self.storeSession( ) # gets the credentials to sign into duolingo via api, and then gets the user session and stores it in class method self.proccessLanguage() numEntriesComp = self.model.compareApiToTable( ) # boolean value for equality self.branchGetData(numEntriesComp) # load data into model hashes = self.branchOutput( ) # gets the user's input to determine the batch of methods used in program wordHash = hashes[0] # unpack the two dictionaries flagHash = hashes[1] print("len of flaghash: ", len(flagHash)) self.iterateVocabHash( wordHash, flagHash) # send and receive data from both model and view self.model.closeDb() else: self.exit() """ The following methods: storeCredentials(), storeSession(), repeatStoreSession() address user authentication and storage """ def storeCredentials(self) -> None: """ Method that obtains from user duolingo credentials and stores it in the model """ cred = self.view.getUserCredentials() # get the user credentials self.model.storeUserCredentials(cred[0], cred[1]) def storeSession(self) -> None: """ Method that obtains from user duolingo credentials and stores it in the model """ self.view.displayOutput("signing into duolingo with credentials... ") session = self.model.signIn( ) # given provided user credentials, attempt login into duolingo if session is None: self.repeatStoreSession( ) # the loop will repeat until valid credentials are given and signin succeeds self.view.displayOutput("signin successful!") def repeatStoreSession(self) -> None: """ Method that obtains from user duolingo credentials and stores it in the model Similar to the storeSession method, but it contains additional print statements """ self.view.displayOutput("signin unsuccessful...") self.view.displayOutput("try again!") self.storeCredentials() # see method for details self.storeSession() # see method for detials """ The following methods: proccessLanguage(), chooseLanguage() address selecting and storing the target language """ def proccessLanguage(self) -> None: """ Method that initials collecting the language information from api and from user input. These two informations are coordinated until a user confirms the desired target language """ languages = self.model.getLanguage() lang = self.chooseLanguage(languages) if lang == None: self.view.displayOutput("exiting application") self.view.displayOutput("no language avaliable to select") print("printing user lang input " + lang) self.model.language = lang def chooseLanguage(self, languages: List[str]) -> any: """ Method that returns the language the user inputs, if and only if its a language started in the user's account """ if len(languages) == 0: self.view.displayOutput("did not begin learning a language") self.view.displayOutput("go to duolingo and select a language") return None elif len(languages) == 1: self.view.displayOutput("selecting the language: {}".format( languages[0])) return languages[0] else: self.view.displayOutput("1 than more language available") self.view.displayOutput("choose a language from the following: ") s = "" for lang in languages: s += lang + " " self.view.displayOutput(s) while True: input_ = input().lower() if input_ in languages: self.view.displayOutput( "Successful. Choosing {}".format(input_)) return input_ self.view.displayOutput("did not select properly") self.view.displayOutput("choose 1 of the following: " + s) """ The following methods: dataToModel(), dataFromTable() address getting vocabulary data and storing the data in storage """ def dataToModel(self) -> None: """ Method that orchestrates obtaining from duolingo, vocabulary words and converts the words from a list to a hashmap """ self.view.displayOutput("obtaining vocabulary...") self.model.pullVocab() # store the vocab words in a list self.model.translateToHash( ) # translates the vocab words in a list into a dictionary/ hashmap def dataFromTable(self) -> None: """ Method that orchestrates obtaining from table, vocabulary words and converts the words from a list to a hashmap """ self.view.displayOutput("loading data...") self.model.queryHashFromTable( ) # converts the table rows and stores it in the class variable of the model keys = list(self.model.getWordHash().keys( )) # gather the keys as a paramter for the makeNewFlagHash method flagHash = self.model.makeNewFlagHash(keys) self.model.setFlagHash(flagHash) # setter method """ The following methods: branchGetData(), branchOutput() address getting branches (if/else) statements that determine the flow of methods executed in the program """ def branchGetData(self, lenComp: bool) -> None: """ Method that determines the flow of the program. It obtains the existing entries in the table if it already exist. Otherwise, it deletes and recreates an empty table and obtains entries from the duolingo api, then saves the entries in the table for later" """ if lenComp == True: # same length self.view.displayOutput("getting data from table...") self.dataFromTable() # get data from table and store in model else: self.view.displayOutput( "getting data from api and creating table...") self.dataToModel( ) # get the data from duolingo via api, and stores the data in the model self.model.queryHashToTable self.model.saveDataToPersistentStorage() def branchOutput(self) -> List[Dict]: """ Method that obtains user input. The input determines the batch of methods that are run """ self.view.displayOutput( "(T)arget to English, or (E)nglish to Target? \n") resp = self.view.displayInput() wordHash = {} flagHash = {} if (resp == "t"): wordHash = self.model.wordHash # store as is flagHash = self.model.flagHash # store as is elif (resp == "e"): wordHash = self.model.invertWordHash( ) # reverse the order of keys and values flagHash = self.model.makeNewFlagHash( wordHash.keys() ) # remake the flagHash variable, but with English words as the key else: self.view.displayOutput( "not an allowed command {}. Try again!".format(resp)) self.branchOutput() hashes = [wordHash, flagHash] # return the two dictionaries in a list return hashes """ The following methods: iterateVocabHash(), vocabIO(), displayNumCorrect() address getting the model data to the view and getting the user input to the model """ def iterateVocabHash(self, wordHash: Dict[str, str], flagHash: Dict[str, int]) -> None: """ Method orchestrates the interactions between the model(data) and view(user) Flag is a boolean variable; it releases the program loop if the user translates all of the words For loop repeats without the correctly translated words """ userSolvedAll = self.model.vocabFlag( flagHash) # boolean variable: default value is False while userSolvedAll != True: for key in wordHash: self.vocabIO( key, wordHash, flagHash ) # give and get data from the view and model, respectively wordHash = self.model.updateVocabHash( wordHash, flagHash) # filter the vocabHash with the translated words userSolvedAll = self.model.vocabFlag( flagHash ) # if all words are translated correctly, then update the flag variable self.displayNumCorrect( flagHash ) # print to the view the number of remaining unlearned words def vocabIO(self, key: str, wordHash: Dict[str, str], flagHash: Dict[str, int]) -> Dict[str, int]: """ Method that displays the vocab word to the view and obtains the translation input from the user It also compares the user translation and recorded translation with the compareInput method """ input_ = self.view.displayWord( key ) # gives the vocab word to the view, and gets the input translation from the user value = wordHash[key] # get the translation of the vocab word flagHash = self.model.compareInput( key, value, input_, flagHash ) # boolean variable that compares user input with translation return flagHash def displayNumCorrect(self, flagHash: Dict[str, int]) -> None: """ Method that computes and displays the number of remaining words unlearned """ numCount = self.model.getNumCorrect(flagHash) # see method for detials self.view.displayOutput("Number remaining: {} ".format( len(flagHash) - numCount)) # the computation gives the number of unlearned words def exit(self) -> None: """ Method that safely exits the program """ self.view.displayOutput("until next time...") sys.exit()
def __init__(self): self._app = QtWidgets.QApplication(sys.argv) # self._model = Model() self._view = View()
class App: def __init__(self): self.__root = Tk() self.__root.protocol('WM_DELETE_WINDOW', self._on_closing_window) self.__view = View(self.__root) self.__view.filepath_button.config( command=lambda: self._get_directory(self.__view.string)) self.__view.paste_button.config( command=lambda: self._paste(self.__view.url_entry)) self.__view.download_button.config(command=self._start) # Variables self.__thread = None threading.Thread(target=self._check_update).start() self.__root.mainloop() def _start(self) -> None: url = self.__view.url_entry.get() filepath = self.__view.filepath_entry.get() if not url: messagebox.showinfo('Missing URL', 'The URL of the lesson is missing') return if not filepath: messagebox.showinfo('Missing Filename', 'The Filename of the lesson is missing') return if os.path.isdir(filepath): messagebox.showerror('Error', 'Cannot be a folder') return if not os.path.isdir(os.path.split(filepath)[0]): messagebox.showerror('Error', 'Folder does not exist') return if os.path.exists(filepath): os.remove(filepath) self.__view.download_button.config(state='disabled') self.__view.state_label.config(text='Downloading...') self.__thread = threading.Thread(target=self._download, args=(url, filepath)) self.__thread.start() def _download(self, url, filepath): try: PanoptoDownloader.download(url, filepath, self._callback) self.__view.state_label.config(text='Done') messagebox.showinfo('Completed', 'Download completed') except RegexNotMatch: messagebox.showerror( 'Error', 'URL not correct.\nPaste the automatically copied link from Browser Extension' ) except Exception as e: messagebox.showerror('Error', str(e)) finally: self._reset() def _callback(self, progress: int) -> None: self.__view.progressbar['value'] = progress self.__view.update_idletasks() def _reset(self) -> None: self.__view.progressbar['value'] = 0 self.__view.download_button.config(state='normal') self.__view.state_label.config(text='') self.__view.update_idletasks() def _on_closing_window(self): if self.__thread is not None and self.__thread.is_alive(): messagebox.showwarning( 'Warning', 'The download is still in progress. Unable to close') else: self.__root.destroy() @staticmethod def _get_directory(element: StringVar) -> None: filetypes = [(f[1:].upper(), f'*{f}') for f in SUPPORTED_FORMATS] filepath = filedialog.asksaveasfilename(filetypes=filetypes, defaultextension='') if filepath: element.set(filepath) @staticmethod def _paste(element: Entry) -> None: element.select_range(0, 'end') element.event_generate('<<Paste>>') @staticmethod def _check_update(): update = utils.get_release_update() if update is not None: body = 'Version: ' + update.get( 'tag') + '\nChangelog:\n' + update.get( 'body') + '\n\nDownload it?' if messagebox.askyesno('New Update!', body): webbrowser.open(update.get('url'))
current = view.interaction else: time.sleep(2) if __name__ == "__main__": DefaultInteract.SIMULATION = False device = Device(data.actuators_8()) # Initialising view with networks, interactions and mouse tracking view = View( device, networks=data.all_networks(), interacts=data.all_interactions(), mouse_tracking=False, default_network='default', default_interact='default' ) # Setting tracking and interacting threadq tracker_thrd = threading.Thread(target=tracker, args=(device,)) interaction_thrd = threading.Thread(target=interact, args=(view,)) # Starting threads tracker_thrd.start() interaction_thrd.start() view.loop() # runs the view, forever
from app.account import Account from app.view import View from app.util import get_price from app.util import top_traded import time view = View() def run(): welcome_homepage() def welcome_homepage(): while True: selection = view.welcome_screen() if selection not in ['1', '2', '3']: view.improper_selection() continue if selection == '1': username, balance, password, confirm_password = view.get_username( ), view.add_balance(), view.get_password(), view.confirm_password( ) if password != confirm_password: view.improper_password() continue if not balance.isdigit() or int(balance) < 0: view.improper_balance() continue
def __init__(self): self.model = Model() self.view = View()
class Controller: def __init__(self): self._app = QtWidgets.QApplication(sys.argv) self._model = Model() self._view = View() self.add_thread = AddThread() self.timer_thread = TimerThread() self.init() def init(self,): self.set_table_and_combox() self.add_thread.add_to_table_signal.connect(lambda: self._view.add_to_table(self.add_thread.items)) self.timer_thread.set_label_signal.connect(self._view.set_label) self.timer_thread.update_signal.connect(self.update_data) self._view.add_btn.clicked.connect( lambda: self.insert_to_db( self._view.title_lineEdit.text(), self._view.time_lineEdit.text()) ) self._view.reset_btn.clicked.connect(self.settlement) self._view.delete_btn.clicked.connect(self.delete_data) self._view.play_btn.clicked.connect(self.start_playing) self._view.pause_btn.clicked.connect(self.pause_playing) self._view.stop_btn.clicked.connect(self.stop_playing) def settlement(self,): items = self._model.get_all_record() for item in items: title = item[0] target = item[1] owe = item[2] now = item[3] record_target = item[4] if owe!=0: owe -= now if owe<0: target += owe owe = 0 if target<0: target = 0 else: target -= now if target<0: target = 0 owe += target self._model.reset_record(title, owe, 0, record_target) self.set_table_and_combox() def update_data(self, item: tuple): self._model.update_data(item[0], item[1], item[2], item[3]) self.set_table_and_combox() def stop_playing(self,): self.timer_thread.stop_flag = True def pause_playing(self,): self.timer_thread.pause_flag = not self.timer_thread.pause_flag def start_playing(self,): if self.timer_thread.isRunning(): self.pause_playing() else: self.timer_thread.title = self._view.comboBox.currentText() item = self._model.get_data('title', self.timer_thread.title) _, self.timer_thread.target, self.timer_thread.owe, self.timer_thread.now = item self.timer_thread.start() def delete_data(self,): items = self._view.tableWidget.selectionModel().selectedRows() for item in items: row = item.row() title = self._view.tableWidget.item(row, 0).text() self._model.delete_data(title) self._view.tableWidget.removeRow(row) def validate_title(self, title: str): if title.isdigit(): return False return not self._model.search_title(title) def validate_time(self, time: str): try: return int(time) except ValueError: print("Invalid time.") return False def insert_to_db(self, title: str, time:str): validated_title = self.validate_title(title)*60 validated_time = self.validate_time(time)*60 if validated_title and validated_time: self._model.insert_to_db(title, validated_time, 0, 0) try: # set items self.add_thread.items = (title, validated_time, 0, 0, validated_time) self.add_thread.start() except Exception as e: print(e) else: if title.isdigit(): self._view.msgBox(f'<{title}> cannot only construct by number.') else: self._view.msgBox(f'<{title}> has repeat or time invalid failed.') def set_table_and_combox(self,): self._view.tableWidget.clear() self._view.tableWidget.setRowCount(0) items = self._model.get_all_record() for item in items: self._view.add_to_table(item) self._view.comboBox.addItem(item[0]) def run(self): self._view.show() return self._app.exec_()