Best Python code snippet using avocado_python
esercizi04.py
Source:esercizi04.py  
...11    ENDC = '\033[0m'12    BOLD = '\033[1m'13    UNDERLINE = '\033[4m'14# Esegue un test e controlla il risultato15def check_test(func: Callable, expected: Any, *args: List[Any]):16    func_str = func.__name__17    args_str = ', '.join(repr(arg) for arg in args)18    try:19        result = func(*args)20        result_str = repr(result)21        expected_str = repr(expected)22        test_outcome = "succeeded" if (result==expected) else "failed"23        color = bcolors.OKGREEN if (result==expected) else bcolors.FAIL24        print(f'{color}Test on {func_str} on input {args_str} {test_outcome}. Output: {result_str} Expected: {expected_str}')25    except BaseException as error:26        error_str = repr(error)27        print(f'{bcolors.FAIL}ERROR: {func_str}({args_str}) => {error_str}')28# Scrivere una funzione che controlla la validita' di una password.29# La password deve avere:30# - Almeno una lettera fra [a-z] e una lettera fra [A-Z]31# - Almeno un numero fra [0-9]32# - Almeno un carattere fra [$#@]33# - Essere lunga almeno 6 caratteri34# - Essere lunga non piu' di 16 caratteri35# - La password non è valida se contiene caratteri diversi da quelli specificati sopra36#   o se viola una delle regole specificate.37# La funzione restituisce true/false a seconda se la password sia valida o meno.38def check_pwd(pwd: str) -> bool:39    _min = lambda x: 'a' <= x <= 'z'40    _MAX = lambda x: 'A' <= x <= 'Z'41    _num = lambda x: '0' <= x <= '9'42    simb = '$#@'43    all_used = [False, False, False, False]44    for c in pwd:45        if _min(c):46            all_used[0] = True47            continue48        elif _MAX(c):49            all_used[1] = True50            continue51        elif _num(c):52            all_used[2] = True53            continue54        elif c in simb:55            all_used[3] = True56            continue57        else:58            return False59    return 6 <= len(pwd) <= 16 and all(all_used)60# Scrivere una funzione che data una tupla (x, y, z)61# restituisca la tupla (z+1, x-1, y+2)62def tuple_ex(t: tuple) -> tuple:63    return t[2] + 1, t[0] - 1, t[1] + 264# Scrivere una funzione che calcola l'intersezione fra due liste.65# Date due liste, deve restituire una nuova lista contenente solo gli66# elementi presenti in entrambe le liste.67def intersect(a: list, b: list) -> list:68    res = []69    minore = a if len(a) <= len(b) else b70    magg = a if len(a) > len(b) else b71    for i, el in enumerate(minore):72        if el in magg:73            res.append(el)74    return res75# Scrivere una funzione che data una lista contenente valori >= 0, 76# crei una nuova lista contentente soltanto gli elementi della lista 77# originale tali che soddisfano la seguente proprietà:78#    lista[i] > 2*media(lista[0:i])79# (Il primo elemento non viene quindi mai inserito)80# Ad esempio, si consideri la lista [5, 3, 10, 0]81#  Il primo elemento è 5. Non viene inserito82#  Il secondo elemento è 3, e la media degli elementi nel range [0, 0] è 5. Poichè 3 < 5*2, l'elemento non viene inserito nella nuova lista83#  Il terzo elemento è 10, e la media degli elementi nel range [0, 1] è 4. Poichè 10 > 4*2, l'elemento viene inserito nella nuova lista84#  Il quarto elemento è 0, e la media degli elementi nel range [0, 2] è 6. Poichè 0 < 6*2, l'elemento non viene inserito nella nuova lista85def media(lista):86    if len(lista) > 0:87        return sum(lista) / len(lista)88def remove_avg(a: list) -> list:89    res = []90    for i, x in enumerate(a):91        if i == 0:92            continue93        if x > 2*media(a[0:i]):94            res.append(x)95    return res96# Data una lista di interi (ciascun intero è compreso fra 0 e 99), scrivere una97# funzione che restituisca una lista di tuple (x, y),98# dove x è un intero, e y è il numero di volte che questo99# intero appare nella lista originale.100# La lista di tuple deve essere ordinata in base al primo elemento.101# Ad esempio, per l'input [5, 4, 1, 4], restituisce la lista [(1, 1), (4, 2), (5, 1)]102# (ordinata in base al primo elemento perché 1 < 4 < 5)103def frequency(a: list) -> list:104    els = list(dict.fromkeys(a))105    els.sort()106    res = [(x, 0) for x in els]107    for i, el in enumerate(els):108        for el2 in a:109            if el == el2:110                res[i] = (el, res[i][1]+1)111    return res112# Scrivere una funzione che restituisce True113# se la lista è palindroma, o False altrimenti114def is_palindrome(a: list) -> bool:115    rev = a.copy()116    rev.reverse()117    for i, el in enumerate(a):118        if el != rev[i]:119            return False120    return True121# Scrivere una funzione che prende in input una lista, e 122# restituisce True se la lista è ordinata in ordine123# crescente o decrescente, e False altrimenti.124# Suggerimento: fare attenzione ai valori duplicati125# Utilizzare un solo ciclo e non utilizzare sorted/sort.126def is_sorted(a: list) -> bool:127    if len(a) <= 1:128        return True129    i = 1130    while i < len(a):131        if a[0] > a[i]:132            a.reverse()133        if a[0] < a[i]:134            break135        i += 1136    for i, el in enumerate(a[:-1]):137        if el > a[i+1]:138            return False139    return True140# Scrivere una funzione che restituisce True se una lista di interi141# è composta da una prima parte ordinata in modo crescente, seguita142# da una seconda parte ordinata in modo decrescente (o viceversa).143# Le due parti non devono avere necessariamente la stessa lunghezza.144# Utilizzare un solo ciclo e non utilizzare sorted/sort, ne la funzione145# is_sorted implementata precedentemente.146# Si assuma che la lista abbia almeno sempre 3 elementi.147def is_sorted_half(a: list) -> bool:148    changed = False149    verso = 0150    for i in range(len(a)-1):151        if verso == 0:152            if a[i] > a[i+1]:153                verso = 2154            if a[i] < a[i + 1]:155                verso = 1156        elif verso == 1:157            if not changed:158                if a[i] > a[i+1]:159                    changed = True160                    verso = 2161            else:162                if a[i] > a[i+1]:163                    return False164        elif verso == 2:165            if not changed:166                if a[i] < a[i+1]:167                    changed = True168                    verso = 2169            else:170                if a[i] < a[i+1]:171                    return False172    return changed173# Test funzioni174check_test(check_pwd, False, "a")175check_test(check_pwd, False, "000000000000000000")176check_test(check_pwd, False, "almeno6")177check_test(check_pwd, False, "Aa@09asng2/")178check_test(check_pwd, True, "Aa@09asng2")179check_test(tuple_ex, (3, -2, 1), (-1, -1, 2))180check_test(intersect, [2, 3], [1, 2, 3], [2, 3, 4])181check_test(intersect, [], [1, 2, 3], [10, 11, 12])182check_test(intersect, [], [1, 2, 3], [])183check_test(intersect, [], [], [1, 2, 3])184check_test(remove_avg, [10], [5, 3, 10, 0])185check_test(remove_avg, [20, 1000], [5, 20, 10, 1000])186check_test(remove_avg, [], [])187check_test(frequency, [(1, 1), (4, 2), (5, 1)], [5, 4, 1, 4])188check_test(frequency, [(0, 1), (23, 3), (99, 1)], [23, 99, 0, 23, 23])189check_test(is_palindrome, True, [])190check_test(is_palindrome, True, [1])191check_test(is_palindrome, True, [1, 2, 8, 2, 1])192check_test(is_palindrome, True, [1, 2, 8, 8, 2, 1])193check_test(is_palindrome, False, [1, 3, 8, 8, 2, 1])194check_test(is_sorted, True, [1])195check_test(is_sorted, True, [1, 1, 1])196check_test(is_sorted, True, [1, 2, 3, 4])197check_test(is_sorted, True, [4, 3, 2, 1])198check_test(is_sorted, True, [1, 1, 2, 3, 3, 4])199check_test(is_sorted, True, [4, 4, 3, 2, 2, 1])200check_test(is_sorted, False, [1, 1, 3, 3, 2])201check_test(is_sorted, False, [4, 4, 3, 3, 5])202check_test(is_sorted_half, False, [1, 2, 3])203check_test(is_sorted_half, False, [3, 2, 1])204check_test(is_sorted_half, True, [1, 3, 2])205check_test(is_sorted_half, True, [3, 1, 2])...Vanilla.py
Source:Vanilla.py  
1# Libraries2import csv3import matplotlib.pyplot as plt4import cv25import tensorflow as tf6import keras7from skimage.measure import compare_ssim8from tensorflow.keras.models import Sequential9from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization10from keras.layers import Conv2D, MaxPooling2D, InputLayer, UpSampling2D, Conv2DTranspose, LeakyReLU, AveragePooling2D, \11    GlobalAveragePooling2D, GlobalMaxPooling2D, Input, RepeatVector, Reshape, concatenate12import matplotlib.pyplot as plt13import numpy as np141516images_gray = np.load("gray_scale.npy")17images_lab = np.load("ab1.npy")181920# gray_scale21size_train = 400022size_test = 10023size_test_begin = 024change_pic = 025X_train_l = images_gray[0+change_pic:change_pic+size_train]26X_train_l = X_train_l.reshape(size_train, 224, 224, 1)27X_test_l = images_gray[size_test_begin + size_train+change_pic:change_pic+size_train + size_test_begin + size_test]28X_test_l = X_test_l.reshape(size_test, 224, 224, 1)2930# colored31X_train_lab = images_lab[0+change_pic:change_pic+size_train]32X_train_lab = X_train_lab.reshape(size_train, 224, 224, 2)33X_test_lab = images_lab[size_test_begin + size_train+change_pic:change_pic+size_train + size_test_begin + size_test]34X_test_lab = X_test_lab.reshape(size_test, 224, 224, 2)3536X_gray_chick = np.zeros((1,224,224,2), dtype=float)37X_gray_chick = X_gray_chick.__add__(128)38check_test = 039X_test_lab_temp = X_test_lab40X_test_l_temp = X_test_l41while check_test < size_test:42    if sum(sum(sum(sum(X_gray_chick == X_test_lab_temp[check_test]))))/100352 > 0.4:43        X_test_l = np.zeros((size_test-1, 224, 224, 1), dtype=float)44        X_test_l[0:check_test] = X_test_l_temp[0:check_test]45        X_test_l[check_test:] = X_test_l_temp[(check_test+1):]46        X_test_l_temp = X_test_l4748        X_test_lab = np.zeros((size_test-1, 224, 224, 2), dtype=float)49        X_test_lab[0:check_test] = X_test_lab_temp[0:check_test]50        X_test_lab[check_test:] = X_test_lab_temp[check_test + 1:]51        X_test_lab_temp = X_test_lab52        size_test = size_test-153        check_test = check_test - 154    check_test = check_test + 15556check_train = 057X_train_lab_temp = X_train_lab58X_train_l_temp = X_train_l59while check_train < size_train:60    if sum(sum(sum(sum(X_gray_chick == X_train_lab_temp[check_train]))))/100352 > 0.4:61        X_train_l = np.zeros((size_train-1, 224, 224, 1), dtype=float)62        X_train_l[0:check_train] = X_train_l_temp[0:check_train]63        X_train_l[check_train:] = X_train_l_temp[(check_train+1):]64        X_train_l_temp = X_train_l6566        X_train_lab = np.zeros((size_train-1, 224, 224, 2), dtype=float)67        X_train_lab[0:check_train] = X_train_lab_temp[0:check_train]68        X_train_lab[check_train:] = X_train_lab_temp[check_train + 1:]69        X_train_lab_temp = X_train_lab70        size_train = size_train-171        check_train = check_train - 172    check_train = check_train + 17374X_test_l = X_test_l/25575X_train_l = X_train_l/2557677X_train_l = tf.cast(X_train_l, tf.float32)78X_test_l = tf.cast(X_test_l, tf.float32)7980# #Vanilla CNN Model 181# model = Sequential()82# model.add(Conv2D(strides=1,filters=32,kernel_size=3,activation='relu',use_bias=True,padding='valid'))83# model.add(Conv2D(strides=1,filters=16,kernel_size=3,activation='relu',use_bias=True,padding='valid'))84# model.add(Conv2DTranspose(strides=1,filters=2,kernel_size=5,activation='relu',use_bias=True,padding='valid'))8586#Vanilla CNN Model 287model = Sequential()88model.add(Conv2D(strides=1,filters=32,kernel_size=3,activation='relu',use_bias=True,padding='valid'))89model.add(MaxPooling2D(pool_size=(2,2),strides=2))90model.add(Conv2D(strides=1,filters=16,kernel_size=3,activation='relu',use_bias=True,padding='valid'))91model.add(Conv2DTranspose(strides=2,filters=2,kernel_size=8,activation='relu',use_bias=True,padding='valid'))9293model.compile(optimizer='adam', loss='mse', metrics=['accuracy'])94history = model.fit(x=X_train_l, y=X_train_lab, validation_split=0.2, epochs=250, batch_size=16)95model.summary()96xx = model.predict(X_test_l)97xx = xx.reshape(size_test, 224, 224, 2)9899h = history100plt.plot(h.history['loss'])101plt.plot(h.history['val_loss'])102plt.xlabel('epoch')103plt.ylabel('loss')104plt.title('Model Loss')105plt.legend(['loss', 'val_loss'])106plt.axis([0, 250, 0, 20000])107plt.show()108plt.plot(h.history['accuracy'])109plt.plot(h.history['val_accuracy'])110plt.legend(['accuracy', 'val_accuracy'])111plt.xlabel('epoch')112plt.ylabel('accuracy')113plt.title('Model Accuracy')114plt.show()115for k in range(size_test):116    # predicted image117    img = np.zeros((224, 224, 3))118    kor = X_test_l[k]*255119120    kor = kor[:, :, 0]121    img[:, :, 1:] = xx[k]122    img[:, :, 0] = kor123124    img = img.astype('uint8')125    img_ = cv2.cvtColor(img, cv2.COLOR_LAB2RGB)126    plt.imshow(img_)127    plt.show()128129    # actual image130    img_truth = np.zeros((224, 224, 3))131    kor_truth = X_test_l[k]*255132    kor_truth = kor_truth[:, :, 0]133    img_truth[:, :, 0] = kor_truth134    img_truth[:, :, 1:] = X_test_lab[k]135136    img_truth = img_truth.astype('uint8')137    img_truth_ = cv2.cvtColor(img_truth, cv2.COLOR_LAB2RGB)138    plt.imshow(img_truth_)139    plt.show()140    (score, diff) = compare_ssim(img_truth, img_truth_, full=True, multichannel=True)141    diff = (diff * 255).astype("uint8")142    print("SSIM: {}".format(score))143    print("PSNR: {}".format(cv2.PSNR(img_truth, img_truth_)))144    m = tf.keras.metrics.Accuracy()145    m.update_state(img_truth, img_truth_)
...main.py
Source:main.py  
...4import sys5DEFAULT = "\033[39m"6GREEN = "\033[32m"7RED = "\033[31m"8def check_test(port: int, name_test: str, test: Callable) -> None:9	try:10		str_result = test(port)11	except:12		str_result = "couldn't connect"13	if (len(str_result) == 0):14		check = GREEN + "V" + DEFAULT15	else:16		check = RED + "X" + DEFAULT17	18	print("test : {:65} | result : {} {}".format(name_test, check, str_result))19def run(option: str, port: int) -> None:20	"""run tests"""21	22	print("All tests  are done requesting on http://localhost:port\n")23	if (option == "basic"):24		check_test(port, "GET / ", simple_get_index)25		check_test(port, "GET /auto autoindex", get_autoindex_subdir)26		check_test(port, "GET /forbidden (403) ", get_forbidden_dir)27		check_test(port, "GET non_existing_dir (404) ", get_404)28		check_test(port, "GET / ports 8080 and 8081", get_index_two_ports)29		check_test(port, "GET / 1 worker 50 times", fifty_get_root)30		check_test(port, "POST / method not authorized (405)  ", wrong_method)31		32		check_test(port, "POST /post ", simple_post)33		check_test(port, "POST /post content length = 0", post_size_0)34		check_test(port, "POST /post request too big (413)", post_too_big)35		check_test(port, "POST /post_upload upload in /upload", post_with_upload)36		37		check_test(port, "DELETE /delete_folder/index.html", delete)38		check_test(port, "DELETE /delete_folder/index.html (404)", delete_already_deleted)39		40		check_test(port, "GET http://webserv:port use of server_name ", server_name)41		check_test(port, "GET /redirect_me/please redirect 301 in /redirection/index.html", redirect_get_ok)42		check_test(port, "GET /redirect_me/wrong redirect 301 in /redirection/lol.html", redirect_get_non_existing)43		check_test(port, "POST /post_upload upload in /upload", post_with_upload)44		check_test(port, "POST /post_upload upload in /upload", post_with_upload)45		check_test(port, "POST /post_upload upload in /upload", post_with_upload)46		check_test(port, "GET /use_location_root/", get_loc_root)47		check_test(port, "POST /use_location_root/", post_loc_root)48		49		print("\nCGI TESTS & CHUNKED REQUESTS:")50		check_test(port, "GET /cgi/file.tester ", cgi_tester_get)51		check_test(port, "POST /cgi/file.tester", cgi_tester_post)52		check_test(port, "GET /use_location_root_cgi/file.tester ", cgi_tester_get_loc_root)53		check_test(port, "POST /use_location_root_cgi/file.tester", cgi_tester_post_loc_root)54		check_test(port, "POST /cgi/file.tester 20 bits", chunked_post_no_upload)55		check_test(port, "POST /cgi/file.tester 500 bits", chunked_post_no_upload_size_500)56		check_test(port, "POST /post-upload/another_file.tester 20 bits", chunked_post_upload)57		check_test(port, "POST /post-upload/another_file.tester 500 bits", chunked_post_size_500)58	if (option == "stress"):59		print("STRESS TESTS:")60		check_test(port, "GET / 25 workers 100 times", stress_test1)61		check_test(port, "GET / 100 workers 25 times", stress_test1bis)62		check_test(port, "POST 100k-1M bits 10 workers 100 times", stress_test2)63		check_test(port, "POST 100k-1M bits 100 workers 10 times", stress_test2bis)64		check_test(port, "POST CGI 1M bits 5 workers 20 times", stress_test3)65		check_test(port, "POST CGI 1M bits 20 workers 5 times", stress_test3bis)66		check_test(port, "POST CGI w/ upload 1M bits 5 workers 10 times", stress_test4)67		check_test(port, "POST CGI w/ upload 1M bits 10 workers 5 times", stress_test4bis)68		check_test(port, "POST /post-upload/another_file.tester 100M bits", chunked_post_size_100M)69if (__name__ == "__main__"):70	if (len(sys.argv) != 2):71		print("Usage: python3 main.py tests.py [port]")72		exit(1)73	try:74		port = int(sys.argv[1])75	except:76		print("please input a valid port (int)")77		exit(1)78	os.chdir("tester_documents")79	os.system("rm -rf ./upload/*")80	os.system("echo \"Delete me please\" > ./delete_folder/index.html")81	option = ""82	while (option != 'basic' and option != 'stress'):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
