Best Python code snippet using lemoncheesecake
Huffman_Coding.py
Source:Huffman_Coding.py  
...8        self.ascii_value = ascii_value9        self.freq = freq10        self.left = None  # stores the left child's reference11        self.right = None  # stores the right child's reference12        HeapNode.__log_obj.add_log(f"Heap Node with {self.ascii_value} ascii value initialized")13    # Functions that help us build the min heap14    def __lt__(self, other):15        """overloading the less than operator"""16        return self.freq < other.freq17    def __eq__(self, other):18        """overloads the equal to operator"""19        if other is None:20            return False21        if not isinstance(other, HeapNode):  # Safeguarding ourselves if other is not a HeapNode22            return False23        return self.freq == other.freq24class HuffmanCoding:25    __log_obj = Logger("logs//log.log")26    def __init__(self, path):27        self.path = path28        self.heap = []  # min heap29        self.codes = {}  # mappings between ASCII code and Huffman Codes30        self.reverse_mapping = {}  # mappings b/w Huffman Code and ASCII code31        self.filename, self.file_format = os.path.splitext(self.path)32        HuffmanCoding.__log_obj.add_log("Huffman Code object initialized")33    def make_freq_dict(self, byte_array_data):34        """method to build ASCII value and frequency mappings"""35        try:36            frequency = {}  # dictionary storing ASCII code and frequencies37            for index, item in enumerate(byte_array_data):38                if item not in frequency:39                    frequency[item] = 140                else:41                    frequency[item] += 142            HuffmanCoding.__log_obj.add_log("frequency dictionary created")43            return frequency44        except Exception as e:45            HuffmanCoding.__log_obj.add_log("Error occured in make_freq_dict function")46            HuffmanCoding.__log_obj.add_log(str(e))47    def make_heap(self, frequency):48        """build the min heap, which helps us in creating the Huffman Tree"""49        try:50            for ascii_value in frequency:51                node = HeapNode(ascii_value, frequency[ascii_value])  # Creating node of Heap Node52                heapq.heappush(self.heap, node)53            HuffmanCoding.__log_obj.add_log("make heap function completed")54        except Exception as e:55            HuffmanCoding.__log_obj.add_log("Error occured in make_heap function")56            HuffmanCoding.__log_obj.add_log(str(e))57    def merge_codes(self):58        """creates the Huffman Tree. Also save the root in heap"""59        try:60            while len(self.heap) > 1:61                node1 = heapq.heappop(self.heap)  # get the top most node62                node2 = heapq.heappop(self.heap)  # get the top most node63                newNode = HeapNode(None, node1.freq + node2.freq)  # create a new node with frequencies of the64                # two nodes65                # newNode becomes the parent of node1 and node266                newNode.left = node167                newNode.right = node268                # push newNode back into the heap69                heapq.heappush(self.heap, newNode)70                HuffmanCoding.__log_obj.add_log("merge codes function executed")71        except Exception as e:72            HuffmanCoding.__log_obj.add_log("error occurred in merge_codes function.")73            HuffmanCoding.__log_obj.add_log(str(e))74    def make_codes_helper(self, node, current_code):75        """helper function to build huffman tree codes"""76        try:77            if node is None:  # reached the leaf node78                return79            if node.ascii_value is not None:  # code can be built for this ASCII Value80                self.codes[node.ascii_value] = current_code81                self.reverse_mapping[current_code] = node.ascii_value82            # recursive call83            self.make_codes_helper(node.left, current_code + "0")  # call on the left child84            self.make_codes_helper(node.right, current_code + "1")  # call on the right child85        except Exception as e:86            HuffmanCoding.__log_obj.add_log("error occurred in make_codes_helper function")87            HuffmanCoding.__log_obj.add_log(str(e))88    def make_codes(self):89        """function to make codes from the Huffman Tree. We will make this recursive."""90        try:91            root = heapq.heappop(self.heap)92            current_code = ""93            self.make_codes_helper(root, current_code)94            HuffmanCoding.__log_obj.add_log("make codes function completed")95        except Exception as e:96            HuffmanCoding.__log_obj.add_log("error occurred in make_codes function")97            HuffmanCoding.__log_obj.add_log(str(e))98    def get_encoded_text(self, byte_array_data):99        """function to encode the ASCII code to the Huffman Codes"""100        try:101            encoded_text = ""102            for index, item in enumerate(byte_array_data):103                encoded_text += self.codes[item]104            HuffmanCoding.__log_obj.add_log("get encoded text function executed")105            return encoded_text106        except Exception as e:107            HuffmanCoding.__log_obj.add_log("Error occurred in get_encoded_text function occured")108            HuffmanCoding.__log_obj.add_log(str(e))109    def pad_encoded_text(self, encoded_text):110        """function to pad the encoded_text so that encoded text is multiple of 8 as 1 bute = 8 bits"""111        try:112            extra_padding = 8 - (len(encoded_text) % 8)113            for i in range(extra_padding):114                encoded_text += "0"115            padded_info = "{0:08b}".format(extra_padding)116            encoded_text = padded_info + encoded_text117            return encoded_text118        except Exception as e:119            HuffmanCoding.__log_obj.add_log("error occurred in pad_encoded_text function")120            HuffmanCoding.__log_obj.add_log(str(e))121    def get_byte_array(self, padded_encoded_text):122        """converts bits to bytes"""123        try:124            b = bytearray()125            for i in range(0, len(padded_encoded_text), 8):126                byte = padded_encoded_text[i:i + 8]127                b.append(int(byte, 2))  # by default base is 10, we want 2 to be the base128            return b129        except Exception as e:130            HuffmanCoding.__log_obj.add_log("Error occurred un get_byte_array function.")131            HuffmanCoding.__log_obj.add_log(str(e))132    def compress(self, output_path):133        """function to compress the file"""134        try:135            output_path += ".bin"136            with open(self.path, 'rb') as file, open(output_path, 'wb') as output:137                text = file.read()  # reading the byte data138                text = text.strip()139                byte_array_data = bytearray(text)  # making byte array140                frequency = self.make_freq_dict(byte_array_data)  # creating mappings b/w ASCII codes and their141                # frequencies142                self.make_heap(frequency)  # creating the min heap143                self.merge_codes()  # creating huffman tree144                self.make_codes()  # creating code for each ASCII code145                encoded_text = self.get_encoded_text(byte_array_data)146                padded_encoded_text = self.pad_encoded_text(encoded_text)147                b = self.get_byte_array(padded_encoded_text)148                output.write(b)149                HuffmanCoding.__log_obj.add_log("compress function executed completely")150        except Exception as e:151            HuffmanCoding.__log_obj.add_log("error occured in compress function")152            HuffmanCoding.__log_obj.add_log(str(e))153    """decompression functions"""154    def remove_padding(self, bit_string):155        """function that removes the padding bits from bit string"""156        try:157            padded_info = bit_string[:8]  # padding bits are added in the first 8 bits158            extra_padding = int(padded_info, 2)  # getting the extra_padding in the form of integer. binary to int159            # conversion done hence base 2160            bit_string = bit_string[8:]  # removing the first 8 bits that store the padded bits161            encoded_text = bit_string[:-1 * extra_padding]  # removing the padded bits162            HuffmanCoding.__log_obj.add_log("remove_padding function executed")163            return encoded_text164        except Exception as e:165            HuffmanCoding.__log_obj.add_log("error in remove_padding function")166            HuffmanCoding.__log_obj.add_log(str(e))167    def decode_text(self, encoded_text):168        """function that converts the Huffman codes to ASCII codes"""169        try:170            current_code = ""171            decoded_byte_data = bytearray()172            for bit in encoded_text:173                current_code += bit174                if current_code in self.reverse_mapping:  # iterate till we get some valid code175                    ascii_code = self.reverse_mapping[current_code]  # recover ASCII code from this Huffman code176                    decoded_byte_data.append(ascii_code)177                    current_code = ""  # reset the current code178            HuffmanCoding.__log_obj.add_log("decode text function executed completely")179            return decoded_byte_data180        except Exception as e:181            HuffmanCoding.__log_obj.add_log("Error in decode_text function")182            HuffmanCoding.__log_obj.add_log(str(e))183    def decompress(self, input_path, output_path):184        """function that decompresses the file"""185        try:186            input_path += ".bin"187            output_path += self.file_format188            with open(input_path, 'rb') as file, open(output_path, 'wb') as output:189                bit_string = ""190                byte = file.read(1)191                while len(byte) > 0:192                    byte = ord(byte)193                    bits = bin(byte)[2:].rjust(8, '0')194                    bit_string += bits195                    byte = file.read(1)196                encoded_text = self.remove_padding(bit_string)197                decoded_byte_data = self.decode_text(encoded_text)198                output.write(decoded_byte_data)199            HuffmanCoding.__log_obj.add_log("Decompress function executed")200            HuffmanCoding.__log_obj.add_log(f"File present at location {output_path}")201        except Exception as e:202            HuffmanCoding.__log_obj.add_log("Error in decompress function")...FileManipulation.py
Source:FileManipulation.py  
...20            if extension in self.__file_system:21                self.__file_system[extension].append(file_name)22            else:23                self.__file_system[extension] = [file_name]24        FileManipulation.__log_obj.add_log("File Manipulation initialized")25    def create_folders(self):26        try:27            """ function that creates folder for each type of file extension"""28            # check if folders folder exits, delete if it does29            if os.path.exists("folders\\"):30                shutil.rmtree("folders\\")  # deleting the folder31            os.mkdir("folders")  # creating the folder which contains separate folder for separate file extension32            FileManipulation.__log_obj.add_log("FOLDERS folder created")33            # creating folders for each file34            for extension in self.__file_system:35                os.mkdir("folders\\" + extension)36                # copying files in the folder37                for individual_file in self.__file_system[extension]:38                    shutil.copyfile(src="staging\\" + individual_file + extension,39                                    dst="folders\\" + extension + "\\" + individual_file + extension)40            FileManipulation.__log_obj.add_log("folder created for each extension in folders folder")41        except Exception as e:42            FileManipulation.__log_obj.add_log("Error in create folder function")43            FileManipulation.__log_obj.add_log(str(e))44    def merge_files_same_extension(self, extension_to_be_merged, final_file_name):45        try:46            """ function that merges all the files with a given extension"""47            final_file = bytearray()  # object storing the bytes of merged file48            for file in self.__file_system[extension_to_be_merged]:49                # iterate over all the files whose extension is "extension to be merged"50                path = "staging\\" + file + extension_to_be_merged51                with open(path, "rb") as file_obj:52                    individual_byte_file = bytearray(file_obj.read())  # read bytes of single file53                    for index, byte in enumerate(individual_byte_file):54                        final_file.append(byte)  # append bytes into final_file55                # writing into final file56                final_path = "Merged_Files\\" + final_file_name + extension_to_be_merged57                with open(final_path, "wb") as file_obj:58                    file_obj.write(final_file)59            FileManipulation.__log_obj.add_log("merged file function successful")60        except Exception as e:61            FileManipulation.__log_obj.add_log("problem in merged file function")62            FileManipulation.__log_obj.add_log(str(e))63    def sort_on_names(self):64        try:65            """function that sorts all the files on the basis of names"""66            sorted_files = []67            for extension in self.__file_system:68                for file in self.__file_system[extension]:69                    sorted_files.append(file)70            FileManipulation.__log_obj.add_log("sort_on_names function successful")71            return sorted(sorted_files)72        except Exception as e:73            FileManipulation.__log_obj.add_log("Problem in sort_on_names function")74            FileManipulation.__log_obj.add_log(str(e))75    def sort_on_size(self):76        try:77            """function that sorts all the files on the basis of size of files"""78            sorted_files_dict = {}79            for extension in self.__file_system:80                for file in self.__file_system[extension]:81                    sorted_files_dict[file] = os.stat("staging\\" + file + extension).st_size82            sorted_files_dict = {k: v for k, v in sorted(sorted_files_dict.items(), key=lambda item: item[1])}83            FileManipulation.__log_obj.add_log("sort_on_size function successful")84            return list(sorted_files_dict.keys())85        except Exception as e:86            FileManipulation.__log_obj.add_log("problem in sort_on_size function")87            FileManipulation.__log_obj.add_log(str(e))88    @staticmethod89    def __patsearching(file_name, pattern):90        try:91            """function that searches for a given pattern in a given file"""92            """implements the naive pattern searching algorithm"""93            """helper function for searching function"""94            m = len(pattern)95            n = len(file_name)96            for i in range(0, n - m + 1):97                j = 098                while j < m:99                    if pattern[j] != file_name[i + j]:100                        break101                    j += 1102                if j == m:103                    return file_name  # Pattern found in this file104            return -1  # Pattern not found in this file105        except Exception as e:106            FileManipulation.__log_obj.add_log("problem in patsearching file")107            FileManipulation.__log_obj.add_log(str(e))108    def searching(self, pattern):109        try:110            """generator function that searches for the files which satisfy a given pattern"""111            for extension in self.__file_system:112                for file in self.__file_system[extension]:113                    x = FileManipulation.__patsearching(file, pattern)114                    if x != -1:115                        yield x116        except Exception as e:117            FileManipulation.__log_obj.add_log("problem in searching algorithm")...main.py
Source:main.py  
...6from game_state_classes import *7from tkinter.simpledialog import askstring8def clear_logs():9    logs_text.delete('1.0', tk.END)10    #add_log("Logs have been cleared:")11def add_log(log):12    logs_text.insert(tk.END,log + "\n")13def stop_playing():14    clear_logs()15    button_start = tk.Button(text="Start playing - RESTART NOT WORKING YET", command =start_playing)16    button_start.grid(column=0,row =1)17def start_playing():18    game_state = Game_state()19    add_log("Looking for a chessboard...")20    found_chessboard, position  = chessboard_detection.find_chessboard()21    if found_chessboard:22        add_log("Found the chessboard " + position.print_custom())23        game_state.board_position_on_screen = position24    else:25        add_log("Could not find the chessboard")26        add_log("Please try again when the board is open on the screen\n")27        return28    29    button_start = tk.Button(text="Stop playing", command =stop_playing)30    button_start.grid(column=0,row =1)31    add_log("Checking if we are black or white...")32    resized_chessboard = chessboard_detection.get_chessboard(game_state)33    #cv2.imshow('Resized image',resized_chessboard)34    game_state.previous_chessboard_image = resized_chessboard35    we_are_white = board_basics.is_white_on_bottom(resized_chessboard)36    game_state.we_play_white = we_are_white37    if we_are_white:38        add_log("We are white" )39        game_state.moves_to_detect_before_use_engine = 040    else:41        add_log("We are black")42        game_state.moves_to_detect_before_use_engine = 143        first_move_registered = False44        while first_move_registered == False:45            first_move_string = askstring('First move', 'What was the first move played by white?')46            if len(first_move_string) > 0:47                first_move = chess.Move.from_uci(first_move_string)48                first_move_registered = game_state.register_move(first_move,resized_chessboard)49        add_log("First move played by white :"+ first_move_string)        50    51    while True:52        window.update()53        #cv2.imshow('Resized image',game_state.previous_chessboard_image)54        #add_log("Moves to detect before use engine" + str(game_state.moves_to_detect_before_use_engine))55        if game_state.moves_to_detect_before_use_engine == 0:56            #add_log("Our turn to play:")57            game_state.play_next_move()58            #add_log("We are done playing")59        60        found_move, move = game_state.register_move_if_needed()61        if found_move:62            clear_logs()63            add_log("The board :\n" + str(game_state.board) + "\n")64            add_log("\nAll moves :\n" + str(game_state.executed_moves))65    66window = tk.Tk()67#window.geometry("300x300")68window.wm_attributes('-topmost', True)69window.title("ChessBot by Stanislas Heili")70label_titre = tk.Label(text="Welcome on my chessbot, hope you will have fun with it",anchor="e", wraplength = 300)#\nThis bot can not work on a game that already started")71label_titre.grid(column = 0,row = 0)72button_start = tk.Button(text="Start playing", command =start_playing)73button_start.grid(column=0,row =1)74logs_text = tk.Text(window,width=40,height=25,background='gray')75logs_text.grid(column = 0,row = 2)...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!!
