Best Python code snippet using localstack_python
psg-autoname.py
Source:psg-autoname.py  
...564        process_events.currbook.seglist[segnum-1] = process_events.currbook.seglist[segnum-1].replace(')',' ')565        process_events.currbook.reassemble_segs()566    else:567        update_statustxt(window, 'Command not recognised.')568def process_events(window, event, values):569    txtboxes = ['txt' + str(x) for x in range(1, NUMBOXES+1)] # doing this every time doesn't seem efficient570    acceptletts = string.ascii_letters + string.digits + " []()-&,.;'"571    if not process_events.currbook and event != 'Help': # no books so disable all buttons except Help572        return573    if event == 'filelist': #update the file list window574        listedbookname = values['filelist'][0]575        process_events.currbook = Book(_LOCS['SCAN_DIR'] + listedbookname)576        process_events.currindex = window['filelist'].Widget.curselection()[0]577    elif event == 'btngo': # a text command is to be executed578        cmd = window['txtcmd'].Get()579        try:580            process_txt_cmd(window, values, cmd)581        except Exception as err:582            update_statustxt(window, f'Command \'{cmd}\' not recognised or invalid - {err}')583    elif event == 'btnrev':584        oldseg = process_events.currbook.seglist[0]585        revseg = process_events.currbook.reverse_seg(window, 0)586        update_statustxt(window, f'Reversing {oldseg} to {revseg}.')587    elif event == 'RAR':588        #oldname = values['filelist']589        newbook = process_events.currbook.rar(window)590        if newbook: #update listbox filename too591            # need to get current listbox value, rename to .rar, and then update592            update_filelist(window, event, values)593            move_to_specified_book(window, newbook)594    elif event == 'Find Dupes':595        process_events.currbook.dupefinder(window)596    elif event == 'Open':597        open_bookfile(window)598    elif event == 'Help':599        show_help(window)600    elif event == 'Undo':601        origname = process_events.currbook.filepath602        process_events.currbook = Book(origname)603    elif event == 'Finish/Move':604        res = process_events.currbook.finish(window, True)605        if res:606            move_to_next_book(window, 'delete')607            update_done_txt(window, True)608    elif event == 'Finish':609        res = process_events.currbook.finish(window, False)610        if res: move_to_next_book(window, 'retain')611    elif event == 'Delete':612        res = process_events.currbook.delete(window)613        if res: move_to_next_book(window, 'delete')614    elif event == 'chklarge':615        update_filelist(window, event, values)616    elif 'delseg' in event: # one of the individual delete segment buttons617        getsegnum = int(event[-1])618        process_events.currbook.del_seg(window, getsegnum)619    elif event in ['radold', 'radnew', 'radalpha', 'radrand']: # file list sort options620        update_filelist(window, event, values)621    elif event in txtboxes: # rebuild filename with edited text622        for num, x in enumerate(process_events.currbook.seglist):623            key = 'txt'+str(num+1)624            if key in values:625                txtboxdata = values[key]626                #validate data627                txtboxdata = ''.join([x for x in txtboxdata if x in acceptletts])628                if txtboxdata != process_events.currbook.seglist[num]:629                    process_events.currbook.edit_seg(window, num, txtboxdata)630            else:631                update_statustxt(window, f'Error renaming book: invalid key.')632    # if editing a text box, don't want focus to snap back to cmd txtbox633    display_currbook(window, values, event not in txtboxes)634def display_currbook(window, values=None, resetfocus=True):635    #takes care of displaying current book's details at the top636    currbook = process_events.currbook637    if currbook:638        window['fullname'].Update(f'{currbook.filename}') # ({currbook.size})639        booksize = currbook.get_size_int()640        if booksize:641            txtcol = 'white' if booksize < 5000 else 'red'642            window['txtsize'].Update(f'{currbook.size}', text_color=txtcol)643        else:644            update_statustxt(window, 'Selected book has been moved, deleted or renamed.'\645                                     ' Refreshing file list.')646            update_filelist(window, None, values)647        update_textboxes(window, currbook.seglist)648        if resetfocus:649            window['txtcmd'].SetFocus()650    else:651        update_statustxt(window, f'No books found in current working directory ({_LOCS["SCAN_DIR"]}).')652def load_config():653    config = ConfigParser()654    try:655        config.read('psg-autoname.ini')656        _LOCS['SCAN_DIR'] = config['Locations']['scandir']657        _LOCS['OUTPUT_DIR'] = config['Locations']['outputdir']658        _LOCS['WINRAR_PATH'] = config['Locations']['winrarpath']659        return True660    except Exception as err:661        print(f'Error reading or parsing config file - {err}')662        return False663def dir_loader():664    load_dir = os.listdir(_LOCS['OUTPUT_DIR'])665def start_preloader():666    '''a major problem has been that the dupefinder function hangs for ~30 secs because667    of the slowness of scanning a dir with ~20K files on an old laptop. This function spins 668    off a thread to do that and thus force the OS to cache results on program startup, speeding 669    all future uses of the dupefinder'''670    t = threading.Thread(target=dir_loader)671    t.start()672def main():673    if not load_config():674        sys.exit(1)675    start_preloader()676    booklist = gen_booklist()677    if booklist:678        currbook = Book(_LOCS['SCAN_DIR'] + booklist[0])679        process_events.currbook = currbook680        process_events.currindex = 0681    else:682        currbook = None683        process_events.currbook = None684    process_events.done = [0, len(booklist)]685    window = layout_window(booklist)686    window['txtdone'].Update(value=f'0/{process_events.done[1]}')687    display_currbook(window)688    while True:689        event, values = window.Read()690        #print(event, values)691        if event is None or event == 'Exit':692            break693        elif event == '__TIMEOUT__':694            pass695        else:696            process_events(window, event, values)697    window.Close()698if __name__ == '__main__':...InputTesting.py
Source:InputTesting.py  
...36                tab_bar = tabs.tabBar()37                rect = tab_bar.tabRect(i)38                QTest.mouseMove(tab_bar, rect.center())39                QTest.mouseClick(tab_bar, Qt.LeftButton, pos=rect.center(), delay=100)40                Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)41                return42    def getNodeWidget(self, w, path, old_path=None):43        node = w.InputFileEditorPlugin.tree.getBlockInfo(path)44        self.assertNotEqual(node, None)45        old_path = node.fullPath()46        node_widget = w.InputFileEditorPlugin.getNodeWidgetFromNode(node, old_path)47        return node_widget48    def changeParamTypeCombo(self, w, path, new_type, old_path=None):49        node_widget = self.getNodeWidget(w, path, old_path)50        self.assertNotEqual(node_widget, None)51        type_combo = Testing.findQObjectsByName(node_widget, "type_combo")52        self.assertEqual(len(type_combo), 1)53        target = type_combo[0]54        QTest.mouseMove(target)55        QTest.mouseClick(target, Qt.LeftButton, delay=100)56        # Now the selector should pop up which is a QListView57        list_views = Testing.findQObjectsByType(target, "PyQt5.QtWidgets.QListView")58        self.assertEqual(len(list_views), 1)59        lv = list_views[0]60        model = lv.model()61        matches = model.findItems(new_type)62        self.assertEqual(len(matches), 1)63        model_idx = model.indexFromItem(matches[0])64        rect = lv.visualRect(model_idx)65        QTest.mouseMove(lv, pos=rect.center())66        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)67        QTest.mouseClick(lv.viewport(), Qt.LeftButton, pos=rect.center(), delay=100)68        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)69    def changeParamCombo(self, w, path, value_name, new_value, old_path=None):70        param_widget = self.getParamWidget(w, path, value_name, old_path)71        self.assertNotEqual(param_widget, None)72        pos = param_widget.valueTestPosition()73        widget = param_widget.valueTestWidget()74        QTest.mouseMove(widget, pos)75        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)76        QTest.mouseClick(widget, Qt.LeftButton, pos=pos)77        # Now the selector should pop up which is a QListView78        list_views = Testing.findQObjectsByType(widget, "PyQt5.QtWidgets.QListView")79        self.assertEqual(len(list_views), 1)80        lv = list_views[0]81        model = lv.model()82        matches = model.findItems(new_value)83        self.assertEqual(len(matches), 1)84        model_idx = model.indexFromItem(matches[0])85        rect = lv.visualRect(model_idx)86        QTest.mouseMove(lv, pos=rect.center())87        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)88        QTest.mouseClick(lv.viewport(), Qt.LeftButton, pos=rect.center(), delay=100)89        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)90    def changeParamValueText(self, w, path, value_name, new_text, old_path=None):91        param_widget = self.getParamWidget(w, path, value_name, old_path)92        self.assertNotEqual(param_widget, None)93        pos = param_widget.valueTestPosition()94        widget = param_widget.valueTestWidget()95        QTest.mouseMove(widget, pos)96        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)97        QTest.mouseClick(widget, Qt.LeftButton, pos=pos)98        QTest.mouseDClick(widget, Qt.LeftButton, pos=pos)99        # The default editing widget on a QTreeWidgetItem is a QLineEdit.100        # But it doesn't seem to show up until the item has focus.101        # This is pretty brittle but seems to work OK for now.102        line_edit = Testing.findQObjectsByType(widget, "PyQt5.QtWidgets.QLineEdit")103        for obj in line_edit:104            if obj.objectName() == "":105                widget = obj106                break107        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)108        QTest.keyClick(widget, Qt.Key_Backspace)109        QTest.keyClicks(widget, new_text)110        QTest.keyClick(widget, Qt.Key_Return)111        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)112    def saveNodeWidget(self, w, path, old_path=None):113        node_widget = self.getNodeWidget(w, path, old_path)114        self.assertNotEqual(node_widget, None)115        apply_button = Testing.findQObjectsByName(node_widget, "apply_button")116        self.assertEqual(len(apply_button), 1)117        self.assertEqual(apply_button[0].isEnabled(), True)118        self.clickButton(apply_button)119        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)120        self.assertEqual(apply_button[0].isEnabled(), False)121    def clickButton(self, button_objs):122        self.assertEqual(len(button_objs), 1)123        QTest.mouseMove(button_objs[0])124        QTest.mouseClick(button_objs[0], Qt.LeftButton, delay=100)125        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)126    def addToNode(self, w, path, expand=False, include=False):127        if expand:128            self.clickOnTree(w, path, expand=True)129        if include:130            self.clickOnTree(w, path, include=True)131        node_widget = self.getNodeWidget(w, path)132        add_button = Testing.findQObjectsByName(node_widget, "add_button")133        self.assertEqual(add_button[0].isEnabled(), True)134        self.clickButton(add_button)135    def getParamWidget(self, w, path, param_name, old_path=None):136        node_widget = self.getNodeWidget(w, path, old_path)137        self.assertNotEqual(node_widget, None)138        param_widget = node_widget.findParamWidget(param_name)139        self.assertNotEqual(param_widget, None)140        param_widget._table.scrollToItem(param_widget._name_item)141        return param_widget142    def clickOnTree(self, w, path, expand=False, include=False):143        tree = self.getTreeWidget(w)144        item = tree.findPathItem(path)145        self.assertNotEqual(item, None)146        tree.scrollToItem(item)147        tree.setCurrentItem(item)148        rect = tree.visualItemRect(item)149        viewport = tree.viewport()150        pos = rect.center()151        if expand or include:152            pos = rect.bottomLeft()153            pos.setY(pos.y() - rect.height()/2)154        if include:155            pos.setX(pos.x() + 10)156        QTest.mouseMove(tree, pos)157        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)158        QTest.mouseClick(viewport, Qt.LeftButton, delay=100, pos=pos)159        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)160    def selectMesh(self, w, mesh_type, dim=2, nx=10, ny=10):161        path = "/Mesh"162        self.clickOnTree(w, path, expand=True, include=True)163        self.changeParamTypeCombo(w, path, mesh_type)164        self.changeParamValueText(w, path, "nx", str(nx))165        self.changeParamValueText(w, path, "ny", str(ny))166        self.changeParamCombo(w, path, "dim", "2")167        self.saveNodeWidget(w, path)168        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)169    def addVariable(self, w, var_name, include_vars=False, expand_vars=False, include=True):170        self.addToNode(w, "/Variables", expand=expand_vars, include=include_vars)171        new_path = "/Variables/New0"172        if include:173            self.clickOnTree(w, new_path, include=True)174        self.clickOnTree(w, new_path)175        self.changeParamValueText(w, new_path, "name", var_name)176        name_path = "/Variables/%s" % var_name177        self.saveNodeWidget(w, name_path, new_path)178        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)179    def addBC(self, w, name, variable, boundary, bc_type="DirichletBC", value="0", include_bc=False, expand_bc=False, include=True):180        self.addToNode(w, "/BCs", expand=expand_bc, include=include_bc)181        new_path = "/BCs/New0"182        if include:183            self.clickOnTree(w, new_path, include=True)184        self.clickOnTree(w, new_path)185        self.changeParamTypeCombo(w, new_path, bc_type)186        self.changeParamValueText(w, new_path, "name", name)187        name_path = "/BCs/%s" % name188        self.changeParamValueText(w, name_path, "value", value, new_path)189        self.changeParamValueText(w, name_path, "boundary", boundary, new_path)190        self.saveNodeWidget(w, name_path, new_path)191        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)192    def addKernel(self, w, name, kernel_type, variable, include_kernels=False, expand_kernels=False):193        self.addToNode(w, "/Kernels", expand=expand_kernels, include=include_kernels)194        new_path = "/Kernels/New0"195        if include_kernels:196            self.clickOnTree(w, new_path, include=True)197        self.clickOnTree(w, new_path)198        self.changeParamTypeCombo(w, new_path, kernel_type)199        self.changeParamCombo(w, new_path, "variable", variable)200        self.changeParamValueText(w, new_path, "name", name)201        name_path = "/Kernels/%s" % name202        self.saveNodeWidget(w, name_path, new_path)203        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)204    def setExecutioner(self, w, exe_type, solve_type=None, petsc_iname=None, petsc_value=None, include_exe=False, expand_exe=False):205        path = "/Executioner"206        self.clickOnTree(w, path, expand=expand_exe, include=include_exe)207        self.changeParamTypeCombo(w, path, exe_type)208        if petsc_iname:209            self.changeParamValueText(w, path, "petsc_options_iname", petsc_iname)210        if petsc_value:211            self.changeParamValueText(w, path, "petsc_options_value", petsc_value)212        if solve_type:213            self.changeParamCombo(w, path, "solve_type", solve_type)214        self.saveNodeWidget(w, path)215        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)216    def changeParamValueToggle(self, w, path, value_name, old_path=None):217        param_widget = self.getParamWidget(w, path, value_name, old_path)218        self.assertNotEqual(param_widget, None)219        pos = param_widget.valueTestPosition()220        widget = param_widget.valueTestWidget()221        QTest.mouseMove(widget, pos)222        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)223        QTest.mouseClick(widget, Qt.LeftButton, pos=pos)224        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)225    def setOutput(self, w, csv=False, exodus=False):226        path = "/Outputs"227        self.clickOnTree(w, path, expand=True, include=True)228        if exodus:229            self.changeParamValueToggle(w, path, "exodus")230        if csv:231            self.changeParamValueToggle(w, path, "csv")232        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)233        self.saveNodeWidget(w, path)234        Testing.process_events(self.qapp, t=PROCESS_EVENT_TIME)235    def createSimpleDiffusion(self, w):236        self.addVariable(w, "u", include_vars=True, expand_vars=True)237        self.selectMesh(w, "GeneratedMesh")238        self.addBC(w, "left", "u", "left", include_bc=True, expand_bc=True)239        self.addBC(w, "right", "u", "right", value="1")240        self.addKernel(w, "diff", "Diffusion", "u", include_kernels=True, expand_kernels=True)241        self.setExecutioner(w, "Steady", solve_type="PJFNK", petsc_iname="-pc_type -pc_hypre_type", petsc_value="hypre boomeramg", include_exe=True, expand_exe=True)...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!!
