Best Python code snippet using fMBT_python
index.py
Source:index.py  
1from typing import Optional23import magic4import pytermgui as ptg56import routes7import session8from src.api.auth.service import getOneUser9from src.api.file_crypto.service import deleteFile, getOneFile, updateFile10from src.components import ConfirmModal, Footer11from src.constants import (12    DEFAULT_PREVIEW_THEME,13    IMAGE_PREVIEW_PADDING,14    IMAGE_PREVIEW_WIDTH,15)16from src.helpers.climage import convert_frombytes17from src.helpers.cryptography import decryptData, encryptData18from src.helpers.file import getSettingField19from src.helpers.highlight import syntaxHighlight20from src.helpers.page_manager import drawPage, switchCurrPageWindowSlot21from src.types.Page import Page, PageWindows2223unsupportedEncoding = (24    ptg.Label(25        "[window__title--warning]Warning: The file is not displayed"26        " because it is either binary or uses an unsupported text"27        " encoding.",28    ),29)3031unsupportedSyntaxHighlighting = (32    ptg.Label(33        "[window__title--error]Error: Syntax highlight is not"34        " supported for this file type. Please switch to 'no theme'"35        " theme to remove this line.",36        parent_align=ptg.HorizontalAlignment.LEFT,37    ),38)3940previewFeatureWarning = (41    "[window__title--warning]Warning: Image preview in ANSI is"42    " preview feature. It may downgrade the performance."43)444546# NOTE: Currently we just can switch between "edit" mode and "preview" mode.47# I added a function to remove highlight from the code, it works but in the48# InputField, we CAN'T edit the highlighted content, it will throw errors on49# edit.50def FilePreview(51    fileName: str,52    passphrase: str,53    theme: str,54    preview: bool = False,55    forcePreview: bool = False,56) -> Optional[Page]:5758    if not theme:59        theme = getSettingField(60            "workbench.preview.defaultColorTheme", DEFAULT_PREVIEW_THEME61        )6263    imageWidth = getSettingField("workbench.preview.imageWidth", IMAGE_PREVIEW_WIDTH)6465    # NOTE: We create empty window slots so we can dynamically insert footer66    windowSlots = []6768    if session.user is None:69        return None7071    user = getOneUser(session.user.email)7273    file = getOneFile(user.email, fileName)7475    if file is None:76        return None7778    decryptedData = decryptData(79        privateKey=user.privateKey,80        # FIXME: Hardcoded passphrase for testing81        passphrase=passphrase,82        encryptedSessionKey=file.sessionKey,83        nonce=file.nonce,84        tag=file.tag,85        cipherText=file.cipher.read(),86    )8788    fileContent = decryptedData if decryptedData is not None else ""8990    def handleDeleteClick():91        def handleConfirmDeleteClick():92            try:93                deleteFile(user.email, fileName)94            except AttributeError:95                pass96            finally:97                # Close the file preview window by swapping with empty window98                handleCloseClick()99                # Clear nav bar window100                switchCurrPageWindowSlot(window.manager, "nav_bar", clear=True)101                # And redraw the dashboard page102                drawPage(window.manager, routes.routes["dashboard"]())103104        ConfirmModal(105            window.manager,106            "Are you sure you want to delete this file?",107            confirmOnClick=lambda *_: handleConfirmDeleteClick(),108            cancelOnClick=lambda *_: None,109        )110111    # DONE: Implement this function to encrypt the file content and then update112    # file on the database113    def handleSaveClick():114115        # NOTE: We remove whitespace from the edited content and original116        # content to check changes. So, if file was edited with "newlines",117        # "tabs" or "whitespace" will result in no changes.118119        # NOTE: Why? Because "InputField" will join all lines with a newline on120        # window resize. So, we can't compare directly the edited content with121        # the original content.122        originalContent = "".join(fileContent.split())123124        editedContent = "".join(editContentField.value.split())125126        if not editedContent == originalContent:127            window.manager.toast("File edited. Saving file...")128            # DONE: Update file on the database129130            encryptedData = encryptData(131                user.publicKey, editContentField.value.encode("utf-8")132            )133134            if encryptedData:135                encryptedSessionKey, nonce, tag, cipherText = encryptedData136137                updateFile(138                    user.email, fileName, encryptedSessionKey, nonce, tag, cipherText139                )140141                window.manager.toast("File saved successfully!")142143            else:144                window.manager.toast("Failed to save file!")145146            handleCloseClick()147        else:148            window.manager.toast("No changes made.")149150    def handleModeButtonClick():151152        # NOTE: We have to clear footer window slot when we change to preview153        # mode154        if preview is False:155            # Clear footer windows156            switchCurrPageWindowSlot(157                window.manager,158                "footer",159                clear=True,160            ),161162        # Toggle between edit and preview mode163        switchCurrPageWindowSlot(164            manager=window.manager,165            targetAssign=("body"),166            newWindow=routes.routes["dashboard/file_preview"](167                fileName=fileName,168                passphrase=passphrase,169                theme=theme,170                preview=not preview,171            ),172        )173174    def handleCloseClick():175        # Clear file preview windows176        switchCurrPageWindowSlot(177            window.manager,178            "body",179            clear=True,180        ),181        # Clear footer windows182        switchCurrPageWindowSlot(183            window.manager,184            "footer",185            clear=True,186        ),187188    def handleThemeButtonClick():189190        drawPage(191            window.manager,192            routes.routes["dashboard/file_preview/theme_picker"](193                fileName=fileName,194                passphrase=passphrase,195                preview=preview,196                currTheme=theme,197            ),198        )199200    # We only show the theme buttons if we are in preview mode201    themeMenu = ptg.Button("Theme", lambda *_: handleThemeButtonClick())202203    # In preview mode, we don't show the save button204    saveButton = ptg.Button("Save", lambda *_: handleSaveClick())205206    functionButton = themeMenu if preview else saveButton207208    # Also, the mode button will change between "Preview" and "Edit"209    modeButton = ptg.Button(210        "Preview mode" if not preview else "Edit mode",211        lambda *_: handleModeButtonClick(),212    )213214    windowWidgets = [215        "",216        ptg.Splitter(217            ptg.Button(218                "i",219                lambda *_: drawPage(220                    window.manager,221                    routes.routes["dashboard/file_preview/file_information"](fileName),222                ),223            ),224            modeButton,225            functionButton,226            ptg.Button("Delete", lambda *_: handleDeleteClick()),227            ptg.Button(228                "Download",229                lambda *_: drawPage(230                    window.manager,231                    routes.routes["dashboard/file_preview/download_file"](fileName),232                ),233            ),234            ptg.Button(235                "Close",236                lambda *_: handleCloseClick(),237                parent_align=ptg.HorizontalAlignment.RIGHT,238            ),239        ),240        "",241    ]242243    def getPreviewField():244        # Plain text preview content245        previewContentField = ptg.Label(fileContent)246        previewContentField.parent_align = ptg.HorizontalAlignment.LEFT247        if theme != "no theme":248            highlightPreviewContent = syntaxHighlight(fileName, fileContent, theme)249            if highlightPreviewContent is not None:250                previewContentField = ptg.Label(highlightPreviewContent)251                previewContentField.parent_align = ptg.HorizontalAlignment.LEFT252            # NOTE: We can add a button label "OK" here, after the error message to253            # switch to 'no theme' theme.254            else:255                windowWidgets.insert(0, unsupportedSyntaxHighlighting)256        return previewContentField257258    # A flag to check image preview is opened. If it is, we set min width to259    # reserve image preview space.260    imageForcePreview = False261262    # NOTE: You can use command "file app.py" (libmagic) on Unix OS to check263    # file type.264    fileType = magic.from_buffer(fileContent)265266    if "text" in fileType and isinstance(fileContent, str):267        if preview:268            previewContentField = getPreviewField()269            windowWidgets.append(previewContentField)270        else:271            editContentField = ptg.InputField(str(fileContent), multiline=True)272            # NOTE: We can use this way to add syntax highlight to the code when273            # editing. But the performance is EXTREMELY slow.274            # editContentField.styles.value = lambda _, text: ptg.tim.parse(275            #     syntaxHighlight(fileName, text, theme)276            # )277278            # We create a footer to track cursor and selection length279            footer = Footer(inputField=editContentField)280281            # NOTE: We dynamically add the footer to the window slots282            windowSlots.append(PageWindows(window=footer, assign="footer"))283284            # Append edit content field to the window widgets285            windowWidgets.append(editContentField)286287    elif "image" in fileType and isinstance(fileContent, bytes):288        if preview:289            if forcePreview:290                # NOTE: ANSI image preview feature is extremely slow.291                imageForcePreview = True292                previewContentField = (293                    ptg.Label(294                        convert_frombytes(295                            fileContent,296                            is_truecolor=True,297                            is_256color=False,298                            is_unicode=True,299                            width=imageWidth,300                        ),301                    ),302                )303                windowWidgets.append(previewContentField)304            else:305                # We print a warning message to warn the user about the preview306                # (beta) feature307                previewContentField = [308                    previewFeatureWarning,309                    "",310                    ptg.Button(311                        "Preview anyway",312                        lambda *_: switchCurrPageWindowSlot(313                            manager=window.manager,314                            targetAssign=("body"),315                            newWindow=routes.routes["dashboard/file_preview"](316                                fileName=fileName,317                                passphrase=passphrase,318                                preview=preview,319                                theme=theme,320                                forcePreview=True,321                            ),322                        ),323                    ),324                ]325                windowWidgets.extend(previewContentField)326    else:327        windowWidgets.append(unsupportedEncoding)328329    # NOTE: We spread those widgets here, so we can dynamically insert widget to330    # this window331    window = ptg.Window(*windowWidgets)332333    # NOTE: Set window min width so when user resize window, the image won't be334    # broken. Except the terminal size is too small.335    if imageForcePreview:336        window.min_width = imageWidth + IMAGE_PREVIEW_PADDING * 2337338    window.overflow = ptg.Overflow.SCROLL339    window.set_title(340        f"[window__title]{fileName}[/window__title]"341        f' [italic nord15]{"(Preview mode)" if preview else "(Edit mode)"}'342    )343    window.vertical_align = ptg.VerticalAlignment.TOP344345    windowSlots.append(PageWindows(window=window, assign="body"))346347    return {348        "layout": None,349        "windows": windowSlots,
...gui.py
Source:gui.py  
1#This is a gui for makepro2from tkinter import *3#set up variables to be assigned with gui parts4#folder = "Hasn't changed"5class WindowWidgets:6    def __init__(self):7        window = Tk()8        window.title("Makepro")9        folder = StringVar()10        strNumOfFiles = StringVar()11        entryFrm = Frame(window)12        entryFrm.pack()13        btnFrm = Frame(window)14        btnFrm.pack()15        btnMake = Button(btnFrm, text = "Make!")16        btnCancel = Button(btnFrm, text = "Cancel", command = window.quit)17        btnUpdate = Button(btnFrm, text = "Update", command = WindowWidgets.update)18        folderLbl = Label(entryFrm, text = "Folder: ")19        folderEnt = Entry(entryFrm, textvariable = folder)20        numFilesLbl = Label(entryFrm, text = "Number of Files: ")21        numFilesEnt = Entry(entryFrm, textvariable = strNumOfFiles)22        fr = Button(window, text = "few", command = window.quit)23        folderLbl.grid(row = 1, column = 1)24        folderEnt.grid(row = 1, column = 2)25        numFilesLbl.grid(row = 2, column = 1)26        numFilesEnt.grid(row = 2, column = 2)27        btnMake.grid(row = 1, column = 1)28        btnCancel.grid(row = 1, column = 2)29        btnUpdate.grid(row = 1, column = 3)30        fr.pack()31        window.mainloop()32    def update():33        print(folder.get())34        print(strNumOfFiles.get())35        numOfFiles = eval(strNumOfFiles.get())36        print(numOfFiles + 1)37        return...footer.py
Source:footer.py  
1from typing import Optional23import pytermgui as ptg45from src.helpers.macros import (6    getCPUPercent,7    getCursor,8    getRAMPercent,9    getSelectionLength,10)111213def Footer(inputField: Optional[ptg.InputField]) -> ptg.Window:1415    ptg.tim.define("!cpu", getCPUPercent)  # type: ignore16    ptg.tim.define("!ram", getRAMPercent)  # type: ignore1718    windowWidgets = [19        # ptg.Label(20        #     "[!cpu]CPU: {cpu}%",21        #     parent_align=ptg.HorizontalAlignment.LEFT,22        # ),23        # ptg.Label(24        #     "[!ram]RAM: {ram}%",25        #     parent_align=ptg.HorizontalAlignment.RIGHT,26        # ),27    ]2829    if inputField:30        ptg.tim.define("!cursor", getCursor(inputField))31        ptg.tim.define("!select_len", getSelectionLength(inputField))3233        windowWidgets.append(34            ptg.Label(35                "[!cursor]Cursor: {row}:{col}[/!cursor] // [!select_len]{select_len}",36                parent_align=ptg.HorizontalAlignment.RIGHT,37            ),38        )3940    footer = ptg.Window(41        ptg.Splitter(*windowWidgets),42        box="EMPTY",43    )44
...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!!
