예제 #1
0
def main():
    #read in data and parse
    files = ['data/iris.csv']  ###### EDIT ######
    train_df = pd.read_csv(files[0], header=None)  ###### EDIT ######
    file_output = "output/output_iris_new.txt"  ###### EDIT ######

    #map classifier as binary
    train_df[4] = train_df[4].map({
        'Iris-setosa': 0,
        'Iris-versicolor': 1,
        'Iris-virginica': 1
    }).astype(int)  ###### EDIT ######

    #separate models
    X_train = train_df.drop(4, axis=1)  ###### EDIT ######
    Y_train = train_df[4]  ###### EDIT ######

    X_train, X_test, Y_train, Y_test = train_test_split(X_train,
                                                        Y_train,
                                                        train_size=0.75,
                                                        test_size=0.25)

    output = [0] * iters
    #print("------Feature Selection Complete------")
    for i in range(iters):
        models = []
        for j in range(0, 15):  ###### EDIT ######
            #try out a new classifier
            pipeline1 = Pipeline([
                ('dtc',
                 DecisionTreeClassifier(max_features=random.randint(1, 4),
                                        max_depth=random.randint(1, 200),
                                        random_state=random.randint(1, 5000))
                 )  ###### EDIT ######
            ])
            models.append(pipeline1)

        output[i] = {}

        # Function calls to create and test ensembles
        ###### EDIT NAMES AND PROGRESS ######
        output[i]['super_dtc'] = add_superlearner('super_dtc', models, X_train,
                                                  Y_train, X_test, Y_test)
        print("---------------  10%  ---------------")
        output[i]['sub_dtc'] = add_subsemble('sub_dtc', models, X_train,
                                             Y_train, X_test, Y_test)
        print("---------------  20%  ---------------")
        output[i]['blend_dtc'] = add_blend('blend_dtc', models, X_train,
                                           Y_train, X_test, Y_test)
        print("---------------  30%  ---------------")

        models = []
        for j in range(0, 15):  ###### EDIT ######
            #try out a new classifier
            pipeline1 = Pipeline([
                ('knc', KNeighborsClassifier(n_neighbors=random.randint(1, 20))
                 )  ###### EDIT ######
            ])
            models.append(pipeline1)

        ###### EDIT NAMES AND PROGRESS ######
        output[i]['super_knc'] = add_superlearner('super_knc', models, X_train,
                                                  Y_train, X_test, Y_test)
        print("---------------  40%  ---------------")
        output[i]['sub_knc'] = add_subsemble('sub_knc', models, X_train,
                                             Y_train, X_test, Y_test)
        print("---------------  50%  ---------------")
        output[i]['blend_knc'] = add_blend('blend_knc', models, X_train,
                                           Y_train, X_test, Y_test)
        print("---------------  60%  ---------------")

    t = Texttable()
    average_acc = {}
    average_time = {}
    t.add_row([
        'Dataset', 'Ensemble', 'Meta Classifier', 'Accuracy Score', 'Runtime'
    ])
    for i in range(iters):
        for key, value in output[i].iteritems():
            t.add_row([
                key, output[i][key]["Ensemble"],
                output[i][key]["Meta_Classifier"],
                output[i][key]["Accuracy_Score"], output[i][key]["Runtime"]
            ])
            if (i == 0):
                average_acc[key] = output[i][key]["Accuracy_Score"]
                average_time[key] = output[i][key]["Runtime"]
            else:
                average_acc[
                    key] = average_acc[key] + output[i][key]["Accuracy_Score"]
                average_time[
                    key] = average_time[key] + output[i][key]["Runtime"]
    for key, value in average_acc.iteritems():
        t.add_row(
            ["Average", key, "SVC", value / iters, average_time[key] / iters])

    print(t.draw())

    if (file_output != None):
        print("Saving output to: {}".format(file_output))
        orig_stdout = sys.stdout
        f = open(file_output, 'w')
        sys.stdout = f

        print(t.draw())

        sys.stdout = orig_stdout
        f.close()
예제 #2
0
def print_data_training(decoded, actions):
    t = Texttable(max_width=130)
    t.add_rows([["Decoded", "Action"]])
    for decode, action in zip(decoded, actions):
        t.add_row([str(decode), str(action)])
    print(t.draw())
예제 #3
0
        if neighbors_id1 in killneighbors or neighbors_id2 in killneighbors:
            continue
        killneighbors.append(neighbors_id1)
        killneighbors.append(neighbors_id2)
        for item in user_rate_dic[neighbors_id2]:
            if item[2] not in killneighbors:
                killneighbors.append(item[2])
                #且加到宿舍,第三个
                break
        for item2 in user_rate_dic[item[2]]:
            #找第三个的邻居
            if item2[2] not in killneighbors:
                killneighbors.append(item2[2])
                #todo 加到宿舍,第四个
                break
        table = Texttable()
        table.set_deco(Texttable.HEADER)
        table.set_cols_dtype(['t', 't', 't', 't'])  # automatic
        table.set_cols_align(["l", "l", "l", "l"])

        #print ("id1:",neighbors_id1)
        #print ("id2:",neighbors_id2)
        rows.append([neighbors_id1, neighbors_id2, item[2], item2[2]])
    table.add_rows(rows)
    #取下一个贪心最大值

    print(table.draw())
    #all_neighbors_dis.sort(reverse=True)
    #user_2=[ i[1] for i in all_neighbors_dis]
    #user_3=[ i[2] for i in all_neighbors_dis]
    #print (all_neighbors_dis)
예제 #4
0
def do_compare(input, output):
    count = 0
    sum_percent = 0
    bigger = []
    not_converted = []
    table = [['File', 'Original', 'Transcoded', 'Percent']]
    total_i = 0
    total_o = 0
    for i, o in get_input_output(input, output):
        name = os.path.basename(i)
        if os.path.exists(o):
            i_size = os.path.getsize(i)
            o_size = os.path.getsize(o)
            percent = o_size / float(i_size) * 100
            if percent < 15:
                not_converted.append('{} (Too small, {:2f}%)'.format(
                    name, percent))
            elif o_size > i_size:
                bigger.append((name, o, i_size, o_size, percent))
            else:
                count += 1
                total_i += i_size
                total_o += o_size
                sum_percent += percent
                table.append([
                    name,
                    sizeof_fmt(i_size),
                    sizeof_fmt(o_size),
                    _f_percent(percent)
                ])
        else:
            not_converted.append(name)

    if count > 0:
        table.append(['', '', '', ''])
        per = total_o / float(total_i) * 100
        table.append([
            'Total',
            sizeof_fmt(total_i),
            sizeof_fmt(total_o),
            _f_percent(per)
        ])

        avg = sum_percent / count
        table.append(['Average', '', '', _f_percent(avg)])

    t = Texttable(max_width=0)
    t.set_deco(Texttable.VLINES | Texttable.HEADER)
    t.set_cols_align(['l', 'r', 'r', 'r'])
    t.add_rows(table)

    print(t.draw())

    print('{} Larger than original'.format(len(bigger)))
    for i, o, i_size, o_size, percent in bigger:
        print('{}: {} -> {} ({:.2f}%)'.format(i, sizeof_fmt(i_size),
                                              sizeof_fmt(o_size), percent))
    if len(not_converted) > 0:
        print('Not Converted:')
        for i in not_converted:
            print('  {}'.format(i))
# Lambda function for resetting terminal window "reset for Raspberry Pi, cls for PC"
clear = lambda: os.system('reset')
#clear = lambda: os.system('cls')
clear()



# Lists hold names of those who want leftovers. Set to be wiped after the reset time: reset_time.
lunch_list = []
dinner_list = []
initialize = 0
last_message_id = ''

# Table creation and initialization
lunch_output_table = Texttable()
dinner_output_table = Texttable()

# Extra spaces to allow for large names to not be on multiple lines
dinner_output_table.add_row([['        Dinner         ']])
lunch_output_table.add_row([['         Lunch         ']])
lunch_output_table.set_cols_align("c")
dinner_output_table.set_cols_align("c")

# Print Banner
print(text.Text("LATE PLATE BOT", color='0000ff', shadow=True, skew=5))
print(lunch_output_table.draw())
print(dinner_output_table.draw())

# Used to make sure fake names are not put onto the lists.
unadjusted_member_list = open(member_path, "r").read().splitlines()
예제 #6
0
 def __init__(self, rowsArray):
     self.__table = Texttable()
     self.__rows_array = rowsArray
     self.__table.add_rows(rowsArray, header=False)
예제 #7
0
            for collab in r:
                sys.stdout.write("%s (%d)\n" %
                                 (collab['login'], collab['contributions']))
                if not collab['login'] in t_collab:
                    t_collab[collab['login']] = 0
                t_collab[collab['login']] = t_collab[
                    collab['login']] + collab['contributions']
        else:
            sys.stdout.write("-\n")

        sys.stdout.write("\n")

print(
    colored('[+] %d contributors found, reading profiles...\n' % len(t_collab),
            'green'))
tab = Texttable(300)
tab.header(
    ['Contributions', 'Profile', 'Name', 'Email', 'Company', 'Public repos'])
# tab.set_max_width( 100 )


def grabUserHtmlLight(ghaccount, login):
    url = 'https://github.com/' + login

    try:
        r = requests.get(url, timeout=5)
    except Exception as e:
        print(colored("[-] error occurred: %s" % e, 'red'))
        return False

    if not 'Not Found' in r.text:
예제 #8
0
        def select_movies():
            clear()
            result1= pyfiglet.figlet_format("Select Movie: ".center(40))
            print(result1)
            movies = {}
            # Storing the contents of the movies file in movies dictionary
            with open('movies.csv', 'r') as read_file:
                csv_reader = list(csv.reader(read_file))
                for line in csv_reader:
                    if line == []:
                        continue
                    movies[line[0]] = {}
                    movies[line[0]]['name'] = line[0]
                    movies[line[0]]['Rating'] = line[1]
                    movies[line[0]]['genre'] = line[2]
                    movies[line[0]]['language'] = line[3]
                    movies[line[0]]['release'] = line[4]
                    movies[line[0]]['length'] = line[5]
                    movies[line[0]]['advisory'] = line[6]
            final = [['Movies']]
            add = []

            print('Movies Now Showing'.title())
            print()
            for dictmovie in movies.keys():
                add.append(dictmovie.title())
                final.append(add)
                add = []

            Cinema = Texttable()
            Cinema.add_rows(final)
            print(Cinema.draw())

            # Enter the movie and check if the movie is present in the movies dictionary

            movie = input('Enter your movie: ').lower()
            while movie not in movies.keys():
                movie = input('Enter valid movie name!!!: ')
            movie = movie.upper()

            print(pyfiglet.figlet_format(movie.center(40)))
            self.movie = movie.lower()

            final = []
            add = []

            # Displaying the movies information table
            for dictmovie in movies.values():
                if dictmovie['name'] == movie.lower():
                    for attribute, info in dictmovie.items():
                        if attribute != 'location' and attribute != 'name':
                            add.append(attribute)
                            add.append(info)
                            final.append(add)
                            add = []
            Cinema = Texttable()
            Cinema.add_rows(final)
            print(Cinema.draw())

            # Asks the user if they want to book tickets for the movie
            # if user enters n/no the loop continues
            choice = input(('Book tickets? (y/n): ')).lower()
            while choice not in ['y','n','yes','no']:
                choice = input(('Enter a valid choice: ')).lower()
            return choice
예제 #9
0
    def payment(self):

        def otp():
            self.email = input('Enter your email Address: ')
            number = input('Enter your mobile number: ')
            while len(number) != 10 and number not in ['7702167946']:
                number = input('Input valid mobile number: ')
            number = '+91' + number
            otp = random.randrange(1000,9999,2)
            otp = str(otp)
            message = f'Book My Cinema never calls you asking for OTP. OTP is confidential. For security reasons, do not share this OTP with anyone. Your OTP is {otp} '
            client = SinchSMS('660367af-18ff-42ca-89d2-8856dcba78dd','fijjTkW5jkuaCARwJlGnKA==')

            print("Sending '%s' to %s" % ('OTP', number))
            response = client.send_message(number, message)
            message_id = response['messageId']

            response = client.check_status(message_id)
            while response['status'] != 'Successful':
                time.sleep(1)
                response = client.check_status(message_id)

            u_otp = input('Enter the 4 digit otp: ')

            while u_otp != otp:
                u_otp = input('Enter valid 4 digit otp!!: ')

            print('OTP matched!!')

        print("\033[1;31;40m")
        result1= pyfiglet.figlet_format("Booking summary".center(0))
        print(result1)
        print("\033[1;37;40m")
        format_list = list(_table_formats.keys())
        table = [["Movie", self.movie],["Theatre", self.theatre], ["Date",self.date],["Time",self.time],["seats",self.selected_seats], ["Total", self.total]]
        print(tabulate(table, tablefmt='grid'))
        print('\033[1;31;40mAmount Payable - ' + str(self.total) + '\033[1;37;40m')

        result1= pyfiglet.figlet_format("Payment Options".center(0))
        print(result1)

        format_list = list(_table_formats.keys())
        table = [["1", "Credit/Debit card"],["2", "Mobile wallet"],["3","UPI"]]
        headers = ['Press', 'Payment method']
        print(tabulate(table, headers,tablefmt='pipe'))

        choice = input()
        while choice not in ['1', '2', '3']:
            choice = input('Enter valid payment method: ')
        clear()

        # Credit card block:
        if choice == '1':
            today = date.today()
            result1= pyfiglet.figlet_format("Credit Card".center(0))
            print(result1)
            card_num = input('Enter card number: ')
            while len(card_num) != 16:
                card_num = input('Enter valid card number!!: ')
            card_name = input('Name on the card: ')
            print('Enter expiry date: ')
            check = list(range(1, 13))
            check = [str(i) for i in check]
            month = input('Enter month: ')

            while month not in check:
                month = input('Enter valid month: ')
            month  = int(month)

            check = ['2019', '2020', '2021', '2022', '2023', '2024']
            year = input('Enter year: ')
            while year not in check:
                year = input('Enter valid year: ')

            year = int(year)

            while month <= today.month and year == today.year:
                print('Enter valid expiry date: ')
                check = list(range(1, 13))
                check = [str(i) for i in check]
                month = input('Enter month: ')

                while month not in check:
                    month = input('Enter valid month: ')
                month  = int(month)

                check = ['2019', '2020', '2021', '2022', '2023', '2024']
                year = input('Enter year: ')
                while year not in check:
                    year = input('Enter valid year: ')

                year = int(year)

            cvv = input('Enter cvv: ')
            while len(cvv) != 3:
                cvv = input('Enter cvv: ')
            clear()
            otp()
            clear()
            print("Your transaction is underway, Don't refresh: ")
            time.sleep(5)
            print('Transaction Sucessfull!!')

        # Mobile wallet block
        elif choice == '2':
            result1= pyfiglet.figlet_format("Mobile Wallet".center(0))
            print(result1)
            format_list = list(_table_formats.keys())
            table = [["1", "PayTm"],["2", "PayPal"], ["3","FreeCharge"]]
            headers = ['Press', 'Mobile wallet']
            print(tabulate(table, headers,tablefmt='pipe'))
            choice = input()
            while choice not in ['1', '2', '3']:
                choice = input('Enter valid mobile wallet: ')

            print('Redirecting...')

            time.sleep(5)
            clear()

            if choice == '1':
                result1 = pyfiglet.figlet_format("PayTm".center(40))
                print(result1)
            elif choice == '2':
                result1 = pyfiglet.figlet_format("PayPal".center(40))
                print(result1)
            elif choice == '3':
                result1 = pyfiglet.figlet_format("FreeCharge".center(40))
                print(result1)

            print(f'Book my Cinema order                          Rs {self.total}')

            choice = input('Proceed? (y/n) ').lower()
            while choice not in ['y','n','yes','no']:
                choice = input('Enter valid choice: ').lower()
            if choice in ['n', 'no']:
                return choice
            otp()
            print('Your transaction is underway, Don\'t refresh')
            time.sleep(5)
            print('Your Transaction is Sucessfull!! ')

        # UPI Block
        elif choice == '3':
            result1= pyfiglet.figlet_format("UPI".center(40))
            print(result1)

            options = ['PayTm', 'Amazon Pay','PhonePe','BHIM']
            print('Enter upi payment option ')
            upi = Texttable()
            upi.add_rows([['ID', 'Options'],['1','PayTm'],['2','Amazon Pay'],['3','PhonePe'],['4','BHIM']])
            print(upi.draw())
            upi = input()
            while upi not in ['1','2','3','4']:
                upi = input('Enter valid choice: ')
            mode = options[int(upi) - 1]
            result1 = pyfiglet.figlet_format(mode.center(40))
            print(result1)
            UPI = input('Enter UPI pin: ')
            while len(UPI) != 6:
                UPI = input('Enter valid UPI pin: ')


            print('Enter Bank ID: ')
            Bank = Texttable()
            Bank.add_rows([['ID', 'Bank'],['1','HDFC Bank'],['2','Axis Bank'],['3','SBI Bank'],['4','Yes Bank'],['5','IDFC Bank']])
            print(Bank.draw())
            bank = input()
            while bank not in ['1','2','3','4','5']:
                bank = input('Enter valid choice: ')
            otp()
            print('Your transaction is underway, Don\'t refresh')
            time.sleep(5)
            print('Your Transaction is Sucessfull!! ')
예제 #10
0
    def select_time(self):
        result1= pyfiglet.figlet_format("Select Time".center(40))
        print(result1)
        d = date.today()
        from datetime import time
        from datetime import datetime

        # Times is a dictionary to store movie times

        times = {}
        count = 1
        now = datetime.now().time()

        # Reads the time.csv file to read time corresponding to the movie and the theater
        with open('time.csv', 'r') as read_file:
            csv_reader = csv.reader(read_file, delimiter = ',')
            for line in csv_reader:
                if line[0] == self.theatre and line[1] == self.movie:
                    for i in range(len(line)):
                        if i not in [0,1]:
                            ti = datetime.strptime(line[i],'%H:%M:%S').time()
                            times[str(count)] = ti
                            count += 1

        read_file.close()
        # If the movie is in the current day
        # Then enter the available time in the dictionary times_edit
        if self.date == d:
            times_edit = {}
            count = 1
            final = [['ID', 'Time']]
            add = []
            for index, time in times.items():
                if time > now:
                    times_edit[str(count)] = time
                    add.append(count)
                    add.append(time)
                    final.append(add)
                    add = []
                    count += 1
            times = times_edit

        # Else show all the time

        else:
            count = 1
            final = [['ID', 'Time']]
            add = []
            for index, time in times.items():
                add.append(count)
                add.append(time)
                final.append(add)
                count += 1
                add = []

        Time = Texttable()
        Time.add_rows(final)
        print(Time.draw())

        user_time = input(f'Enter your time (1-{len(times)}): ')
        check = list(range(1, len(times) + 1))
        check = [str(i) for i in check]
        # To check if the user entered the correct option
        while user_time not in check:
            user_time = input(f'Enter time from (1-{len(times)}): ')

        # To convert the time and date entered by the user into string
        self.time = str(times[user_time])
        self.date = str(self.date)

        print(f'Selected movie time - {user_time}')
        choice = input('continue? (y/n): ')
        while choice not in ['y','n','yes','no']:
            choice = input(('Enter valid choice: ')).lower()
        return choice
