コード例 #1
0
def printQuerys(k): # listar consultas
  os.system("cls")
  querys = loadQuerys()
  parameters = ["Nº da Consulta", "Nome do Médico", "Nome do Paciente", "Data", "Horário"]
  printHeader2(parameters)
  print()
  for item in querys[:5+k]:
    for i in item:
      print("{0:<20}".format(i), end="")
    print()
  if len(querys[k:]) != 0:
    msg = "Deseja mostrar mais Consultas? [y/n]: "
    if validateToContinue(msg):
      k = k+5
      printQuerys(k)
    else:
      msg = "Deseja voltar para o menu? [y/n]: "
      if validateToContinue(msg):
        menu()
      else:
        printQuerys(k)
  else:
    msg = "Deseja voltar para o menu? [y/n]: "
    if validateToContinue(msg):
      menu()
    else:
      printQuerys(k)
コード例 #2
0
def restituzione(database):
    rows = database.select_prestiti_daRestituire(None)
    for row in rows:
        id_utente = row['id_utente']
        id_libro = row['id_libro']
        UtenteIsbloccato(database, id_utente)

    print(
        tabulate(rows,
                 headers=[
                     "ID", "Data inizio", "Data Restituzione", "Data scedenza",
                     "ID utente", "Nome", "Cognome", "ID Libro", "Titolo"
                 ],
                 tablefmt="github"))

    print("Inserisci il libro da restituire:")
    ID = input()
    rows = database.select_libri_categorie(id_libro)
    numerocopie = 0
    for row in rows:
        numerocopie = row['numerocopie']
    database.update_libri_numlibri(id_libro, numerocopie + 1)
    database.update_prestiti(ID)
    database.conn_db.commit()
    M.menu(database)
コード例 #3
0
def insert_row():
    list_table = []
    cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
    tables = cursor.fetchall()
    tables_str = ""
    for i,k in enumerate(tables):
        for j in k:
            list_table.append(j)
            tables_str += f"\n{i+1} {j}"
    print(tables_str)
    check = int(input("Select Table: "))
    cursor.execute(f"Select * FROM {list_table[check-1]} LIMIT 0")
    colnames = [desc[0] for desc in cursor.description]
    col_str = ""
    value_str = ""
    record = []
    for i in colnames:
        val_col = input(f"enter value for {i}: ")
        col_str += f" {i},"
        value_str += " %s,"
        record.append(val_col)
    postgres_insert_query = f""" INSERT INTO {list_table[check-1]} ({col_str[1:-1]}) VALUES ({value_str[1:-1]})"""
    record_to_insert = tuple(record)
    cursor.execute(postgres_insert_query, record_to_insert)
    connection.commit()
    main.menu()
コード例 #4
0
def eliminaUtente(database):
    rows = database.select_utenti(None)
    print("Quali tra i seguenti utenti vuoi eliminare? ")
    print(
        tabulate(
            rows,
            headers=["ID", "Nome", "Cognome", "Data registrazione", "Stato"],
            tablefmt="github"))
    id = input()
    # controllo che il numero inserito sia un intero altrimenti genero un errore
    try:
        id = int(id)
    except ValueError:
        print("Errore inserirsci un id corretto! ")
        Menu.scelta3(database)

    try:
        database.delete_utenti(id)
    except:
        print(
            "Impossibile eliminare utente perchè è già stato utilizzato in un altra tabella "
        )
        Menu.scelta2(database)
    database.conn_db.commit()
    M.menu(database)
コード例 #5
0
def aggiungiUtente():
    global utentiAggiunti
    print("Inserisci il nome \n")
    nome = input()
    print("Inserisci il cognome \n")
    cognome = input()
    M.menu()
コード例 #6
0
def hash_cracking_menu():
    print("1: register a wordlist ")
    print("2: register a word ")
    print("3: crack hash ")
    print("4: Return ")
    while True:
        choix_1_1 = int(input("please type your choice : "))
        try:
            if choix_1_1 in [1, 2, 3, 4]:

                if choix_1_1 == 1:
                    register_wordlist()
                    break
                if choix_1_1 == 2:
                    word = input(
                        "please type the word you'd like to regiser : ")
                    register_word(word)
                    print("word registred successfully")
                    hash_cracking_menu()
                    break
                if choix_1_1 == 3:
                    crack_word()
                    break
                elif choix_1_1 == 4:
                    main.menu()
                    break

            else:
                print("Please provide integer between 1 and 4")

        except ValueError:
            print("Please provide integer")
            break
コード例 #7
0
def loose_message(word):
    os.system('clear')
    print(life_status.get_loose_ascii())
    print("The puzzle was " + word + "...\n")
    life_status.dead_status()
    time.sleep(4.3)
    main.menu()
コード例 #8
0
def printPatients(k): # listar lista de pacientes
  os.system("cls")
  patients = loadPatients()
  parameters = ["Nome", "E-Mail", "Telefone", "RG", "CPF", "Endereço", "Numero", "Bairro", "Cidade", "Estado", "Plano de Saúde"]
  printHeader(parameters)
  print()
  for item in patients[:5+k]:
    for i in range(len(item)):
      if i != 1:
        print("{0:<12}".format(item[i]), end="")
      else:
        print("{0:<24}".format(item[i]), end="")
    print()
  if len(patients[k:]) != 0:
    msg = "Deseja mostrar mais Pacientes? [y/n]: "
    if validateToContinue(msg):
      k = k+5
      printPatients(k)
    else:
      msg = "Deseja voltar para o menu? [y/n]: "
      if validateToContinue(msg):
        menu()
      else:
        printPatients(k)
  else:
    msg = "Deseja voltar para o menu? [y/n]: "
    if validateToContinue(msg):
      menu()
    else:
      printPatients(k)
コード例 #9
0
ファイル: games.py プロジェクト: muzhma/ib-cs-sl1-midterm
def scrambled():
	"""Unscramble the word"""

	content = helpers.init()
	print('\nYou can exit at anytime by entering \'menu\'.\n')

	random.shuffle(content)
	count = len(content)
	correct = 0
	incorrect = 0
	i = 0
	shuffled = []

	for word in content:
		scrmbld = helpers.scramble_string(word['key'])
		shuffled.append(scrmbld)

	for scr in shuffled:
		res = input('\n{}. {}.\n\t=>'.format(i + 1, scr)).lower()

		if res == content[i]['key'].lower():
			count -= 1
			correct += 1
			if count > 0:
				print('\nGood Job! next word!')		
		elif res == 'menu':
			main.menu()
		else:
			incorrect += 1
			count -= 1
			if count > 1:
				print('\nIncorrect. Next word.')
		i += 1
	print('\nYou got {} correct and {} incorrect'.format(correct, incorrect))
	helpers.callback(scrambled)
