Ejemplo n.º 1
0
    def test_bruteforce_complex_float(self):
        self.assertEqual(self.wallet.max_budget, 500)
        available_shares = [
            Share("Share - DUPH", "100.01", "12.25"),
            Share("Share - GTAN", "26.04", "38.06"),
            Share("Share - USUF", "9.25", "27.69"),
            Share("Share - CFOZ", "10.64", "38.21"),
            Share("Share - QLRX", "50.72", "27.47"),
            Share("Share - HKFP", "230.97", "19.66"),
            Share("Share - PPPH", "24.06", "38.2"),
            Share("Share - HLJY", "78.98", "5.54"),
            Share("Share - CTCR", "160.6", "12.4")
        ]
        bruteforce(self.wallet, available_shares)

        # Expected_folder values come from the output of utils/knapsack_solver_google.py
        # used with roundings of this test values (the scripts only accepts integers as input)
        # Script results:
        #   Total value (total_profit)                  = 98
        #   Total weight (total_cost)                   : 493
        #   Packed items (indexes in available_shares)  : [1, 4, 5, 6, 8]
        #   Packed_weights (prices in available_shares) : [26, 51, 231, 24, 161]
        expected_folder = {
            "Share - GTAN": 26.04,
            "Share - QLRX": 50.72,
            "Share - HKFP": 230.97,
            "Share - PPPH": 24.06,
            "Share - CTCR": 160.6
        }

        self.assertEqual(dict(self.wallet.folder), expected_folder)
        self.assertEqual(self.wallet.total_cost, 492.39)
        self.assertEqual(self.wallet.total_profit, 98.35)
Ejemplo n.º 2
0
def between(lst):
    if len(lst) <= 3:
        return bruteforce(lst)

    lhalf = lst[0:len(lst) / 2]
    rhalf = lst[len(lst) / 2:len(lst)]

    d = between(lhalf)
    d_new = between(rhalf)

    if d_new[0] < d[0]:
        d = d_new
    elif d_new[0] == d[0]:
        d = (d[0], d[1] + d_new[1])

    min_y = lhalf[-1][1] - d[0]
    max_y = rhalf[0][1] + d[0]

    d_new = bruteforce([p for p in lhalf if p[1] > min_y] +
                       [p for p in rhalf if p[1] < max_y])

    if d_new[0] < d[0]:
        d = d_new
    elif d_new[0] == d[0]:
        d = (d[0], d[1] + [p for p in d_new[1] if p not in d[1]])

    return d
Ejemplo n.º 3
0
def brute(domain, dict, thread):
    print('The brute scanning for subdomain is running.....\n')
    if dict is None:
        position = os.getcwd()
        position = position + '/_dict/222.txt'
        # print(position)
    else:
        position = dict
    bruteforce.bruteforce(domain, position, thread)