예제 #11
0
    def food_menu(self):
        clear()
        meal = input('Do you wanna a grab a bite (y/n)?: ')
        while meal not in ['y','n','yes','no']:
            meal = input(('Enter valid choice!!: ')).lower()
        if meal in ['n', 'no']:
            return

        if meal in ['y', 'yes']:
            from texttable import Texttable
            def read_food(data, sub):
                prices = []
                with open('food.csv', 'r') as read_file:
                    csv_reader = csv.reader(read_file)
                    for line in csv_reader:
                        if line[0] == sub:
                            for i in range(len(line)):
                                if i != 0:
                                    prices.append(line[i])
                            data.append(prices)
                            prices = []
                temp = data[0]
                del data[0]
                data.sort()
                k = list(data for data,_ in itertools.groupby(data))
                data = k
                data.insert(0, temp)
                return data
                return data

            result1 = pyfiglet.figlet_format('Food Menu'.center(40))
            print(result1)

            data = [['Item', 'Small', 'Medium', 'Large']]
            final = read_food(data, 'Iced-Tea')

            price = 0
            print("Iced-Tea:-")

            IcedTea = Texttable()
            IcedTea.add_rows(final)
            print(IcedTea.draw())

            data = [['Item', 'Small', 'Medium', 'Large']]
            final = read_food(data, 'Cold Coffee')

            i=1
            while (i<=4):
                i=i+1
                print()


            print('Cold Coffee:-')
            from texttable import Texttable
            ColdCoffee = Texttable()
            ColdCoffee.add_rows(final)
            print(ColdCoffee.draw())


            i=1
            while (i<=4):
                i=i+1
                print()


            data = [['Item', 'Price']]
            final = read_food(data, 'Aerated Drinks (200 ml)')



            print ("Aerated Drinks (200 ml):-")
            from texttable import Texttable
            AeratedDrinks = Texttable()
            AeratedDrinks.add_rows(final)
            print(AeratedDrinks.draw())



            i=1
            while (i<=4):
                i=i+1
                print()

            data = [['Item', 'Price']]
            final = read_food(data, 'Mineral Water')



            print ("Mineral Water:-")
            from texttable import Texttable
            MineralWater = Texttable()
            MineralWater.add_rows(final)
            print(MineralWater.draw())


            i=1
            while (i<=4):
                i=i+1
                print()

            data = [['Item', 'Price']]
            final = read_food(data, 'Hot Beverages (80 ml)')

            print ("Hot Beverages (80 ml):-")
            from texttable import Texttable
            HotBeverages = Texttable()
            HotBeverages.add_rows(final)
            print(HotBeverages.draw())


            i=1
            while (i<=4):
                i=i+1
                print()

            data = [['Item', 'Small', 'Medium', 'Large']]
            final = read_food(data, 'Popcorn')


            print ("Popcorn:-")
            from texttable import Texttable
            Popcorn = Texttable()
            Popcorn.add_rows(final)
            print(Popcorn.draw())



            i=1
            while (i<=4):
                i=i+1
                print()


            data = [['Item', 'Price']]
            final = read_food(data, 'Appetizers')


            print ("Appetizers:-")
            from texttable import Texttable
            Appetizers = Texttable()
            Appetizers.add_rows(final)
            print(Appetizers.draw())


            i=1
            while (i<=4):
                i=i+1
                print()

            data = [['Item', 'Small', 'Medium', 'Large']]
            final = read_food(data, 'Rolls')

            print ("Rolls:-")
            from texttable import Texttable
            Rolls = Texttable()
            Rolls.add_rows(final)
            print(Rolls.draw())



            i=1
            while (i<=4):
                i=i+1
                print()

            data = [['Item', 'Price']]
            final = read_food(data, 'Special Combos')

            print ("Special Combos:-")
            from texttable import Texttable
            SpecialCombos = Texttable()
            SpecialCombos.add_rows(final)
            print(SpecialCombos.draw())



            i=1
            while (i<=4):
                i=i+1
                print()

            data = [['Item', 'Single Scoop', 'Double Scoop', 'Cone']]
            final = read_food(data, 'Ice Creams')

            print ("Ice Creams:-")
            from texttable import Texttable
            IceCream = Texttable()
            IceCream.add_rows(final)
            print(IceCream.draw())
            choice = 'y'

            while choice in ['y', 'yes']:
                pre = False
                while pre == False:
                    sub = input('Enter submenu: ')

                    with open('food.csv', 'r') as read_file:

                        csv_reader = csv.reader(read_file)
                        for line in csv_reader:
                            if line == []:
                                break
                            if line[0] == sub:
                                pre = True
                                break
                    if pre == True:
                        break
                pre = False
                while pre == False:
                    item = input('\nEnter item from ' + sub + ': ')
                    with open('food.csv', 'r') as read_file:

                        csv_reader = csv.reader(read_file)
                        for line in csv_reader:
                            if line == []:
                                break
                            if line[0] == sub:
                                if line[1] == item:
                                    quantity = input('Enter quantity ')
                                    while quantity not in ['0','1', '2', '3', '4', '5', '6', '7']:
                                        quantity = input('Control yourself and enter quantity : ')

                                    quantity = int(quantity)
                                    pre = True
                                    if sub in ['Iced-Tea','Cold Coffee','Popcorn','Rolls']:

                                        Tab = Texttable()
                                        Tab.add_rows([['Press', 'Option'], ['1','To order Small'],['2', 'To order Medium'],['3', 'To order Large']])
                                        print(Tab.draw())
                                        choice = input()
                                        while choice not in ['1','2','3']:
                                            choice = input('Enter 1 or 2 or 3: ')

                                        if choice == '1':
                                            add = int(line[2]) * quantity
                                            price += add
                                            break

                                        elif choice == '2':
                                            add = int(line[3]) * quantity
                                            price += add
                                            break

                                        elif choice == '3':
                                            add = int(line[4]) * quantity
                                            price += add
                                            break

                                    elif sub in ['Ice Creams']:
                                        Tab = Texttable()
                                        Tab.add_rows([['Press', 'Option'], ['1','To order Single Scoop'],['2', 'To order Double Scoop'],['3', 'To order Cone']])
                                        print(Tab.draw())
                                        choice = input()
                                        while choice not in ['1','2','3']:
                                            choice = input('Enter 1 or 2 or 3: ')

                                        if choice == '1':
                                            add = int(line[2]) * quantity
                                            price += add
                                            break

                                        elif choice == '2':
                                            add = int(line[3]) * quantity
                                            price += add
                                            break

                                        elif choice == '3':
                                            add = int(line[4]) * quantity
                                            price += add
                                            break
                                    else:
                                        add = int(line[2]) * quantity
                                        price += add
                                        break
                                    pre = True
                        if pre == True:
                            break
                self.food_item.append(item)
                self.food_price += price
                self.total += self.food_price
                choice = input('Order more? (y/n): ')
                while choice not in ['y','n','yes','no']:
                    choice = input(('Enter valid choice: ')).lower()
                if choice in ['n', 'no']:
                    print(self.food_item)
                    break
                pre = False
예제 #12
0
def rrt(lang, module, Input_):
    table = kakunin(module)

    data = module.Open("./config/setting.conf")
    datas = data.read().splitlines()[0]
    data.close()
    datas = datas.split(",")
    datal = []
    for i in range(2, len(datas), 2):
        datal.append((datas[i + 1], datas[i]))
    if len(datal) == 0:
        k = ""
        while k != "\n":
            cuitools.box(lang.lang("エラー"), [
                lang.lang("簡単サッカー実行リストにチームが設定されていないのでこの機能は使用できません。"),
                lang.lang("settingコマンドでチームの追加ができます。詳しくはsettingコマンドを確認してください。"),
                lang.lang("Enterキーを押して続行...")
            ])
            k = cuitools.Key()
    elif yes_no_dialog(
            title=lang.lang("cszp 簡単サッカー実行プログラム") + "/" + lang.lang("設定確認"),
            text=table.draw() + lang.lang("\nEnterキーを押して続行...")).run():
        k = ""
        csv_save = False
        ok = False
        ver = open("./version")
        v = ver.read()
        ver.close()
        kantan_list = list(map(lambda n: n[1], datal))
        kantan_cmd = list(map(lambda n: n[0], datal))
        select = 0
        selector = []
        synch = False
        while k != "\n" or not ok:
            cuitools.reset()
            print("\033[1;1H\033[0m\033[38;5;172m")
            figlet("cszp " + v)
            if select == -1:
                print("\033[1m\033[38;5;9m>  \033[38;5;10m" +
                      lang.lang("前ページへ戻る(ホーム)") + "\033[0m\n")
            else:
                print("   \033[38;5;10m" + lang.lang("前ページへ戻る(ホーム)") +
                      "\033[0m\n")
            print("\033[38;5;12m" + lang.lang("総当たり戦をさせるチームを選択してください。"))
            for i, j in enumerate(kantan_list):
                if i in selector:
                    if select == i:
                        print(
                            "\033[1m\033[38;5;9m>\033[38;5;11m* \033[38;5;10m"
                            + j + "\033[0m")
                    else:
                        print("\033[38;5;11m * \033[38;5;10m" + j + "\033[0m")
                elif select == i:
                    print("\033[1m\033[38;5;9m>  \033[38;5;10m" + j +
                          "\033[0m")
                else:
                    print("   \033[38;5;10m" + j + "\033[0m")
            print("")
            if select == len(kantan_list):
                print("\033[1m\033[38;5;9m>  \033[38;5;14m" +
                      lang.lang("synchモードでの実行") +
                      ":\033[0m\033[4m\033[38;5;14m" + "No" *
                      ((synch - 1) * -1) + "Yes" * synch + "\033[0m")
            else:
                print("   \033[38;5;14m" + lang.lang("synchモードでの実行") +
                      ":\033[0m\033[4m\033[38;5;14m" + "No" *
                      ((synch - 1) * -1) + "Yes" * synch + "\033[0m")
            if select == len(kantan_list) + 1:
                if csv_save is False:
                    print("\033[1m\033[38;5;9m>  \033[38;5;11m" +
                          lang.lang("csvログの保存") + ":\033[0m\033[4m\033["
                          "38;5;14mNo\033[0m")
                else:
                    print("\033[1m\033[38;5;9m>  \033[38;5;11m" +
                          lang.lang("csvログの保存") +
                          ":\033[0m\033[4m\033[38;5;14m" + csv_save +
                          "\033[0m")
            else:
                if csv_save is False:
                    print("   \033[38;5;11m" + lang.lang("csvログの保存") +
                          ":\033[0m\033[4m\033[38;5;14mNo\033[0m")
                else:
                    print("   \033[38;5;11m" + lang.lang("csvログの保存") +
                          ":\033[0m\033[4m\033[38;5;14m" + csv_save +
                          "\033[0m")
            if select == len(kantan_list) + 2 and len(selector) > 1:
                print("\033[1m\033[38;5;9m>  \033[38;5;10m" +
                      lang.lang("サッカーを実行") + "\033[0m")
            elif len(selector) < 2:
                print("   \033[38;5;243m" + lang.lang("サッカーを実行") + "\033[0m")
            else:
                print("   \033[38;5;10m" + lang.lang("サッカーを実行") + "\033[0m")

            table = []
            tmp = [""]
            for i in selector:
                tmp.append(kantan_list[i])
            table.append(tmp)
            for i in selector:
                table.append([kantan_list[i]] + [""] * len(selector))
            print(Texttable().add_rows(table).draw())
            k = cuitools.Key()
            if k == "\x1b":
                k = cuitools.Key()
                if k == "[":
                    k = cuitools.Key()
                    if k == "B":
                        if len(kantan_list) + 2 > select:
                            select += 1
                            if len(kantan_list) + 2 == select and len(
                                    selector) < 2:
                                select -= 1
                    elif k == "A":
                        if -1 < select:
                            select -= 1
            if (k == " " or k == "\n") and select == -1:
                break
            elif (k == " " or k == "\n") and select == len(kantan_list) + 2:
                ok = True
                break
            elif (k == " " or k == "\n") and select == len(kantan_list) + 1:
                tmp = yesno(lang.lang("選択"), [lang.lang("csvログを保存しますか?")])
                if tmp == 0:
                    tmp = Input()
                    tmp = tmp.Input("filename")
                    if len(tmp.split(".")) == 1:
                        tmp += ".csv"
                    csv_save = tmp
                else:
                    csv_save = False
            elif (k == " " or k == "\n") and select == len(kantan_list):
                tmp = yesno(lang.lang("選択"), [lang.lang("synchモードで実行しますか?")])
                if tmp == 0:
                    synch = True
                else:
                    synch = False
            elif (k == " " or k == "\n") and select > -1:
                if select in selector:
                    for i, j in enumerate(selector):
                        if j == select:
                            del selector[i]
                            break
                else:
                    selector.append(select)
        if ok:
            table = []
            tmp = [""]
            for i in selector:
                tmp.append(kantan_list[i])
            table.append(tmp)
            for i in selector:
                table.append([kantan_list[i]] + [""] * len(selector))
            for i in range(len(table)):
                if i != 0:
                    table[i][i] = "N/A"
            tmp = []
            for i in selector:
                for j in selector:
                    if kantan_cmd[i] != kantan_cmd[j] and not [
                            kantan_cmd[j], kantan_cmd[i]
                    ] in tmp:
                        tmp.append([kantan_cmd[i], kantan_cmd[j]])
            tmp2 = []
            for i in selector:
                for j in selector:
                    if kantan_cmd[i] != kantan_cmd[j] and not [
                            kantan_list[j], kantan_list[i]
                    ] in tmp2:
                        tmp2.append([kantan_list[i], kantan_list[j]])
            # print(tmp)
            data = module.Open("./config/config.conf")
            datas = data.read().splitlines()
            data.close()
            datas = datas[0].split(",")
            arg = "server::auto_mode=true server::kick_off_wait=20 server::game_over_wait=20 " \
                  "server::connect_wait=2000 server::game_log_dir=" + datas[7] + " server::text_log_dir=" + datas[
                      7] + " server::game_logging=" + (
                          "true" * (datas[3] == "on") + "false" * (datas[3] == "off")) + " server::text_logging=" + (
                          "true" * (datas[3] == "on") + "false" * (datas[3] == "off"))
            # arg += " server::nr_normal_halfs=1 server::nr_extra_halfs=0 server::penalty_shoot_outs=0 " \
            #        "server::half_time=10"
            s = [0, 1]
            results = []
            for i, j in zip(tmp, tmp2):
                cuitools.reset()
                print("\033[1;1H\033[0m\033[38;5;172m")
                figlet("cszp " + v)
                print("\033[0m")
                print(Texttable().add_rows(table).draw() + "\n" + "━" * 50)
                try:
                    _ = soccer([i[0], i[1], arg], lang, 1, module,
                               [False, False, False, synch], Input_, False,
                               False, False)
                except KeyboardInterrupt:
                    break
                result = _.get_result()
                if len(result) == 0:
                    table[s[0] + 1][s[1] + 1] = "Error"
                else:
                    tmp3 = result[0]
                    tmp3[1] = table[s[0] + 1][0]
                    tmp3[2] = table[0][s[1] + 1]
                    results.append(tmp3)
                    table[s[0] +
                          1][s[1] +
                             1] = str(result[0][3]) + "-" + str(result[0][4])
                s[1] += 1
                if s[1] > len(selector) - 1:
                    s[0] += 1
                    s[1] = 0
                tmp3 = list(map(lambda n: n + 1, s))
                while [j[1], j[0]] != [table[tmp3[0]][0], table[0][tmp3[1]]]:
                    print([table[tmp3[0]][0], table[0][tmp3[1]]], [j[1], j[0]])
                    tmp3[1] += 1
                    if tmp3[1] > len(selector):
                        tmp3[0] += 1
                        tmp3[1] = 0
                if len(result) == 0:
                    table[tmp3[0]][tmp3[1]] = "Error"
                else:
                    table[tmp3[0]][tmp3[1]] = str(result[0][4]) + "-" + str(
                        result[0][3])

                while s[1] <= s[0]:
                    s[1] += 1
                    if s[1] > len(selector):
                        s[0] += 1
                        s[1] = 0
            if csv_save is not False:
                with open(datas[7] + "/" + csv_save, "w") as f:
                    f.write("\n".join(
                        list(map(lambda n: ",".join(map(str, n)), results))))
            cuitools.reset()
            print("\033[1;1H\033[0m\033[38;5;172m")
            figlet("cszp " + v)
            print("\033[0m")
            print("\033[1m\033[38;5;11m" + lang.lang("集計結果") + "\033[0m\n" +
                  "━" * 50 + "\n" + Texttable().add_rows(table).draw())
            tmp = []
            for i in results:
                if not i[1] in list(map(lambda n: n[0], tmp)):
                    tmp.append([i[1], [0, 0, 0]])
                for j, k in enumerate(tmp):
                    if k[0] == i[1]:
                        break
                if i[3] > i[4]:
                    tmp[j][1][0] += 1
                elif i[3] < i[4]:
                    tmp[j][1][1] += 1
                else:
                    tmp[j][1][2] += 1

                if not i[2] in list(map(lambda n: n[0], tmp)):
                    tmp.append([i[2], [0, 0, 0]])
                for j, k in enumerate(tmp):
                    if k[0] == i[2]:
                        break
                if i[4] > i[3]:
                    tmp[j][1][0] += 1
                elif i[4] < i[3]:
                    tmp[j][1][1] += 1
                else:
                    tmp[j][1][2] += 1
            table = [["", "W", "D", "L", "Total"]]
            for i in tmp:
                table.append(
                    [i[0], i[1][0], i[1][2], i[1][1], i[1][0] - i[1][1]])
            print("\n" + "━" * 50 + "\n" + Texttable().add_rows(table).draw())
            Input_.Input(lang.lang("Enterキーを押して続行..."), dot=False)
예제 #13
0
    def display_late_info(self):
        late_cats = ["1 - 15", "16 - 30", "31 - 60", "61 - 90", "91 - 120"]
        # create dict
        late_dict = {}
        current_count = 0
        total_late_count = 0
        for cat in late_cats:
            late_dict[cat] = {
                "count": 0,
                "outstanding principal": 0,
                "ratings": []
            }
        # {'1 - 15': {'count': 0, 'outstanding principal': 0, 'ratings': []},
        #  '16 - 30': {'count': 0, 'outstanding principal': 0, 'ratings': []},
        #  '31 - 60': {'count': 0, 'outstanding principal': 0, 'ratings': []},
        #  '61 - 90': {'count': 0, 'outstanding principal': 0, 'ratings': []},
        #  '91 - 120': {'count': 0, 'outstanding principal': 0, 'ratings': []}}

        notes_data = self.notes.pull_notes_table()
        for note in notes_data:
            if note['note_status_description'] == "CURRENT" and note[
                    'days_past_due'] == 0:
                current_count += 1
            if note['note_status_description'] == "CURRENT" and note[
                    'days_past_due'] > 0 and note['days_past_due'] < 16:
                late_dict["1 - 15"]["count"] += 1
                late_dict["1 - 15"]["outstanding principal"] += note[
                    'principal_balance_pro_rata_share']
                late_dict["1 - 15"]["ratings"].append(note['prosper_rating'])
            if note['note_status_description'] == "CURRENT" and note[
                    'days_past_due'] > 15 and note['days_past_due'] < 31:
                late_dict["16 - 30"]["count"] += 1
                late_dict["16 - 30"]["outstanding principal"] += note[
                    'principal_balance_pro_rata_share']
                late_dict["16 - 30"]["ratings"].append(note['prosper_rating'])
            if note['note_status_description'] == "CURRENT" and note[
                    'days_past_due'] > 30 and note['days_past_due'] < 61:
                late_dict["31 - 60"]["count"] += 1
                late_dict["31 - 60"]["outstanding principal"] += note[
                    'principal_balance_pro_rata_share']
                late_dict["31 - 60"]["ratings"].append(note['prosper_rating'])
            if note['note_status_description'] == "CURRENT" and note[
                    'days_past_due'] > 60 and note['days_past_due'] < 91:
                late_dict["61 - 90"]["count"] += 1
                late_dict["61 - 90"]["outstanding principal"] += note[
                    'principal_balance_pro_rata_share']
                late_dict["61 - 90"]["ratings"].append(note['prosper_rating'])
            if note['note_status_description'] == "CURRENT" and note[
                    'days_past_due'] > 90:
                late_dict["91 - 120"]["count"] += 1
                late_dict["91 - 120"]["outstanding principal"] += note[
                    'principal_balance_pro_rata_share']
                late_dict["91 - 120"]["ratings"].append(note['prosper_rating'])
        table = Texttable()
        table.add_row([
            "Late Category", "Count", "Outstanding Principal",
            "Comprised Notes"
        ])
        for d in late_dict:
            table.add_row([
                d, late_dict[d]["count"],
                late_dict[d]["outstanding principal"], late_dict[d]["ratings"]
            ])
            total_late_count += late_dict[d]["count"]
        self.message += "\nLate Note Data:"
        self.message += "\nCurrent notes late is {num}% of all notes\n".format(
            num=round((total_late_count /
                       (total_late_count + current_count) * 100), 2))
        self.message += table.draw()
        self.message += "\n"
예제 #14
0
    def display_default_rate_tracking(self):
        table = Texttable()
        table.add_row([
            "Rating", "Expected", "Baseline", "Actual", "Diff",
            "Diff Baseline", "Late"
        ])
        projected_default_dict, projected_default_dict_prosper, actual_default_dict, actual_default_rates_dict, actual_late_dict = self.notes.default_rate_tracking(
        )
        total_expected_defaulted_v1 = 0
        total_expected_defaulted_prosper = 0
        total_actual_num = 0
        total_late = 0
        self.message += "\n"
        late_dict = {}
        for k in sorted(projected_default_dict):
            try:
                actual_num = actual_default_dict[k]
            except KeyError:
                actual_num = 0

            try:
                # self.message += "Rating {k}: expected defaulted notes for v1 is {num}, with prosper expected of {prosper_num}, actual is {actual_num} (Including {late_num} late)".format(k=k, num=round(projected_default_dict[k], 4), prosper_num=round(projected_default_dict_prosper[k], 4), actual_num=actual_num, late_num=actual_late_dict[k])
                table.add_row([
                    k,
                    round(projected_default_dict[k], 4),
                    round(projected_default_dict_prosper[k], 4),
                    actual_num,
                    # "actual is {actual_num} (Including {late_num} late)".format(actual_num=actual_num, late_num=actual_late_dict[k]),
                    round(projected_default_dict[k], 4) - actual_num,
                    round(projected_default_dict_prosper[k], 4) - actual_num,
                    actual_late_dict[k]
                ])
                total_late += actual_late_dict[k]
            except KeyError:
                # self.message += "Rating {k}: expected defaulted notes for v1 is {num}, with prosper expected of {prosper_num}, actual is {actual_num} (Including {late_num} late)".format(k=k, num=round(projected_default_dict[k], 4), prosper_num=round(projected_default_dict_prosper[k], 4), actual_num=actual_num, late_num=0)
                table.add_row([
                    k,
                    round(projected_default_dict[k], 4),
                    round(projected_default_dict_prosper[k], 4),
                    actual_num,
                    # "actual is {actual_num} (Including {late_num} late)".format(actual_num=actual_num, late_num=0),
                    round(projected_default_dict[k], 4) - actual_num,
                    round(projected_default_dict_prosper[k], 4) - actual_num,
                    0
                ])
            # self.message += "\n"
            total_expected_defaulted_v1 += projected_default_dict[k]
            total_expected_defaulted_prosper += projected_default_dict_prosper[
                k]
            total_actual_num += actual_num
        table.add_row([
            "Total",
            round(total_expected_defaulted_v1, 4),
            round(total_expected_defaulted_prosper, 4), total_actual_num,
            round(total_expected_defaulted_v1, 4) - total_actual_num,
            round(total_expected_defaulted_prosper, 4) - total_actual_num,
            total_late
        ])
        self.message += "Default And Late Rate Tracking:\n"
        self.message += table.draw()
        self.message += "\n"
예제 #15
0
    def similarity_text(self, idx, distance_matrix, data):
        """
        Use indici API and Fuzzy Search to select the answer for the Customer

        idx: the index of the text we're looking for similar questions to
             (data[idx] corresponds to the actual text we care about)
        distance_matrix: an m by n matrix that stores the distance between
                         document m and document n at distance_matrix[m][n]
        data: a flat list of text data
        """

        t = Texttable()
        t.set_cols_width([50, 20])

        # these are the indexes of the texts that are most similar to the text at data[idx]
        # note that this list of 10 elements contains the index of text that we're comparing things to at idx 0
        sorted_distance_idxs = np.argsort(
            distance_matrix[idx])[:5]  # EX: [252, 102, 239, ...]

        #Fuzzy Search Dictionary Index
        fuzzy_ratio_array = sorted_distance_idxs.tolist()
        fuzzy_ratio_array.pop(0)
        print("fuzzy ratio array : %r" % fuzzy_ratio_array)

        # this is the index of the text that is most similar to the query (index 0)
        most_sim_idx = sorted_distance_idxs[1]
        print("sorted distance idx : %r" % most_sim_idx)
        # header for texttable
        t.add_rows([['Text', 'Similarity']])
        print(t.draw())

        # set the variable that will hold our matching FAQ
        faq_match = None

        for similar_idx in sorted_distance_idxs:
            # actual text data for display
            datum = data[similar_idx]

            # distance in cosine space from our text example to the similar text example
            distance = distance_matrix[idx][similar_idx]

            # how similar that text data is to our input example
            similarity = 1 - distance

            # add the text + the floating point similarity value to our Texttable() object for display
            t.add_rows([[datum, str(round(similarity, 2))]])
            print(t.draw())

            # set a confidence threshold
            if similar_idx == most_sim_idx and similarity >= 0.75:
                faq_match = data[most_sim_idx]

            elif similar_idx == most_sim_idx and similarity >= 0.4:
                fuzzy_search_dict = {}
                fuzzy_max_similarity_index = []
                for idx in fuzzy_ratio_array:
                    value = fuzz.ratio(data[0], data[idx])
                    fuzzy_search_dict[idx] = value
                    fuzzy_max_similarity_index = max(fuzzy_search_dict.items(),
                                                     key=lambda x: x[1])[0]

                faq_match = data[fuzzy_max_similarity_index]
            else:
                sorry = "Sorry, I'm not sure how to respond. Let me find someone who can help you."

        # print the appropriate answer to the FAQ, or bring in a human to respond
        # TODO
        if faq_match is not None:
            return faqs[faq_match]

        else:
            return sorry
예제 #16
0
def PredictAndShowResult(classifiers, test_data):
    y_test = test_data['authors']
    X_test = test_data['texts']

    for classifier in classifiers:
        clf = classifier['clf']
        predicted = cross_val_predict(clf, X_test, y_test, cv=10)
        #predicted = clf.predict(X_test)
        Macro_P = (
            metrics.precision_score(y_test, predicted, average='macro') * 100)
        A = (metrics.accuracy_score(y_test, predicted) * 100)
        Macro_R = (metrics.recall_score(y_test, predicted, average='macro') *
                   100)
        Macro_F = (metrics.f1_score(y_test, predicted, average='macro') * 100)
        Micro_P = (
            metrics.precision_score(y_test, predicted, average='micro') * 100)
        Micro_R = (metrics.recall_score(y_test, predicted, average='micro') *
                   100)
        Micro_F = (metrics.f1_score(y_test, predicted, average='micro') * 100)
        fpr, tpr, thresholds = metrics.roc_curve(y_test,
                                                 predicted,
                                                 pos_label=16)
        AUC = (metrics.auc(fpr, tpr) * 100)
        ######################### Presenting results ###################################################
        table = Texttable()
        print(classifier['name'] + ' measures: ')
        table.add_rows([['Measure', 'Result'], ['ACCURACY ', A],
                        ['Error Rate', 100 - A],
                        ['The MACRO Precission ', Macro_P],
                        ['The MACRO Recall ', Macro_R],
                        ['The MACRO FScore ', Macro_F],
                        ['The MICRO Precission ', Micro_P],
                        ['The MICRO Recall ', Micro_R],
                        ['The MICRO FScore ', Micro_F],
                        ['Area Under Curve', AUC]])
        print(table.draw())
        print('\n Detailed classification report for ' + classifier['name'] +
              ':')
        print(classification_report(y_test, predicted))

        #################################### Confusion Matrix ##########################################

        def plot_confusion_matrix(cm,
                                  classes,
                                  title='Confusion matrix',
                                  cmap=plt.cm.Blues):
            plt.imshow(cm, interpolation='nearest', cmap=cmap)
            plt.title(title)
            plt.colorbar()
            tick_marks = np.arange(len(classes))
            plt.xticks(tick_marks, classes, rotation=45)
            plt.yticks(tick_marks, classes)
            cmRound = []
            print(cm)
            thresh = cm.max() / 2.
            for i, j in itertools.product(range(cm.shape[0]),
                                          range(cm.shape[1])):
                plt.text(j,
                         i,
                         cm[i, j],
                         horizontalalignment="center",
                         color="white" if cm[i, j] > thresh else "black")
            plt.tight_layout()
            plt.ylabel('True authors')
            plt.xlabel('Predicted authors')

        # Compute confusion matrix
        conf_m = confusion_matrix(y_test, predicted)
        np.set_printoptions(precision=2)
        # Plot normalized confusion matrix for emotions
        plt.figure()
        plot_confusion_matrix(conf_m,
                              classes=set(y_test_old),
                              title=features_name + '. Classifier name: ' +
                              classifier['name'])
        # fname = features_name+'_'+classifier['name']
        #fpath = 'D:/Sasha/subversion/trunk/AuthorshipAttributionRussianTexts/results/conf_matrix/'+fname #to save in file
        plt.show()
예제 #17
0
    if args.query:
        query = args.query

    check = args.check
    maxresults = args.maxresults

    if maxresults < 100:
        maxresults = 100

    maxwidth = args.maxwidth

    inputfile = False
    if args.file:
        inputfile = args.file

    t = Texttable(max_width=maxwidth)
    malwaredomains = 'http://mirror1.malwaredomains.com/files/justdomains'
    expireddomainsqueryurl = 'https://www.expireddomains.net/domain-name-search'

    timestamp = time.strftime("%Y%m%d_%H%M%S")

    useragent = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)'
    headers = {'User-Agent': useragent}

    requests.packages.urllib3.disable_warnings()

    # HTTP Session container, used to manage cookies, session tokens and other session information
    s = requests.Session()

    data = []
예제 #18
0
    items = {
    }  #1|Toy Story (1995)|01-Jan-1995||http://us.imdb.com/M/title-exact?Toy%20Story%20(1995)|0|0|0|1|1|1|0|0|0|0|0|0|0|0|0|0|0|0|0

    f = open(item, "r", encoding="ISO-8859-1")
    movie_content = f.readlines()
    f.close()
    for movie in movie_content:
        movieLine = movie.split("|")
        items[int(movieLine[0])] = movieLine[1:]
    return items


#主程序
if __name__ == '__main__':
    itemTemp = getMovieList(r"./ml-100k/u.item")  #获取电影列表
    fileTemp = readFile(r"./ml-100k/u.data")  #读取文件
    user_dic, movie_dic = createDict(fileTemp)  #创建字典

    user_id = 66
    movieTemp = recommondation(user_id, user_dic, 80)  #对电影排序
    rows = []
    table = Texttable()  #创建表格并显示
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype(['t', 'f', 'a'])
    table.set_cols_align(["l", "l", "l"])
    rows.append(["user name", "recommondation_movie", "from userid"])
    for i in movieTemp:
        rows.append([user_id, itemTemp[i[0]][0], ""])
    table.add_rows(rows)
    print(table.draw())
예제 #19
0
        i += 1
        if i == 1000:
            break

    print('Saving training_set to', training_set_filename)
    data = np.array(data)
    np.save(training_set_filename, data)
    with open(images_filename, 'wb') as output:
        pickle.dump(images, output, pickle.HIGHEST_PROTOCOL)

print('Predicting the cameras based on the images')
labels = logistic.predict(data)
predictions = dict(zip(images, labels))

print('Prediction list')
text_table = Texttable()
text_table.add_row(['Image', 'Predicted', 'Actual', 'Correct ?'])

right_classifier_counter = 0
for image in images:
    images_filename = image.split("/")[-1]
    actual_camera = image.split("/")[-2]
    predicted_camera = predictions[image]
    text_table.add_row([
        images_filename, predicted_camera, actual_camera,
        predicted_camera == actual_camera
    ])
    if actual_camera == predicted_camera: right_classifier_counter += 1

print(text_table.draw())
print('Accuracy:', right_classifier_counter / len(images))
예제 #20
0
 def __str__(self):
     res = Texttable()
     for line in self.__cells:
         s = " ".join([str(int(value)) for value in line]) + "\n"
         res.add_row(s)
     return res.draw()
예제 #21
0
def main(domain, threads, savefile, ports, silent, verbose, enable_bruteforce,
         engines):
    bruteforce_list = set()
    search_list = set()

    if is_windows:
        subdomains_queue = list()
    else:
        subdomains_queue = multiprocessing.Manager().list()

    # Check Bruteforce Status
    if enable_bruteforce or enable_bruteforce is None:
        enable_bruteforce = True

    # Validate domain
    domain_check = re.compile(
        "^(http|https)?[a-zA-Z0-9]+([\-\.]{1}[a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$")
    if not domain_check.match(domain):
        if not silent:
            print(R + "Error: Please enter a valid domain" + W)
        return []

    if not domain.startswith('http://') or not domain.startswith('https://'):
        domain = 'http://' + domain

    parsed_domain = urlparse.urlparse(domain)

    if not silent:
        print(B +
              "[-] Enumerating subdomains now for %s" % parsed_domain.netloc +
              W)

    if verbose and not silent:
        print(
            Y +
            "[-] verbosity is enabled, will show the subdomains results in realtime"
            + W)

    supported_engines = {
        'baidu': BaiduEnum,
        'yahoo': YahooEnum,
        'google': GoogleEnum,
        'bing': BingEnum,
        'ask': AskEnum,
        'netcraft': NetcraftEnum,
        'dnsdumpster': DNSdumpster,
        'virustotal': Virustotal,
        'threatcrowd': ThreatCrowd,
        'ssl': CrtSearch,
        'passivedns': PassiveDNS
    }

    chosenEnums = []

    if engines is None:
        chosenEnums = [
            BaiduEnum, YahooEnum, GoogleEnum, BingEnum, AskEnum, NetcraftEnum,
            DNSdumpster, Virustotal, ThreatCrowd, CrtSearch, PassiveDNS
        ]
    else:
        engines = engines.split(',')
        for engine in engines:
            if engine.lower() in supported_engines:
                chosenEnums.append(supported_engines[engine.lower()])

    # Start the engines enumeration
    enums = [
        enum(domain, [], q=subdomains_queue, silent=silent, verbose=verbose)
        for enum in chosenEnums
    ]
    for enum in enums:
        enum.start()
    for enum in enums:
        enum.join()

    subdomains = set(subdomains_queue)
    for subdomain in subdomains:
        search_list.add(subdomain)

    if enable_bruteforce:
        if not silent:
            print(G + "[-] Starting bruteforce module now using subbrute.." +
                  W)
        record_type = False
        path_to_file = os.path.dirname(os.path.realpath(__file__))
        subs = os.path.join(path_to_file, 'subbrute', 'names.txt')
        resolvers = os.path.join(path_to_file, 'subbrute', 'resolvers.txt')
        process_count = threads
        output = False
        json_output = False
        bruteforce_list = subbrute.print_target(parsed_domain.netloc,
                                                record_type, subs, resolvers,
                                                process_count, output,
                                                json_output, search_list,
                                                verbose)

    subdomains = search_list.union(bruteforce_list)

    if subdomains:
        subdomains = sorted(
            subdomains,
            key=functools.cmp_to_key(subdomain_cmp),
        )
        if savefile:
            write_file(savefile, subdomains)

        if not silent:
            print(Y +
                  "[-] Total Unique Subdomains Found: %s" % len(subdomains) +
                  W)

        if ports:
            if not silent:
                print(G +
                      "[-] Start port scan now for the following ports: %s%s" %
                      (Y, ports) + W)
            ports = ports.split(',')
            pscan = portscan(subdomains, ports)
            pscan.run()

        elif not silent:
            table = Texttable()
            table.set_deco(Texttable.HEADER)
            for subdomain in subdomains:
                try:
                    geo = geolite2.lookup(socket.gethostbyname(subdomain))
                    if geo:
                        table.add_rows(
                            [["Subdomain", "IP Address", "Location"],
                             [
                                 subdomain,
                                 socket.gethostbyname(subdomain),
                                 str(geo.country) + " - " + str(geo.location)
                             ]])
                    else:
                        table.add_rows(
                            [["Subdomain", "IP Address", "Location"],
                             [subdomain,
                              socket.gethostbyname(subdomain), "-"]])
                except socket.gaierror:
                    table.add_rows([["Subdomain", "IP Address", "Location"],
                                    [subdomain, "-", "-"]])
            print(G + table.draw() + W)
    return subdomains