コード例 #10
0
def take_a_guess(word):
    guess = " "
    while guess not in string.ascii_letters:
        guess = input("Take a guess and type a letter! ")
        if guess == "quit" or guess == "exit":
            main.menu()
    return guess
コード例 #11
0
ファイル: about.py プロジェクト: unsa2017/Lockdoor-Framework
def show():
    clscprilo()
    print("""

    #############################################################
    #                   Lockdoor Framework                      #
    #  A Penetration Testing framework with CyberSec Resources  #
    #############################################################
    #    -- Version: v2.2 01/01/2020                            #
    #    -- Developer: Sofiane Hamlaoui                         #
    #    -- Thanks: No One                                      #
    #############################################################

                        \033[94m-[!]-Description-[!]-\033[91m
   LockDoor is a Framework aimed at helping penetration testers,
   bug bounty hunters And cyber security engineers.
   This tool is designed for Debian/Ubuntu/ArchLinux based
   distributions to create a similar and familiar distribution
   for Penetration Testing. But containing the favorite and the most used tools by
   Pentesters.
   As pentesters, most of us has his personal ' /pentest/ ' directory so this
   Framework is helping you to build a perfect one.
    """)
    oktocont()
    main.menu()
コード例 #12
0
ファイル: games.py プロジェクト: muzhma/ib-cs-sl1-midterm
def def_first():
	"""Game for matching word to definiton"""
	content = helpers.init()
	print('\nYou can exit at anytime by entering \'menu\'.\n') 
	random.shuffle(content)
	count = len(content)
	correct = 0
	incorrect = 0
	for word in content:
		print('\n{}. {}'.format(operator.indexOf(content, word) + 1, word['definition']))
		res = input('\nWhat word does this definition belong to?\n\t=>').lower()

		if res == word['key'].lower():
			count -= 1
			correct += 1
			if count > 0:
				print('\nGood Job! next word!')		
		elif res == 'menu':
			main.menu()
		else:
			incorrect += 1
			count -= 1
			if count > 1:
				print('\nIncorrect. Next word.')
				
	print('\nYou got {} correct and {} incorrect'.format(correct, incorrect))
	helpers.callback(def_first)
コード例 #13
0
ファイル: more.py プロジェクト: kinsei/resume
def more():

    sub.call("clear")
    cprint ("Below is a list of GitHub repositories if you would like to download one enter", 'green')
    cprint ("the name of the repo as shown or just press inter to exit:", 'green')
    cprint ("\n\n\n1) Learn-Python-The-Hard-Way:", 'green', attrs=['bold'])
    cprint ("    This repo is, at this time, most of the exercises from the book 'Learn\n    Python The Hard way'. I found this book to be of great use.", 'green')
    cprint ("\n2) Pluralsight:", 'green', attrs=['bold'])
    cprint ("    This repo is a project I did to learn PyQt and how to build GUI's. Its\n    its called Pluarlsight because its a great websight that teaches differant programming languages and this is where I learned PyQt.", 'green')
    cprint ("\n3) Random:", 'green', attrs=['bold'])
    cprint ("    This holds random code like a port scaner and a copy of my .bashrc.", 'green')
    cprint ("\n\n\n\nGit is required for the download to work:", 'green', 'on_red',attrs=['bold'])
    responce = raw_input(colored(">>> "))

    if responce == "":
        main.menu()

    elif responce == "Learn-Python-The-Hard-Way":
        sub.call(['git', 'clone', 'https://github/kinsei/Learn-Python-The-Hard-Way'])
        more()
     
    elif responce == "Pluralsight":
        sub.call(['git', 'clone', 'https://github.com/kinsei/Pluralsight'])
        more()

    elif responce == "Random":
        sub.call(['git', 'clone', 'https://github.com/kinsei/Random'])
        more()


    else:
        main.menu()
コード例 #14
0
def printDoctors(k): # listar lista de médicos
  os.system("cls")
  doctors = loadDoctors()
  parameters = ["Nome", "E-Mail", "Telefone", "Celular", "CRM", "RG", "CPF", "Espec", "End", "^Nº ", "Cidade", "UF", "Plano"]
  printHeader(parameters)
  print()
  for item in doctors[:5+k]:
    for i in range(len(item)):
      if i != 1:
        print("{0:<12}".format(item[i]), end="")
      else:
        print("{0:<24}".format(item[i]), end="")
    print()
  if len(doctors[k:]) != 0:
    msg = "Deseja mostrar mais Médicos? [y/n]: "
    if validateToContinue(msg):
      k = k+5
      printDoctors(k)
    else:
      msg = "Deseja voltar para o menu? [y/n]: "
      if validateToContinue(msg):
        menu()
      else:
        printDoctors(k)
  else:
    msg = "Deseja voltar para o menu? [y/n]: "
    if validateToContinue(msg):
      menu()
    else:
      printDoctors(k)
コード例 #15
0
def menu():
    print('\nElija que item desea actualizar\n')
    print('1 - Modificar datos en Martillos')
    print('2 - Modificar datos de la Camara 1')
    print('3 - Modificar datos de la Camara 2')
    print('9 - Salir a menu Principal')

    # SE LE SOLICITA UNA OPCION AL USUARIO
    opcion = input('\nIngrese la opcion deseada:\n>>>')
    if not opcion:
        print('\nNo escribio nada\n')
        print('\nVUelve a intentar\n')
        menu()

    if opcion == '1':
        os.system('clear')
        menu_martillo()

    elif opcion == '2':
        os.system('clear')
        menu_camara1()

    elif opcion == '3':
        os.system('clear')
        menu_camara2()

    elif opcion == '9':
        os.system('clear')
        main.menu()
    else:
        print('\n*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*')
        print('No se encuentra la opcion requerida, elija de nuevo!!!')
        print('*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n')
        menu()
