Best Python code snippet using lisa_python
tablecontrollers.py
Source:tablecontrollers.py  
...30        if index < len(self._items) - 1:31            self._swap(index, index + 1)32    def _swap(self, ind1, ind2):33        self._items[ind1], self._items[ind2] = self._items[ind2], self._items[ind1]34        self.mark_dirty()35    def delete(self, index):36        if isinstance(self._items, list):37            self._items.pop(index)38        else:39            self._items.data.pop(index)40        self.mark_dirty()41    @property42    def _items(self):43        raise NotImplementedError(self.__class__)44    def mark_dirty(self):45        raise NotImplementedError(self.__class__)46class _TableController(ControllerWithParent):47    def __init__(self, parent_controller, table):48        self._parent = parent_controller49        self._table = table50class VariableTableController(_TableController, _WithListOperations):51    def __init__(self, parent_controller, table):52        _TableController.__init__(self, parent_controller, table)53        self._variable_cache = {}54    def _get(self, variable):55        if variable not in self._variable_cache:56            self._variable_cache[variable] = VariableController(self, variable)57        return self._variable_cache[variable]58    def __iter__(self):59        return iter(self._get(v) for v in self._table)60    def __getitem__(self, index):61        return self._get(self._items[index])62    def index(self, ctrl):63        return [v for v in self].index(ctrl)64    @property65    def _items(self):66        return self._table.variables67    def move_up(self, index):68        ctrl = self[index]69        _WithListOperations.move_up(self, index)70        other = self[index]71        self.mark_dirty()72        RideVariableMovedUp(item=ctrl, other=other).publish()73    def move_down(self, index):74        ctrl = self[index]75        _WithListOperations.move_down(self, index)76        other = self[index]77        self.mark_dirty()78        RideVariableMovedDown(item=ctrl, other=other).publish()79    def add_variable(self, name, value, comment=None):80        self._table.add(name, value, comment)81        self.mark_dirty()82        var_controller = self[-1]83        self.notify_variable_added(var_controller)84        return var_controller85    def validate_scalar_variable_name(self, name, item=None):86        return self._validate_name(_ScalarVarValidator(), name, item)87    def validate_list_variable_name(self, name, item=None):88        return self._validate_name(_ListVarValidator(), name, item)89    def _validate_name(self, validator, name, item=None):90        return VariableNameValidation(self, validator, name, item)91    def delete(self, index):92        self.remove_var(self[index])93    def remove_var(self, var_controller):94        self._items.remove(var_controller.data)95        del self._variable_cache[var_controller.data]96        self.mark_dirty()97        self.notify_variable_removed(var_controller)98    def notify_variable_added(self, ctrl):99        self.datafile_controller.update_namespace()100        RideVariableAdded(datafile=self.datafile,101                          name=ctrl.name, item=ctrl,102                          index=ctrl.index).publish()103    def notify_variable_removed(self, ctrl):104        self.datafile_controller.update_namespace()105        RideVariableRemoved(datafile=self.datafile,106                            name=ctrl.name, item=ctrl).publish()107    def contains_variable(self, name):108        vars_as_list = []109        for var in self._items:110            vars_as_list += var.as_list()111        return any(variablematcher.value_contains_variable(string, name)112                   for string in vars_as_list)113class _ScalarVarValidator(object):114    __call__ = lambda self, name: is_scalar_var(name)115    name = 'Scalar'116    prefix = '$'117class _ListVarValidator(object):118    __call__ = lambda self, name: is_list_var(name)119    name = 'List'120    prefix = '@'121class _NameValidation(object):122    def __init__(self, table, name, named_ctrl=None):123        self._table = table124        self.error_message = ''125        self._named_ctrl = named_ctrl126        self._validate(name.strip())127    def _name_taken(self, name):128        return any(utils.eq(name, item.name, ignore=['_'])129                   for item in self._table if item != self._named_ctrl)130class VariableNameValidation(_NameValidation):131    def __init__(self, table, validator, name, named_ctrl=None):132        self._validator = validator133        _NameValidation.__init__(self, table, name, named_ctrl)134    def _validate(self, name):135        if not self._validator(name):136            self.error_message = '%s variable name must be in format %s{name}' % \137                    (self._validator.name, self._validator.prefix)138        if self._name_taken(name):139            self.error_message = 'Variable with this name already exists.'140class MacroNameValidation(_NameValidation):141    def _validate(self, name):142        if not name:143            self.error_message = '%s name cannot be empty.' % \144                    self._table.item_type145        if self._name_taken(name):146            self.error_message = '%s with this name already exists.' % \147                    self._table.item_type148        if "\n" in name:149            self.error_message = '%s name contains newlines' % \150                    self._table.item_type151class _MacroTable(_TableController):152    @property153    def _items(self):154        raise NotImplementedError(self.__class__)155    def __iter__(self):156        return iter(self._create_controller(item) for item in self._table)157    def _create_controller(self, item):158        if item not in self._item_to_controller:159            self._item_to_controller[item] = self._controller_class(self, item)160        return self._item_to_controller[item]161    @property162    def _item_to_controller(self):163        if not hasattr(self, '_item_to_controller_attribute'):164            self._item_to_controller_attribute = {}165        return self._item_to_controller_attribute166    def __len__(self):167        return len(self._items)168    def __getitem__(self, index):169        return self._create_controller(self._items[index])170    def move_up(self, item):171        items = self._items172        idx = items.index(item)173        if idx == 0:174            return False175        upper = idx - 1176        items[upper], items[idx] = items[idx], items[upper]177        self.mark_dirty()178        RideItemMovedUp(item=self._create_controller(item)).publish()179        return True180    def move_down(self, item):181        items = self._items182        idx = items.index(item)183        if idx + 1 == len(items):184            return False185        lower = idx + 1186        items[idx], items[lower] = items[lower], items[idx]187        self.mark_dirty()188        RideItemMovedDown(item=self._create_controller(item)).publish()189        return True190    def validate_name(self, name, named_ctrl=None):191        return MacroNameValidation(self, name, named_ctrl)192    def delete(self, ctrl):193        self._items.remove(ctrl.data)194        if ctrl.data in self._item_to_controller:195            del self._item_to_controller[ctrl.data]196        self.datafile_controller.update_namespace()197        self.mark_dirty()198        self._notify_removal(ctrl)199    def add(self, ctrl):200        item = ctrl.data201        item.parent = self._table202        self._items.append(item)203        new_controller = self._create_controller(item)204        self.datafile_controller.update_namespace()205        self.mark_dirty()206        self._notify_creation(new_controller.name, new_controller)207    def _create_new(self, name, config=None):208        name = name.strip()209        ctrl = self._create_controller(self._table.add(name))210        self._configure_controller(ctrl, config)211        self.datafile_controller.update_namespace()212        self.mark_dirty()213        self._notify_creation(name, ctrl)214        return ctrl215    def _configure_controller(self, ctrl, config):216        pass217class TestCaseTableController(_MacroTable):218    item_type = 'Test case'219    _controller_class = TestCaseController220    @property221    def _items(self):222        return self._table.tests223    def _notify_creation(self, name, ctrl):224        RideTestCaseAdded(datafile=self.datafile, name=name, item=ctrl).publish()225    def _notify_removal(self, item):226        RideTestCaseRemoved(datafile=self.datafile, name=item.name, item=item).publish()227    def new(self, name):228        return self._create_new(name)229class KeywordTableController(_MacroTable):230    item_type = 'User keyword'231    _controller_class = UserKeywordController232    @property233    def _items(self):234        return self._table.keywords235    def _notify_creation(self, name, ctrl):236        RideUserKeywordAdded(datafile=self.datafile, name=name, item=ctrl).publish()237    def _notify_removal(self, item):238        RideUserKeywordRemoved(datafile=self.datafile, name=item.name, item=item).publish()239    def new(self, name, argstr=''):240        return self._create_new(name, argstr)241    def _configure_controller(self, ctrl, config):242        if config:243            ctrl.arguments.set_value(config)244    def sort(self):245        """Sorts the keywords of the controller by name"""246        keywords_sorted = sorted(self._table.keywords, key=lambda userkeyword: userkeyword.name)247        index_difference = self._index_difference(self._table.keywords, keywords_sorted)248        self._table.keywords = keywords_sorted249        return index_difference250    def _index_difference(self, original_list, sorted_list):251        """Determines the difference in sorting order for undo/redo"""252        index_difference = []253        for kw in original_list:254            counter = 0255            for kw2 in sorted_list:256                if kw.name == kw2.name:257                    index_difference.append(counter)258                    break259                counter += 1260        return index_difference261    def restore_keyword_order(self, list):262        """Restores the old order of the keyword list"""263        keywords_temp = []264        for i in list:265            keywords_temp.append(self._table.keywords[i])266        self._table.keywords = keywords_temp267class ImportSettingsController(_TableController, _WithListOperations):268    def __init__(self, parent_controller, table, resource_file_controller_factory=None):269        _TableController.__init__(self, parent_controller, table)270        self._resource_file_controller_factory = resource_file_controller_factory271        self.__import_controllers = None272    def __iter__(self):273        return iter(self._import_controllers)274    def __getitem__(self, index):275        return self._import_controllers[index]276    @property277    def _import_controllers(self):278        if self.__import_controllers is None:279            self.__import_controllers = [self._import_controller(imp) for imp in self._items]280        return self.__import_controllers281    def _import_controller(self, import_):282        return ImportController(self, import_)283    @property284    def _items(self):285        return self._table.imports286    @property287    def resource_file_controller_factory(self):288        return self._resource_file_controller_factory289    @overrides(_WithListOperations)290    def _swap(self, ind1, ind2):291        imps = self._import_controllers292        imps[ind1], imps[ind2] = imps[ind2], imps[ind1]293        _WithListOperations._swap(self, ind1, ind2)294    def remove_import_data(self, imp):295        self.delete(self._items.data.index(imp))296    def delete(self, index):297        item = self[index]298        _WithListOperations.delete(self, index)299        self._import_controllers.pop(index)300        item.publish_removed()301        self.notify_imports_modified()302    def add_library(self, name, argstr, alias, comment=None):303        self._import_controllers # Call property since it has to exist before adding new304        import_ = self._table.add_library(name, utils.split_value(argstr),305                                          comment)306        import_.alias = alias307        self._parent.mark_dirty()308        self._add_controller(import_)309        self.notify_imports_modified()310        return self[-1]311    def _add_controller(self, import_):312        ctrl = self._import_controller(import_)313        ctrl.publish_added()314        self._import_controllers.append(ctrl)315    def add_resource(self, path, comment=None):316        self._import_controllers # Have to exist before adding new317        import_ = self._table.add_resource(path, comment)318        self._parent.mark_dirty()319        self.resource_import_modified(path)320        self._add_controller(import_)321        self.notify_imports_modified()322        return self[-1]323    def add_variables(self, path, argstr, comment=None):324        self._import_controllers # Have to exist before adding new325        import_ = self._table.add_variables(path, utils.split_value(argstr), comment)326        self._parent.mark_dirty()327        self._add_controller(import_)328        return self[-1]329    def notify_imports_modified(self):330        self.datafile_controller.update_namespace()331    def resource_import_modified(self, path):332        return self._parent.resource_import_modified(path)333class MetadataListController(_TableController, _WithListOperations):334    def __iter__(self):335        return iter(MetadataController(self, m) for m in self._items)336    def __getitem__(self, index):337        return MetadataController(self, self._items[index])338    @property339    def _items(self):340        return self._table.metadata341    def add_metadata(self, name, value, comment=None):342        self._table.add_metadata(name, value, comment)343        self._parent.mark_dirty()...store.py
Source:store.py  
...65                if value[key] != flt:66                    return False67            return True68        return filter(matching, self.values())69    def mark_dirty(self, pkey):70        """Mark this and all parent rows dirty."""71        self.dirty.add(pkey)72    def init_from_table(self, table):73        """74        Clear and re-read all rows from the database.75        """76        self.rows.clear()77        for row in table.all():78            pkey = getattr(row, self.PKEY)79            self.rows[pkey] = {}80            for key, value in row.__dict__.items():81                if not key.startswith('_'):82                    self.rows[pkey][key] = value83        for pkey in self.rows:84            self.mark_dirty(pkey)85    def update_with_change(self, old, new):86        """87        Update row from a database change notification.88        """89        if old is not None:90            pkey = old[self.PKEY]91            self.mark_dirty(pkey)92            if pkey in self.rows:93                self.rows.pop(pkey)94        if new is not None:95            pkey = new[self.PKEY]96            self.rows[pkey] = new97            self.mark_dirty(pkey)98    def __getitem__(self, pkey):99        return self.rows[pkey]100    def __iter__(self):101        return iter(self.rows)102    def __len__(self):103        return len(self.rows)104class Device (Table):105    PKEY = 'id'106class Program (Table):107    pass108class Segment (Table):109    def mark_dirty(self, pkey):110        super().mark_dirty(pkey)111        segment = self.get(pkey)112        if segment is not None:113            self.store.program.mark_dirty(segment['program'])114    def update_with_change(self, old, new):115        if old is not None:116            old['range'] = from_range(old['range'])117        if new is not None:118            new['range'] = from_range(new['range'])119        return super().update_with_change(old, new)120class Event (Table):121    def mark_dirty(self, pkey):122        super().mark_dirty(pkey)123        event = self.get(pkey)124        if event is not None:125            self.store.program.mark_dirty(event['program'])126    def update_with_change(self, old, new):127        if old is not None:128            old['range'] = from_range(old['range'])129        if new is not None:130            new['range'] = from_range(new['range'])131        return super().update_with_change(old, new)132class Playlist (Table):133    def mark_dirty(self, pkey):134        super().mark_dirty(pkey)135        playlist = self.get(pkey)136        if playlist is not None:137            for segment in self.store.segment.filter(playlist=pkey):138                self.store.segment.mark_dirty(segment['uuid'])139            for event in self.store.event.filter(playlist=pkey):140                self.store.event.mark_dirty(event['uuid'])141class Item (Table):142    def mark_dirty(self, pkey):143        super().mark_dirty(pkey)144        item = self.get(pkey)145        if item is not None:146            self.store.playlist.mark_dirty(item['playlist'])147class File (Table):148    def mark_dirty(self, pkey):149        super().mark_dirty(pkey)150        file = self.get(pkey)151        if file is not None:152            for item in self.store.item.filter(file=pkey):153                self.store.item.mark_dirty(item['uuid'])154class Store (Mapping):155    def __init__(self):156        self.tables = {157            'device': Device(self),158            'event': Event(self),159            'file': File(self),160            'item': Item(self),161            'playlist': Playlist(self),162            'program': Program(self),163            'segment': Segment(self),164        }165        for name, table in self.tables.items():166            setattr(self, name, table)167    def init_from_db(self, db):...basic_ops.py
Source:basic_ops.py  
...9    @staticmethod10    def forward(ctx, a, b, inplace=False):11        ctx.b_size = b.size()12        if inplace:13            ctx.mark_dirty(a)14            return a.add_(b)15        else:16            return a.add(b)17    @staticmethod18    def backward(ctx, grad_output):19        return grad_output, maybe_view(grad_output, ctx.b_size), None20class Sub(InplaceFunction):21    @staticmethod22    def forward(ctx, a, b, inplace=False):23        ctx.b_size = b.size()24        if inplace:25            ctx.mark_dirty(a)26            return a.sub_(b)27        else:28            return a.sub(b)29    @staticmethod30    def backward(ctx, grad_output):31        return grad_output, maybe_view(grad_output.neg(), ctx.b_size), None32class Mul(Function):33    @staticmethod34    def forward(ctx, a, b):35        ctx.b_size = b.size()36        ctx.save_for_backward(a, b)37        return a.mul(b)38    @staticmethod39    def backward(ctx, grad_output):40        a, b = ctx.saved_variables41        return grad_output.mul(b), maybe_view(grad_output.mul(a), ctx.b_size)42class Div(Function):43    @staticmethod44    def forward(ctx, a, b):45        ctx.b_size = b.size()46        ctx.save_for_backward(a, b)47        return a.div(b)48    @staticmethod49    def backward(ctx, grad_output):50        a, b = ctx.saved_variables51        b_rec = b.reciprocal()52        grad_a = grad_output.mul(b_rec)53        grad_b = grad_output.neg().mul(a).mul(b_rec).mul(b_rec)54        return grad_a, maybe_view(grad_b, ctx.b_size)55class Pow(Function):56    @staticmethod57    def forward(ctx, a, b):58        ctx.b_size = b.size()59        ctx.save_for_backward(a, b)60        return a.pow(b)61    @staticmethod62    def backward(ctx, grad_output):63        a, b = ctx.saved_variables64        grad_a = grad_output.mul(b).mul(a.pow(b - 1))65        grad_b = grad_output.mul(a.pow(b)).mul(a.log())66        return grad_a, maybe_view(grad_b, ctx.b_size)67def sort_args(a, b):68    return (a, b, True) if torch.is_tensor(a) else (b, a, False)69class AddConstant(InplaceFunction):70    @staticmethod71    def forward(ctx, a, b, inplace=False):72        tensor, constant, ctx.tensor_first = sort_args(a, b)73        if inplace:74            ctx.mark_dirty(tensor)75            return tensor.add_(constant)76        else:77            return tensor.add(constant)78    @staticmethod79    def backward(ctx, grad_output):80        if ctx.tensor_first:81            return grad_output, None, None82        else:83            return None, grad_output, None84class SubConstant(InplaceFunction):85    @staticmethod86    def forward(ctx, a, b, inplace=False):87        tensor, constant, ctx.tensor_first = sort_args(a, b)88        if ctx.tensor_first:89            if inplace:90                ctx.mark_dirty(tensor)91                return tensor.sub_(constant)92            else:93                return tensor.sub(constant)94        else:95            if inplace:96                ctx.mark_dirty(tensor)97                return tensor.neg_().add_(constant)98            else:99                return tensor.neg().add_(constant)100    @staticmethod101    def backward(ctx, grad_output):102        if ctx.tensor_first:103            return grad_output, None, None104        else:105            return None, grad_output.neg(), None106class MulConstant(InplaceFunction):107    @staticmethod108    def forward(ctx, a, b, inplace=False):109        tensor, ctx.constant, ctx.tensor_first = sort_args(a, b)110        if inplace:111            ctx.mark_dirty(tensor)112            return tensor.mul_(ctx.constant)113        else:114            return tensor.mul(ctx.constant)115    @staticmethod116    def backward(ctx, grad_output):117        grad_input = grad_output.mul(ctx.constant)118        if ctx.tensor_first:119            return grad_input, None, None120        else:121            return None, grad_input, None122class DivConstant(InplaceFunction):123    @staticmethod124    def forward(ctx, a, b, inplace=False):125        tensor, ctx.constant, ctx.tensor_first = sort_args(a, b)126        ctx.inplace = inplace127        if ctx.tensor_first:128            if inplace:129                ctx.mark_dirty(tensor)130                return tensor.div_(ctx.constant)131            else:132                return tensor.div(ctx.constant)133        else:134            ctx.save_for_backward(tensor)135            if inplace:136                ctx.mark_dirty(tensor)137                return tensor.reciprocal_().mul_(ctx.constant)138            else:139                return tensor.reciprocal().mul_(ctx.constant)140    @staticmethod141    def backward(ctx, grad_output):142        if ctx.tensor_first:143            return grad_output.div(ctx.constant), None, None144        else:145            v, = ctx.saved_variables146            if ctx.inplace:147                return None, grad_output.mul(v).mul(v).div_(-ctx.constant), None148            else:149                v_rep = v.reciprocal()150                return None, grad_output.mul_(-ctx.constant).mul(v_rep).mul(v_rep), None151class PowConstant(Function):152    @staticmethod153    def forward(ctx, a, b):154        tensor, ctx.constant, ctx.tensor_first = sort_args(a, b)155        if ctx.tensor_first:156            ctx.save_for_backward(tensor)157            return tensor.pow(ctx.constant)158        else:159            result = torch.pow(ctx.constant, tensor)160            ctx.save_for_backward(result)161            return result162    @staticmethod163    def backward(ctx, grad_output):164        if ctx.tensor_first:165            var, = ctx.saved_variables166            return grad_output.mul(ctx.constant).mul(var.pow(ctx.constant - 1)), None167        else:168            var_result, = ctx.saved_variables169            return None, grad_output.mul(var_result).mul_(math.log(ctx.constant))170class Negate(InplaceFunction):171    @staticmethod172    def forward(ctx, i, inplace=False):173        if inplace:174            ctx.mark_dirty(i)175            return i.neg_()176        else:177            return i.neg()178    @staticmethod179    def backward(ctx, grad_output):...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!!