def main():
    # Enter folder name with video files.
    location = input('Directory path: ')

    # length of new video in s
    length = int(input('Length of sequence (in s): '))

    video_files = []
    file_names = []
    print("\nOutput written to output.txt")

    f = open("output.txt", "w")

    table = Texttable()
    table.add_row(["Clip Position", "Clip Name", "Start Point", "End Point", "Total Duration"])

    for root, dirs, files in os.walk(location):
        for file in files:
            if file.endswith(FILE_EXTENSION):
                video_files.append(os.path.join(root, file))
                file_names.append(file)

    count = 0
    while length > 0:
        file = random.choice(video_files)

        index = video_files.index(file)

        if file.endswith(FILE_EXTENSION):
            # Video length
            clip = VideoFileClip(file)

            frame_rate = clip.fps

            # random frame
            start_frame = random.randint(1, int(frame_rate))
            end_frame = random.randint(1, int(frame_rate))

            # Start timestamp of clip
            a = random.uniform(0, clip.duration)
            b = random.uniform(0, clip.duration)

            start = 0
            end = 0

            if a < b:
                start = a
                end = b
            else:
                end = a
                end = b

            duration = end - start

            start_string = f'{datetime.timedelta(seconds=round(start))}:{start_frame}'
            end_string = f'{datetime.timedelta(seconds=round(end))}:{end_frame}'

            table.add_row([count + 1, file_names[index],
                           start_string,
                           end_string,
                           datetime.timedelta(seconds=round(duration))])
            count += 1

            length -= duration

    print(file_names)
    f.write(table.draw())
예제 #23
0
파일: dep.py 프로젝트: thesps/ipbb
def report(env, filters):
    '''Summarise the dependency tree of the current project'''

    lCmdHeaders = ['path', 'flags', 'package', 'component', 'lib']

    lFilterFormat = re.compile('([^=]*)=(.*)')
    lFilterFormatErrors = []
    lFieldNotFound = []
    lFilters = []

    # print ( filters )

    for f in filters:
        m = lFilterFormat.match(f)
        if not m:
            lFilterFormatErrors.append(f)
            continue

        if m.group(1) not in lCmdHeaders:
            lFieldNotFound.append(m.group(1))
            continue

        try:
            i = lCmdHeaders.index(m.group(1))
            r = re.compile(m.group(2))
            lFilters.append((i, r))
        except RuntimeError as e:
            lFilterFormatErrors.append(f)

    if lFilterFormatErrors:
        raise click.ClickException(
            "Filter syntax errors: " +
            ' '.join(['\'' + e + '\'' for e in lFilterFormatErrors]))

    if lFieldNotFound:
        raise click.ClickException(
            "Filter syntax errors: fields not found {}. Expected one of {}".
            format(
                ', '.join("'" + s + "'" for s in lFieldNotFound),
                ', '.join(("'" + s + "'" for s in lCmdHeaders)),
            ))

    # return
    lParser = env.depParser
    secho('* Variables', fg='blue')
    printDictTable(lParser.vars, aHeader=False)

    echo()
    secho('* Parsed commands', fg='blue')

    lPrepend = re.compile('(^|\n)')
    for k in lParser.commands:
        echo('  + {0} ({1})'.format(k, len(lParser.commands[k])))
        if not lParser.commands[k]:
            echo()
            continue

        lCmdTable = Texttable(max_width=0)
        lCmdTable.header(lCmdHeaders)
        lCmdTable.set_deco(Texttable.HEADER | Texttable.BORDER)
        lCmdTable.set_chars(['-', '|', '+', '-'])
        for lCmd in lParser.commands[k]:
            # print(lCmd)
            # lCmdTable.add_row([str(lCmd)])
            lRow = [
                relpath(lCmd.FilePath, env.srcdir),
                ','.join(lCmd.flags()),
                lCmd.Package,
                lCmd.Component,
                # lCmd.Map,
                lCmd.Lib,
            ]

            if lFilters and not all(
                [rxp.match(lRow[i]) for i, rxp in lFilters]):
                continue

            lCmdTable.add_row(lRow)

        echo(lPrepend.sub(r'\g<1>  ', lCmdTable.draw()))
        echo()

    secho('Resolved packages & components', fg='blue')

    lString = ''

    # lString += '+----------------------------------+\n'
    # lString += '|  Resolved packages & components  |\n'
    # lString += '+----------------------------------+\n'
    lString += 'packages: ' + ' '.join(iterkeys(lParser.components)) + '\n'
    lString += 'components:\n'
    for pkg in sorted(lParser.components):
        lString += u'* %s (%d)\n' % (pkg, len(lParser.components[pkg]))
        lSortCmp = sorted(lParser.components[pkg])
        for cmp in lSortCmp[:-1]:
            lString += u'  ├── ' + str(cmp) + '\n'
        lString += u'  └── ' + str(lSortCmp[-1]) + '\n'
    echo(lString)

    if lParser.missing:
        lString = ''
        if lParser.missingPackages:
            secho('Missing packages:', fg='red')
            echo(' '.join(list(lParser.missingPackages)))

        # ------
        lCNF = lParser.missingComponents
        if lCNF:
            secho('Missing components:', fg='red')

            for pkg in sorted(lCNF):
                lString += '+ %s (%d)\n' % (pkg, len(lCNF[pkg]))
                lSortCNF = sorted(lCNF[pkg])
                for cmp in lSortCNF[:-1]:
                    lString += u'  ├──' + str(cmp) + '\n'
                lString += u'  └──' + str(lSortCNF[-1]) + '\n'

        # ------

        # ------
        echo(lString)

    lFNF = lParser.missingFiles

    if lFNF:
        secho('Missing files:', fg='red')

        lFNFTable = Texttable(max_width=0)
        lFNFTable.header(
            ['path expression', 'package', 'component', 'included by'])
        lFNFTable.set_deco(Texttable.HEADER | Texttable.BORDER)

        for pkg in sorted(lFNF):
            lCmps = lFNF[pkg]
            for cmp in sorted(lCmps):
                lPathExps = lCmps[cmp]
                for pathexp in sorted(lPathExps):

                    lFNFTable.add_row([
                        relpath(pathexp, env.srcdir),
                        pkg,
                        cmp,
                        '\n'.join([
                            relpath(src, env.srcdir)
                            for src in lPathExps[pathexp]
                        ]),
                    ])
        echo(lPrepend.sub(r'\g<1>  ', lFNFTable.draw()))
예제 #24
0
def get_table_printer() -> Texttable:
    t = Texttable(max_width=130)
    t.set_deco(Texttable.BORDER | Texttable.HEADER | Texttable.VLINES)
    t.set_precision(2)
    return t