コード例 #16
0
def cancellaLibro(database):
    print("Seleziona dal elenco il libro da eliminare: ")
    rows = database.select_libri_categorie(None)
    # tabulete crea una tabella per migliorare la visulizzazione dei nostri dati
    print(
        tabulate(rows,
                 headers=[
                     "ID", "autore", "titolo", "Numero copie",
                     "Anno produzione", "Categoria"
                 ],
                 tablefmt="github"))
    id = input()
    # controllo che il numero inserito sia un intero altrimenti genero un errore
    try:

        id = int(id)
    except ValueError:
        print("Errore inserirsci un id corretto! ")
        Menu.scelta4(database)
    try:
        database.delete_libri(id)
    except:
        print(
            "Impossibile eliminare la categoria perchè è già stata utilizzata in un altra tabella "
        )
        Menu.scelta2(database)
    database.conn_db.commit()
    M.menu(database)
コード例 #17
0
def close_db():
    if(connection):
                cursor.close()
                connection.close()
                print("PostgreSQL connection is closed")
    time.sleep(2)
    main.menu()
コード例 #18
0
def def_first():
	"""Game for matching word to definiton"""
	content = helpers.init()
	print('\nYou can exit at anytime by entering \'menu\'.\n') 
	random.shuffle(content)
	count = len(content)
	correct = 0
	incorrect = 0
	for word in content:
		print('\n{}. {}'.format(operator.indexOf(content, word) + 1, word['definition']))
		res = input('\nWhat word does this definition belong to?\n\t=>').lower()

		if res == word['key'].lower():
			count -= 1
			correct += 1
			if count > 0:
				print('\nGood Job! next word!')		
		elif res == 'menu':
			main.menu()
		else:
			incorrect += 1
			count -= 1
			if count > 1:
				print('\nIncorrect. Next word.')
				
	print('\nYou got {} correct and {} incorrect'.format(correct, incorrect))
	helpers.callback(def_first)
コード例 #19
0
def roundBooking(email, CONN_STRING, flightno, rs, dep_date, ret_date, source, dest):
    row = rs[flightno-1]
    if row[-2] <= 0:
        print("tickets not exists, please choose another flight")
        printInfo(email, CONN_STRING, source, dest, dep_date, "1")
    try:
        sql = "select max(tno) from tickets"
        maxTno = main.sqlWithReturn(sql, CONN_STRING)[0][0]
        sql = "select name from passengers where email = '{0}'".format(email)
        name = main.sqlWithReturn(sql, CONN_STRING)[0][0]
        sql = "insert into tickets values({0}, '{1}', '{2}', '{3}')".format(maxTno+1, name, email, row[-1])
        main.sqlWithNoReturn(sql, CONN_STRING)
        sql = "insert into bookings values({0}, '{1}', '{2}', to_date('{3}', 'DD/MM/YYYY'), null)".format(maxTno+1, row[0], row[8], dep_date)
        main.sqlWithNoReturn(sql, CONN_STRING)
        sql = "insert into bookings values({0}, '{1}', '{2}', to_date('{3}', 'DD/MM/YYYY'), null)".format(maxTno+1, row[10], row[-5], ret_date)
        main.sqlWithNoReturn(sql, CONN_STRING)
        if row[1] is not None:
            sql = "insert into bookings values({0}, '{1}', '{2}', to_date('{3}', 'DD/MM/YYYY'), null)".format(maxTno+1, row[1], row[9], dep_date)
            main.sqlWithNoReturn(sql, CONN_STRING)
        if row[11] is not None:
            sql = "insert into bookings values({0}, '{1}', '{2}', to_date('{3}', 'DD/MM/YYYY'), null)".format(maxTno+1, row[11], row[-4], ret_date)
            main.sqlWithNoReturn(sql, CONN_STRING)
        print("success")
    except:
        print("There was an error during booking. Please try again")
        main.menu(email, CONN_STRING)
    printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date)
コード例 #20
0
ファイル: venda.py プロジェクト: bkullmanns/estoque-calcados
def venda():
    modelo = dados.modelosFixos[pegou.pegaModelo()-1]
    numeracao = pegou.pegaNumeracao()
    quantidade = pegou.pegaQuantidade()
    cor = dados.lstCor[pegou.pegaCor()-1]

    achei = False
    for i, m in enumerate(dados.lstModelo):
        if modelo == dados.lstModelo[i] and int(numeracao) == int(dados.lstNumeracao[i]) and cor == dados.lstCor[i]:
            achei = True
            if int(dados.lstQtd[i]) >= quantidade:
                achei = True
                tabelas.tabelaVenda(modelo, numeracao, cor, quantidade)
                confirmacao = input("\n Confirma? s/n: ")
                if confirmacao == "s":
                    dados.lstQtd[i] = int(dados.lstQtd[i]) - quantidade
                    input("Venda confirmada. ")
                    menu()
            else:
                input("Venda cancelada. ")

    calculos.calculaEstoqueModelo()
    calculos.calculaEstoqueTotal()

    if not achei:
        op = input("Produto não encontrado. Digite um produto cadastrado ou 0 para retornar ao menu. ")
        if op == "0":
            principal.menu()
        else:
            venda()
コード例 #21
0
ファイル: hashing.py プロジェクト: yazidbouallagui/cyptobox
def hashing():
    print("1: md5 ")
    print("2: sh1 ")
    print("3: sh256 ")
    print("4: sh512 ")
    print("5: Return ")
    while True:
        choix_1_1 = int(input("please type your choice : "))
        try:
            if choix_1_1 in [1, 2, 3, 4, 5]:

                if choix_1_1 == 1:
                    md5_enc()
                    break
                if choix_1_1 == 2:
                    sha1_enc()
                    break
                if choix_1_1 == 3:
                    sha256_enc()
                    break
                if choix_1_1 == 4:
                    sha512_enc()
                    break
                elif choix_1_1 == 5:
                    main.menu()
                    break

            else:
                print("Please provide integer between 1 and 5")

        except ValueError:
            print("Please provide integer")
            break
