def run(self): set_test_environ() # Wipe existing modules, to make sure coverage data is properly # generated for them. for key in list(sys.modules.keys()): if key.startswith('pgi'): del(sys.modules[key]) try: from coverage import coverage except ImportError: print("Missing 'coverage' module. See " "https://pypi.python.org/pypi/coverage or try " "`apt-get install python-coverage`") return cov = coverage() cov.start() import tests tests.test(False, "cffi") dest = os.path.join(os.getcwd(), "coverage") cov.stop() cov.html_report( directory=dest, ignore_errors=True, include=["pgi/*"]) print("Coverage summary: file://%s/index.html" % dest)
def run(self): import tests import os import platform set_test_environ() if os.name == "nt": self.pgi_only = True self.backend = "ctypes" self.gi_only = False if platform.python_implementation() != "CPython": self.pgi_only = True self.gi_only = False if self.pgi_only and self.gi_only: raise ValueError("You can't set both pgi-only and gi-only") if self.backend and self.gi_only : raise ValueError("Backend selection only works with pgi") filtered_runs = [] runs = [(False, "ctypes"), (False, "cffi"), (True, None)] for (run_gi, backend) in runs: if run_gi and self.pgi_only: continue if not run_gi and self.gi_only: continue if self.backend and self.backend != backend: continue filtered_runs.append((run_gi, backend)) # create a filter function for selecting tests by regexp if self.filter: def filter_tests(name): return re.search(self.filter, name) is not None else: filter_tests = None # don't fork with one run if len(filtered_runs) == 1: run_gi, backend = filtered_runs[0] exit(tests.test( run_gi, backend, self.strict, filter_tests, self.exitfirst)) for is_gi, backend in filtered_runs: pid = os.fork() if pid != 0: pid, status = os.waitpid(pid, 0) kill_signal = (status & 0xff) returncode = (status >> 8) & 0xff if not kill_signal: if returncode: exit(returncode) else: exit(1) else: exit(tests.test( is_gi, backend, self.strict, filter_tests, self.exitfirst))
def run(self): set_test_environ() # Wipe existing modules, to make sure coverage data is properly # generated for them. for key in list(sys.modules.keys()): if key.startswith('pgi'): del (sys.modules[key]) try: from coverage import coverage except ImportError: print("Missing 'coverage' module. See " "https://pypi.python.org/pypi/coverage or try " "`apt-get install python-coverage`") return cov = coverage() cov.start() import tests tests.test(False, "cffi") dest = os.path.join(os.getcwd(), "coverage") cov.stop() cov.html_report(directory=dest, ignore_errors=True, include=["pgi/*"]) print("Coverage summary: file://%s/index.html" % dest)
def run(self): import tests import os import platform set_test_environ() if os.name == "nt": self.pgi_only = True self.backend = "ctypes" self.gi_only = False if platform.python_implementation() != "CPython": self.pgi_only = True self.gi_only = False if self.pgi_only and self.gi_only: raise ValueError("You can't set both pgi-only and gi-only") if self.backend and self.gi_only: raise ValueError("Backend selection only works with pgi") filtered_runs = [] runs = [(False, "ctypes"), (False, "cffi"), (True, None)] for (run_gi, backend) in runs: if run_gi and self.pgi_only: continue if not run_gi and self.gi_only: continue if self.backend and self.backend != backend: continue filtered_runs.append((run_gi, backend)) # create a filter function for selecting tests by regexp if self.filter: def filter_tests(name): return re.search(self.filter, name) is not None else: filter_tests = None # don't fork with one run if len(filtered_runs) == 1: run_gi, backend = filtered_runs[0] exit( tests.test(run_gi, backend, self.strict, filter_tests, self.exitfirst)) for is_gi, backend in filtered_runs: pid = os.fork() if pid != 0: pid, status = os.waitpid(pid, 0) if status: exit(status) else: exit( tests.test(is_gi, backend, self.strict, filter_tests, self.exitfirst))
def main(): nStart = 10000 nmax = 100000 gap = 1000 startTime = timer() tests.test(nStart, nmax, gap) stopTime = timer() print(stopTime - startTime)
def main(): """ runs functions according to given args :return: """ if args.command == "discover" and args.custom_auth == "dvwa": print("{url}/setup.php".format(url=url)) browser.open("{url}/setup.php".format(url=url)) browser.select_form('form[action="#"]') browser.submit_selected() dvwa_auth() if args.common_words: links = discover_pages() print("Links found --------------------------------------------------------------------") for link in links: print(link) print("Inputs in link -------------------------------------------------------------") discover_input(link) print("Cookies ------------------------------------------------------------------------") discover_cookies() elif args.command == "test": dvwa_auth() links = discover_pages() print(links) forms = discover_forms(links) vectors = open(args.vectors).readlines() sanitized_chars = None if args.sanitized_chars: sanitized_chars = open(args.sanitized_chars).readlines() sensitive_file = args.sensitive if args.slow: test(forms, vectors, sanitized_chars, sensitive_file, args.slow) else: test(forms, vectors, sanitized_chars, sensitive_file) else: # assuming we are going to go to fuzzer_tests if we don't have dvwa auth browser.open("{url}".format(url=url)) browser.select_form('form[action="/fuzzer-tests/index.php"]') browser["calzone"] = "chicken bacon ranch" # just to see if the text has been put into the textbox" browser.launch_browser() browser.submit_selected() browser.open(url) if args.common_words: links = discover_pages() print(links) for link in links: discover_input(link) discover_cookies()
def main(): parser = argparse.ArgumentParser(description='WiFi Mapper') parser.add_argument("-s", type=int, nargs=3, default=[12, 12, 12], dest="size", help="Grid size. [x, y, z]") parser.add_argument("-a", type=int, default=1, dest="src_amt", help="Amount of signal sources.") parser.add_argument("-m", type=int, default=12, dest="samples", help="Amount of UGV samples.") parser.add_argument("-v", type=int, default=4, dest="uav_rows", help="Amount of UAV rows.") parser.add_argument("-r", type=int, default=8, dest="radius", help="UGV movement radius.") parser.add_argument("--rmse", type=int, default=0, dest="rmse", help="Interval between RMSE logs. 0 for none.") parser.add_argument("--csv", action="store_true", dest="csv", help="Generate CSV version of RMSE log instead of displaying graphs.") parser.add_argument("--display", type=int, dest="display", help="Interval between display of matplotlib graphs. 0 for none. Does nothing if --csv is active.") parser.add_argument("--no_rand", action="store_true", dest="no_rand", help="Whether to skip testing of random robot. Does nothing if --csv is active.") parser.add_argument("--profile", action="store_true", dest="profile", help="Profile this program using cProfile.") args = parser.parse_args() start = time.time() if args.profile: import cProfile, pstats, io profile = cProfile.Profile(builtins=False) profile.enable() if args.csv: print(tests.rmse_csv(args.size, args.src_amt, args.samples, args.uav_rows, args.radius)) elif args.no_rand: grid = Map(size=args.size, src_amt=args.src_amt) guess, rmse, samples = tests.test(grid, args.samples, args.uav_rows, args.radius, False, args.rmse, args.display) print(f"RMSE: {rmse[-1]}") print(f"Time: {time.time() - start}") else: v_err, r_err = tests.compare(args.size, args.src_amt, args.samples, args.uav_rows, args.radius, args.rmse, args.display) if args.rmse > 0: print(f"Error: V: {v_err[-1]}, R: {r_err[-1]}") print(f"Time: {time.time() - start}") if args.profile: profile.disable() s_stream = io.StringIO() p_stats = pstats.Stats(profile, stream=s_stream).sort_stats("time") p_stats.print_stats() print(s_stream.getvalue()) if args.display: input("Press enter to continue...")
self.data['chst'] = 'd_%s'%args[0] assert args[2] in NOTE_WEATHERS,'Invalid weather' args = args[1:] self.data['chld'] = '|'.join(map(str, args))\ .replace('\r\n','|').replace('\r','|').replace('\n','|').replace(' ','+') class Bubble(GChart): def render(self): pass def __init__(self, type, *args): GChart.__init__(self) assert type in BUBBLE_TYPES, 'Invalid type' if type in ('icon_text_small','icon_text_big'): args = color_args(args, 3,4) assert args[0] in BUBBLE_SICONS,'Invalid icon type' elif type == 'icon_texts_big': args = color_args(args, 2,3) assert args[0] in BUBBLE_LICONS,'Invalid icon type' elif type == 'texts_big': args = color_args(args, 1,2) self.data['chst'] = 'd_bubble_%s'%type self.data['chld'] = '|'.join(map(str, args))\ .replace('\r\n','|').replace('\r','|').replace('\n','|').replace(' ','+') def shadow(self): image = copy(self) image.data['chst'] = '%s_shadow'%self.data['chst'] return image if __name__=='__main__': from tests import test test()
def main(): m = 51133 nstart = 1000 gap = 1000 tests.test(nstart, m, gap)
return 2 * i + 2 def heapify(A): """Convert A into a max-heap in-place by building ever-larger subheaps from the bottom up.""" n = len(A) # For more efficiency, can eliminate leaves from the loop as they already constitute heaps for i in range(n - 1, -1, -1): sink_root(A, i, heap_end=n - 1) def sink_root(A, heap_start, heap_end): """Repair the heap at A[heap_start..heap_end] by sinking the root until the max-heap invariant is true.""" root = heap_start while left_child( root) <= heap_end: # i.e. while root has at least one child if right_child(root) > heap_end or A[left_child(root)] > A[right_child( root)]: larger_child = left_child(root) else: larger_child = right_child(root) if A[root] >= A[larger_child]: # root is in correct position return else: # swap root with larger child and continue A[root], A[larger_child] = A[larger_child], A[root] root = larger_child if __name__ == "__main__": test(heap_sort)
def reverse_in_order(self) -> List[T]: left_values = self.left.reverse_in_order() if self.left else [] right_values = self.right.reverse_in_order() if self.right else [] return [*right_values, *self.values, *left_values] def post_order(self) -> List[T]: left_values = self.left.post_order() if self.left else [] right_values = self.right.post_order() if self.right else [] return [*left_values, *right_values, *self.values] class BinarySearchTree(BinaryTree): def insert(self, x: T): if x == self.value: self.count += 1 elif x < self.value: if self.left is None: self.left = BinarySearchTree(x) else: self.left.insert(x) elif x > self.value: if self.right is None: self.right = BinarySearchTree(x) else: self.right.insert(x) if __name__ == "__main__": test(bst_sort)
from tests import test def insertion_sort(A): """ Insertion sort. Time complexity, worst case: O(n^2) Time complexity, average case: O(n^2) Time complexity, best case: O(n) Aux. space: O(1) (in-place) """ n = len(A) for i in range(1, n): # 1. At start of step, a[0...i-1] is sorted current = A[i] j = i # 2. Shift current left until it's in the correct position while j > 0: if current < A[j - 1]: # out of order, swap with element to left A[j - 1], A[j] = A[j], A[j - 1] j -= 1 else: break # 3. At end of step, a[0...i] is sorted return A if __name__ == "__main__": test(insertion_sort)
import pandas as pd import numpy as np import os import helper from tests import test import helper from sklearn.neighbors import KNeighborsClassifier dir_path = os.path.dirname(os.path.realpath(__file__)) if __name__ == "__main__": df = pd.read_excel(os.path.join(dir_path, '../data/Stany_ostrego_brzucha-dane.xls'), header=0, skipfooter=15, use_cols="A:AG") #print(df) test(df.to_numpy()) #helper.cross_validation(df.to_numpy(), KNeighborsClassifier(n_neighbors=9, p=1, metric='minkowski')) #helper.kolgomorov_test(df.to_numpy())
v[l], v[h] = v[h], v[l] pivot_index = l h -= 1 else: v[l], v[h] = v[h], v[l] l += 1 h -= 1 elif v[l] >= pivot <= v[h]: if l != pivot_index != h: v[l], v[pivot_index] = v[pivot_index], v[l] pivot_index = l h -= 1 elif h == pivot_index: v[l], v[h] = v[h], v[l] pivot_index = l h -= 1 elif v[l] <= pivot >= v[h]: if l != pivot_index != h: v[h], v[pivot_index] = v[pivot_index], v[h] pivot_index = h l += 1 quicksort_inplace(v, low, pivot_index - 1) quicksort_inplace(v, pivot_index + 1, high) return v if __name__ == "__main__": test(quicksort_inplace, 10**6, 10**6, 0, 10**6 - 1) # "in place" implementation is twice as slow
import helper from sklearn.neighbors import KNeighborsClassifier dir_path = os.path.dirname(os.path.realpath(__file__)) if __name__ == "__main__": df = pd.read_excel(os.path.join(dir_path, '../data/meaterD.xls'), header=0, skipfooter=15) features = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43 ] a = 43 count = 164 test(df.to_numpy(), features, a, count) df = pd.read_excel(os.path.join(dir_path, '../data/Stany_ostrego_brzucha-dane.xls'), header=0, skipfooter=15, use_cols="A:AG") features = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ] a = 30 count = 475 test(df.to_numpy(), features, a, count)
def insert_sort(v, low, high): for i in range(low + 1, high): t = v[i] j = i - 1 while v[j] > t and j >= low: v[j + 1] = v[j] j -= 1 v[j + 1] = t return v[low:high] def tim_sort(v, *args): arr_size = len(v) for i in range(0, len(v), run_size): insert_sort(v, i, min(i + run_size, arr_size)) merge_size = run_size while merge_size < arr_size: for low in range(0, arr_size, 2 * merge_size): mid = low + merge_size high = min(low + 2 * merge_size, arr_size) merge_arrays(v, low, mid, high) merge_size *= 2 return v if __name__ == "__main__": test(tim_sort, 10**6, 10**4)
heapq.heappush(frontier_q, (estimated_total_cost, adjacent_node)) prev_nodes[adjacent_node] = current_node # We've explored the entire frontier and haven't reached the goal. Must be a disconnected graph. return 'No route found.' if __name__ == "__main__": from helpers import load_map from tests import test # Tests on a connected map map_40 = load_map('/Users/ad7073/Documents/Sharpen the saw/Udacity/DSAND/projects/Project 4/map-40.pickle') assert shortest_path(map_40, 5, 5) == [5] # Single hop route assert shortest_path(map_40, 5, 9000) == 'Invalid start or goal nodes.' # Invalid goal node assert shortest_path(map_40, 5000, 5) == 'Invalid start or goal nodes.' # Invalid start node assert shortest_path(map_40, 5, 34) == [5, 16, 37, 12, 34] # Example routes assert shortest_path(map_40, 19, 24) == [19, 2, 36, 28, 31, 10, 24] assert shortest_path(map_40, 38, 11) == [38, 29, 22, 12, 17, 15, 11] # Tests on a disconnected map map_10 = load_map('/Users/ad7073/Documents/Sharpen the saw/Udacity/DSAND/projects/Project 4/map-10.pickle') assert shortest_path(map_10, 6, 4) == [6, 0, 5, 3, 4] # Works on one subgraph assert shortest_path(map_10, 9, 8) == [9, 8] # Also works on the other subgraph assert shortest_path(map_10, 6, 9) == 'No route found.' # Cannot route between the disconnected subgraphs test(shortest_path)
from tests import test def count_sort(v, *args): if not v: # if the array is empty return v max_val = max(v) freq = [0] * (max_val + 1) sorted_array = [] for i in v: freq[i] += 1 for value, _ in enumerate(freq): while freq[value]: sorted_array.append(value) freq[value] -= 1 return sorted_array if __name__ == "__main__": test(count_sort, 10**6, 10**7) # test(sorted, 10**6, 10**4)
from tests import test def selection_sort(A): """ Selection sort. Time complexity, worst case: O(n^2) Time complexity, average case: O(n^2) Time complexity, best case: O(n) Aux. space: O(1) (in-place) """ if len(A) <= 1: return A n = len(A) for i in range(n): # Find smallest value in sequence # At start of step, a[0...i-1] is sorted: only search A[i..n] min_val, min_index = A[i], i for j in range(i, n): if A[j] < min_val: min_val = A[j] min_index = j # Swap minimum with leftmost element in sequence, A[i] A[i], A[min_index] = A[min_index], A[i] # At end of step, a[0...i] is sorted return A if __name__ == "__main__": test(selection_sort)
#!/usr/bin/env python3 import ex10ref as ex10 from tests import test test(ex10)
print "Please enter your passphrase." passphrase = getpass.getpass("Passphrase:") wallet_data = base58.b58decode_check(wallet) root_key = bip38v2.decrypt_wallet(wallet_data, passphrase)[3] print "Root key:" print root_key.encode('hex') if __name__ == '__main__': if "--decrypt" in sys.argv: decrypt_wallet() elif "--create" in sys.argv: generate_new_wallet() elif "--test" in sys.argv: import tests tests.test() elif "--maketests" in sys.argv: import tests vectors = tests.make_tests() tests.pretty_print_vectors(vectors) else: print """ Usage: Commands: --decrypt to decrypt a wallet code. --create to generate a new encrypted wallet Options: --unencrypted to make the new wallet unencrypted (default: encrypted) --passphrase to specify a passphrase on the command line (default: prompt user) --fake-passphrase to specify a fake passphrase (default: prompt user) --wallet to specify a base58_check encoded encrypted wallet value (default: prompt user)
from timsort import insert_sort from timsort import tim_sort from tests import test, averages if __name__ == "__main__": try: nr_of_elements = int(float(input("Number of elements in scientific notaion: "))) except: nr_of_elements = 10**3 try: max_element = int(float(input("Maximum element in scientific notation: "))) except: max_element = 10**6 sorts = [bubble_sort, count_sort, insert_sort, merge_sort, quick_sort, quicksort_inplace, radix_sort, tim_sort, sorted] nr_of_tests = 8 for _ in range(nr_of_tests): test(sorts, nr_of_elements, max_element, 0, nr_of_elements) print() with open("results_smaller_sample.txt", "w") as f: f.write("Nr of tests: " + str(nr_of_tests) + "\n") f.write("Nr of elements: " + str(nr_of_elements) + "\n") f.write("Maximum elements: " + str(max_element) + "\n\n") for name, time in averages.items(): f.write(name + ": " + str((time/nr_of_tests) * 1000) + " ms\n")
from tests import test def bubble_sort(v, *args): for i in range(len(v)): for j in range(i, len(v)): if v[j] < v[i]: v[i], v[j] = v[j], v[i] return v if __name__ == "__main__": # test(bubble_sort, 10**5, 10**3) test(bubble_sort, 10**6, 10**4)
from tests import test from timsort import tim_sort from pprint import pprint from math import log def radix_sort(arr, *args, radix=2**4): if not arr: return [] max_val = max(arr) iterations = int(log(max_val, radix)) + 1 digits = [[] for _ in range(radix)] for power in range(1, iterations + 1): digit = radix**power for i in arr: index = (i % digit) // (digit // radix) digits[index].append(i) arr = [] for i in range(len(digits)): if digits[i]: arr += digits[i] digits[i] = [] return arr if __name__ == "__main__": test(radix_sort, 10**6, 10**6) # test(radix_sort, 20, 56)
if arr[l] <= arr[m]: merged_array.append(arr[l]) l += 1 else: merged_array.append(arr[m]) m += 1 if l == mid: merged_array += arr[m:high] else: merged_array += arr[l:mid] arr[low:high] = merged_array def merge_sort(arr, low, high): arr_len = high - low if arr_len <= 1: return arr mid = (low + high) // 2 merge_sort(arr, low, mid) merge_sort(arr, mid, high) merge_arrays(arr, low, mid, high) return arr if __name__ == "__main__": test(merge_sort, 10**6, 10**4, 0, 10**6)
def insertion_sort_binary(A): """ Insertion sort with binary search implemented to reduce number of comparisons. Useful when comparison is more expensive than swaps (e.g. an array of strings). Note that number of swaps is still O(n^2) in worst case. Time complexity, worst case: O(n^2) - O(n*log n) comparisons, O(n^2) swaps Time complexity, average case: O(n^2) - O(n*log n) comparisons, O(n^2) swaps Time complexity, best case: O(n) Aux. space: O(1) (in-place) """ n = len(A) for i in range(1, n): # 1. At start of step, a[0...i-1] is sorted current = A[i] # 2. Because a[0...i-1] is sorted, we can do binary search correct_loc = binary_search(A, 0, i - 1, current) # Move all items to right of correct_loc up one j = i - 1 while j >= correct_loc: A[j + 1] = A[j] j -= 1 A[correct_loc] = current # 3. At end of step, a[0...i] is sorted return A if __name__ == "__main__": test(insertion_sort_binary)
# Add leftover elements if l_index < len(L): result += L[l_index:] elif r_index < len(R): result += R[r_index:] return result def merge_sort(A): """ Top-down merge sort using lists: https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation_using_lists. Time complexity, worst case: O(n*log n) Time complexity, average case: O(n*log n) Time complexity, best case: O(n) Aux. space: O(n) """ if len(A) <= 1: return A middle = len(A) // 2 L = A[:middle] R = A[middle:] left_sorted = merge_sort(L) right_sorted = merge_sort(R) result = merge(left_sorted, right_sorted) return result if __name__ == "__main__": test(merge_sort)
action='store_true', help='A menu that allows you to print information on each ' 'function of this program.') optional.add_argument('--tests', action='store_true', help='Run tests that checks to see if regex and string ' 'comparison is working correctly. Returns nothing if ' 'tests all pass.') args = parser.parse_args() if args.info: printdocs.docs() elif args.tests: tests.test() print("Tests complete, if nothing returned all tests passed.") elif args.r and args.s: userRegex = str(args.r) userString = str(args.s) result = (regex.match(userRegex, userString)) if result: print("\nThe regex " + userRegex + " matches the string " + userString) else: print("\nThe regex " + userRegex + " does not match the string " + userString) else: