Best Python code snippet using assertpy_python
context.py
Source:context.py  
1# -*- coding: utf-8 -*-2"""3This is the specialised dictionary that is used by Sanic Plugins Framework4to manage Context objects. It can be hierarchical, and it searches its5parents if it cannot find an item in its own dictionary. It can create its6own children.7"""8class HierDict(object):9    """10This is the specialised dictionary that is used by Sanic Plugins Framework11to manage Context objects. It can be hierarchical, and it searches its12parents if it cannot find an item in its own dictionary. It can create its13own children.14    """15    __slots__ = ('_parent_hd', '_dict', '__weakref__')16    @classmethod17    def _iter_slots(cls):18        use_cls = cls19        bases = cls.__bases__20        base_count = 021        while True:22            if use_cls.__slots__:23                for _s in use_cls.__slots__:24                    yield _s25            if base_count >= len(bases):26                break27            use_cls = bases[base_count]28            base_count += 129        return30    def _inner(self):31        """32        :return: the internal dictionary33        :rtype: dict34        """35        return object.__getattribute__(self, '_dict')36    def __repr__(self):37        _dict_repr = repr(self._inner())38        return "HierDict({:s})".format(_dict_repr)39    def __str__(self):40        _dict_str = str(self._inner())41        return "HierDict({:s})".format(_dict_str)42    def __len__(self):43        return len(self._inner())44    def __setitem__(self, key, value):45        # TODO: If key is in __slots__, ignore it and return46        return self._inner().__setitem__(key, value)47    def __getitem__(self, item):48        try:49            return self._inner().__getitem__(item)50        except KeyError as e1:51            parents_searched = [self]52            parent = self._parent_hd53            while parent:54                try:55                    return parent._inner().__getitem__(item)56                except KeyError:57                    parents_searched.append(parent)58                    # noinspection PyProtectedMember59                    next_parent = parent._parent_hd60                    if next_parent in parents_searched:61                        raise RuntimeError("Recursive HierDict found!")62                    parent = next_parent63            raise e164    def __delitem__(self, key):65        self._inner().__delitem__(key)66    def __getattr__(self, item):67        if item in self._iter_slots():68            return object.__getattribute__(self, item)69        try:70            return self.__getitem__(item)71        except KeyError as e:72            raise AttributeError(*e.args)73    def __setattr__(self, key, value):74        if key in self._iter_slots():75            if key == '__weakref__':76                if value is None:77                    return78                else:79                    raise ValueError("Cannot set weakrefs on Context")80            return object.__setattr__(self, key, value)81        try:82            return self.__setitem__(key, value)83        except Exception as e:  # pragma: no cover84            # what exceptions can occur on setting an item?85            raise e86    def __contains__(self, item):87        return self._inner().__contains__(item)88    def get(self, key, default=None):89        try:90            return self.__getattr__(key)91        except (AttributeError, KeyError):92            return default93    def set(self, key, value):94        try:95            return self.__setattr__(key, value)96        except Exception as e:  # pragma: no cover97            raise e98    def items(self):99        """100        A set-like read-only view HierDict's (K,V) tuples101        :return:102        :rtype: frozenset103        """104        return self._inner().items()105    def keys(self):106        """107        An object containing a view on the HierDict's keys108        :return:109        :rtype: tuple  # using tuple to represent an immutable list110        """111        return self._inner().keys()112    def values(self):113        """114        An object containing a view on the HierDict's values115        :return:116        :rtype: tuple  # using tuple to represent an immutable list117        """118        return self._inner().values()119    def replace(self, key, value):120        """121        If this HierDict doesn't already have this key, it sets122        the value on a parent HierDict if that parent has the key,123        otherwise sets the value on this HierDict.124        :param key:125        :param value:126        :return: Nothing127        :rtype: None128        """129        if key in self._inner().keys():130            return self.__setitem__(key, value)131        parents_searched = [self]132        parent = self._parent_hd133        while parent:134            try:135                if key in parent.keys():136                    return parent.__setitem__(key, value)137            except (KeyError, AttributeError):138                pass139            parents_searched.append(parent)140            # noinspection PyProtectedMember141            next_parent = parent._parent_context142            if next_parent in parents_searched:143                raise RuntimeError("Recursive HierDict found!")144            parent = next_parent145        return self.__setitem__(key, value)146    # noinspection PyPep8Naming147    def update(self, E=None, **F):148        """149        Update HierDict from dict/iterable E and F150        :return: Nothing151        :rtype: None152        """153        if E is not None:154            if hasattr(E, 'keys'):155                for K in E:156                    self.replace(K, E[K])157            elif hasattr(E, 'items'):158                for K, V in E.items():159                    self.replace(K, V)160            else:161                for K, V in E:162                    self.replace(K, V)163        for K in F:164            self.replace(K, F[K])165    def __new__(cls, parent, *args, **kwargs):166        self = super(HierDict, cls).__new__(cls)167        self._dict = dict(*args, **kwargs)168        if parent is not None:169            assert isinstance(parent, HierDict),\170                "Parent context must be a valid initialised HierDict"171            self._parent_hd = parent172        else:173            self._parent_hd = None174        return self175    def __init__(self, *args, **kwargs):176        args = list(args)177        args.pop(0)  # remove spf178        args.pop(0)  # remove parent179        super(HierDict, self).__init__()180    def __getstate__(self):181        state_dict = {}182        for s in HierDict.__slots__:183            if s == "__weakref__":184                continue185            state_dict[s] = object.__getattribute__(self, s)186        return state_dict187    def __setstate__(self, state):188        for s, v in state.items():189            setattr(self, s, v)190    def __reduce__(self):191        state_dict = self.__getstate__()192        spf = state_dict.pop('_spf')193        parent_context = state_dict.pop('_parent_hd')194        return (HierDict.__new__, (self.__class__, spf, parent_context),195                state_dict)196class SanicContext(HierDict):197    __slots__ = ('_spf',)198    def __repr__(self):199        _dict_repr = repr(self._inner())200        return "SanicContext({:s})".format(_dict_repr)201    def __str__(self):202        _dict_str = str(self._inner())203        return "SanicContext({:s})".format(_dict_str)204    def create_child_context(self, *args, **kwargs):205        return SanicContext(self._spf, self, *args, **kwargs)206    def __new__(cls, spf, parent, *args, **kwargs):207        if parent is not None:208            assert isinstance(parent, SanicContext),\209                "Parent context must be a valid initialised SanicContext"210        self = super(SanicContext, cls).__new__(cls, parent, *args, **kwargs)211        self._spf = spf212        return self213    def __getstate__(self):214        state_dict = super(SanicContext, self).__getstate__()215        for s in SanicContext.__slots__:216            state_dict[s] = object.__getattribute__(self, s)217        return state_dict218    def __reduce__(self):219        state_dict = self.__getstate__()220        spf = state_dict.pop('_spf')221        parent_context = state_dict.pop('_parent_hd')222        return (SanicContext.__new__, (self.__class__, spf, parent_context),...print_funcs.py
Source:print_funcs.py  
2"Some functions which print data in a different way"3import numpy as np4def dicttree(dictionary):5    """Print a hierarchical dictionary"""6    print('\n'.join(_dict_repr(dictionary)))7def _dict_repr(dictionary, indent=0):8    out = []9    head = ' ' * indent10    for k, v in dictionary.items():11        if isinstance(v, dict):12            out.append(head + repr(k))13            out.extend(_dict_repr(v, indent=indent + 3))14        else:15            r = repr_1line(v, w=40)16            out.append(head + repr(k) + ': ' + r)17    return out18def printdict(dictionary, w=100, fmt='%r', sort=True, max_v_lines=6):19    """Print only one key-value pair per line"""20    print(strdict(dictionary, w=w, fmt=fmt, sort=sort, max_v_lines=max_v_lines))21def strdict(dictionary, w=100, fmt='%r', sort=True, max_v_lines=6):22    items = []23    k_len = 024    keys = sorted(dictionary) if sort else dictionary.keys()25    for k in keys:26        v = dictionary[k]27        k = str(k) if isinstance(k, tuple) else fmt % k...nwb_input_json.py
Source:nwb_input_json.py  
1import json2from pathlib import Path3class NwbInputJson:4    def __init__(self):5        dir = Path(__file__).parent.resolve()6        test_data_dir = dir / 'test_data'7        with open(test_data_dir / 'test_input.json') as f:8            dict_repr = json.load(f)9        dict_repr = dict_repr['session_data']10        dict_repr['sync_file'] = str(test_data_dir / 'sync.h5')11        dict_repr['behavior_stimulus_file'] = str(test_data_dir /12                                                  'behavior_stimulus_file.pkl')13        dict_repr['dff_file'] = str(test_data_dir / 'demix_file.h5')14        dict_repr['demix_file'] = str(test_data_dir / 'demix_file.h5')15        dict_repr['events_file'] = str(test_data_dir / 'events.h5')16        self._dict_repr = dict_repr17    @property18    def dict_repr(self):...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!!