コード例 #22
0
def menu():
    clscprilo()
    print("""\033[94m
    [ REVERSE ENGINEERING  ]

        Make A Choice :\033[90m
    \033[91m -[!]----- Tools ------[!]-\033[90m

            \033[93m1)  Radar2
            2)  Virustotal
            3)  Miasm
            4)  Mirror
            5)  Dnspy
            6)  Angrio
            7)  DLLRunner
            8)  Yara\033[90m
    \033[91m-[!]----- Cheatsheets ------[!]-\033[90m

        \033[93m    9) Reverse Engineering Cheatsheets\033[90m
    ------------------------
    \033[94mb)    Back to ROOT MENU
    q)    Leave  Lockdoor\033[94m
       """)
    choice = input("\033[92mLockdoor@ReverseEngineering~# \033[0m")
    os.system('clear')
    if choice == "1":
        radar2()
    elif choice == "2":
        virustotal()
    elif choice == "3":
        miasm()
    elif choice == "4":
        mirror()
    elif choice == "5":
        Dnspy()
    elif choice == "6":
        angrio()
    elif choice == "7":
        dllrunner()
    elif choice == "8":
        yara()
    elif choice == "9":
        revsh()
    elif choice == "b":
        main.menu()
    elif choice == "q":
        prilogspc()
        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        print(
            "                 \033[91m-[!]- LOCKDOOR IS EXITING -[!]-\033[0m")
        spc()
        print("                 \033[91m-[!]- EXITING AT " + dt_string +
              " -[!]-\033[0m")
        sys.exit()
    elif choice == "":
        menu()
    else:
        menu()
コード例 #23
0
def aggiungiUtente(database):
    print("Inserisci il nome \n")
    nome = input()
    print("Inserisci il cognome \n")
    cognome = input()
    database.insert_utenti(nome, cognome, DB.UTENTE_STATO_ATTIVO)
    database.conn_db.commit()
    M.menu(database)
コード例 #24
0
def katsu_hash_menu():
    import cipher.hashbased.hashFunctions as hf
    import base64

    choices = ["Generate a hash", "Check a hash", "Back to menu"]

    enumerate_menu(choices)

    selection = getInt(1, "choices")

    if selection == 1:

        size = getInt(256, "hash", True)

        if query_yn("Do you want to hash a file?", "no"):

            f = getFile()

            if f:
                print(f"File hash: {base64.b64encode(hf.sponge(bm.fileToBytes(f), size)).decode()}")

            else:
                katsu_hash_menu()
        else:
            msg = readFromUser("Enter the text to hash:")

            print(f"Text hash: {base64.b64encode(hf.sponge(msg.encode(), size)).decode()}")


    elif selection == 2:

        def verifyHash(h, msg):
            h2 = hf.sponge(msg, len(h) * 8)

            if h == h2:
                print("Hashes are the same !")
            else:
                print("Hashes are not the same !")

        h = getb64("hash")

        if h:
            if query_yn("Do you want to compare this hash to a file's one?", "no"):
                f = getFile()
                if f:
                    verifyHash(h, bm.fileToBytes(f))
                else:
                    katsu_hash_menu()
            else:
                verifyHash(h, readFromUser("Enter the text to compare with the hash:").encode())
        else:
            katsu_hash_menu()
    else:
        import main

        main.menu()

    doSomethingElse(katsu_hash_menu)
コード例 #25
0
def validateToRepeat(msg, function):  # confirmar uma repetição de um metodo
    opc = input(msg).lower()
    if opc == "y":
        function()
    elif opc == "n":
        menu()
    else:
        print("OPÇÃO INCORRETA!!!")
        validateToRepeat(msg, function)
コード例 #26
0
def psafrt():
    clscprilo()
    print("\033[91mHere is the list of the files :\033[90m")
    print("\033[92m")
    os.system("     find " + installdirc + "/REPORT/TEMPLATES/ -type f")
    print("\033[90m")
    spc()
    oktocont()
    main.menu()
コード例 #27
0
def wtpp():
    clscprilo()
    print("\033[91mHere is the list of the files :\033[90m")
    print("\033[92m")
    os.system("     find " + installdirc + "/WALK -type f")
    print("\033[90m")
    spc()
    oktocont()
    main.menu()
コード例 #28
0
def effettuaPrestito(database):
    print("Quale utente deve effettuare il prestito:\n")
    rows = database.select_utenti(None)
    # tabulete crea una tabella per migliorare la visulizzazione dei nostri dati
    print(
        tabulate(
            rows,
            headers=["ID", "Nome", "Cognome", "Data registrazione", "stato"],
            tablefmt="github"))
    idUtente = input()
    print("Quale libro deve essere preso in prestito: \n")
    rows = database.select_libri_categorie(None)
    print(
        tabulate(rows,
                 headers=[
                     "ID", "autore", "titolo", "Numero copie",
                     "Anno produzione", "Categoria"
                 ],
                 tablefmt="github"))
    idLibro = input()
    try:
        idLibro = int(idLibro)
        idUtente = int(idUtente)
    except ValueError:
        print("Errore inserirsci un id corretto! \n")
        Menu.scelta3(database)
    UtenteIsbloccato(database, idUtente)
    rows = database.select_libri_categorie(idLibro)
    numeroCopie = 0
    for row in rows:
        numeroCopie = row['numerocopie']
    rows = database.select_utenti(idUtente)
    stato = None
    NumPrenotazioniAttive = None
    for row in rows:
        stato = row['stato']
    rows = database.select_NumPrestiti(idUtente)
    for row in rows:
        NumPrenotazioniAttive = row[0]
    if numeroCopie > 0 and stato == DB.UTENTE_STATO_ATTIVO and NumPrenotazioniAttive < 5:
        database.update_libri_numlibri(idLibro, numeroCopie - 1)
        database.insert_prestiti(__calcola_data_scadenza_prestito(), idUtente,
                                 idLibro)
        #Mantiene in memoria i dati nel database
        database.conn_db.commit()
    if numeroCopie <= 0:
        print("Non sono più disponibili copie per questo libro\n")
    if stato == DB.UTENTE_STATO_BLOCCATO:
        print(
            "Non è stato possibile effettuare il prestito perchè l'utente è stato bloccato\n"
        )
    if NumPrenotazioniAttive == 5:
        print(
            "è stato superato il numero massimo di libri presi in presitito\n")

    M.menu(database)
コード例 #29
0
def stats_menu_watching(db, watched, diary, year):

    dict_stats = {
        0: "General stats",
        1: "Films viewed by year of release;",
        2: "Most frequent people of the year;",
        3: "Most liked people of the year;",
        4: "Map;",
        5: "Back;",
        6: "Exit"
    }

    filter2 = 0
    while filter2 != 8:
        print("\nSTATS\nWhat do you want to do?")
        for n2 in dict_stats:
            print(str(n2) + " - " + str(dict_stats[n2]))
        filter2 = int(input())

        if filter2 == 0:
            from stats import general_year
            general_year(db, year)

        if filter2 == 1:
            try:
                from stats import watched_by_release_year
                watched_by_release_year(watched)
            except:
                print("\nError, check that you have built the main DB")
                pass
        if filter2 == 2:
            try:
                from stats import people_count
                people_count(db, 5)
            except:
                print("\nError, check that you have built the main DB")
                pass
        if filter2 == 3:
            try:
                from stats import people_top_count
                people_top_count(db, 5)
            except:
                print("\nError, check that you have built the main DB")
                pass
        if filter2 == 4:
            try:
                from stats import movie_map, movie_country
                movie_map(db)
            except:
                print("\nError, check that you have built the main DB")
                pass
        if filter2 == 5:
            from main import menu
            menu()
        if filter2 == 6:
            exit()