def main():
    # Метод проверки разностей средних уровней
    print(5 * "=", "average difference", 5 * "=")

    # USD 2014
    # https://net.dn.ua/money/stat.php?valute=12&year=2014&mon=0
    usd = [7.99, 8.65, 9.91, 11.63, 11.40, 11.74, 12.90, 13.02, 12.95, 14.64]

    # GBP 2014
    # https://net.dn.ua/money/stat.php?valute=8&year=2014&mon=0
    gbp = [
        13.16, 14.31, 16.48, 19.46, 19.17, 20.03, 21.58, 21.27, 20.84, 23.15
    ]
    data = gbp

    arr1 = data[:len(data) // 2]
    print("arr1", arr1)
    arr2 = data[len(data) // 2:]
    print("arr2", arr2)

    average1 = round(sum(arr1) / len(arr1), 2)
    print("average1", average1)
    average2 = round(sum(arr2) / len(arr2), 2)
    print("average2", average2)

    dispersion1 = dispersion(arr1, average1)
    print("dispersion1", dispersion1)
    dispersion2 = dispersion(arr2, average2)
    print("dispersion2", dispersion2)

    f_calc = round(
        dispersion1 /
        dispersion2 if dispersion1 > dispersion2 else dispersion2 /
        dispersion1, 2)
    assert (len(arr1) - 1 == 4)
    assert (len(arr2) - 1 == 4)
    f_tabl = 6.39  # because P <= 0.05 and len(arr1) - 1 == 4 and len(arr2) - 1 = 4

    print("f_calc", f_calc)
    print("f_tabl", f_tabl)
    is_accepted = f_calc < f_tabl
    print("the hypothesis of homogeneity of dispersion is accepted:",
          is_accepted)
    if is_accepted:
        t_criterion_calc = round(
            student_t_criterion(average1, average2, dispersion1, dispersion2,
                                len(arr1), len(arr2)), 2)
        print("t_criterion_calc:", t_criterion_calc)
        assert (len(arr1) + len(arr2) - 2 == 8)
        t_criterion_tabl = 2.31  # because P <= 0.05 and len(arr1) + len(arr2) - 2 == 8
        print("t_criterion_tabl:", t_criterion_tabl)
        print("trend exist:", t_criterion_calc > t_criterion_tabl)

    # Метод Фостера-Стьюарта
    print(5 * "=", "foster–stuart", 5 * "=")
    result_list = []
    for i, val in enumerate(data):
        if i == 0:
            result_list.append((None, None, None, None))
        else:
            # calculate k
            j = 0
            while j < i:
                if val < data[j]:
                    j = -1
                    break
                j += 1
            k_val = 0 if j == -1 else 1
            # calculate l
            j = 0
            while j < i:
                if val > data[j]:
                    j = -1
                    break
                j += 1
            l_val = 0 if j == -1 else 1
            # calculate s
            s_val = k_val + l_val
            # calculate d
            d_val = k_val - l_val
            result_list.append((k_val, l_val, s_val, d_val))

    t = Texttable()
    t.add_rows([["k", "l ", "s", "d"], *result_list])
    print(t.draw())

    s_sum = 0
    d_sum = 0
    for k, l, s, d in result_list[1:]:
        s_sum += s
        d_sum += d
    print("s_sum:", s_sum)
    print("d_sum:", d_sum)

    assert (len(data) == 10)
    m = 3.858  # because len(data) == 10
    t_s = abs(d_sum - 0) / 1.964
    print("t_s", round(t_s, 2))

    t_d = round((s_sum - m) / 1.288, 2)
    print("t_d", t_d)

    assert (len(data) - 1 == 9)
    t_tabl = 2.26  # because  P <= 0.05 and len(data) - 1 == 9
    print("t_tabl", t_tabl)
    print("row trend exist:", t_s > t_tabl)
    print("dispersion trend exist:", t_d > t_tabl)
예제 #26
0
 def print_global_status(self):
     socat_flag = False
     racadm_flag = False
     ipmi_console_flag = False
     if not self.__node_list:
         print "There is no node."
         return
     for node in self.__node_list:
         nd_status = node.get_node_status()
         if 'socat' in nd_status:
             socat_flag = True
         if 'racadm' in nd_status:
             racadm_flag = True
         if 'ipmi_console' in nd_status:
             ipmi_console_flag = True
         if racadm_flag and ipmi_console_flag and socat_flag:
             break
     header_line = ['name', 'bmc pid', 'node pid']
     width = [12, 6, 6]
     align = ['c', 'l', 'l']
     if socat_flag:
         header_line.append('socat pid')
         width.append(6)
         align.append('l')
     if racadm_flag:
         header_line.append('racadm pid')
         width.append(6)
         align.append('l')
     if ipmi_console_flag:
         header_line.append('ipmi-console pid')
         width.append(12)
         align.append('l')
     header_line.append('ports')
     port_width = 80 - 14 - 9 - 9 - socat_flag*9 - \
         racadm_flag*9 - ipmi_console_flag*15
     width.append(port_width - 1)
     align.append('l')
     rows = []
     rows.append(header_line)
     for node in self.__node_list:
         nd_status = node.get_node_status()
         line = [node.get_node_name()]
         if 'bmc' in nd_status:
             line.append(nd_status['bmc'])
         else:
             line.append('-')
         if 'node' in nd_status:
             line.append(nd_status['node'])
         else:
             line.append('-')
         if socat_flag:
             if 'socat' in nd_status:
                 line.append(nd_status['socat'])
             else:
                 line.append('-')
         if racadm_flag:
             if 'racadm' in nd_status:
                 line.append(nd_status['racadm'])
             else:
                 line.append('-')
         if ipmi_console_flag:
             if 'ipmi_console' in nd_status:
                 line.append(nd_status['ipmi_console'])
             else:
                 line.append('-')
         port = ''
         for p in node.get_port_status():
             port += "{} ".format(p)
         if port == '':
             line.append('-')
         else:
             line.append(port)
         rows.append(line)
     table = Texttable()
     table_type = ~Texttable.BORDER
     table.set_deco(table_type)
     table.set_cols_width(width)
     table.set_cols_align(align)
     table.add_rows(rows)
     print table.draw() + '\n'
 def printTextTable(board):
     table = Texttable()
     table.add_rows(board, [])
     print(table.draw())
예제 #28
0
def spp():
    table = Texttable(max_width=900)
    no = 0
    nama = []
    nim = []
    kelas = []
    bay_uts = []
    bay_uas = []
    bay_bulan = []
    bay_seminar = []
    bay_kas = []
    admin = []

    print("_" * 40)
    print("      Program Pembayaran Mahasiswa")
    print("_" * 40)
    nama = (input("Masukan Nama  : "))
    nim = (input("Masukan NIM   : "))
    kelas = (input("Masukan Kelas : "))
    print("Pilih jenis pembayaran")
    print("1.UTS (Rp.250.000)")
    print("2.UAS (Rp.500.000")
    pilih1 = (input("Pilih (1/2) ? "))
    if pilih1 == '1':
        uts_uas = 'UTS'
        bay_uts = 250000
        bay_uas = 0
        jawab = 't'
    elif pilih1 == '2':
        uts_uas = 'UAS'
        bay_uas = 500000
        bay_uts = 0
        jawab = 't'

    else:
        print("\n!!! Failed ,Please Try Again !!!")

    pilih = (
        input("Apakah Anda mau membayar BULANAN (Rp.500.000/bulan) (y/t) ? "))
    if pilih == 'y':
        bulanan = int(
            input("\nPembayaran BULANAN \nDi bayar untuk berapa bulan ? "))
        d_bulanan = 'BULANAN'
        bay_bulan = 5000000 * bulanan
    else:
        bulanan_ = ''
        bay_bulan = 0
    pilih = (input("Apakah Anda mau membayar SEMINAR (Rp.100.000) (y/t) ? "))
    if pilih == 'y':
        seminar = 'SEMINAR'
        bay_seminar = 100000
    else:
        seminar = ''
        bay_seminar = 0
    pilih = (input("Apakah Anda mau membayar KAS (Rp.20.000/bulan) (y/t) ? "))
    if pilih == 'y':
        d_kas = 'KAS'
        kas = int(input("\nPembayaran KAS \nDi bayar untuk berapa bulan ? "))
        bay_kas = 20000 * kas
    else:
        kas = ''
        bay_kas = 0
    print("Anda Akan dikenakan Biaya Admin sebesar (Rp.5.000)")
    input('')
    admin = 5000
    no = +1
    for ia in range(no):
        total_bayar = bay_uts + bay_uas + bay_bulan + bay_seminar + bay_kas
        grand_total = total_bayar + admin
    table.set_cols_dtype(
        ['a', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i', 'i'])
    table.add_rows([[
        'NO', 'NAMA', 'NIM', 'KELAS', 'UTS', 'UAS', 'BULAN', 'SEMINAR', 'KAS',
        'TOTAL', 'ADMIN', 'GRAND TOTAL'
    ],
                    [
                        ia + 1, nama, nim, kelas, bay_uts, bay_uas, bay_bulan,
                        bay_seminar, bay_kas, total_bayar, admin, grand_total
                    ]])
    print("_" * 30)
    print("     Rincian Pembayaran")
    print("_" * 30)
    print(table.draw())
    jawab3 = input("\n  Tambahkan Data PEMBAYARAN (y/t)? ")
    print("")
예제 #29
0
    for token in tokens:
        if token.lower() in domains:
            domainset.append(token)
    
    # check for bi-grams and tri-grams (example: machine learning)
    for token in noun_chunk:
        token = token.lower().strip()
        if token in domains:
            domainset.append(token)
    
    return [i.capitalize() for i in set([i.lower() for i in domainset])]

name = extract_name(text)
phone = extract_mobile_numbers(text)
email = extract_emails(text)
education = extract_education(text)
skills = extract_skills(text)
domains = extract_domains(text)
from texttable import Texttable
t = Texttable()
t.set_cols_dtype(['t','t','t', 't', 't', 't']) 
t.set_cols_width([10, 16, 16, 10, 15, 15])
t.add_rows([['Name', 'Mobile Number', 'Email', 'Education', 'Technical Skills', 'Domains'], [name, phone, email, education, skills, domains]])
print(t.draw())
#print(tabulate([[name, phone, email, education]], headers=['Name', 'Mobile Number', 'Email', 'Education'], tablefmt='orgtbl'))



#import spacy

예제 #30
0
def draw_single_response_table(response):
    table = Texttable(max_width=140)
    table.add_row(response.keys())
    table.add_row(response.values())
    return table.draw()