def login(mail, passwd, code): print(mail, passwd, code) a = [] a.append(mail) b = [] b.append(passwd) c = [] c.append(code) cnt = 14 number = 0 for i in range(0, 10): k = "a!B" + str(cnt) n = database.read(k) r = "a!G" + str(cnt) h = database.read(r) codeval = "a!B5" code = database.read(codeval) if a == n: number = cnt if b == h: number = cnt if c == code: print("Succes") return "Success" cnt = cnt + 1
async def edit(ctx, *argv): if not is_admin(ctx.message.author.id): return if not is_dm(ctx.channel): return title = "" description = "" inputs = "" output = "" difficulty = -1 hidden = None language = "all" timeout = -1 enable = None for i, arg in enumerate(argv): if len(argv)-1 >= i+1 and '-' not in argv[i+1]: if arg in ['-t', '--title']: title = argv[i+1] if arg in ['-D', '--description']: description = argv[i+1] if arg in ['-i', '--input']: inputs = argv[i+1] if arg in ['-o', '--output']: output = argv[i+1] if arg in ['-d', '--difficulty']: difficulty = int(argv[i+1]) if arg in ['-h', '--hidden']: hidden = bool(argv[i+1].lower() == 'true') if arg in ['-l', '--language']: language = argv[i+1] if arg in ['-T', '--timeout']: timeout = int(argv[i+1]) if arg in ['-e', '--enable']: enable = bool(argv[i+1].lower() == 'true') if language != "all" and language.lower() not in listLang: await ctx.send(f":x: **Le langage `{language}` n'est pas (encore) supporté !**") return try: database.read("exercices.json")[title] await ctx.send(embed=edit_ex(title, difficulty, description, inputs, output, hidden, language.lower(), timeout, enable)) print(f"Exercise '{title}' [{language}] edited by {ctx.message.author.name}") except KeyError: await ctx.send(f":x: **Aucun exercice du nom de `{title}` n'a été trouvé !**")
def check_time(): update_read_from_db = 0 db_list = database.read("alarm") while True: if update_read_from_db >= 20: update_read_from_db = 0 db_list = database.read("alarm") curr_timestamp = datetime.datetime.now() for row in db_list: if len(row) == 0: continue # row[0] is id # row[1] is timestamp # row[2] is running # row[3] is snooze count alarm_timestamp = datetime.datetime.fromtimestamp( int(float( row[1]))) + (int(row[3]) * datetime.timedelta(minutes=8)) if alarm_timestamp < curr_timestamp and int(row[2]) == 0: print("Alarm trigger") row[2] = 1 database.update("alarm", row, row[0]) strings = ["resp", "alarm", "sound"] resp = '&'.join(strings) client.publish("openhome/controller", resp) else: continue update_read_from_db += 1 time.sleep(.05)
def keypair(): private = database.read('keypair', 'private') if private is None: _, _, keygen = crypto.eddsa() public, private = keygen() database.write(public, 'keypair', 'public') database.write(private, 'keypair', 'private') else: public = database.read('keypair', 'public') return public, private
def exam(): examval = "a!B2" examcode = "a!B5" examstime = "a!B3" exametime = "a!B4" a = "" a = a + " " + str(database.read(examval)[0]) a = a + " " + str(database.read(examcode)[0]) a = a + " " + str(database.read(examstime)[0]) a = a + " " + str(database.read(exametime)[0]) print(a) return a
def delete_ex(title): rmtree(title, ignore_errors=True) dec = database.read("exercices.json") del dec[title] database.write("exercices.json", dec) dec = database.read("users.json") for user in dec.values(): try: user['score']['general'] -= user['submit'][title]['best_score'] for sub, data in user['submit'][title].items(): if sub not in ["best_score", "complete"]: user['score'][sub] -= data['score'] del user['submit'][title] except KeyError: pass database.write("users.json", dec)
def retrieve(uid): entry = database.read(uid) if _is_expired(entry): database.delete(uid) raise database.NonExistentUID(uid) else: return entry['text']
def map(ea, size, newea, **kwds): """Map `size` bytes of data from `ea` into a new segment at `newea`. The keyword `name` can be used to name the segment. """ # grab the file offset and the data we want fpos, data = idaapi.get_fileregion_offset(ea), database.read(ea, size) if len(data) != size: raise E.ReadOrWriteError( u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to read {:#x} bytes from {:#x}." .format( __name__, ea, size, newea, u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '', size, ea)) # rebase the data to the new address res = idaapi.mem2base(data, newea, fpos) if not res: raise E.DisassemblerError( u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to remap {:#x}:{:+#x} to {:#x}." .format( __name__, ea, size, newea, u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '', ea, size, newea)) # now we can create the new segment return new(newea, size, kwds.get("name", "map_{:x}".format(ea)))
async def leaderboard(ctx, lang="all"): if lang != "all" and lang.lower() not in listLang: await ctx.send(f":x: **Le langage `{lang}` n'est pas (encore) supporté !**") return dec = database.read("users.json") res = {} for i, u in dec.items(): if lang.lower() == "all": if u['score']['general'] != 0: res[u['name']] = u['score']['general'] else: try: if u['score'][lang.lower()]: res[u['name']] = u['score'][lang.lower()] except KeyError: pass res = dict(sorted(res.items(), key=operator.itemgetter(1), reverse=True)) emoji = {'1': ':first_place:', '2': ':second_place:', '3': ':third_place:'} last = -1 if lang.lower() == "all": embed = discord.Embed(title=":trophy: Classement général") else: embed = discord.Embed(title=f":trophy: Classement général {lang.capitalize()}") desc = "" for i, (name, score) in enumerate(res.items()): if score != last: ind = emoji[str(i+1)] if str(i+1) in emoji.keys() else str(i+1)+" " desc += f"{ind}: {name} ({score}pts)\n" last = score if desc == "": desc = "*Aucune participation n'a été trouvée !*" embed.description = desc await ctx.send(embed=embed)
def checkout(): try: memberID = txtbox.get() int(memberID) # Tests if input is integer msg = "Are you sure you want to checkout \ \nID: %s\ \nTITLE: %s\ \nTO MEMBERID: %s" % (bookID, booktitle, memberID) # Verifies action before checking in confirmed = messagebox.askquestion("Confirm checkout", msg) if confirmed == "yes": bc.checkout(memberID, bookID) populate(read(__DB__)) messagebox.showinfo( "Success!", "Book successfully lent to ID: " + memberID) except ValueError: messagebox.showwarning("Watch out!", "Input is not a number") dialogue.focus_force() except Exception as e: # Displays warnings raised by bookreturn messagebox.showwarning("Watch out!", e) dialogue.focus_force() finally: dialogue.destroy()
def checkinBook(): """ Checks in a book that has been selected on the table. """ import bookreturn as br try: # Gets book info from table selection selection = table.focus() book = table.item(selection) bookID = book["text"] booktitle = book["values"][0] msg = "Are you sure you want to check in \ \nID: %s\ \nTITLE: %s" % (bookID, booktitle) # Verifies action before checking in confirmed = messagebox.askquestion("Confirm check-in", msg) if confirmed == "yes": br.returnBook(bookID) populate(read(__DB__)) except IndexError: # Flashes check-in button if nothing is selected returnBtn.flash() except Exception as e: # Displays warnings raised by bookreturn messagebox.showwarning("Watch out!", e)
def withdraw(): # get current balance # get amount to withdraw # check if current balance > withdraw balance # deduct withdrawn amount form current balance # display current balance current_user_account_number = int(input("Enter your account number: \n")) is_account_valid = validation.account_number_validation( current_user_account_number) if is_account_valid: current_user = str.split(database.read(current_user_account_number), ',') print("Your current account balance is " + "NGN" + current_user[4] + ".00") withdrawal_amount = int( input("Enter the amount you want to withdraw: \n")) if withdrawal_amount <= int(current_user[4]): new_balance = int(current_user[4]) - withdrawal_amount print("Please take your cash.") # update user account balance # database.update(current_user_account_number, 4) print("Your new account balance is " + "NGN" + str(new_balance) + ".00 \n") print("Thank you for banking with us \n") exit() else: print("Insufficient account balance. Please try again") auth.login() else: print("Invalid account number. Please try again") auth.login()
def create_ex(title, author, difficulty, desc, inputs, output, hidden, language, timeout, enable): os.mkdir(title) dec = database.read("exercices.json") data = {'difficulty': difficulty, 'date': database.get_time(), 'author': str(author), 'description': desc, 'inputs': inputs, 'output': output, 'hidden': hidden, 'language': language, 'timeout': timeout, 'enable': enable, 'test_amount': 0, 'executed_test': 0} dec[title] = data database.write("exercices.json", dec) return show_ex(title, data)
def add_transactions(): while mining[0]: new_transactions = database.read('transaction', 'cache') transactions.extend(new_transactions) database.write([], 'transaction', 'cache') database.append(new_transactions, 'transaction', 'mined') time.sleep(1)
def filterMonth(dateRange): """ Filters the logs to checkouts at the specified date range to today. Inputs: dateRange (Int) : Number of days to today Returns: [[String]] : List of transactions matching the filter """ from datetime import date, timedelta from booksearch import inDateRange as dr import database as db # Calculating date range dt1 = date.today() dt2 = dt1 - timedelta(days=dateRange) lastMonth = dt2.strftime("%d/%m/%Y") today = dt1.strftime("%d/%m/%Y") # filtering logs log = db.read(db.__LOG__) checkouts = [entry for entry in log if entry[0] != "" and entry[4] == "checkout" and dr(entry[3], lastMonth, today)] return checkouts
def getInfo(self): #get the object from the database and update fields try: itemID = str(self.platformVar.get()) newObj = db.read(itemID) self.platform = newObj.platform self.url = newObj.link self.username = newObj.username self.password = newObj.password except: #if except, alert and exit self.alertUser(f'''Could not find {itemID} in database. Try adding it.''') return #delete the current values self.passwordBox.delete(0, END) self.usernameBox.delete(0, END) self.linkBox.delete(0, END) self.platformBox.delete(0, END) #put the updated info into the appropriate boxes self.passwordBox.insert(0, self.password) self.usernameBox.insert(0, self.username) self.linkBox.insert(0, self.url) self.platformBox.insert(0, self.platform) return
async def profile(ctx, user=None): dec = database.read("users.json") if user is None: u_disc = ctx.message.author else: if isinstance(user, str): if user.startswith("<@!") and user.endswith(">"): user = user[3:][:-1] try: user = int(user) except ValueError: for u, d in dec.items(): if d['name'] == user: user = int(u) break else: await ctx.send(f":x: Aucun participant du nom de `{user}` n'a été trouvé !") return if isinstance(user, int): u_disc = client.get_user(user) if u_disc is None: await ctx.send(f":x: Aucun participant avec l'id `{user}` n'a pas été trouvé !") return try: user = dec[str(u_disc.id)] except KeyError: username = client.get_guild(688355824934060032).get_member(u_disc.id).nick if username is None: username = client.get_user(u_disc.id).display_name user = database.create_user(dec, username, u_disc.id) await ctx.send(embed=show_user(u_disc, user))
def getItemResource(self, path: str, pageType: str): try: item_id = int(path.split('/')[-1]) course_id = int(path.split('/')[2]) except ValueError: item_id = 0 course_id = 0 if database.exist(item_id=item_id): if database.read(item_id=item_id): print('\t\t\t\tfile downloaded') return else: database.insert(item_id=item_id, course_id=course_id) for retry_count_index in range(10): try: itemRespond = s.get(HOST + path, headers=headers) break except ssl.SSLError as e: print(e) if SAVE_RESPONSE: with open(OUTPUT2_DIR, 'w', encoding='utf-8') as f: f.write(itemRespond.text) if pageType == 'Attachment': parserA = AttachmentParser() parserA.item_id = int(path.split('/')[-1]) parserA.feed(itemRespond.text) if pageType == 'External Tool': post_headers['Referer'] = HOST + path parserV = VideoParser() parserV.item_id = int(path.split('/')[-1]) parserV.feed(itemRespond.text)
async def detail(ctx, title=""): dec = database.read("exercices.json") try: ex = dec[title] except KeyError: await ctx.send(f":x: **Aucun exercice du nom de `{title}` n'a été trouvé !**") return await ctx.send(embed=show_ex(title, ex))
async def add(ctx, *argv): # if not is_admin(ctx.message.author.id): return if not is_dm(ctx.channel): return title = "" inputs = "" outputs = "" author = ctx.message.author for i, arg in enumerate(argv): if len(argv)-1 >= i+1: if arg in ['-t', '--title']: title = argv[i+1] if arg in ['-i', '--input', '--inputs']: inputs = argv[i+1] if arg in ['-o', '--output', '--outputs']: outputs = argv[i+1] dec = database.read("exercices.json") try: exo = dec[title] except KeyError: await ctx.send(f":x: **Aucun exercice du nom de `{title}` n'a été trouvé !**") return if title != "" and inputs != "" and outputs != "": if exo['author'] == str(author.id) or author.id in ADMIN: add_test(title, inputs.replace('/n', '\n').replace("\\n", "\n"), outputs.replace('/n', '\n').replace("\\n", "\n")) else: ctx.send(":x: **Vous n'êtes pas l'auteur de cet exercice !**") return await ctx.send(f":white_check_mark: **Test pour le défi `{title}` créé avec succès !**") print(f"Test added for '{title}' by {ctx.message.author.name}") else: if title == "": await ctx.send(":x: **Veuillez préciser le __titre__ du défi !** (`-t`)") return if inputs == "" and outputs == "": await ctx.send(":x: **Veuillez préciser un __input__ et un __output__ à ce test !** (`-i` et `-o`)") return if inputs == "": await ctx.send(":x: **Veuillez préciser un __input__ à ce test !** (`-i`)") if outputs == "": await ctx.send(":x: **Veuillez préciser un __output__ à ce test !** (`-o`)")
def deposit(): # get current balance # get amount to deposit # add deposited amount to current balance # display current balance current_user_account_number = int(input("Enter your account number: \n")) is_account_valid = validation.account_number_validation( current_user_account_number) if is_account_valid: current_user = str.split(database.read(current_user_account_number), ',') print("Your current account balance is " + "NGN" + current_user[4] + ".00") deposit_amount = int(input("Enter the amount you want to deposit: \n")) new_balance = int(current_user[4]) + deposit_amount # update user account balance # database.update(current_user_account_number, 4) print("Your new account balance is " + "NGN" + str(new_balance) + ".00 \n") print("Thank you for banking with us \n") exit() else: print("Invalid account number. Please try again") auth.login()
def get(self, email): self.isLegalUser(email) if self.request.url.endswith('apply'): self.checkData(mafRead(email)) elif self.request.url.endswith('retreat'): self.checkData(retreatRead(email)) else: self.checkData(read(email))
def read_block(block_index, return_hash=False): block_hash = block_hash_at_index(block_index) if block_hash is None: return None block = database.read('block', block_hash) if return_hash: return block, block_hash return block
def balance(address=None, atomic=False): if address is None: address = public_key() atomic_amount = database.read('wallet', address) if atomic_amount is None: return 0 if atomic: return atomic_amount return atomic_amount / config.UNIT
def get(self, email): if not self.isLegalUser(email): self.error(404) else: if self.request.url.endswith('apply'): data = mafRead(email) else: data = read(email) self.checkData(data)
def verify(): updated_signature = transaction_dict.pop('signature') transaction_dict['signature'] = None if not verifier(crypto.pickle_hash(transaction_dict), updated_signature): transaction_dict['signature'] = updated_signature return False transaction_dict['signature'] = updated_signature try: if not database.read('wallet', wallet_in) >= amount: return False except TypeError: return False tx_hash = crypto.pickle_hash(transaction_dict).decode(errors='ignore') if database.read('transaction', tx_hash) is not None: return False validated[0] = True transaction_hash[0] = tx_hash return True
def fetchRandom(): #random 1 to 30 return that as json scrape_time = datetime.datetime.now().strftime("%Y_%m_%d_%H") rank = random.randint(1,30) if not database.tableExists(scrape_time): database.createTable(scrape_time) database.write(scrape_time,final) data = database.read(scrape_time,rank) return {"rank": data[0], "title": data[1], "time": data[2]}
def undo_block(block_index): block, block_hash = read_block(block_index, True) block_size = sys.getsizeof(pickle.dumps(block, protocol=4)) _ = add_mean_block_size(-block_size, 4, 3) old_mean = database.read('block_size', 'mean') reward = config.reward_function(block_index, block_size, old_mean) database.sub('wallet', block['wallet'], reward) database.sub('block_height', 'main', 1) database.write('block', block_hash, {})
def getHistory(): '''Returns the list containing the existing clipboard history. The list contains dictionaries in the format specified in the getData function. Returns: A list of dict elements containing entries in the clipboard history list ''' return database.read()
def start_timer(profile, name=None): if name: profile = db.read(db.Profile, name[0]) if profile.start == False: profile.begin = time.time() profile.start = True db.update(profile) print(f"> Started timer for {profile.name}") else: print(f"> Timer for {profile.name} is already started.")
async def remove(ctx, title): if not is_admin(ctx.message.author.id): return if not is_dm(ctx.channel): return dec = database.read("exercices.json") try: dec[title] except KeyError: await ctx.send(f":x: **Aucun exercice du nom de `{title}` n'a été trouvé !**") return delete_ex(title) await ctx.send(f":white_check_mark: **Défi `{title}` supprimé avec succès !**") print(f"Exercise '{title}' deleted by {ctx.message.author.name}")
def stop_timer(profile, name=None): if name: profile = db.read(db.Profile, name[0]) if profile.start == True: total = time.time() - profile.begin profile = h.add_time(profile, total) profile.start = False db.update(profile) print(f"> Stopped timer for {profile.name}") else: print(f"> Profile {profile.name} has not been started.")
def map(ea, size, newea, **kwds): '''Map /size/ bytes of data from /ea/ into a new segment at /newea/ /name/ can be used to name the segment. ''' fpos,data = idaapi.get_fileregion_offset(ea),database.read(ea, size) if len(data) != size: raise Exception, "Unable to read %x bytes from %x"% (size, ea) res = idaapi.mem2base(data, newea, fpos) if not res: raise Exception, "Unable to remap %x:+%x to %x"% (ea, size, newea) return create(newea, size, kwds.get('name', 'map_%x'% ea))
def map(ea, size, newea, **kwds): """Map `size` bytes of data from `ea` into a new segment at `newea`. The keyword `name` can be used to name the segment. """ # grab the file offset and the data we want fpos, data = idaapi.get_fileregion_offset(ea), database.read(ea, size) if len(data) != size: raise E.ReadOrWriteError(u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to read {:#x} bytes from {:#x}.".format(__name__, ea, size, newea, u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '', size, ea)) # rebase the data to the new address res = idaapi.mem2base(data, newea, fpos) if not res: raise E.DisassemblerError(u"{:s}.map({:#x}, {:+#x}, {:#x}{:s}) : Unable to remap {:#x}:{:+#x} to {:#x}.".format(__name__, ea, size, newea, u", {:s}".format(utils.string.kwargs(kwds)) if kwds else '', ea, size, newea)) # now we can create the new segment return new(newea, size, kwds.get("name", "map_{:x}".format(ea)))
def list(connection, user): while True: cursor = database.cursor(connection) search.create_views(cursor) menu.clearScreen() print("Existing Bookings\n\n" + \ "Select Row Number for more details or press enter to go back\n\n") query = "select t.tno, t.name, to_char(b.dep_date, 'dd-mon-yy') as dep_date, t.paid_price, b.flightno \ from bookings b, tickets t where b.tno = t.tno and t.email = '{}'".format(user) cursor.execute(query) rows = cursor.fetchall() count_view = 1 print(str("Row").ljust(6) + str("Tno").ljust(6) + str("Passenger Name").ljust(21) + str("Dep Date").ljust(12)\ +str("Price").ljust(8)) x = "-" * 61 print(x) already_seen = [] if len(rows)!= 0: for row in rows: entry_string = [row[0],row[1], row[2],row[3]] if entry_string not in already_seen: print(str(count_view).ljust(6) + str(entry_string[0]).ljust(6) + str(entry_string[1]).strip().ljust(21) + str(entry_string[2]).ljust(12) + str(entry_string[3]).ljust(8)) already_seen.append(entry_string) count_view+=1 else: print("User has no flights") entry = input("\n") if entry == "": break elif not(verify.rowSelection(entry, count_view)): print("Invalid entry, Try Again") elif verify.rowSelection(entry, len(rows)): entry = int(count_view)-2 # actual position in list of rows menu.clearScreen() print("Detailed Booking\n\n" + \ "Press enter to go back or enter 'cancel' to cancel flight\n") query = "select count(tno) from bookings where tno = '{}'".format(str(already_seen[entry][0])) cursor.execute(query) ticket_count = database.read(query, cursor) if int(ticket_count[0])>1: # non-direct flight choose from good_connections query = "select t.tno, to_char(b.dep_date, 'dd-mon-yy') as dep_date, t.paid_price, b.flightno, t.name \ from bookings b, tickets t where b.tno = t.tno and t.tno='{}' and t.email = '{}'".format(str(already_seen[entry][0]),user) cursor.execute(query) rows = cursor.fetchall() query = "select * from good_connections where flightno1 = '{}' or flightno1 = '{}' or flightno2 = '{}'\ or flightno2 = '{}' and price = '{}' \ and dep_date = to_date('{}', 'dd-mon-yy')".format(str(rows[0][3]),str(rows[1][3]),str(rows[1][3]),\ str(rows[0][3]), str(rows[0][2]),str(rows[0][1])) cursor.execute(query) result = cursor.fetchall() #tno is str(already_seen[entry][0]) for x in result: if x[6] == str(rows[0][1]): break print("Tno: " + str(already_seen[entry][0])) print("Passenger Name: " + str(rows[0][4])) print("Departure Date: " + str(rows[0][1])) print("Price: " + str(result[0][6])) print("Flight No1: " + str(x[3])) print("Flight No2: " + str(x[4])) print("Flight Source: " +str(x[0])) print("Flight Destination: " + str(x[1])) print("Fare Type1: " + str(x[8])) print("Fare Type2: " + str(x[9])) query = "select f.descr, ff.bag_allow from flight_fares ff, fares f where ff.flightno = '{}'\ and ff.fare = '{}' and ff.fare = f.fare".format(str(x[3]), str(x[8])) cursor.execute(query) additional_rows = cursor.fetchall() for add_row in additional_rows: print("Fare Type1 Description: " + str(add_row[0])) print("Bags Type1 Allowed: " + str(add_row[1])) query = "select f.descr, ff.bag_allow from flight_fares ff, fares f where ff.flightno = '{}'\ and ff.fare = '{}' and ff.fare = f.fare".format(str(x[4]), str(x[9])) cursor.execute(query) additional_rows = cursor.fetchall() for add_row in additional_rows: print("Fare Type2 Description: " + str(add_row[0])) print("Bags Type2 Allowed: " + str(add_row[1])) while True: nope = input("\n") if nope == "" : break elif nope == "cancel": menu.clearScreen() print("Canceling booking...") query = "DELETE FROM bookings WHERE tno = '{}' and \ dep_date = to_date('{}', 'dd-mon-yy')".format(str(already_seen[entry][0]), str(rows[0][1])) cursor.execute(query) query = "SELECT email FROM tickets" users = database.read(query, cursor) if user.ljust(20) not in users: query = "DELETE FROM passengers WHERE email = '{}' and name = '{}'".format(user, str(rows[0][4])) cursor.execute(query) connection.commit() break else: # direct flight query = "select f.src, f.dst, b.seat, b.fare from bookings b, flights f, tickets t where b.tno = t.tno\ and b.flightno = f.flightno and b.tno = '{}' and b.flightno = '{}'\ and b.dep_date = to_date('{}', 'dd-mon-yy')".format(str(rows[entry][0]), str(rows[entry][4]), str(rows[entry][2])) cursor.execute(query) detailed_rows = cursor.fetchall() for row in detailed_rows: print("Tno: " + str(rows[entry][0])) print("Passenger Name: " + str(rows[entry][1])) print("Departure Date: " + str(rows[entry][2])) print("Price: " + str(rows[entry][3])) print("Flight No: " + str(rows[entry][4])) print("Flight Source: " + str(row[0])) print("Flight Destination: " + str(row[1])) print("Seat No: " + str(row[2])) print("Fare Type: " + str(row[3])) query = "select f.descr, ff.bag_allow from flight_fares ff, fares f where ff.flightno = '{}'\ and ff.fare = '{}' and ff.fare = f.fare".format(str(rows[entry][4]), str(row[3])) cursor.execute(query) additional_rows = cursor.fetchall() for add_row in additional_rows: print("Fare Description: " + str(add_row[0])) print("Bags Allowed: " + str(add_row[1])) while True: nope = input("\n") if nope == "" : break elif nope == "cancel": menu.clearScreen() print("Canceling booking...") query = "DELETE FROM bookings WHERE tno = '{}' and \ dep_date = to_date('{}', 'dd-mon-yy')".format(str(rows[entry][0]), str(rows[entry][2])) cursor.execute(query) query = "SELECT email FROM tickets" users = database.read(query, cursor) if user.ljust(20) not in users: query = "DELETE FROM passengers WHERE email = '{}' and name = '{}'".format(user, str(rows[entry][1])) cursor.execute(query) connection.commit() break else: print("Invalid entry, Try Again")
) parser.add_argument( "-p", "--plotfolder", default="/users/stollenw/projects/euo/database/analysis/hetero/avmag/", help="Database file name", ) parser.add_argument("-s", "--short", action="store_true", help="Less output") args = parser.parse_args() if not os.path.exists(args.plotfolder): os.makedirs(args.plotfolder) database = database.heterostructure_database() if args.database != "/users/stollenw/projects/euo/database/hetero.db": database.read(args.database) else: database.download() # get columns of data and remove duplicates by converting to # a set (no duplicates) and back to a list material_list = list(set([row[0] for row in database.data])) N_list = list(set([int(row[1]) for row in database.data])) M_list = list(set([int(row[2]) for row in database.data])) ni_list = list(set([float(row[3]) for row in database.data])) ncr_list = list(set([float(row[4]) for row in database.data])) dW_list = list(set([float(row[5]) for row in database.data])) # sort data material_list.sort() N_list.sort()
def genTicket(cursor): query = "SELECT tno FROM tickets" tickets = database.read(query, cursor) return max(tickets)+1
def make(user, row, connection): cursor = database.cursor(connection) try: query = "SELECT name FROM passengers where email='{}'".format(user) names = database.read(query, cursor) name="" while not(verify.char20(name)): name = input("Please enter a name: ").strip() if not(verify.char20(name)): print("Invalid Name Length, Try Again") if name.strip().ljust(20) not in names: print("Creating passenger...\n") country="" while not(verify.char10(country)): country = input("Please enter a country: ").strip() if not(verify.char10(country)): print("Invalid Country Name Length, Try Again") query = "INSERT INTO passengers (email, name, country) VALUES ('{}','{}','{}')".format(user, str(name), str(country)) cursor.execute(query) connection.commit() tno = genTicket(cursor) if row[7] != "Direct": # not a direct booking multiple tickets needed # flight no 1 row[0], fare type f1 row[10] # flight no 2 row[1], fare type f2 row[11] # dep_date row[12] #UPDATE THE VIEWS search.create_views(cursor) query = "select seats from good_connections WHERE flightno1 = '{}' AND flightno2 = '{}' and a1_fare = '{}'\ and a2_fare = '{}' ".format(str(row[0]),str(row[1]),str(row[10]),str(row[11])) seat = database.read(query, cursor) if int(seat[0])>0: print("Creating booking...\n") #generate our ticket #price row[8] query = "insert into tickets (tno, name, email, paid_price)\ VALUES ('{}','{}','{}','{}')".format(tno, name, user, str(row[8])) cursor.execute(query) # now we can make our bookings query = "insert into bookings (tno, flightno, fare, dep_date, seat)\ VALUES ('{}','{}','{}','{}','{}')".format(tno, str(row[0]), str(row[10]), str(row[12]), "TBD1") cursor.execute(query) #first part of flight query = "insert into bookings (tno, flightno, fare, dep_date, seat)\ VALUES ('{}','{}','{}','{}','{}')".format(tno, str(row[1]), str(row[11]), str(row[12]), "TBD2") cursor.execute(query) #second part of flight connection.commit() print("Booking created successfully") print("Tno:{} under {}".format(tno,name)) return True else: print("Booking failed, try again") return False else: # direct booking, same procedure one less time search.create_views(cursor) query = "select seats from available_flights WHERE flightno = '{}' AND fare = '{}'".format(str(row[0]),str(row[10])) seat = database.read(query, cursor) if int(seat[0])>0: print("Creating booking...\n") #generate our ticket #price row[8] query = "insert into tickets (tno, name, email, paid_price)\ VALUES ('{}','{}','{}','{}')".format(tno, name, user, str(row[8])) cursor.execute(query) query = "insert into bookings (tno, flightno, fare, dep_date, seat)\ VALUES ('{}','{}','{}','{}','{}')".format(tno, str(row[0]), str(row[10]), str(row[12]), "TBD") cursor.execute(query) connection.commit() print("Booking created successfully") print("Tno:{} under {}".format(tno,name)) return True else: print("Booking failed, try again") return False except: error, = cx_Oracle.DatabaseError.args print(sys.stderr, "Oracle code:", error.code) print(sys.stderr, "Oracle message:", error.message) print("Booking failed, try again") return False
def get_linked(uid): entry = database.read(uid) return entry['linked']
def db_read(self, key): return database.read(key)
def round_trip(user, row, return_date, connection): cursor = database.cursor(connection) search.create_views(cursor) connection.commit() try: query = "SELECT name FROM passengers where email='{}'".format(user) names = database.read(query, cursor) name="" while not(verify.char20(name)): name = input("Please enter a name: ").strip() if not(verify.char20(name)): print("Invalid Name Length, Try Again") if name.strip().ljust(20) not in names: print("Creating passenger...\n") country="" while not(verify.char10(country)): country = input("Please enter a country: ").strip() if not(verify.char10(country)): print("Invalid Country Name Length, Try Again") query = "INSERT INTO passengers (email, name, country) VALUES ('{}','{}','{}')".format(user, str(name), str(country)) cursor.execute(query) connection.commit() tno = genTicket(cursor) if row[7] != "Direct": # not a direct booking multiple tickets needed # flight no 1 row[0], fare type f1 row[10] # flight no 2 row[1], fare type f2 row[11] # dep_date row[12] #UPDATE THE VIEWS search.create_views(cursor) query = "select seats from good_connections WHERE flightno1 = '{}' AND flightno2 = '{}' and a1_fare = '{}'\ and a2_fare = '{}' ".format(str(row[0]),str(row[1]),str(row[10]),str(row[11])) seat = database.read(query, cursor) if int(seat[0])>0: print("Creating booking...\n") #generate our ticket #price row[8] query = "insert into tickets (tno, name, email, paid_price)\ VALUES ('{}','{}','{}','{}')".format(tno, name, user, str(row[8])) cursor.execute(query) # now we can make our bookings query = "insert into bookings (tno, flightno, fare, dep_date, seat)\ VALUES ('{}','{}','{}','{}','{}')".format(tno, str(row[0]), str(row[10]), str(row[12]), "TBD1") cursor.execute(query) #first part of flight query = "insert into bookings (tno, flightno, fare, dep_date, seat)\ VALUES ('{}','{}','{}','{}','{}')".format(tno, str(row[1]), str(row[11]), str(row[12]), "TBD2") cursor.execute(query) #second part of flight connection.commit() print("Booking created successfully") print("Tno:{} under {}".format(tno,name)) return True else: print("Booking failed, try again") return False else: # direct booking, same procedure one less time search.create_views(cursor) query = "select seats from available_flights WHERE flightno = '{}' AND fare = '{}'".format(str(row[0]),str(row[10])) seat = database.read(query, cursor) if int(seat[0])>0: print("Creating booking...\n") #generate our ticket #price row[8] query = "insert into tickets (tno, name, email, paid_price)\ VALUES ('{}','{}','{}','{}')".format(tno, name, user, str(row[8])) cursor.execute(query) query = "insert into bookings (tno, flightno, fare, dep_date, seat)\ VALUES ('{}','{}','{}','{}','{}')".format(tno, str(row[0]), str(row[10]), str(row[12]), "TBD") cursor.execute(query) connection.commit() print("Booking created successfully") print("Tno:{} under {}".format(tno,name)) print("\nGoing to select your return trip...") sort = "" while sort!="0" and sort!="1": sort = input("Enter 0 to sort by price or 1 to sort by number of connections for return trip: ") source = row[3] destination = row[2] departure_date = return_date search_query_gc = "select * from good_connections gc where gc.src='{}' and gc.dst='{}' and \ gc.dep_date = to_date('{}', 'dd-mm-yy')\ order by price asc, layover asc".format(source, destination, departure_date) search_query_af = "select * from available_flights af where af.src='{}' and af.dst='{}' and \ af.dep_date = to_date('{}', 'dd-mm-yy') order by price asc".format(source, destination, departure_date) cursor.execute(search_query_gc) search_query_gc_rows = cursor.fetchall() cursor.execute(search_query_af) search_query_af_rows = cursor.fetchall() count = 1 menu.clearScreen() print("Return Trips Found\n\n" + \ "Select Row Number to book or press enter to cancel\n\n") print(str("Row").ljust(6) + str("Fl no1").ljust(9) + str("Fl no2").ljust(9) + str("Src").ljust(5) + str("Dst").ljust(5) + str("Dep Time").ljust(10)\ + str("Arr Time").ljust(10) + str("Stops").ljust(7) + str("Layover(hrs)").ljust(14) + str("Total Price").ljust(14)\ + str("Seats").ljust(7)) x = "-" * 98 print(x) all_roxs = [] for rox in search_query_af_rows: all_roxs.append([rox[0],"N/A",rox[2],rox[3],rox[4].strftime('%H:%M'),rox[5].strftime('%H:%M'),"0","Direct",int(rox[8])+row[8],rox[7],rox[6],"N/A", departure_date]) for rox in search_query_gc_rows: all_roxs.append([rox[3],rox[4],rox[0],rox[1],rox[10].strftime('%H:%M'),rox[11].strftime('%H:%M'),"1","{0:.2f}".format(rox[5]),rox[6]+row[8],rox[7],rox[8], rox[9], departure_date]) if len(search_query_af_rows) == 0 and len(search_query_gc_rows) == 0: print("No flights found") elif sort == "0": all_roxs.sort(key=lambda x:x[8]) for rox in all_roxs: print(str(count).ljust(6) + str(rox[0]).ljust(9) + str(rox[1]).ljust(9) + str(rox[2]).ljust(5) + str(rox[3]).ljust(5) + str(rox[4]).ljust(10)\ + str(rox[5]).ljust(10) + str(rox[6]).ljust(7) + str(rox[7]).ljust(14) + str(rox[8]).ljust(14)\ + str(rox[9]).ljust(7)) count += 1 elif sort == "1": all_roxs.sort(key=lambda x:x[6]) for rox in all_roxs: print(str(count).ljust(6) + str(rox[0]).ljust(9) + str(rox[1]).ljust(9) + str(rox[2]).ljust(5) + str(rox[3]).ljust(5) + str(rox[4]).ljust(10)\ + str(rox[5]).ljust(10) + str(rox[6]).ljust(7) + str(rox[7]).ljust(14) + str(rox[8]).ljust(14)\ + str(rox[9]).ljust(7)) count += 1 while True: entry = input("\n") if entry == "": break elif verify.rowSelection(entry, len(all_roxs)): entry = int(entry)-1 # actual position in list of roxs make(user,all_roxs[entry], connection) else: print("Booking failed, try again") return False except: error, = cx_Oracle.DatabaseError.args print(sys.stderr, "Oracle code:", error.code) print(sys.stderr, "Oracle message:", error.message) print("Booking failed, try again") return False
def login(connection): cursor = database.cursor(connection) menu.clearScreen() print( "Login to Airline Booking System\n" + "-------------------------\n" + "Select an option:\n\n" + "0 - Login\n" + "1 - Create Account\n" + "2 - Exit\n" + "-------------------------" ) entries = [x for x in range(3)] while True: option = input("\nOption: ") if option == "0": email = "" password = "" while len(email) > 20 or len(email) == 0: email = input("\nEmail: ").strip().lower() if len(email) > 20 or len(email) == 0: print("Invalid Email Length, Try Again") users = database.read("SELECT email FROM USERS", cursor) if email not in users: print("User does not exist!") else: while len(password) > 4 or len(password) == 0: password = getpass.getpass("Password: "******"Invalid Password length, Try Again") users_pass = database.read("SELECT pass FROM USERS", cursor) if password != users_pass[users.index(email)]: print("Incorrect password!") elif password == users_pass[users.index(email)]: break elif option == "1": email = "" password = "" while len(email) > 20 or len(email) == 0: email = input("\nNew Email: ").strip().lower() if len(email) > 20 or len(email) == 0: print("Invalid Email Length, Try Again") while len(password) > 4 or len(password) == 0: password = getpass.getpass("New Password: "******"Invalid Password length, Try Again") createUser(email, password, cursor) connection.commit() break elif option == "2": menu.clearScreen() sys.exit() elif option not in entries: print("Invalid input, try again") database.close(cursor) return email