コード例 #30
0
def show_tables():
    cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
    tables = cursor.fetchall()
    tables_str = ""
    for i,k in enumerate(tables):
        for j in k:
            tables_str += f"\n{i+1} {j}"
    print(tables_str)
    input("press enter")
    main.menu()
コード例 #31
0
def visualizzaUtenti(database):
    rows = database.select_utenti(None)
    # tabulete crea una tabella per migliorare la visulizzazione dei nostri dati
    print(
        tabulate(rows,
                 headers=[
                     "ID", "Nome", "Cognome", "Data registrazione", "Bloccato"
                 ],
                 tablefmt="github"))
    M.menu(database)
コード例 #32
0
def connect_db():
    # Print PostgreSQL Connection properties
    print ( connection.get_dsn_parameters(),"\n")

    # Print PostgreSQL version
    cursor.execute("SELECT version();")
    record = cursor.fetchone()
    print("You are connected to - ", record,"\n")
    time.sleep(2)
    main.menu()
コード例 #33
0
def storicoPresitti(database):
    rows = database.select_prestiti_utenti_libri()
    print(
        tabulate(rows,
                 headers=[
                     "ID", "Data inizio", "Data Restituzione", "Data scedenza",
                     "ID utente", "Nome", "Cognome", "ID Libro", "Titolo"
                 ],
                 tablefmt="github"))
    M.menu(database)
コード例 #34
0
def visualizzaInventario(database):
    rows = database.select_libri_categorie(None)
    print(
        tabulate(rows,
                 headers=[
                     "ID", "autore", "titolo", "Numero copie",
                     "Anno produzione", "Categoria"
                 ],
                 tablefmt="github"))
    M.menu(database)
コード例 #35
0
ファイル: objective.py プロジェクト: kinsei/resume
def objective():
    subprocess.call('clear')
    cprint("\n\nObjective:", 'green', attrs=['bold'])
    cprint("    Looking for a Python programmer position to refine my skills and to build\n    new ones.", 'green')
    main_menu = raw_input(colored("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nHit Enter to return to the Main Menu:\n>>> ", 'green',attrs=['bold']))

    if main_menu == "":
        main.menu()

    else:
        main.menu()
コード例 #36
0
ファイル: edu.py プロジェクト: kinsei/resume
def edu():
    subprocess.call("clear")
    cprint ("\n\n\nEducation:", 'green', attrs=['bold'])
    cprint ("   Self-educated from online recorces and books. Such recorces include\n   linuxacademy.com, puralsight.com, and books like Learn Python The \n   Hard Way.", 'green')


    main_menu = raw_input(colored("\n\n\n\n\n\n\n\n\n\n\n\n\nHit Enter to return to Main Menu:\n>>> ", 'green', attrs=['bold']))
    
    if main_menu == "":
        main.menu()
    else:
        main.menu()    
コード例 #37
0
ファイル: work.py プロジェクト: kinsei/resume
def history():

    cl = subprocess.call("clear")
    cprint ("\nWork History:", 'green', attrs=['bold'])
    cprint ("    Your looking at. This is a project to highlight some of my abilities. I\n    also have more projects that can be seen on git hub at\n    https://github.com/kinsei/", 'green')
    
    main_menu = raw_input(colored("\n\n\n\n\n\n\n\n\n\n\n\n\n\nWould you like to see more? (y/n):\n\n>>> ", 'green', attrs=['bold']))

    if main_menu == "n":
        cl
        main.menu()
    elif main_menu == "no":
        cl
        main.menu()
    elif main_menu == "No":
        cl
        main.menu()
    elif main_menu == "y":
        cl
        more.more()
    elif main_menu == "yes":
        cl
        more.more()
    elif main_menu == "Yes":
        cl
        more.more()
        
    else:
        cl
        main.menu()
コード例 #38
0
ファイル: agents.py プロジェクト: Simpleple/291MiniProject
def recordDepart(email, CONN_STRING):
    # get user input
    flightno = input("Please enter the flight number: ")
    
    # check if the user entered a value
    if len(flightno) == 0:
        print("Flight number cannot be blank")
        return main.menu(email, CONN_STRING)
        
    # get more user input
    dep_date = input("Please enter the departure date(DD/MM/YYYY): ")

    if len(dep_date) == 0:
        print("Departure date must have a value.")
        return main.menu(email, CONN_STRING)

    # check if the user's input flight exists
    sql ="""
    select * from sch_flights 
    where flightno = '{0}' 
    and to_char(dep_date, 'DD/MM/YYYY') = '{1}'
    """.format(flightno, dep_date)
    try:
        output = main.sqlWithReturn(sql, CONN_STRING)
    except:
        print("Improper input. Please try again")
        return main.menu(email, CONN_STRING)
    if len(output) == 0:
        print("There is no flight with that flight number and departure date")
        return main.menu(email, CONN_STRING)

    # get the value of the date and time of the actual departure time
    act_dep_time = input("Please enter the actual departure time(DD/MM/YYYY HH24:MI): ")
    
    # create command to update act_dep_time in sch_flights table
    sql = "update sch_flights set act_dep_time = to_date('{0}', 'DD/MM/YYYY HH24:MI') where flightno = '{1}' and to_char(dep_date, 'DD/MM/YYYY') = '{2}'".format(act_dep_time, flightno, dep_date)

    # see if the command works
    try:
        main.sqlWithNoReturn(sql, CONN_STRING)
    except:
        # if it does not, tell the user and return to the menu
        print("failed to record")
        return main.menu(email, CONN_STRING)

    # if it does, tell the user and return to the menu
    print("successfully recorded")
    return main.menu(email, CONN_STRING)
コード例 #39
0
ファイル: agents.py プロジェクト: Simpleple/291MiniProject
def recordArr(email, CONN_STRING):
    # get the user's desired flightno
    flightno = input("Please enter the flight number: ")
    
    # check if the user actually entered anything
    if len(flightno) == 0:
        print("Flight number cannot be blank")
        return main.menu(email, CONN_STRING)

    # get the user's flight's desired departure date
    dep_date = input("Please enter the departure date(DD/MM/YYYY): ")
    
    # check if the user actually entered anything
    if len(dep_date) == 0:
        print("Departure date must have a value.")
        return main.menu(email, CONN_STRING)

    # check if the user's input flight exists
    sql ="""
    select * from sch_flights 
    where flightno = '{0}' 
    and to_char(dep_date, 'DD/MM/YYYY') = '{1}'
    """.format(flightno, dep_date)
    try:
        output = main.sqlWithReturn(sql, CONN_STRING)
    except:
        print("Improper input. Please try again")
        return main.menu(email, CONN_STRING)
    if len(output) == 0:
        print("There is no flight with that flight number and departure date")
        return main.menu(email, CONN_STRING)
    # get the departure date and time from the user
    act_arr_time = input("Please enter the actual arrival time(DD/MM/YYYY HH24:MI): ")
    
    # sql command that sets the actual arrival time of the flight
    sql = "update sch_flights set act_arr_time = to_date('{0}', 'DD/MM/YYYY HH24:MI') where flightno = '{1}' and to_char(dep_date, 'DD/MM/YYYY') = '{2}'".format(act_arr_time, flightno, dep_date)

    # see if the command can successfully execute
    try:
        main.sqlWithNoReturn(sql, CONN_STRING)
    except:
        # if it can't, tell the user and go to the menu
        print("failed to record")
        return main.menu(email, CONN_STRING)
    # if it can, tell the user and go to the menu
    print("successfully recorded")
    return main.menu(email, CONN_STRING)
コード例 #40
0
ファイル: runme.py プロジェクト: muzhma/ib-cs-sl1-midterm
import main

main.menu()
コード例 #41
0
ファイル: search.py プロジェクト: BottledTime/291MiniProject
def printInfo(email, CONN_STRING, source, dest, dep_date, sortBy="1"):
    sortByPrice = """
    select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from 
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    order by price asc)
    """.format(source, dest, dep_date)
    sortByStops = """
    select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from 
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    order by stops, price asc)
    """.format(source, dest, dep_date)
    try:
        if sortBy == "1":
            rs, desc = main.sqlWithReturnDesc(sortByPrice, CONN_STRING)
        else:
            rs, desc = main.sqlWithReturnDesc(sortByStops, CONN_STRING)
    except:
        print("There was an error in finding your flight. Please try again.")
        return main.menu(email, CONN_STRING)
    if len(rs) != 0:
        i = 1
        for row in desc:
            print(row[0], end=" ")
        print("")
        for row in rs:
            print(str(i)+".",row)
            i+=1
    else:
        sortByPrice = """
        select x.flightno1, x.flightno2, x.src, x.dst, to_char(x.dep_date)
               as dep_date,
               to_char(dep_time, 'HH24:MI') as dep_time,
               to_char(arr_time, 'HH24:MI') as arr_time,
               x.stops, 60 * x.layover as layover, x.price, x.fare1, x.fare2,
               (x.seats1 + x.seats2) / 2 - abs(x.seats1 - x.seats2)/2 as seats
        from airports a1, airports a2,
            (select flightno1, flightno2, src, dst, dep_time, arr_time,
            stops, layover, price, seats1, seats2, dep_date, fare1, fare2
            from 
            (select flightno1, flightno2, src, dst, dep_time, arr_time,
            1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
            from good_connections
            where to_char(dep_date,'DD/MM/YYYY')='{2}'
            union
            select flightno flightno1, '' flightno2, src, dst, dep_time,
            arr_time, 0 stops, 0 layover, price, seats seats1, seats+1 seats2,
            dep_date, fare as fare1, null fare2
            from available_flights
            where to_char(dep_date,'DD/MM/YYYY')='{2}')) x
        where (lower(a1.city) like '%{0}%'
              or lower(a1.name) like '%{0}%')
              and a1.acode = x.src and a2.acode = x.dst
              and (lower(a2.city) like '%{1}%' or 
              lower(a2.name) like '%{1}%')
        order by price asc        
        """.format(source.lower(), dest.lower(), dep_date)
        # query that selects suitable flights sorted by stops then price and 
        # similar aiport name or city name 
        sortByStops = """
        select x.flightno1, x.flightno2, x.src, x.dst, to_char(x.dep_date)
               as dep_date,
               to_char(dep_time, 'HH24:MI') as dep_time,
               to_char(arr_time, 'HH24:MI') as arr_time,
               x.stops, 60 * x.layover as layover, x.price, x.fare1, x.fare2,
               (x.seats1 + x.seats2) / 2 - abs(x.seats1 - x.seats2)/2 as seats
        from airports a1, airports a2,
            (select flightno1, flightno2, src, dst, dep_time, arr_time,
            stops, layover, price, seats1, seats2, dep_date, fare1, fare2
            from 
            (select flightno1, flightno2, src, dst, dep_time, arr_time,
            1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
            from good_connections
            where to_char(dep_date,'DD/MM/YYYY')='{2}'
            union
            select flightno flightno1, '' flightno2, src, dst, dep_time,
            arr_time, 0 stops, 0 layover, price, seats seats1, seats+1 seats2,
            dep_date, fare as fare1, null fare2
            from available_flights
            where to_char(dep_date,'DD/MM/YYYY')='{2}')) x
        where (lower(a1.city) like '%{0}%'
              or lower(a1.name) like '%{0}%')
              and a1.acode = x.src and a2.acode = x.dst
              and (lower(a2.city) like '%{1}%' or 
              lower(a2.name) like '%{1}%')
        order by stops, price asc
        """.format(source.lower(), dest.lower(), dep_date)
        try:
            if sortBy == "1":
                rs, desc = main.sqlWithReturnDesc(sortByPrice, CONN_STRING)
            else:
                rs, desc = main.sqlWithReturnDesc(sortByStops, CONN_STRING)
        except:
            print("Unexpected error occurred while trying to find flights. Please try again.")
            return main.menu(email, CONN_STRING)
        if len(rs) != 0:
            i = 1
            for row in desc:
                print(row[0], end=" ")
            print("")
            for row in rs:
                print(str(i)+".", row)
                i+=1
        else:
            print("no results")
            main.menu(email, CONN_STRING)
    print(str(len(rs)+1)+".", "Sort by number of connections")
    print(str(len(rs)+2)+".", "Make a booking")
    print(str(len(rs)+3)+".", "Go back to menu")
    option = input("Enter the number of an option: ")
    try:
        optNum = int(option)
        if optNum<0 or optNum>len(rs)+3:
            print("Not valid number")
        elif optNum == len(rs)+1:
            printInfo(email, CONN_STRING, source, dest, dep_date, "2")
        elif optNum == len(rs)+2:
            flightno = int(input("Enter the number before the flight you want to book: "))
            if sortBy == "1":
                rs = main.sqlWithReturn(sortByPrice, CONN_STRING)
            else:
                newRs = main.sqlWithReturn(sortByStops, CONN_STRING)

            # compare each row in new result set with user selected row and
            # record the index
            selected = rs[flightno-1]
            i = 0
            for row in newRs:
                if row[0] == selected[0] and row[1] == selected[1] and row[-3] == selected[-3] and row[-2] == selected[-2]:
                    break
                else:
                    i += 1
            # if not found, print error message and go back
            if i == len(newRs):
                print("tickets for your selected flight has run out")
                return printInfo(email, CONN_STRING, source, dest, dep_date, sortBy)
            # call booking function
            return booking(email, CONN_STRING, i+1, newRs, dep_date, source, dest)
        elif optNum == len(rs)+3:
            main.menu(email, CONN_STRING)
        else:
            print("Not valid number")
            printInfo(email, CONN_STRING, source, dest, dep_date, "1")
    except:
        print("Not valid number")
        printInfo(email, CONN_STRING, source, dest, dep_date, "1")
コード例 #42
0
def printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, sortBy="1"):
    sortByPrice = """
    select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
    from
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    order by price asc)) t1,
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    order by price asc)) t2
    order by price asc
    """.format(source, dest, dep_date, ret_date)
    sortByStops = """
    select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
    from
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    order by price asc)) t1,
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    order by price asc)) t2
    order by stops, price asc
    """.format(source, dest, dep_date, ret_date)
    if sortBy == "1":
        try:
            rs, desc = main.sqlWithReturnDesc(sortByPrice, CONN_STRING)
        except:
            print("no match found")
            return main.menu(email, CONN_STRING)
    else:
        try:
            rs, desc = main.sqlWithReturnDesc(sortByStops, CONN_STRING)
        except:
            print("no match found")
            return main.menu(email, CONN_STRING)
    if len(rs) != 0:
        i = 1
        for row in desc:
            print(row[0], end=" ")
        print("")
        for row in rs:
            print(str(i)+".",row)
            i+=1
    else:
        sortByPrice = """
        select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
        from airports a1, airports a2,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
        arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        order by price asc)) t1,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        order by price asc)) t2
        where (lower(a1.city) like '%{0}%'
              or lower(a1.name) like '%{0}%')
              and a1.acode = t1.src and a2.acode = t1.dst
              and (lower(a2.city) like '%{1}%' or
              lower(a2.name) like '%{1}%') and
              t1.src = t2.dst and t1.dst = t2.src
        order by price asc
        """.format(source.lower(), dest.lower(), dep_date, ret_date)
        sortByStops = """
        select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
        from airports a1, airports a2,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
        arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        order by price asc)) t1,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        order by price asc)) t2
        where (lower(a1.city) like '%{0}%'
              or lower(a1.name) like '%{0}%')
              and a1.acode = t1.src and a2.acode = t1.dst
              and (lower(a2.city) like '%{1}%' or
              lower(a2.name) like '%{1}%') and
              t1.src = t2.dst and t1.dst = t2.src
        order by price asc
        """.format(source.lower(), dest.lower(), dep_date, ret_date)
        if sortBy == "1":
            try:
                rs, desc = main.sqlWithReturnDesc(sortByPrice, CONN_STRING)
            except:
                print("There was an unexpected error while trying to find flights. Please try again.")
                return main.menu(email, CONN_STRING)
        else:
            try:
                rs, desc = main.sqlWithReturnDesc(sortByStops, CONN_STRING)
            except:
                print("There was an unexpected error while trying to find flights. Please try again.")
                return main.menu(email, CONN_STRING)
        if len(rs) != 0:
            i = 1
            for row in desc:
                print(row[0], end=" ")
            print("")
            for row in rs:
                print(str(i)+".", row)
                i+=1
        else:
            print("no results")
            return main.menu(email, CONN_STRING)
    print(str(len(rs)+1)+".", "Sort by number of connections")
    print(str(len(rs)+2)+".", "Make a booking")
    print(str(len(rs)+3)+".", "Go back to menu")
    option = input("Enter the number of an option: ")
    try:
        optNum = int(option)
        if optNum<0 or optNum>len(rs)+3:
            print("Not valid number")
        elif optNum == len(rs)+1:
            printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, "2")
        elif optNum == len(rs)+2:
            flightno = int(input("Enter the number before the flight you want to book: "))
            if sortBy == "1":
                rs = main.sqlWithReturn(sortByPrice, CONN_STRING)
            else:
                newRs = main.sqlWithReturn(sortByStops, CONN_STRING)

            # compare each row in new result set with user selected row and
            # record the index
            selected = rs[flightno-1]
            i = 0
            for row in newRs:
                if row[0] == selected[0] and row[1] == selected[1] and row[8] == selected[8] and row[9] == selected[9] and row[10] == selected[10] and row[11] == selected[11] and row[-5] == selected[-5] and row[-4] == selected[-4]:
                    break
                else:
                    i += 1
            # if not found, print error message and go back
            if i == len(newRs):
                print("tickets for your selected flight has run out")
                return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, sortBy)
            # call booking function
            return roundBooking(email, CONN_STRING, i+1, newRs, dep_date, ret_date, source, dest)
        elif optNum == len(rs)+3:
            main.menu(email, CONN_STRING)
        else:
            print("Not valid number")
            return main.menu(email, CONN_STRING)
    except:
        print("Not valid number")
        return main.menu(email, CONN_STRING)
コード例 #43
0
ファイル: roundtrip.py プロジェクト: Simpleple/291MiniProject
def printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, sortBy="1"):
    # query that selects suitable round trip flights sorted by price and
    # airport code
    sortByPrice = """
    select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
    from
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    order by price asc)) t1,
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    order by price asc)) t2
    order by price asc
    """.format(source, dest, dep_date, ret_date)
    # query that selects suitable round trip flights sorted by first stops
    # then price and airport code
    sortByStops = """
    select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
    from
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{2}' and src='{0}' and dst='{1}'
    order by price asc)) t1,
    (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
    from
    (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
    from good_connections
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    union
    select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
    from available_flights
    where to_char(dep_date,'DD/MM/YYYY')='{3}' and src='{1}' and dst='{0}'
    order by price asc)) t2
    order by stops, price asc
    """.format(source, dest, dep_date, ret_date)

    # use the corresponding query to sort the result
    if sortBy == "1":
        try:
            rs, desc = main.sqlWithReturnDesc(sortByPrice, CONN_STRING)
        except:
            print("no match found")
            return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, "1")
    else:
        try:
            rs, desc = main.sqlWithReturnDesc(sortByStops, CONN_STRING)
        except:
            print("no match found")
            return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, "1")

    # if there is result print column name and rows
    if len(rs) != 0:
        i = 1
        for row in desc:
            print(row[0], end=" ")
        print("")
        for row in rs:
            print(str(i)+".",row)
            i+=1
    # if no result then use implicit search
    else:
        # query that selects suitable round trip flights sorted by price and
        # similar aiport name or city name
        sortByPrice = """
        select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
        from airports a1, airports a2,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
        arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        order by price asc)) t1,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        order by price asc)) t2
        where (lower(t1.src) = '{0}' and a1.acode = t1.src or
              (t1.src = a1.acode and lower(a1.city) like '%{0}%'
              or lower(a1.name) like '%{0}%'))
              and
              (lower(t1.dst) = '{1}' and a2.acode = t1.dst or
              (t1.dst = a2.acode and lower(a2.city) like '%{1}%'
              or lower(a2.name) like '%{1}%'))
              and t1.src = t2.dst and t1.dst = t2.src
        order by price asc
        """.format(source.lower(), dest.lower(), dep_date, ret_date)
        # query that selects suitable round trip flights sorted by stops
        # then price and similar aiport name or city name
        sortByStops = """
        select t1.flightno1, t1.flightno2, t1.src, t1.dst, t1.dep_date, 
           t1.dep_time, t1.arr_time, t1.layover, t1.fare1,
           t1.fare2, t2.flightno1 as flightno3, t2.flightno2 as flightno4,
           t2.dep_date as ret_date, t2.dep_time, t2.arr_time,
           t2.layover, t2.fare1 as fare3, t2.fare2 as fare4, 
           t1.stops + t2.stops as stops,
           (t1.seats + t2.seats) / 2 - abs(t1.seats - t2.seats) / 2 as seats,
           t1.price + t2.price as price
        from airports a1, airports a2,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
        arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{2}'
        order by price asc)) t1,
        (select flightno1, flightno2, src, dst, to_char(dep_date) as dep_date,
           to_char(dep_time, 'HH24:MI') as dep_time,
           to_char(arr_time, 'HH24:MI') as arr_time,
           stops, 60 * layover as layover
           , price, fare1, fare2,
           (seats1 + seats2) / 2 - abs(seats1 - seats2) / 2 as seats
        from
        (select flightno1, flightno2, src, dst, dep_time, arr_time,
          1 stops, layover, price, seats1, seats2, dep_date, fare1, fare2
        from good_connections
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        union
        select flightno flightno1, '' flightno2, src, dst, dep_time,
          arr_time, 0 stops, 0 layover, price, seats seats1,
          seats+1 as seats2, dep_date, fare as fare1, null fare2
        from available_flights
        where to_char(dep_date,'DD/MM/YYYY')='{3}'
        order by price asc)) t2
        where (lower(t1.src) = '{0}' and a1.acode = t1.src or
              (t1.src = a1.acode and lower(a1.city) like '%{0}%'
              or lower(a1.name) like '%{0}%'))
              and
              (lower(t1.dst) = '{1}' and a2.acode = t1.dst or
              (t1.dst = a2.acode and lower(a2.city) like '%{1}%'
              or lower(a2.name) like '%{1}%'))
              and t1.src = t2.dst and t1.dst = t2.src
        order by stops, price asc
        """.format(source.lower(), dest.lower(), dep_date, ret_date)
        if sortBy == "1":
            rs, desc = main.sqlWithReturnDesc(sortByPrice, CONN_STRING)
        else:
            rs, desc = main.sqlWithReturnDesc(sortByStops, CONN_STRING)
        # print searching result if exists
        if len(rs) != 0:
            i = 1
            for row in desc:
                print(row[0], end=" ")
            print("")
            for row in rs:
                print(str(i)+".", row)
                i+=1
        # print error message and go back to menu
        else:
            print("no results")
            return main.menu(email, CONN_STRING)

    # print options
    print(str(len(rs)+1)+".", "Sort by number of connections")
    print(str(len(rs)+2)+".", "Make a booking")
    print(str(len(rs)+3)+".", "Go back to menu")

    # get options and call corresponding method
    option = input("Enter the number of an option: ")
    try:
        optNum = int(option)
        if optNum<0 or optNum>len(rs)+3:
            print("Not valid number")
        elif optNum == len(rs)+1:
            return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, "2")
        elif optNum == len(rs)+2:
            # get user selected number of flight
            flightno = int(input("Enter the number before the flight you want to book: "))
            # go back to start of function if flightno is less than one
            # to prevent negative indexing issues
            if flightno < 1:
                return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, sortBy)
                
            # get a new result set of current data
            if sortBy == "1":
                newRs = main.sqlWithReturn(sortByPrice, CONN_STRING)
            else:
                newRs = main.sqlWithReturn(sortByStops, CONN_STRING)

            # compare each row in new result set with user selected row and
            # record the index
            selected = rs[flightno-1]
            i = 0
            for row in newRs:
                if row[0] == selected[0] and row[1] == selected[1] and row[8] == selected[8] and row[9] == selected[9] and row[10] == selected[10] and row[11] == selected[11] and row[-5] == selected[-5] and row[-4] == selected[-4]:
                    break
                else:
                    i += 1
            # if not found, print error message and go back
            if i == len(newRs):
                print("tickets for your selected flight has run out")
                return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, sortBy)
            # call booking function
            return roundBooking(email, CONN_STRING, i+1, newRs, dep_date, ret_date, source, dest)
        elif optNum == len(rs)+3:
            return main.menu(email, CONN_STRING)
        else:
            print("Not valid number")
            return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, sortBy)
    except:
        print("Not valid number")
        return printRoundInfo(email, CONN_STRING, source, dest, dep_date, ret_date, sortBy)