Best Python code snippet using tox_python
endecrypter.py
Source:endecrypter.py
1from Crypto.Cipher import AES2from secrets import choice3from string import ascii_letters4from Crypto import Random5from hashlib import md56import os78def pad(text):9 padding_size = AES.block_size - len(text) % AES.block_size10 return text + b"\0" * padding_size, padding_size1112def decrypttext(key, ciphertext):13 nonce = ciphertext[:AES.block_size]14 cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)15 plaintext = cipher.decrypt(ciphertext[AES.block_size:-1])16 padding_size = ciphertext[-1] * (-1)17 return plaintext[:padding_size]1819def encrypttext(key, text):20 text, padding_size = pad(text)21 nonce = Random.new().read(AES.block_size)22 cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)23 enc_bytes = nonce + cipher.encrypt(text) + bytes([padding_size])24 return enc_bytes2526def generatekey():27 letters = ascii_letters, "0123456789", "!\"'#$%&()*+,-./;<>?@[\]^_`{|}~"28 key = ""29 for i in range(20):30 key += choice(letters[0]) + choice(letters[1]) + choice(letters[2])31 return key[:20]3233#$ -- MAIN -- #34file_selection_method = input("Endecrypter | V2 | AES GCM\nOptions: [1] File [2] Multiple Files [3] Folder\nSelect: ")35while file_selection_method not in ["1","2","3"]:36 file_selection_method = input("Not a valid option, try again.\nSelect: ")37file_action = input("What do you want to do?: [1] Encrypt [2] Decrypt\nSelect: ")38while file_action not in ["1","2"]:39 file_action = input("Not a valid option, try again.\nSelect: ")40match file_selection_method:41 case "1": # one file selection42 file_path = input("File Path: ")43 while not os.path.isfile(file_path):44 file_path = input("File does not exist, try again.\nFile Path: ")45 if file_action != "2":46 key_method = input("Key Options: [1] Generate a random key [2] Manually enter a key\nSelect: ")47 match key_method:48 case "1":49 key_unhashed = generatekey()50 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()51 case "2":52 key_unhashed = input("Key: ")53 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()54 else:55 key_unhashed = input("Key: ")56 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()57 match file_action:58 case "1":59 if not file_path.endswith(".endenc"):60 with open(file_path, "rb+") as file:61 print(f"Encrypting '{file_path}'...")62 content = file.read()63 file.seek(0)64 encrypted_content = encrypttext(key_hashed, content)65 file.write(encrypted_content)66 file.truncate()67 file.close()68 os.rename(file_path, file_path + ".endenc")69 print(f"Encryption of '{file_path}' completed!\nKey: {key_unhashed}")70 else:71 print(f"Skipped '{file_path}' because it is already encrypted with this encrypter.")72 case "2":73 if file_path.endswith(".endenc"):74 with open(file_path, "rb+") as file:75 print(f"Decrypting '{file_path}'...")76 content = file.read()77 file.seek(0)78 decrypted_content = decrypttext(key_hashed, content)79 file.write(decrypted_content)80 file.truncate()81 file.close()82 os.rename(file_path, file_path[:-7])83 print(f"Decryption of '{file_path}' completed!\nKey: {key_unhashed}")84 else:85 print(f"Skipped '{file_path}' because it is not encrypted with this encrypter.")86 case "2": # multiple files selection87 file_path_list = []88 print("Enter the paths of the files (enter 'done' when done)")89 while True:90 file_path = input("File Path: ")91 if file_path.lower() == "done":92 break93 while not os.path.isfile(file_path):94 file_path = input("File does not exist, try again.\nFile Path: ")95 file_path_list.append(file_path)96 if len(file_path_list) < 1:97 print("No files in file path list, aborting process...")98 exit()99 if file_action != "2":100 key_method = input("Key Options: [1] Generate a random key [2] Manually enter a key\nSelect: ")101 match key_method:102 case "1":103 key_unhashed = generatekey()104 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()105 case "2":106 key_unhashed = input("Key: ")107 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()108 else:109 key_unhashed = input("Key: ")110 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()111 match file_action:112 case "1":113 for for_file in file_path_list:114 if not for_file.endswith(".endenc"):115 with open(for_file, "rb+") as file:116 print(f"Encrypting '{for_file}'...")117 content = file.read()118 file.seek(0)119 encrypted_content = encrypttext(key_hashed, content)120 file.write(encrypted_content)121 file.truncate()122 file.close()123 os.rename(for_file, for_file + ".endenc")124 else:125 print(f"Skipped '{for_file}' because it is already encrypted with this encrypter.")126 print(f"Encryption of the files completed!\nKey: {key_unhashed}")127 case "2":128 for for_file in file_path_list:129 if for_file.endswith(".endenc"):130 with open(for_file, "rb+") as file:131 print(f"Decrypting '{for_file}'...")132 content = file.read()133 file.seek(0)134 decrypted_content = decrypttext(key_hashed, content)135 file.write(decrypted_content)136 file.truncate()137 file.close()138 os.rename(for_file, for_file[:-7])139 else:140 print(f"Skipped '{for_file}' because it is not encrypted with this encrypter.")141 print(f"Decryption of the files completed!\nKey: {key_unhashed}")142 case "3": # folder selection143 folder_path = input("Folder Path: ")144 while not os.path.isdir(folder_path):145 folder_path = input("Folder does not exist, try again.\nFolder Path: ")146 if file_action != "2":147 key_method = input("Key Options: [1] Generate a random key [2] Manually enter a key\nSelect: ")148 match key_method:149 case "1":150 key_unhashed = generatekey()151 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()152 case "2":153 key_unhashed = input("Key: ")154 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()155 else:156 key_unhashed = input("Key: ")157 key_hashed = md5(key_unhashed.encode()).hexdigest().encode()158 match file_action:159 case "1":160 for for_file in os.listdir(folder_path):161 if not for_file.endswith(".endenc"):162 with open(folder_path + "\\" + for_file, "rb+") as file:163 print(f"Encrypting '{folder_path}\\{for_file}'...")164 content = file.read()165 file.seek(0)166 encrypted_content = encrypttext(key_hashed, content)167 file.write(encrypted_content)168 file.truncate()169 file.close()170 os.rename(folder_path + "\\" + for_file, folder_path + "\\" + for_file + ".endenc")171 else:172 print(f"Skipped '{for_file}' because it is already encrypted with this encrypter.")173 print(f"Encryption of the files completed!\nKey: {key_unhashed}")174 case "2":175 for for_file in os.listdir(folder_path):176 if for_file.endswith(".endenc"):177 with open(folder_path + "\\" + for_file, "rb+") as file:178 print(f"Decrypting '{folder_path}\\{for_file}'...")179 content = file.read()180 file.seek(0)181 decrypted_content = decrypttext(key_hashed, content)182 file.write(decrypted_content)183 file.truncate()184 file.close()185 os.rename(folder_path + "\\" + for_file, folder_path + "\\" + for_file[:-7])186 else:187 print(f"Skipped '{for_file}' because it is already encrypted with this encrypter.")
...
def_setup.py
Source:def_setup.py
1from tkinter.filedialog import * # Ð´Ð»Ñ os.path2import time34# ÑÑнкÑÐ¸Ñ Ð²ÑбоÑа csv Ñайла Ð´Ð»Ñ Ð·Ð°Ð¿Ð¸Ñи даннÑÑ
Ñ Ð°ÑдÑино и пÑовеÑка ÑазмеÑа Ñайла5def work_with_csv():6 time_stump_file = time.strftime('%Y_%m_%d')7 for_file = ['_0', '_1', '_2', '_3', '_4', '_5', '_6', '_7', '_8', '_9', '_10']8 i = 09 file_size = 2000 # ÑÐ°Ð·Ð¼ÐµÑ Ñайла в кб10 for zz in for_file:11 filename = time_stump_file + '_data' + for_file[i] + '.csv'12 if i < len(for_file) and os.path.exists(filename) and os.path.getsize(filename) < file_size:13 print('Файл_', filename, ' Ñже еÑÑÑ Ð¸ он < ', file_size, 'кб')14 break15 elif os.path.exists(filename) and os.path.getsize(filename) > file_size:16 print('Файл_', filename, ' > ', file_size, 'кб')17 filename = time_stump_file + '_data' + for_file[i + 1] + '.csv'18 print('Файл_', filename, ' Ñоздан из-за пÑевÑÑÐµÐ½Ð¸Ñ ÑазмеÑа')19 outfile1 = open(filename, 'a')20 if os.path.getsize(filename) == 0:21 outfile1.write('ÐаÑа' + ';' + 'ÐлажноÑÑÑ' + ';' + 'ТемпеÑаÑÑÑа' + ';' + "\n")22 break23 else:24 filename = time_stump_file + '_data' + for_file[i] + '.csv'25 print('Файл_', filename, ' Ñоздан ')26 outfile1 = open(filename, 'a')27 if os.path.getsize(filename) == 0:28 outfile1.write('ÐаÑа' + ';' + 'ÐлажноÑÑÑ' + ';' + 'ТемпеÑаÑÑÑа' + ';' + "\n")29 break30 i += 131 print('ÐапиÑÑ Ð±ÑÐ´ÐµÑ Ð²', filename)
...
old_forcreator.py
Source:old_forcreator.py
1 def forcreator(self):2 '''Dies ist ein kleiner Assistent der eine .for Datei erstellen kann.'''3 import sys4 print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for Creator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"5 filename = str(raw_input('Wie soll die Datei heissen: '))6 for_file = file(filename, 'w')7 name = str(raw_input('Wie heisst die Formel mit Namen: '))8 for_file.write(name + '\n')9 grundformel = str(raw_input('Wie heisst die Grundformel: '))10 for_file.write(grundformel + '\n')11 var_anzahl = int(raw_input('Wie viele Variablen hat die Formel: '))12 if var_anzahl < 3:13 sys.exit()14 var_anzahl_str = str(var_anzahl) + ' \n'15 for_file.write(var_anzahl_str)16 wiederholungen = var_anzahl + 117 t1 = "'"18 t2 = "' \n"19 print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"20 print "|Variablen Abfrage"21 print "--------------------------------------------------------"22 for i in range(1, wiederholungen):23 i = str(i)24 exec "var" + i + " = str(raw_input('|" + i + ". Variable | '))"25 exec "for_file.write(t1 + var" + i + " + t2)"26 print "--------------------------------------------------------"27 print "|Formel Abfrage"28 print "|Gebe die Formel zu den Variablen an"29 print "--------------------------------------------------------"30 for i in range(1, wiederholungen):31 i = str(i)32 exec "for" + i + " = str(raw_input('Wie heisst die Formel fuer ' + var" + i + "+ ': '))"
...
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!!