Ejemplo n.º 4
0
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(email=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            pass

        # bruteforce
        if username is not None:
            bruteforce(username)
        return None
Ejemplo n.º 5
0
 def test_bruteforce_simple(self):
     self.assertEqual(self.wallet.max_budget, 500)
     available_shares = [
         Share("Share-1", "1", "1"),
         Share("Share-2", "10", "1"),
         Share("Share-3", "100", "1")
     ]
     bruteforce(self.wallet, available_shares)
     expected_folder = {"Share-1": 1, "Share-2": 10, "Share-3": 100}
     self.assertEqual(self.wallet.folder, expected_folder)
     self.assertEqual(self.wallet.total_cost, 111)
     self.assertEqual(self.wallet.total_profit, 1.11)
Ejemplo n.º 6
0
 def test_bruteforce_simple_float(self):
     self.assertEqual(self.wallet.max_budget, 500)
     available_shares = [
         Share("Share-1", "0.5", "1.5"),
         Share("Share-2", "10.22", "12.3"),
         Share("Share-3", "100.3", "22")
     ]
     bruteforce(self.wallet, available_shares)
     expected_folder = {"Share-1": 0.5, "Share-2": 10.22, "Share-3": 100.3}
     self.assertEqual(self.wallet.folder, expected_folder)
     self.assertEqual(self.wallet.total_cost, 111.02)
     self.assertEqual(self.wallet.total_profit, 23.34)
Ejemplo n.º 7
0
def verify(G, s, cutoff):
    n = G.order()

    #read graph from G
    happiness = {}
    stress = {}
    for i in range(n):
        happiness[i] = {}
        stress[i] = {}
    for i in range(n):
        for j in range(i + 1, n):
            happiness[i][j] = G.get_edge_data(i, j)['happiness']
            stress[i][j] = G.get_edge_data(i, j)['stress']

    if n <= 10:
        bf_arr, bf_val = bruteforce.bruteforce(happiness, stress,
                                               len(list(happiness.keys())), s)
        bf_val = bf_val
        assignments = {}
        for i in range(len(bf_arr)):
            for person in bf_arr[i]:
                assignments[person] = i
        return assignments, len(bf_arr), bf_val
    elif n == 20 or n == 50:
        answer, rooms, best_k = lp_cutoff(happiness, stress, s, n, cutoff)
        return rooms, best_k, answer
    else:
        return "Graph sizes that aren't <=10, 20, or 50 nodes aren't accepted"
Ejemplo n.º 8
0
def naive(lst):
    lst = sorted(lst)
    if (len(lst) <= 3):
        return bruteforce(lst)
    else:
        lhalf = lst[0:len(lst) / 2]
        rhalf = lst[len(lst) / 2:len(lst)]

        d = naive(lhalf)
        d_new = naive(rhalf)

        if d_new[0] < d[0]:
            d = d_new
        elif d_new[0] == d[0]:
            d = (d[0], d[1] + d_new[1])

        m = []
        for p in lhalf:
            if p[0] > lhalf[-1][0] - d[0]:
                m.append(p)
        for p in rhalf:
            if p[0] < rhalf[0][0] - d[0]:
                m.append(p)

        sorted_m = sorted(m, sorty)
        d_new = between(sorted_m)

        if d_new[0] < d[0]:
            d = d_new
        elif d_new[0] == d[0]:
            d = (d[0], d[1] + [p for p in d_new[1] if p not in d[1]])

        return d
Ejemplo n.º 9
0
def generating(iter):
    number_of_machines = int(input("Ile maszyn?: "))
    number_of_tasks = int(input("Ile zadan?: "))
    times = []
    durationBruteforce = []
    durationJohnson = []
    i = 0
    while i < iter:
        generatedTasks = []
        cnt_tasks = 0
        cnt_machines = 0
        for cnt_tasks in range(0, number_of_tasks):
            rows = []
            for cnt_machines in range(0, number_of_machines):
                rows.append(int(random.uniform(1, 10)))
            print("{}".format(rows))
            generatedTasks.append(Task(cnt_tasks, rows))
        bruteforceOrder, timeBruteforce = bruteforce(
            copy.deepcopy(generatedTasks), number_of_machines)
        johnsonOrder, timeJohnson = johnson(copy.deepcopy(generatedTasks),
                                            number_of_machines)
        durationBruteforce.append(timeBruteforce)
        durationJohnson.append(timeJohnson)
        bruteforceMakespan = makespan(bruteforceOrder, generatedTasks,
                                      number_of_machines)
        johnsonMakespan = makespan(johnsonOrder, generatedTasks,
                                   number_of_machines)
        i += 1
        if johnsonMakespan == bruteforceMakespan:
            times.append(johnsonMakespan)
        else:
            times.append(-1)
    x = PrettyTable()
    print("")
    print("----------------------------------------------------------")
    x.field_names = [
        "l.p.", "Johnson Makespan", "Poprawnosc", "Czas Bruteforce [ms]",
        "Czas Johnson [ms]"
    ]

    k = 0
    for k in range(0, iter):
        if times[k] == -1:
            x.add_row([
                k + 1, "{}".format(times[k]), "Nie",
                "{}".format(durationBruteforce[k]),
                "{}".format(durationJohnson[k])
            ])
        else:
            x.add_row([
                k + 1, "{}".format(times[k]), "Tak",
                "{}".format(durationBruteforce[k]),
                "{}".format(durationJohnson[k])
            ])
    print(x)
Ejemplo n.º 10
0
def run():
    path = input(
        "Which method do you want to use? \nBrute force (1), Dynamic (2), Best First Branch Bound (3), or Backtracking (4)?\nOr press q to quit  : "
    )

    if path == '1':
        time1 = datetime.datetime.now()
        print(bruteforce.bruteforce(W, items[2], items[1], len(items[0])))
        time2 = datetime.datetime.now()
        tdelta = time2 - time1
        print("Brute force: Time taken: %s ms" %
              int(tdelta.total_seconds() * 1000))
        print("\n")
        run()

    elif path == '2':
        time1 = datetime.datetime.now()
        print(dynamic.dynamic(W, items[2], items[1], len(items[0])))
        time2 = datetime.datetime.now()
        tdelta = time2 - time1
        print("Dynamic: Time taken: %s ms" %
              int(tdelta.total_seconds() * 1000))
        print("\n")
        run()

    elif path == '3':
        time1 = datetime.datetime.now()
        print(
            firstBranchBound.firstBranchBound(W, items[2], items[1],
                                              len(items[0])))
        time2 = datetime.datetime.now()
        tdelta = time2 - time1
        print("Best First Branch Bound: Time taken: %s ms" %
              int(tdelta.total_seconds() * 1000))
        print("\n")
        run()

    elif path == '4':
        time1 = datetime.datetime.now()
        print(backtracking.backtracking(W, items[2], items[1], len(items[0])))
        time2 = datetime.datetime.now()
        tdelta = time2 - time1
        print("Backtracking: Time taken: %s ms" %
              int(tdelta.total_seconds() * 1000))
        print("\n")
        run()

    elif path == 'q':
        sys.exit("See ya!")

    else:
        print("Error: no valid option chosen. Please try again.")
        print("\n")
        run()
Ejemplo n.º 11
0
def main_menu():
    choice = input(
        "Press :\n1 to manage users\n2 to manage ftp\n3 to test brute force\n4 to scan ports\n5 to try the mail bombing\n6 to see the logs file\n7 to exit\n"
    )
    if choice == "1":
        logs.writeInLogSimple(user.username, " à lancer la gestion d'User")
        users_menu()
        main_menu()
    elif choice == "2":
        logs.writeInLogSimple(user.username, " à lancer la gestion FTP")
        checkdirect()
        ftp_menu()
        main_menu()
    elif choice == "3":
        logs.writeInLogSimple(user.username, " à lancer le bruteforce")
        bruteforce.bruteforce()
        main_menu()
    elif choice == "4":
        logs.writeInLogSimple(user.username, " à lancer le scan de port")
        portscan_menu()
        main_menu()
    elif choice == "5":
        logs.writeInLogSimple(user.username, " à lancer le mail bombing")
        smtp.lancement()
        main_menu()
    elif choice == "6":
        filename = "log.txt"
        with open(filename) as f:
            data = f.readlines()
        for n, line in enumerate(data, 1):
            print('{:2}.'.format(n), line.rstrip())
        # logs()
        main_menu()
    elif choice == "7":
        exit()
    else:
        print("Wrong key")
        main_menu()
Ejemplo n.º 12
0
def between(lst):
    if (len(lst) <= 3):
        return bruteforce(lst)
    else:
        lhalf = lst[0:len(lst) / 2]
        rhalf = lst[len(lst) / 2:len(lst)]

        d = between(lhalf)
        d_new = between(rhalf)

        if d_new[0] < d[0]:
            d = d_new
        elif d_new[0] == d[0]:
            d = (d[0], d[1] + d_new[1])

        d_new = bruteforce([p for p in lhalf if p[0] > lhalf[-1][0] - d[0]] +
                           [p for p in rhalf if p[0] < rhalf[0][0] + d[0]])

        if d_new[0] < d[0]:
            d = d_new
        elif d_new[0] == d[0]:
            d = (d[0], d[1] + [p for p in d_new[1] if p not in d[1]])

        return d
Ejemplo n.º 13
0
def run():
	path = input("Which method do you want to use? \nBrute force (1), Dynamic (2), Best First Branch Bound (3), or Backtracking (4)?\nOr press q to quit  : ")
	
	if path == '1':
		time1 = datetime.datetime.now()
		print( bruteforce.bruteforce(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Brute force: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()
		
	elif path == '2':
		time1 = datetime.datetime.now()
		print( dynamic.dynamic(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Dynamic: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()
	
	elif path == '3':
		time1 = datetime.datetime.now()
		print( firstBranchBound.firstBranchBound(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Best First Branch Bound: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()
	
	elif path == '4':
		time1 = datetime.datetime.now()
		print( backtracking.backtracking(W, items[2], items[1], len(items[0])) )
		time2 = datetime.datetime.now()
		tdelta = time2 - time1
		print("Backtracking: Time taken: %s ms" % int(tdelta.total_seconds()*1000) )
		print("\n")
		run()
		
	elif path == 'q':
		sys.exit("See ya!")
		
	else:
		print("Error: no valid option chosen. Please try again.")
		print("\n")
		run()
Ejemplo n.º 14
0
def solve(G, s):
    """
    Args:
        G: networkx.Graph
        s: stress_budget
    Returns:
        D: Dictionary mapping for student to breakout room r e.g. {0:2, 1:0, 2:1, 3:2}
        k: Number of breakout rooms
    """
    n = G.order()
    happiness = {}
    stress = {}
    for i in range(n):
        happiness[i] = {}
        stress[i] = {}

    for i in range(n):
        for j in range(i + 1, n):
            happiness[i][j] = G.get_edge_data(i, j)['happiness']
            stress[i][j] = G.get_edge_data(i, j)['stress']

    print("Input Size:", n)
    if n <= 10:  #brute force approach
        start_time = time.perf_counter()
        bf_arr, bf_val = bruteforce.bruteforce(happiness, stress,
                                               len(list(happiness.keys())), s)
        bf_val = round(bf_val, 3)
        end_time = time.perf_counter()
        print("Brute Force Approach Time:", end_time - start_time)

    #ILP
    start_time = time.perf_counter()
    answer, rooms, best_k = lp.lp_solve(happiness, stress, s, n)
    end_time = time.perf_counter()
    times.append(end_time - start_time)
    print("Gurobi Approach Time:     ", end_time - start_time)
    print("Gurobi Answer:            ", answer)
    #print("Gurobi Rooms (raw):       ", rooms, best_k)
    print("Gurobi Rooms:", order(rooms)[0])
    if n <= 10:
        #assert bf_val == answer, "Incorrect computation"
        print("Brutef Rooms:", bf_arr)
        print("Brutef Answer:", bf_val)
    return rooms, order(rooms)[1]
Ejemplo n.º 15
0
def main():
    # x_list = [100, 75, 15, 495, 995, 995, 995, 995, 510, 110]
    # target = 635
    x_list = [
        1150,
        495,
        995,
        995,
        995,
        995,
        100,
        750,
        3305,
        75,
        510,
        3265,
        2145,
        1935,
        140,
        140,
        15,
        1330,
        2800,
        1250,
        350,
        850,
        110,
    ]
    target = 8270

    time0 = time()
    bf = bruteforce.bruteforce(x_list, target)
    time1 = time()
    so = stackoverflow.stackoverflow(x_list, target)
    time2 = time()
    he = hetland.bb_knapsack(x_list, target)
    time3 = time()
    wi = wikipedia.approx_with_accounting_and_duplicates(x_list, target)
    time4 = time()

    print "Brute force:", bf, time1 - time0
    print "Stackoverflow:", so, time2 - time1
    print "Hetland:", he, time3 - time2
    print "Wikipedia:", wi, time4 - time3
Ejemplo n.º 16
0
def main():
    # x_list = [100, 75, 15, 495, 995, 995, 995, 995, 510, 110]
    # target = 635
    x_list = [1150, 495, 995, 995, 995, 995, 100, 750, 3305, 75, 510, 3265, 2145, 1935, 140, 140, 15, 1330, 2800, 1250, 350, 850, 110]
    target = 8270

    time0 = time()
    bf = bruteforce.bruteforce(x_list, target)
    time1 = time()
    so = stackoverflow.stackoverflow(x_list, target)
    time2 = time()
    he = hetland.bb_knapsack(x_list, target)
    time3 = time()
    wi = wikipedia.approx_with_accounting_and_duplicates(x_list, target)
    time4 = time()

    print 'Brute force:', bf, time1 - time0
    print 'Stackoverflow:', so, time2 - time1
    print 'Hetland:', he, time3 - time2
    print 'Wikipedia:', wi, time4 - time3
Ejemplo n.º 17
0
def naive(lst):
    if len(lst) <= 3:
        return bruteforce(lst)

    lhalf = lst[0:len(lst) / 2]
    rhalf = lst[len(lst) / 2:len(lst)]

    d = naive(lhalf)
    d_new = naive(rhalf)

    if d_new[0] < d[0]:
        d = d_new
    elif d_new[0] == d[0]:
        d = (d[0], d[1] + d_new[1])

    min_x = lhalf[-1][0] - d[0]
    max_x = rhalf[0][0] + d[0]

    lst = []
    for i in reversed(xrange(len(lhalf))):
        if lhalf[i][0] > min_x:
            lst.append(lhalf[i])
        else:
            break

    for i in xrange(len(rhalf)):
        if rhalf[i][0] < max_x:
            lst.append(rhalf[i])
        else:
            break

    d_new = between(sorted(lst, sorty))

    if d_new[0] < d[0]:
        d = d_new
    elif d_new[0] == d[0]:
        d = (d[0], d[1] + [p for p in d_new[1] if p not in d[1]])

    return d
Ejemplo n.º 18
0
def enhanced(lst, ysorted):
    if len(lst) <= 3:
        return bruteforce(lst)

    lhalf = lst[0:len(lst) / 2]
    rhalf = lst[len(lst) / 2:len(lst)]

    lmax_x = lhalf[-1][0]
    rmin_x = rhalf[0][0]

    lysorted = []
    rysorted = []
    for p in ysorted:
        if p[0] <= lmax_x:
            lysorted.append(p)
        else:
            rysorted.append(p)

    d = enhanced(lhalf, lysorted)
    d_new = enhanced(rhalf, rysorted)

    if d_new[0] < d[0]:
        d = d_new
    elif d_new[0] == d[0]:
        d = (d[0], d[1] + d_new[1])

    min_x = lmax_x - d[0]
    max_x = rmin_x + d[0]

    d_new = between([p for p in lysorted if p[0] > min_x] +
                    [p for p in rysorted if p[0] < max_x])

    if d_new[0] < d[0]:
        d = d_new
    elif d_new[0] == d[0]:
        d = (d[0], d[1] + [p for p in d_new[1] if p not in d[1]])

    return d
Ejemplo n.º 19
0
def solve(G, s):
    """
    Args:
        G: networkx.Graph
        s: stress_budget
    Returns:
        D: Dictionary mapping for student to breakout room r e.g. {0:2, 1:0, 2:1, 3:2}
        k: Number of breakout rooms
    """
    n = G.order()

    #read graph from G
    happiness = {}
    stress = {}
    for i in range(n):
        happiness[i] = {}
        stress[i] = {}
    for i in range(n):
        for j in range(i + 1, n):
            happiness[i][j] = G.get_edge_data(i, j)['happiness']
            stress[i][j] = G.get_edge_data(i, j)['stress']

    if n <= 10:
        bf_arr, bf_val = bruteforce.bruteforce(happiness, stress,
                                               len(list(happiness.keys())), s)
        bf_val = bf_val
        assignments = {}
        for i in range(len(bf_arr)):
            for person in bf_arr[i]:
                assignments[person] = i
        return assignments, len(bf_arr), bf_val
    elif n == 20 or n == 50:
        answer, rooms, best_k = lp.lp_solve(happiness, stress, s, n)
        return rooms, best_k, answer
    else:
        return "Graph sizes that aren't <=10, 20, or 50 nodes aren't accepted"
Ejemplo n.º 20
0
 def __call__(self):
     self.menu.add("Force brute", MethodMenu(data_file=self.data_file))
     self.menu.add("Glouton", MethodMenu(data_file=self.data_file))
     self.menu.add("Force brute sur les meilleurs profits (%)",
                   MethodMenu(data_file=self.data_file))
     self.menu.add("Programmation dynamique",
                   MethodMenu(data_file=self.data_file))
     self.menu.add("Retour au menu principal", HomeMenu())
     self.menu.add("Quitter", ExitMenu())
     user_choice = self.menu.get_user_choice()
     market = import_actions_data(file=self.data_file)
     if isinstance(user_choice, ExitMenu) or isinstance(
             user_choice, HomeMenu):
         return user_choice()
     cap = input_cap()
     start_time = time.time()
     if self.menu.choice == 0:
         portfolio = bruteforce(market, cap=cap)
     elif self.menu.choice == 1:
         portfolio = greedy(market=market, cap=cap)
     elif self.menu.choice == 2:
         number_best_actions = input_number_of_actions()
         portfolio = bruteforce_with_n_best_actions(market=market,
                                                    cap=cap,
                                                    n=number_best_actions)
     elif self.menu.choice == 3:
         number_of_decimals = input_number_of_decimals()
         portfolio = KS_dynamic(market=market,
                                cap=cap,
                                ndigits=number_of_decimals)
     end_time = time.time()
     display_best_portfolio(portfolio)
     print(
         f"Temps d'exécution : {int((end_time - start_time)//60)} min {int(round((end_time - start_time)%60, ndigits=0))} s."
     )
     return user_choice()
Ejemplo n.º 21
0
	output_file = open("output_" + name + ".txt", "w")
	output_file.write(str(result[0]) + "\n")
	for pair in sorted(result[1]):
		output_file.write(str(pair[0][0]) + " " + str(pair[0][1]) + " " + str(pair[1][0]) + " " + str(pair[1][1]) + "\n")
	output_file.close()

if __name__ == "__main__":
	input_file = open(argv[2], "r")
	points = []
	
	for line in input_file:
		line = line.split()
		try:
			points.append((int(line[0]), int(line[1])))
		except ValueError:
			points.append((float(line[0]), float(line[1])))
		
	input_file.close()

	xsorted = sorted(points, sortx)

	import time
	t = time.time()
	if argv[1] == "-b":
		print_to_file(bruteforce.bruteforce(xsorted), "bruteforce")
	elif argv[1] == "-d":
		print_to_file(divideandconquer.naive(xsorted), "divideandconquer")
	elif argv[1] == "-e":
		print_to_file(enhanceddnc.enhanced(xsorted, (sorted(points, sorty))), "enhanceddnc")
	print time.time() - t
Ejemplo n.º 22
0
from bruteforce import bruteforce
import genetic
from analyze import timer

things = knapsack.generate_things(22)
things = knapsack.second_example

weight_limit = 3000

print("Weight Limit: %dkg" % weight_limit)
print("")
print("Bruteforce Algorithm")
print("----------")

with timer():
    result = bruteforce(things, weight_limit)

knapsack.print_stats(result[1])

print("")
print("Genetic Algorithm")
print("----------")

with timer():
    population, generations = genetic.run_evolution(
        populate_func=partial(genetic.generate_population,
                              size=10,
                              genome_length=len(things)),
        fitness_func=partial(knapsack.fitness,
                             things=things,
                             weight_limit=weight_limit),
Ejemplo n.º 23
0
import read_data, bruteforce, johnson

##############################################
TWO_OR_THREE = 3  #Two or three machines algorithm??
##############################################
print("Starting program...")

##MAIN##
if (TWO_OR_THREE == 2):
    tasks_val, machines_val, tasks = read_data.read_data("data_2m.txt")
if (TWO_OR_THREE == 3):
    tasks_val, machines_val, tasks = read_data.read_data("data_3m.txt")
    print("The package ta000 has been loaded")

bruteforce.bruteforce(tasks, machines_val, tasks_val)
johnson.johnson_algorithm(machines_val, tasks)
Ejemplo n.º 24
0
def bruteforce_with_n_best_actions(market, cap, n):
    market_selection = n_best_actions(market, n)
    portfolio = bruteforce(market_selection, cap)
    return portfolio
Ejemplo n.º 25
0
    # #################################实现登录过程结束

    # #################################检查密码是否正确开始
    #    if True:
    # if r.status_code == 302:  # 根据实际情况修改此处,判定登录成功
    if "错误" not in r.text:  # 根据实际情况修改此处,判定登录成功
        msg = login_info
        # 登录成功则把登录信息保存到success_queue
        success_queue.put(msg)
        # 把登录成功的用户名添加到 success_username中,之后可以跳过这个用户名的密码的爆破
        success_username.append(username)
        print('【爆破成功,用户名:{},密码:{}】'.format(username, password))

        # 如果想要爆破出来一个密码就立刻停止爆破,那么此处调用函数stop_brute,反之则注释此处
        # stop_brute()

    # ################################# 检查密码是否正确结束





if __name__ == "__main__":
    args = utils.get_parse()
    dict_username = args.get('dict_username', "username.txt")
    dict_password = args.get('dict_password', "password.txt")

    utils.get_dict(dict_username, dict_password)

    bruteforce(login, thread_num=5)
Ejemplo n.º 26
0

def get_parse() -> dict:
    parser = argparse.ArgumentParser()
    parser.add_argument("--username", "-u", help="用户名字典")
    parser.add_argument("--password", "-p", help="密码字典")
    dic = vars(parser.parse_args())
    return dic


def get_captcha(img):
    """
    识别验证码
    :return:
    """
    # 识别验证码
    pass
    code = "af3z"

    return code


if __name__ == "__main__":
    args = get_parse()
    dict_username = args.get('dict_username', "username.txt")
    dict_password = args.get('dict_password', "password.txt")

    get_dict(dict_username, dict_password)

    bruteforce(login_captcha, thread_num=1)
Ejemplo n.º 27
0
Archivo: main.py Proyecto: s14965/MHE
        evaluations.append(utility.countConnections(s, edges))

    if utility.isclique(solution, edges):
        penalty = 0
    else:
        penalty = -1

    return penalty + sum(evaluations) / (len(nodes) *
                                         (len(nodes) - len(solution)) *
                                         (len(solution) - 1))


print("from input")
print(goalFunction([6, 7, 4, 5], input_nodes, input_edges))
print(goalFunction([2, 3, 4, 6], input_nodes, input_edges))
print(goalFunction([2, 3, 4, 7], input_nodes, input_edges))
print(goalFunction([2, 3, 4, 5], input_nodes, input_edges))
solution = bruteforce.bruteforce(input_nodes, input_edges)
print(goalFunction(solution, input_nodes, input_edges))
print(solution)

print()
print("from rand")
nodes2, edges2 = utility.generateGraph(graphSize=20)
rand_solution = utility.randSolution(nodes2)
print(rand_solution)
print(goalFunction(rand_solution, nodes2, edges2))
brut_solution = bruteforce.bruteforce(nodes2, edges2)
print(goalFunction(brut_solution, nodes2, edges2))
print(brut_solution)
Ejemplo n.º 28
0
#PREPROCESSING
tic = time.clock()
dol = Dolphinn(P, D, K)
toc = time.clock()
print "Preprocessing time: ", toc - tic

#QUERIES
tic = time.clock()
#assign keys to queries
solQ = dol.queries(Q, M, num_of_probes)
toc = time.clock()
print "Average query time (Dolphinn): ", (toc - tic) / len(Q)

#BRUTEFORCE
tic = time.clock()
solQQ = bf.bruteforce(P, Q)
toc = time.clock()
print "Average query time (Bruteforce): ", (toc - tic) / len(Q)

#COMPUTE ACCURACY: max ratio (found distance)/(NN distance), number of exact NNs found
n = 0
mmax = 0
for i in range(len(solQ)):
    if mmax < np.linalg.norm(np.subtract(P[solQ[i][0]],
                                         Q[i])) / np.linalg.norm(
                                             np.subtract(P[solQQ[i]], Q[i])):
        mmax = np.linalg.norm(np.subtract(P[solQ[i][0]],
                                          Q[i])) / np.linalg.norm(
                                              np.subtract(P[solQQ[i]], Q[i]))
    if solQ[i][0] == solQQ[i]:
        n = n + 1
Ejemplo n.º 29
0
def driver_function(output_name, MAX_POINTS, MAX_SETS):
    #generating 2d list for testing
    max_average_time = 0
    list_of_lists = []
    current_list = []

    for i in range(0, MAX_SETS):
        for j in range(0, MAX_POINTS):
            a = point_class.Point(random.randint(MIN_VAL, MAX_VAL),
                                  random.randint(MIN_VAL, MAX_VAL))
            current_list.append(a)
        list_of_lists.append(current_list[:])
        current_list = []

    list_of_times = []
    bf_rets = []
    qh_rets = []
    """
    #rough way to test hulls being drawn
    extra_points = []
    MAX_POINTS = MAX_POINTS + 8
    extra_points.append(point_class.Point(3,3))
    extra_points.append(point_class.Point(50,0))
    extra_points.append(point_class.Point(97,3))
    extra_points.append(point_class.Point(100,50))
    extra_points.append(point_class.Point(97,97))
    extra_points.append(point_class.Point(50,100))
    extra_points.append(point_class.Point(3,97))
    extra_points.append(point_class.Point(0,50))
    for i in extra_points:
        list_of_lists[0].append(i)
    """

    #    print("\n\nbruteforce:")
    for index, current_list in enumerate(list_of_lists):
        #    print("current list:")
        #    for p in current_list:
        #        print("\t", p.x, ",", p.y)

        run_time = time.time_ns()
        a = bruteforce(current_list)
        run_time = time.time_ns() - run_time
        run_time /= 1000000000.0
        list_of_times.append(run_time)
        a = sorted(a)
        bf_rets.append(a)

    #    for p in a:
    #        print("\t", p.x, ",", p.y)
    #    print("# of items: ", len(a))

    f = open(output_name + "bf.txt", 'w')
    f.write("brute force:\n")

    average_time = 0
    list_of_times = sorted(list_of_times)
    for i in list_of_times:
        output_string = "\trun time: " + str(i) + " seconds\n"
        f.write(output_string)
        average_time = average_time + i
    average_time /= len(list_of_times)
    average_time_string = "average time: " + str(average_time)
    f.write(average_time_string)

    if (average_time > max_average_time):
        max_average_time = average_time

#    print("\n\nquickhull:")

    list_of_times = []
    for index, current_list in enumerate(list_of_lists):
        #    print("current list:")
        #    for p in current_list:
        #        print("\t", p.x, ",", p.y)

        run_time = time.time_ns()
        b = quickhull(current_list)
        run_time = time.time_ns() - run_time
        run_time /= 1000000000.0
        list_of_times.append(run_time)
        b.sort()
        qh_rets.append(b)

    #    for p in b:
    #        print("\t", p.x, ",", p.y)
    #    print("# of items: ", len(b))

    g = open(output_name + "qh.txt", 'w')
    g.write("quickhull\n")

    average_time = 0
    list_of_times = sorted(list_of_times)
    for i in list_of_times:
        output_string = "\trun time: " + str(i) + " seconds\n"
        g.write(output_string)
        average_time = average_time + i
    average_time /= len(list_of_times)
    average_time_string = "average time: " + str(average_time)
    g.write(average_time_string)

    if (average_time > max_average_time):
        max_average_time = average_time

    bf_rets = sorted(bf_rets)
    qh_rets = sorted(qh_rets)

    if (bf_rets == qh_rets):
        print("returns match!")
    else:
        h = open(output_name + "_ERROR_LOG.txt", 'w')
        print("ERROR RETURNS DO NOT MATCH")
        for bf, qh in zip(bf_rets, qh_rets):
            h.write("     bf             qh")
            for i, j in zip(bf, qh):
                b = ""
                if i != j:
                    b = "NONMATCHING"
                h.write(str(i) + " " + str(j) + b)
        h.close()

    f.close()
    g.close()

    return max_average_time
Ejemplo n.º 30
0
def main():
    # Create arguments parser
    parser = argparse.ArgumentParser(
        description='Program which helps to crack zip passwords by bruteforce',
        epilog=
        'Default symbols set is all lowercase and uppercase letter and digits')
    parser.add_argument('filename', help='Name of zip file to crack')
    parser.add_argument('-min',
                        type=int,
                        default=1,
                        nargs='?',
                        help='Minimal length of password (default = 1)')
    parser.add_argument('-max',
                        type=int,
                        default=6,
                        nargs='?',
                        help='Maximal length of password (default = 6)')
    parser.add_argument('-l',
                        '--lower',
                        action='store_true',
                        help='Includes lowercase alphabet symbols')
    parser.add_argument('-u',
                        '--upper',
                        action='store_true',
                        help='Includes uppercase alphabet symbols')
    parser.add_argument('-d',
                        '--digits',
                        action='store_true',
                        help='Includes numerical symbols')
    parser.add_argument('-s',
                        '--special',
                        action='store_true',
                        help='Includes special symbols')
    parser.add_argument('-b',
                        '--bar',
                        default=True,
                        action='store_false',
                        help='Disable statusbar')
    parser.add_argument(
        '-e',
        '--estimate',
        type=str,
        nargs='?',
        help=
        'Check entered password and calculate number of password checked to bruteforce it. If you\'re using special symbols or spaces, please wrap your password by \' \' for instance: \'password\''
    )
    args = parser.parse_args()

    try:
        z = zipfile.ZipFile(args.filename, 'r')
    except:
        print('Wrong filename')
        exit(1)

    # Create alphabet for brute force method
    symbols = ''
    if args.lower:
        symbols += string.ascii_lowercase
    if args.upper:
        symbols += string.ascii_uppercase
    if args.digits:
        symbols += string.digits
    if args.special:
        symbols += string.punctuation
    if len(symbols) == 0:
        symbols += string.ascii_letters + string.digits

    combinationNumber = 0
    for i in range(args.min, args.max + 1):
        combinationNumber += len(symbols)**i
    print('Number of possible password combinations is:',
          combinationNumber,
          end='\n\n')

    if args.estimate:
        for char in args.estimate:
            if char not in symbols:
                print('Wrong set of symbols')
                exit(0)
        symbols = ''.join(OrderedDict.fromkeys(symbols))
        print('{} password'.format(
            ('Incorrect',
             'Correct')[bruteforce.checkpass(z, bytes(args.estimate,
                                                      'utf8'))]))
        checked = bruteforce.calculate(args.estimate, symbols)
        print('Number of passwords need to bruteforce it:', checked)
        args.max = 1
        start = time()
        bruteforce.bruteforce(1, 1, symbols, z, args.bar, False)
        end = time()
        speed = len(symbols) / (end - start)
        print('Average speed is', str(round(speed, 2)) + 'p/s')
        print('\nTime needed to bruteforce it: ',
              str(round(checked / speed, 2)) + 's')
        exit(1)
    else:
        if (int(args.min) > int(args.max)):
            print('-min should be less than -max')
            exit(1)

    start = time()
    counter = bruteforce.bruteforce(args.min, args.max, symbols, z, args.bar)
    end = time()
    if counter != combinationNumber:
        print('Number of passwords checked:', counter)
        print('Average speed:',
              str(round((counter / (end - start)), 2)) + 'p/s',
              end='\n\n')
    else:
        print('Password not found')
    print('Time elapsed:', str(round((end - start), 2)) + 's')
Ejemplo n.º 31
0
                    return False
                else:
                    pass
            else:
                print("连接异常")
        except Exception as e:
            print(e)
        # except requests.exceptions.ConnectionError:
        #     print("代理不可用,更换代理")
        #     CUR_PROXY = utils.get_proxy()
        #     print("当前使用代理:{}".format(CUR_PROXY))
        # except requests.exceptions.Timeout:
        #     print("代理连接速度过慢,更换代理!")
        #     CUR_PROXY = utils.get_proxy()
        #     print("当前使用代理:{}".format(CUR_PROXY))

        # except:
        #     # print('未知情况')
        #     pass


if __name__ == "__main__":
    # 开启代理池

    args = utils.get_parse()
    dict_username = args.get('dict_username', "username.txt")
    dict_password = args.get('dict_password', "password.txt")
    utils.get_dict(dict_username, dict_password)

    bruteforce(login_bypass_ip_limit, thread_num=5)
Ejemplo n.º 32
0
import numpy as np

if __name__ == "__main__":
    #original system
    A,b,c,func,MatrixSigns,VariablesSigns = enter.ReadFile('problem.txt')

    #canonical form
    CanonSys = canon.Convert(A,b,c,func,MatrixSigns, VariablesSigns)

    NpCanonForm = simplex.NpCanonicalForm(CanonSys)
    x = simplex.starting_vector(NpCanonForm)
    # x = simplex.starting_vector_method2(NpCanonForm).x  # TODO разобраться
    print("--- simplex algorithm: primal problem ---")
    print(simplex.simplex_method(NpCanonForm, x).x)
    print("------ brute force: primal problem ------")
    print(bruteforce.bruteforce(NpCanonForm))

    #dual system
    dual.CheckSigns(A, b, MatrixSigns) #only >= sign allowed in finding min problem
    TransA = dual.TransposeMatrix(A) #transposing matrix A
    Newb = dual.NewVector(c) #finding dual vector b
    Newc = dual.NewCoeff(b) #finding coefficients of dual goal function
    NewMatrixSigns = dual.NewMSigns(VariablesSigns) #finding signs of dual matrix
    NewVariableSigns = dual.NewVSigns(MatrixSigns) #finding signs of dual variables
    Newfunc = dual.NewFunction(func) #finding dual problem type

    #canon dual system
    DualCanonSys = canon.Convert(TransA,Newb,Newc,Newfunc,NewMatrixSigns,NewVariableSigns)
    

    NpCanonForm = simplex.NpCanonicalForm(DualCanonSys)
Ejemplo n.º 33
0
def init_dict():
    # args = utils.get_parse()
    args = dict()
    dict_username = args.get('dict_username', "username.txt")
    dict_password = args.get('dict_password', "password.txt")

    utils.get_dict(dict_username, dict_password)
    return dict_username, dict_password


if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == 'i':
            # ip limit
            init_dict()
            bruteforce(login_bypass_ip_limit, thread_num=5)
        elif sys.argv[1] == 's':
            # slide captcha
            init_dict()
            bruteforce(login_slide, thread_num=1)
        elif sys.argv[1] == 'u':
            # user limit
            dict_username, dict_password = init_dict()
            for curr_round in range(0, settings.MAX_ROUND):
                print("[INFO] 开始第{0}轮爆破".format(curr_round))
                utils.get_dict(dict_username, dict_password)
                bruteforce(login_limit_user, thread_num=5)
                print("[INFO] Sleep.")
                time.sleep(2)

            print_result()