def insert(self): data = Pessoa.find_by_name(self.nome) if data is None: Database.insert(coleccao + '(nome)', "'{}'".format(self.nome)) return True return False
def insert(self): data = MetodoPreservacao.find_by_name(self.metodo) if data is None: Database.insert(coleccao + '(metodo)', "'{}'".format(self.metodo)) return True return False
def insert(self): Database.insert(coleccao+"(especie, idgenero, habitat, coordenadas, notas, detalhes,"+ "nomecomum, codigo, validacao, datacriacao)", "'{}','{}','{}','{}','{}','{}','{}','{}','{}','{}'" .format(self.especie, self.idgenero, self.habitat, self.coordenadas, self.notas, self.detalhes, self.nomecomum, self.codigo, self.validacao, self.datacriacao)) return self.codigo
def insert(self): data = Reino.find_by_name(self.reino) if data is None: Database.insert(coleccao + '(reino)', "'{}'".format(self.reino)) return True return False
def pedido(self): data = Utilizador.find_by_email(self.email) if data is None: Database.insert(pedido + '(email,password)', "'{}','{}'".format(self.email, self.password)) return True return False
def load_stylesheet(): db = Database() stylesheet = db.get_property(3) db.db_connection.close() file = QFile(f"_gui/stylesheets/{stylesheet}") file.open(QFile.ReadOnly | QFile.Text) stream = QTextStream(file) return stream.readAll()
def insert(self): data = Provincia.find_by_name(self.provincia) if data is None: Database.insert(coleccao + '(provincia,idregiao)', "'{}',{}".format(self.provincia, self.idregiao)) return True return False
def insert(self): data = Distrito.find_by_name(self.distrito) if data is None: Database.insert(coleccao + '(distrito,idprovincia)', "'{}',{}".format(self.distrito, self.idprovincia)) return True return False
def insert(self): data = Familia.find_by_name(self.familia) if data is not None: if (d for d in data) == self.familia and (d for d in data) == self.idordem: return False Database.insert(coleccao+'(familia,idordem)', "'{}',{}".format(self.familia, self.idordem)) return True
def insert(self): data = TipoUtilizador.find_by_name(self.tipoutilizador) if data is None: Database.insert(coleccao + '(tipoutilizador)', "'{}'".format(self.tipoutilizador)) return True return False
def test_database_01(): project_id = '224472' db = Database() try: url = db.get_project_url(project_id) logger.info('The url for project {} was {}'.format(project_id, url)) except ProjectNotFoundException: logger.error('The project {} was not in database.'.format(project_id)) pass
def insert(self): data = Filo.find_by_name(self.filo) if data is not None: if data[2] == self.idreino and data[1] == self.filo: return False Database.insert(coleccao + '(filo,idreino)', "'{}',{}".format(self.filo, self.idreino)) return True
class Queries: def __init__(self): self.__database = Database() def create_tables(self) -> None: """ Builds table structure if it doesn't exist. :return: None """ self.__database.execute_query(''' CREATE TABLE IF NOT EXISTS history ( id serial PRIMARY KEY, artist varchar(255), title varchar(255), release_format varchar(255), number_of_tracks INT, release_year INT, rating FLOAT, votes INT, have INT, want INT, limited_edition BOOL, media_condition INT, sleeve_condition INT, predicted_price FLOAT ); ''') def log_prediction(self, input_data, response) -> None: """ Writes the request and prediction data to a database. :param input_data: validated json :param response: item price prediction json :return: None """ query = f''' INSERT INTO history( artist, title, release_format, number_of_tracks, release_year, rating, votes, have, want, limited_edition, media_condition, sleeve_condition, predicted_price) VALUES('{input_data["artist"]}', '{input_data["title"]}', '{input_data["release_format"]}', '{input_data["number_of_tracks"]}', '{input_data["release_year"]}',' {input_data["rating"]}', '{input_data["votes"]}', '{input_data["have"]}', '{input_data["want"]}', '{input_data["limited_edition"]}', '{input_data["media_condition"]}', '{input_data["sleeve_condition"]}', '{response["predicted_price"]}'); ''' self.__database.execute_query(query) def get_predictions(self, predictions_to_show: int = 10) -> list: """ Gets a specified number of predictions from the database. :param predictions_to_show: :return: list """ return self.__database.execute_query_and_fetch(f''' SELECT * FROM history ORDER BY id DESC LIMIT {predictions_to_show}''')
def insert(self): data = Classe.find_by_name(self.classe) if data is not None: if data[2] == self.idfilo and data[1] == self.classe: return False Database.insert(coleccao + '(classe,idfilo)', "'{}',{}".format(self.classe, self.idfilo)) return True
def insert(self): data = Ordem.find_by_name(self.ordem) if data is not None: if data[2] == self.idordem and data[1] == self.ordem: return False Database.insert(coleccao + '(ordem,idclasse)', "'{}',{}".format(self.ordem, self.idclasse)) return True
def register(self): data = Utilizador.find_by_email(self.email) if data is None: Database.insert( coleccao + '(email,senha,idtipoutilizador)', "'{}','{}','{}'".format(self.email, self.password, self.idtipoutilizador)) return True return False
def insert(self): data = Genero.find_by_name(self.genero) if data is not None: if (d for d in data) == self.genero and ( d for d in data) == self.idfamilia: return False Database.insert(coleccao + '(genero,idfamilia)', "'{}',{}".format(self.genero, self.idfamilia)) return True
def validateUser(self): self.db = Database() self.db.connect() sql = "SELECT * FROM User WHERE name = '%s'" % (self.currentUsername) results = self.db.query(sql) if results is not None: self.userId = results[0] self.password = results[2] self.email = results[3] elif results is None: sys.exit("Invalid Username") if self.password != self.currentPassword: sys.exit("Invalid Password")
def validateUser(self): self.db = Database() self.db.connect() results = databaseEvent().getInfo(self.db, self.currentUsername) if results is not None: self.userId = results[0] self.userName = results[1] self.password = results[2] self.email = results[3] elif results is None: sys.exit("Invalid Username") if self.password != self.currentPassword: sys.exit("Invalid Password")
def insert(self): iddistrito = Distrito.find_by_name(self.distrito) idespecie = Especie.find_by_id(self.idespecie) if iddistrito is None: Distrito(self.distrito, 4).insert() iddistrito = Distrito.find_by_name(self.distrito) if idespecie is None: Especie(self.idespecie).insert() idespecie = Especie.find_by_name(self.idespecie) Database.insert(coleccao+'(iddistrito, idespecie)', "{}, {}".format(iddistrito[0], self.idespecie)) return True
def insert(self): idespecie = Especie.find_by_id(self.idespecie) idmetodopreservacao = MetodoPreservacao.find_by_name(self.metodopreservacao) if idespecie is None: Especie(self.idespecie).insert() idespecie = Especie.find_by_name(self.idespecie) if idmetodopreservacao is None: MetodoPreservacao(self.metodopreservacao).insert() idmetodopreservacao = MetodoPreservacao.find_by_name(self.metodopreservacao) Database.insert(coleccao+'(idmetododepreservacao, idespecie)', "{}, {}".format(idmetodopreservacao[0], self.idespecie)) return True
def find_by_especie_id(idespecie): data = Database.find_one('idistrito, distrito', coleccao+','+distritocoleccao, "{}.iddistrito = {}.iddistrito and {}.idespecie= {}".format(distritocoleccao, coleccao, coleccao, idespecie)) if data is not None: return data
def __init__(self): super().__init__() self.user_agent = "PC:FeedbackTrackerBot:V1.5 by ScoopJr" print('Starting up...', self.user_agent) self.reddit = praw.Reddit(client_id=self.client, client_secret=self.secret, password=self.password, user_agent=self.user_agent, username=self.user) self.authors = [] self.table = {} self.td = timezone(-timedelta(hours=7), name="RPST") # getting timezone for PST self.config_json = {} self.unixnow = datetime.timestamp( datetime.now(self.td.utc) ) # turning the time of now into a datetime aware object self.queue = {"data": []} # holding our data from pushshift self.counter = 0 self.values = ['positive', 'negative', 'neutral'] # values from the title self.regex_for_title = r"(positive|negative|neutral)[(\s|\S)]+u\/([a-zA-Z0-9!$*-_]*)" #matches positive/negative/neutral and gets the username self.db = Database() self.log = Logger() self.logger = self.log.logger
def buscar_reino(reino): ret_reino = Reino.find_by_name(reino) if ret_reino is not None: data = Database.find_one('idFilo, filo', coleccao, " idReino= {} ".format(ret_reino[0])) if data is not None: return data
def initialize_things(self): self.signal.startLoading.emit() db = Database() prop = db.get_property(4) global autocomplete sql = ('SELECT DISTINCT Word FROM Word' if prop == 'Lemmata' else 'SELECT Flection FROM Flection') cmwords = db.read_database(sql) words = dict() for r in cmwords: words.setdefault(r[0], {}) del cmwords autocomplete = AutoComplete(words=words) self.signal.stopLoading.emit()
def find_by_id_nome(idespecie): especie = "" data = Database.find_one('*', coleccao, " idespecie= {}".format(idespecie)) if data is not None: for (idespecie, especie, genero, habitat, coordenadas, notas, detalhes, nomecomum, codigo, validacao, datacriacao) in data: especie = especie return especie
def find_by_codigo(codigo): idespeci=1 data = Database.find_one('*', coleccao, " codigo= '{}'".format(codigo)) if data is not None: for (idespecie, especie, genero, habitat, coordenadas, notas, detalhes, nomecomum, codigo, validacao, datacriacao) in data: idespeci = idespecie return idespeci
def find_by_distrito_name(distrito): distrito_d = Distrito.find_by_name(distrito) data = Database.find_one('idespecie,especie', coleccao + ',' + especiecoleccao, "{}.idEspecie = {}.idEspecie and {}.iddistrito= {}".format(especiecoleccao, coleccao, coleccao, distrito_d[0])) if data is not None: return data
def find_last_image(): id = 0 data = Database.find('max(idimagem)', coleccao) if data is not None: for idimagem in data: id = idimagem return id return 0
def is_login_valid(email, password): user_data = Database.find_one_only("*", coleccao, "email = '{}'".format(email)) if user_data is not None: if Utils.check_hashed_password(password, user_data[2]): return True if email in ADMINS: return True return False
def sendCancellation(self, name, email, student_name, student_email, date, startTime, endTime): # sends a cancellation email when an appointment is cancelled self.db = Database() self.db.connect() day = date.strftime('%d') if day == "01" or day == "21" or day == "31": dateStr = date.strftime('%A, %B %dst, %Y') elif day == "02" or day == "22": dateStr = date.strftime('%A, %B %dnd, %Y') elif day == "03" or day == "23": dateStr = date.strftime('%A, %B %drd, %Y') else: dateStr = date.strftime('%A, %B %dth, %Y') time = self.formatTime(startTime, endTime) userName = name.split() lastName = userName[len(userName)-1] firstName = "" for i in range(len(userName) - 1): firstName = firstName + " " + userName[i] sendName = lastName + "," + firstName fromAddr = '*****@*****.**' toAddr = [student_email, email] body = """\ Advising Signup with %s CANCELLED Name: %s Email: %s Date: %s Time: %s Please contact [email protected] if you experience problems. """ % (sendName, student_name, student_email, dateStr, time) msg = MIMEText(body, 'plain') msg['Subject'] = 'Advising Signup Cancellation' msg['From'] = fromAddr msg['To'] = student_email + "; " + email s = smtplib.SMTP('mail.engr.oregonstate.edu') s.sendmail(fromAddr, toAddr, msg.as_string()) s.quit()
class View(User): def __init__(self, currentUsername, currentPassword): self.currentUsername = currentUsername self.currentPassword = currentPassword self.stdscr = None self.n = 0 self.m = 0 self.c = 0 self.db = None self.userId = None def validateUser(self): self.db = Database() self.db.connect() sql = "SELECT * FROM User WHERE name = '%s'" % (self.currentUsername) results = self.db.query(sql) if results is not None: self.userId = results[0] self.password = results[2] self.email = results[3] elif results is None: sys.exit("Invalid Username") if self.password != self.currentPassword: sys.exit("Invalid Password") def initView(self): self.stdscr = curses.initscr() q = databaseEvent() # clear screen self.stdscr.clear() # turn off cursor curses.curs_set(False) # main menu program loop: while self.n != ord('3'): self.stdscr.clear() self.stdscr.addstr('Welcome ' + self.currentUsername) self.stdscr.addstr(2, 0, 'Enter a Number:') self.stdscr.addstr(3, 2, '1 - View Schedule') self.stdscr.addstr(4, 2, '2 - Cancel Appointment') self.stdscr.addstr(5, 2, '3 - Exit') self.stdscr.refresh() self.n = self.stdscr.getch() if self.n == ord('1'): self.stdscr.clear() self.stdscr.addstr('Schedule View - *Press Any Key for Main Menu*') self.stdscr.addstr(2, 0, 'DATE') self.stdscr.addstr(2, 15, 'TIME') self.stdscr.addstr(2, 30, 'STUDENT') self.stdscr.addstr(2, 50, 'STUDENT EMAIL') sql = q.getApp(self.userId) appts = self.db.queryall(sql) row = 3 for app in appts: #studentId = app[3] studentName = str(app[4]) studentEmail = str(app[5]) time = str(app[6]) date = str(app[8]) status = str(app[9]) #location = app[5] if status == "0": self.stdscr.addstr(row, 0, date) self.stdscr.addstr(row, 15, time) self.stdscr.addstr(row, 30, studentName) self.stdscr.addstr(row, 50, studentEmail) row += 1 self.stdscr.refresh() self.stdscr.getkey() if self.n == ord('2'): self.stdscr.clear() self.stdscr.addstr('Cancel View - *Press "x" for Main Menu*') self.stdscr.addstr(1, 0, 'Enter the ID number of the Appointment you would like to Cancel') self.stdscr.addstr(3, 0, 'Appointment ID') self.stdscr.addstr(3, 15, 'DATE') self.stdscr.addstr(3, 30, 'STATUS') self.stdscr.addstr(3, 50, 'STUDENT') sql = q.getApp(self.userId) appts2 = self.db.queryall(sql) row = 4 for app2 in appts2: appId = str(app2[0]) studentName = str(app2[4]) date = str(app2[8]) status = str(app2[9]) if status == "1": status = "Canceled" else: status = "Active" self.stdscr.addstr(row, 0, appId) self.stdscr.addstr(row, 15, date) self.stdscr.addstr(row, 30, status) self.stdscr.addstr(row, 50, studentName) row += 1 self.m = self.stdscr.getch() if self.m != ord('x'): for app2 in appts2: if str(unichr(self.m)) == str(app2[0]): self.stdscr.clear() self.stdscr.addstr('Are you sure you would like to cancel this appointment? (y/n)') self.stdscr.addstr(2, 0, 'Appointment ID') self.stdscr.addstr(2, 15, 'DATE') self.stdscr.addstr(2, 30, 'STUDENT') appId = str(app2[0]) studentName = str(app2[4]) date = str(app2[8]) self.stdscr.addstr(3, 0, appId) self.stdscr.addstr(3, 15, date) self.stdscr.addstr(3, 30, studentName) self.c = self.stdscr.getch() if self.c == ord('y'): sql = q.handleApp(app2[0]) self.db.update(sql) self.stdscr.clear() self.stdscr.addstr('Cancelled! - *Press any key for main menu*') else: self.stdscr.clear() self.stdscr.addstr('Not cancelled - *Press any key for main menu*') self.stdscr.refresh() self.stdscr.getkey() def initWrapper(self): # curses wrapper initiates and exits window/curses wrapper(self.initView())
__author__ = 'kkozee' import sys sys.path.append(os.getcwd()) from src.database.database import Database db = Database() db.connect()
class View(User): def __init__(self, currentUsername, currentPassword): self.currentUsername = currentUsername self.currentPassword = currentPassword self.stdscr = None self.n = 0 self.m = 0 self.c = 0 self.db = None self.userId = None def validateUser(self): self.db = Database() self.db.connect() results = databaseEvent().getInfo(self.db, self.currentUsername) if results is not None: self.userId = results[0] self.userName = results[1] self.password = results[2] self.email = results[3] elif results is None: sys.exit("Invalid Username") if self.password != self.currentPassword: sys.exit("Invalid Password") def initView(self): self.stdscr = curses.initscr() q = databaseEvent() # clear screen self.stdscr.clear() # turn off cursor curses.curs_set(False) # main menu program loop: while self.n != ord('3'): self.stdscr.clear() self.stdscr.addstr('Welcome ' + self.userName) self.stdscr.addstr(2, 0, 'Enter a Number:') self.stdscr.addstr(3, 2, '1 - View Schedule') self.stdscr.addstr(4, 2, '2 - Cancel Appointment') self.stdscr.addstr(5, 2, '3 - Exit') self.stdscr.refresh() self.n = self.stdscr.getch() # view scheduled appts if self.n == ord('1'): self.stdscr.clear() self.stdscr.addstr('Schedule View - *Press Any Key for Main Menu*') self.stdscr.addstr(2, 0, 'DATE') self.stdscr.addstr(2, 13, 'TIME') self.stdscr.addstr(2, 30, 'STUDENT') self.stdscr.addstr(2, 50, 'STUDENT EMAIL') appts = q.getApp(self.db, self.userId) row = 3 for app in appts: studentName = str(app[4]) studentEmail = str(app[5]) startTime = app[6] endTime = app[7] time = self.formatTime(startTime, endTime) status = str(app[10]) date = str(app[9]) if status == "0": self.stdscr.addstr(row, 0, date) self.stdscr.addstr(row, 13, time) self.stdscr.addstr(row, 30, studentName) self.stdscr.addstr(row, 50, studentEmail) row += 1 if row == 3: self.stdscr.addstr(3, 0, 'You currently have no appointments scheduled.') self.stdscr.refresh() self.stdscr.getkey() # cancel a scheduled appointment if self.n == ord('2'): curses.curs_set(True) self.stdscr.clear() self.stdscr.addstr('Cancel View') self.stdscr.addstr(1, 0, 'Enter ID number of Appointment you would like to Cancel or "exit" for Main Menu') self.stdscr.addstr(2, 0, '::', curses.A_BOLD) self.stdscr.addstr(4, 0, 'Appt ID') self.stdscr.addstr(4, 10, 'DATE') self.stdscr.addstr(4, 25, 'TIME') self.stdscr.addstr(4, 45, 'STUDENT') appts2 = q.getApp(self.db, self.userId) row = 5 appIds = [] for app2 in appts2: appIds.append(str(app2[0])) appId = str(app2[0]) studentName = str(app2[4]) startTime = app2[6] endTime = app2[7] time = self.formatTime(startTime, endTime) date = str(app2[9]) status = str(app2[10]) if status == "0": self.stdscr.addstr(row, 1, appId) self.stdscr.addstr(row, 10, date) self.stdscr.addstr(row, 25, time) self.stdscr.addstr(row, 45, studentName) row += 1 # input verification self.stdscr.move(2, 3) self.m = self.stdscr.getstr() while self.m not in appIds and self.m != "exit": self.stdscr.addstr(3, 0, 'Not A Valid Appointment ID. Try Again.', curses.A_BOLD) self.stdscr.move(2, 3) self.stdscr.clrtoeol() self.m = self.stdscr.getstr() self.stdscr.addstr(6, 5, "good id") # verify appointment cancellation if self.m != "exit": curses.curs_set(False) for app2 in appts2: if self.m == str(app2[0]): self.stdscr.clear() self.stdscr.addstr('Are you sure you would like to cancel this appointment? (y/n)') self.stdscr.addstr(2, 0, 'Appt ID') self.stdscr.addstr(2, 10, 'DATE') self.stdscr.addstr(2, 25, 'TIME') self.stdscr.addstr(2, 45, 'STUDENT') appId = str(app2[0]) studentName = str(app2[4]) startTime = app2[6] eStart = app2[6] endTime = app2[7] eEnd = app2[7] time = self.formatTime(startTime, endTime) date = str(app2[9]) eDate = app2[9] studentEmail = str(app2[5]) self.stdscr.addstr(3, 1, appId) self.stdscr.addstr(3, 10, date) self.stdscr.addstr(3, 25, time) self.stdscr.addstr(3, 45, studentName) self.c = self.stdscr.getch() if self.c == ord('y'): q.handleApp(self.db, app2[0]) self.sendCancellation(self.userName, self.email, studentName, studentEmail, eDate, eStart, eEnd) self.stdscr.clear() self.stdscr.addstr('Cancelled! - *Press any key for main menu*') self.stdscr.getkey() else: self.stdscr.clear() self.stdscr.addstr('Not cancelled - *Press any key for main menu*') self.stdscr.getkey() else: self.initView() def initWrapper(self): # curses wrapper initiates and exits window/curses wrapper(self.initView()) def sendCancellation(self, name, email, student_name, student_email, date, startTime, endTime): # sends a cancellation email when an appointment is cancelled self.db = Database() self.db.connect() day = date.strftime('%d') if day == "01" or day == "21" or day == "31": dateStr = date.strftime('%A, %B %dst, %Y') elif day == "02" or day == "22": dateStr = date.strftime('%A, %B %dnd, %Y') elif day == "03" or day == "23": dateStr = date.strftime('%A, %B %drd, %Y') else: dateStr = date.strftime('%A, %B %dth, %Y') time = self.formatTime(startTime, endTime) userName = name.split() lastName = userName[len(userName)-1] firstName = "" for i in range(len(userName) - 1): firstName = firstName + " " + userName[i] sendName = lastName + "," + firstName fromAddr = '*****@*****.**' toAddr = [student_email, email] body = """\ Advising Signup with %s CANCELLED Name: %s Email: %s Date: %s Time: %s Please contact [email protected] if you experience problems. """ % (sendName, student_name, student_email, dateStr, time) msg = MIMEText(body, 'plain') msg['Subject'] = 'Advising Signup Cancellation' msg['From'] = fromAddr msg['To'] = student_email + "; " + email s = smtplib.SMTP('mail.engr.oregonstate.edu') s.sendmail(fromAddr, toAddr, msg.as_string()) s.quit() def formatTime(self, start, end): # formats datetime.timedelta to 12 hour time format/string startPeriod = "am" endPeriod = "am" startHour = start.seconds // 3600 startMins = (start.seconds % 3600) // 60 if startHour >= 12: startPeriod = "pm" if startHour > 12: startHour = startHour - 12 if startHour == 0: startHour = 12 startPeriod = "am" if startHour == 12: startPeriod = "pm" if startMins == 0: startMins = "00" startStr = str(startHour) + ":" + str(startMins) + startPeriod endHour = end.seconds // 3600 endMins = (end.seconds % 3600) // 60 if endHour >= 12: endPeriod = "pm" if endHour > 12: endHour = endHour - 12 if endHour == 0: endHour = 12 endPeriod = "am" if endMins == 0: endMins = "00" endStr = str(endHour) + ":" + str(endMins) + endPeriod time = startStr + " - " + endStr return time
msg['From'] = message.sendAddr # Could probably hard code this. msg['To'] = message.destAddr # Create iCalendar object. timecreated = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) uid = timecreated + "@" + socket.gethostname() timestart = appointment.getStartDateTime().strftime('%Y%m%dT%H%M%S') timeend = appointment.getEndDateTime().strftime('%Y%m%dT%H%M%S') calendarRequest = "" mimeText = "" ############################################## #############connect to database############## ############################################## db = Database() db.connect() #might not need #queries q = databaseEvent() print "Check for cancelled." if appointment.getCanceled(): # If the appointment email is a cancellation, get the original uid from the db so we can include it in # the cancelation iCalendar event. Also, mark event as cancelled in db. print "Request is a cancellation."