Best Python code snippet using stestr_python
config.py
Source:config.py  
...144        else:145            setter(value)146        self.set_options.append(option_name)147    @classmethod148    def _parse_list(cls, value, separator=','):149        """Represents value as a list.150        Value is split either by separator (defaults to comma) or by lines.151        :param value:152        :param separator: List items separator character.153        :rtype: list154        """155        if isinstance(value, list):  # _get_parser_compound case156            return value157        if '\n' in value:158            value = value.splitlines()159        else:160            value = value.split(separator)161        return [chunk.strip() for chunk in value if chunk.strip()]162    @classmethod163    def _parse_dict(cls, value):164        """Represents value as a dict.165        :param value:166        :rtype: dict167        """168        separator = '='169        result = {}170        for line in cls._parse_list(value):171            key, sep, val = line.partition(separator)172            if sep != separator:173                raise DistutilsOptionError(174                    'Unable to parse option value to dict: %s' % value)175            result[key.strip()] = val.strip()176        return result177    @classmethod178    def _parse_bool(cls, value):179        """Represents value as boolean.180        :param value:181        :rtype: bool182        """183        value = value.lower()184        return value in ('1', 'true', 'yes')185    @classmethod186    def _exclude_files_parser(cls, key):187        """Returns a parser function to make sure field inputs188        are not files.189        Parses a value after getting the key so error messages are190        more informative.191        :param key:192        :rtype: callable193        """194        def parser(value):195            exclude_directive = 'file:'196            if value.startswith(exclude_directive):197                raise ValueError(198                    'Only strings are accepted for the {0} field, '199                    'files are not accepted'.format(key))200            return value201        return parser202    @classmethod203    def _parse_file(cls, value):204        """Represents value as a string, allowing including text205        from nearest files using `file:` directive.206        Directive is sandboxed and won't reach anything outside207        directory with setup.py.208        Examples:209            file: README.rst, CHANGELOG.md, src/file.txt210        :param str value:211        :rtype: str212        """213        include_directive = 'file:'214        if not isinstance(value, string_types):215            return value216        if not value.startswith(include_directive):217            return value218        spec = value[len(include_directive):]219        filepaths = (os.path.abspath(path.strip()) for path in spec.split(','))220        return '\n'.join(221            cls._read_file(path)222            for path in filepaths223            if (cls._assert_local(path) or True)224            and os.path.isfile(path)225        )226    @staticmethod227    def _assert_local(filepath):228        if not filepath.startswith(os.getcwd()):229            raise DistutilsOptionError(230                '`file:` directive can not access %s' % filepath)231    @staticmethod232    def _read_file(filepath):233        with io.open(filepath, encoding='utf-8') as f:234            return f.read()235    @classmethod236    def _parse_attr(cls, value, package_dir=None):237        """Represents value as a module attribute.238        Examples:239            attr: package.attr240            attr: package.module.attr241        :param str value:242        :rtype: str243        """244        attr_directive = 'attr:'245        if not value.startswith(attr_directive):246            return value247        attrs_path = value.replace(attr_directive, '').strip().split('.')248        attr_name = attrs_path.pop()249        module_name = '.'.join(attrs_path)250        module_name = module_name or '__init__'251        parent_path = os.getcwd()252        if package_dir:253            if attrs_path[0] in package_dir:254                # A custom path was specified for the module we want to import255                custom_path = package_dir[attrs_path[0]]256                parts = custom_path.rsplit('/', 1)257                if len(parts) > 1:258                    parent_path = os.path.join(os.getcwd(), parts[0])259                    module_name = parts[1]260                else:261                    module_name = custom_path262            elif '' in package_dir:263                # A custom parent directory was specified for all root modules264                parent_path = os.path.join(os.getcwd(), package_dir[''])265        sys.path.insert(0, parent_path)266        try:267            module = import_module(module_name)268            value = getattr(module, attr_name)269        finally:270            sys.path = sys.path[1:]271        return value272    @classmethod273    def _get_parser_compound(cls, *parse_methods):274        """Returns parser function to represents value as a list.275        Parses a value applying given methods one after another.276        :param parse_methods:277        :rtype: callable278        """279        def parse(value):280            parsed = value281            for method in parse_methods:282                parsed = method(parsed)283            return parsed284        return parse285    @classmethod286    def _parse_section_to_dict(cls, section_options, values_parser=None):287        """Parses section options into a dictionary.288        Optionally applies a given parser to values.289        :param dict section_options:290        :param callable values_parser:291        :rtype: dict292        """293        value = {}294        values_parser = values_parser or (lambda val: val)295        for key, (_, val) in section_options.items():296            value[key] = values_parser(val)297        return value298    def parse_section(self, section_options):299        """Parses configuration file section.300        :param dict section_options:301        """302        for (name, (_, value)) in section_options.items():303            try:304                self[name] = value305            except KeyError:306                pass  # Keep silent for a new option may appear anytime.307    def parse(self):308        """Parses configuration file items from one309        or more related sections.310        """311        for section_name, section_options in self.sections.items():312            method_postfix = ''313            if section_name:  # [section.option] variant314                method_postfix = '_%s' % section_name315            section_parser_method = getattr(316                self,317                # Dots in section names are translated into dunderscores.318                ('parse_section%s' % method_postfix).replace('.', '__'),319                None)320            if section_parser_method is None:321                raise DistutilsOptionError(322                    'Unsupported distribution option section: [%s.%s]' % (323                        self.section_prefix, section_name))324            section_parser_method(section_options)325    def _deprecated_config_handler(self, func, msg, warning_class):326        """ this function will wrap around parameters that are deprecated327        :param msg: deprecation message328        :param warning_class: class of warning exception to be raised329        :param func: function to be wrapped around330        """331        @wraps(func)332        def config_handler(*args, **kwargs):333            warnings.warn(msg, warning_class)334            return func(*args, **kwargs)335        return config_handler336class ConfigMetadataHandler(ConfigHandler):337    section_prefix = 'metadata'338    aliases = {339        'home_page': 'url',340        'summary': 'description',341        'classifier': 'classifiers',342        'platform': 'platforms',343    }344    strict_mode = False345    """We need to keep it loose, to be partially compatible with346    `pbr` and `d2to1` packages which also uses `metadata` section.347    """348    def __init__(self, target_obj, options, ignore_option_errors=False,349                 package_dir=None):350        super(ConfigMetadataHandler, self).__init__(target_obj, options,351                                                    ignore_option_errors)352        self.package_dir = package_dir353    @property354    def parsers(self):355        """Metadata item name to parser function mapping."""356        parse_list = self._parse_list357        parse_file = self._parse_file358        parse_dict = self._parse_dict359        exclude_files_parser = self._exclude_files_parser360        return {361            'platforms': parse_list,362            'keywords': parse_list,363            'provides': parse_list,364            'requires': self._deprecated_config_handler(365                parse_list,366                "The requires parameter is deprecated, please use "367                "install_requires for runtime dependencies.",368                DeprecationWarning),369            'obsoletes': parse_list,370            'classifiers': self._get_parser_compound(parse_file, parse_list),371            'license': exclude_files_parser('license'),372            'license_files': parse_list,373            'description': parse_file,374            'long_description': parse_file,375            'version': self._parse_version,376            'project_urls': parse_dict,377        }378    def _parse_version(self, value):379        """Parses `version` option value.380        :param value:381        :rtype: str382        """383        version = self._parse_file(value)384        if version != value:385            version = version.strip()386            # Be strict about versions loaded from file because it's easy to387            # accidentally include newlines and other unintended content388            if isinstance(parse(version), LegacyVersion):389                tmpl = (390                    'Version loaded from {value} does not '391                    'comply with PEP 440: {version}'392                )393                raise DistutilsOptionError(tmpl.format(**locals()))394            return version395        version = self._parse_attr(value, self.package_dir)396        if callable(version):397            version = version()398        if not isinstance(version, string_types):399            if hasattr(version, '__iter__'):400                version = '.'.join(map(str, version))401            else:402                version = '%s' % version403        return version404class ConfigOptionsHandler(ConfigHandler):405    section_prefix = 'options'406    @property407    def parsers(self):408        """Metadata item name to parser function mapping."""409        parse_list = self._parse_list410        parse_list_semicolon = partial(self._parse_list, separator=';')411        parse_bool = self._parse_bool412        parse_dict = self._parse_dict413        return {414            'zip_safe': parse_bool,415            'use_2to3': parse_bool,416            'include_package_data': parse_bool,417            'package_dir': parse_dict,418            'use_2to3_fixers': parse_list,419            'use_2to3_exclude_fixers': parse_list,420            'convert_2to3_doctests': parse_list,421            'scripts': parse_list,422            'eager_resources': parse_list,423            'dependency_links': parse_list,424            'namespace_packages': parse_list,425            'install_requires': parse_list_semicolon,426            'setup_requires': parse_list_semicolon,427            'tests_require': parse_list_semicolon,428            'packages': self._parse_packages,429            'entry_points': self._parse_file,430            'py_modules': parse_list,431            'python_requires': SpecifierSet,432        }433    def _parse_packages(self, value):434        """Parses `packages` option value.435        :param value:436        :rtype: list437        """438        find_directives = ['find:', 'find_namespace:']439        trimmed_value = value.strip()440        if trimmed_value not in find_directives:441            return self._parse_list(value)442        findns = trimmed_value == find_directives[1]443        if findns and not PY3:444            raise DistutilsOptionError(445                'find_namespace: directive is unsupported on Python < 3.3')446        # Read function arguments from a dedicated section.447        find_kwargs = self.parse_section_packages__find(448            self.sections.get('packages.find', {}))449        if findns:450            from setuptools import find_namespace_packages as find_packages451        else:452            from setuptools import find_packages453        return find_packages(**find_kwargs)454    def parse_section_packages__find(self, section_options):455        """Parses `packages.find` configuration file section....findlib.py
Source:findlib.py  
1# Copyright (C) 2015  Allen Li2#3# This file is part of Dantalian.4#5# Dantalian is free software: you can redistribute it and/or modify6# it under the terms of the GNU General Public License as published by7# the Free Software Foundation, either version 3 of the License, or8# (at your option) any later version.9#10# Dantalian is distributed in the hope that it will be useful,11# but WITHOUT ANY WARRANTY; without even the implied warranty of12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the13# GNU General Public License for more details.14#15# You should have received a copy of the GNU General Public License16# along with Dantalian.  If not, see <http://www.gnu.org/licenses/>.17"""This module implements searching and queries."""18# pylint: disable=too-few-public-methods19import abc20from collections import deque21import functools22import logging23import os24import shlex25from dantalian import pathlib26from dantalian import tagnames27_LOGGER = logging.getLogger(__name__)28def search(search_node):29    """Return paths by tag query.30    Args:31        search_node: Root Node of search query tree32    Returns:33        List of paths.34    """35    return list(search_node.get_results().values())36class SearchNode(metaclass=abc.ABCMeta):37    """Abstract interface for search query nodes.38    Methods:39        get_results(): Get results of node query.40    """41    # pylint: disable=no-init42    @abc.abstractmethod43    def get_results(self):44        """Return a dictionary mapping inode objects to paths."""45class GroupNode(SearchNode, metaclass=abc.ABCMeta):46    """Abstract class for nodes that have a list of child nodes."""47    # pylint: disable=abstract-method48    def __init__(self, children):49        self.children = children50    def __eq__(self, other):51        return (self.__class__ is other.__class__ and52                len(self.children) == len(other.children) and53                all(ours == theirs54                    for (ours, theirs) in zip(self.children, other.children)))55class AndNode(GroupNode):56    """57    AndNode merges the results of its children nodes by set intersection.58    """59    def get_results(self):60        results = self.children[0].get_results()61        inodes = (set(node.get_results()) for node in self.children)62        inodes = functools.reduce(set.intersection, inodes)63        return dict((inode, results[inode]) for inode in inodes)64class OrNode(GroupNode):65    """66    OrNode merges the results of its children nodes by set union.67    """68    def get_results(self):69        results = {}70        for node in self.children:71            pathmap = node.get_results()72            for inode in pathmap:73                if inode not in results:74                    results[inode] = pathmap[inode]75        return results76class MinusNode(GroupNode):77    """78    MinusNode returns the results of its first child minus the results of the79    rest of its children.80    """81    def get_results(self):82        results = self.children[0].get_results()83        for node in self.children[1:]:84            pathmap = node.get_results()85            for inode in pathmap:86                if inode in results:87                    del results[inode]88        return results89class DirNode(SearchNode):90    """91    DirNode returns the inodes and paths of the contents of its directory.92    """93    def __init__(self, dirpath):94        self.dirpath = dirpath95    def __eq__(self, other):96        return (self.__class__ is other.__class__ and97                self.dirpath == other.dirpath)98    @staticmethod99    def _get_inode(filepath):100        """Return inode and path pair."""101        return (os.stat(filepath), filepath)102    def get_results(self):103        return dict(self._get_inode(filepath)104                    for filepath in pathlib.listdirpaths(self.dirpath))105def parse_query(rootpath, query):106    r"""Parse query string into query node tree.107    See documentation for details.108    Args:109        rootpath: Rootpath for tag conversions.110        query: Search query string.111    """112    tokens = deque(shlex.split(query))113    parse_stack = []114    parse_list = []115    while tokens:116        token = tokens.popleft()117        _LOGGER.debug("Parsing token %s", token)118        if token[0] == '\\':119            token = token[1:]120            parse_list.append(DirNode(token))121        elif token == 'AND':122            parse_stack.append(parse_list)123            parse_stack.append(AndNode)124            parse_list = []125        elif token == 'OR':126            parse_stack.append(parse_list)127            parse_stack.append(OrNode)128            parse_list = []129        elif token == 'MINUS':130            parse_stack.append(parse_list)131            parse_stack.append(MinusNode)132            parse_list = []133        elif token == 'END':134            node_type = parse_stack.pop()135            node = node_type(parse_list)136            parse_list = parse_stack.pop()137            parse_list.append(node)138        else:139            token = tagnames.path(rootpath, token)140            parse_list.append(DirNode(token))141    if len(parse_list) != 1:142        raise ParseError(parse_stack, parse_list,143                         "Not exactly one node at top of parse")144    return parse_list[0]145class ParseError(Exception):146    """Error parsing query."""147    def __init__(self, parse_stack, parse_list, msg=''):148        super().__init__()149        self.parse_stack = parse_stack150        self.parse_list = parse_list151        self.msg = msg152    def __str__(self):153        return "{}\nstack={}\nlist={}".format(154            self.msg, self.parse_stack, self.parse_list)155    def __repr__(self):156        return "ParseError({!r}, {!r}, {!r})".format(...ads131m04.py
Source:ads131m04.py  
1"""2ADS131MO4 Python Raspberry Pi Driver3By: Benjamin de Vos4Digital Shovel5"""6import math.binary7import numpy as math8# ----------------------------------------------------------------------------------------------------------------------9# Registers10ID = 0x0011STATUS = 0x0112MODE = 0x0213CLOCK = 0x0314GAIN = 0x0415CFG = 0x0616THRSHLD_MSB = 0x0717THRSHLD_LSB = 0x0818REGMAP_CRC = 0x3e19RESERVED = 0x3f20# Ch021CH0_CFG = 0x0922CH0_OCAL_MSB = 0x0a23CH0_OCAL_LSB = 0x0b24CH0_GCAL_MSB = 0x0c25CH0_GCAL_LSB = 0x0d26# Ch127CH1_CFG = 0x0e28CH1_OCAL_MSB = 0x0f29CH1_OCAL_LSB = 0x1030CH1_GCAL_MSB = 0x1131CH1_GCAL_LSB = 0x1232# Ch233CH2_CFG = 0x1334CH2_OCAL_MSB = 0x1435CH2_OCAL_LSB = 0x1536CH2_GCAL_MSB = 0x1637CH2_GCAL_LSB = 0x1738# Ch339CH3_CFG = 0x1840CH3_OCAL_MSB = 0x1941CH3_OCAL_LSB = 0x1a42CH3_GCAL_MSB = 0x1b43CH3_GCAL_LSB = 0x1c44# ------------------------------------------------------------------------------------------------------------45# Commands46BYTE_PAD = [0x0]47NULL = [0x0, 0x0, 0x0, 0x0]48RESET = [0x0, 0x0, 0x1, 0x1]49STANDBY = [0x0, 0x0, 0x2, 0x2]50WAKEUP = [0x0, 0x0, 0x3, 0x3]51LOCK = [0x0, 0x5, 0x5, 0x5]52UNLOCK = [0x0, 0x6, 0x5, 0x5]53DATA_PAD_READ = [0x0, 96]54DATA_PAD_WRITE = [0x0, 72]55DATA_PAD_WRITE2 = [0x0, 48]56NULL_FRAME = [0x0, 120]57def getChunks(frame_width, word_size):58    loop_length = frame_width / word_size59    out_list =  [None] * loop_length60    count = 061    for i in range(0, loop_length):62class ADS131M0x:63    def __init__(self, spi, frame_size, samples, channels):64        self.spi = spi65        self.frame_size_diff = frame_size - 1666        self.samples = samples67        self.channels = channels68    def readSingleReg(self, REG_BYTE):69        parse_list = [[0x5, 3], [REG_BYTE, 6], [0x0, 7], [0x0, self.frame_size_diff], DATA_PAD]70        out_list = GenerateSPIFrame(parse_list, 2)71        sendSPI(out_list)72        return sendSPI(NULL)73    def readMultipleReg(self, REG_BYTE, NUM_BYTE):74        parse_list = [[0x5, 3], [REG_BYTE, 6], [NUM_BYTE, 5], [0x0, self.frame_size_diff], DATA_PAD]75        out_list = GenerateSPIFrame(parse_list, 2)76        sendSPI(out_list)77        return sendSPI(NULL)78    def writeSingle(self, REG_BYTE, WRITE_FRAME):79        parse_list = [[0x3, 3], [REG_BYTE, 6], [0x0, 7], [0x0, self.frame_size_diff], [WRITE_FRAME, 16], [0x0, self.frame_size], DATA_PAD]80        out_list = GenerateSPIFrame(parse_list, 2)81        return sendSPI(out_list)82    def configureChannel(self, mux, filter, phase_delay, channel):83        REG_BYTE = 0x084        if channel == 0:85            REG_BYTE = CH0_CFG86        elif channel == 1:87            REG_BYTE = CH1_CFG88        elif channel == 2:89            REG_BYTE = CH2_CFG90        elif channel == 3:91            REG_BYTE = CH3_CFG92        parse_list = [[0x3, 3], [REG_BYTE, 6], [0x0, 7], [0x0, self.frame_size_diff], [phase_delay, 10], [0x0, 3], [filter, 1], [mux, 2], [0x0, self.frame_size_diff]]93        out_list = GenerateSPIFrame(parse_list, 2)94        return sendSPI(out_list)95    def configureGainCalibration(self, channel, gcal_val1, gcal_val2):96        REG_BYTE = 0x097        REG_BYTE2 = 0x098        if channel == 0:99            REG_BYTE = CH0_GCAL_MSB100            #REG2_BYTE = CH0_GCAL_LSB101        elif channel == 1:102            REG_BYTE = CH1_GCAL_MSB103            #REG2_BYTE = CH1_GCAL_LSB104        elif channel == 2:105            REG_BYTE = CH2_GCAL_MSB106            #REG2_BYTE = CH2_GCAL_LSB107        elif channel == 3:108            REG_BYTE = CH3_GCAL_MSB109            #REG2_BYTE = CH3_GCAL_LSB110        parse_list = [[0x3, 3], [REG_BYTE, 6], [0x0, 7], [0x0, self.frame_size_diff], [gcal_val1, 16], [0x0, self.frame_size_diff], [gcal_val2, 16], [0x0, self.frame_size_diff], DATA_PAD_WRITE2]111        out_list = GenerateSPIFrame(parse_list, 2)112        sendSPI(out_list)113        return sendSPI(NULL)114    def configureClockReg(self, ch0, ch1, ch2, ch3, osr, pm):115        parse_list = [[0x3, 3], [0x3, 6], [0x0, 7], [0x0, self.frame_size_diff], [0x0, 4], [ch0, 1], [ch1, 1], [ch2, 1], [ch3, 1], [0x0, 2], [0x0, 1], [osr, 3], [pm, 2], [0x0, self.frame_size_diff], DATA_PAD_WRITE]116        sendSPI(GenerateSPIFrame(parse_list))117        return sendSPI(GenerateSPIFrame(NULL_FRAME))118    def readStatusReg(self):119        parse_list = [[0x5, 3], [0x1, 6], [0x0, 7], [0x0, self.frame_size_diff], DATA_PAD]120        sendSPI(GenerateSPIFrame(parse_list))121        return sendSPI(GenerateSPIFrame(NULL_FRAME))122    def configureModeReg(self, reg_crc, crc_en, crc_t, wlength, timeout, drdy_sel, reset):123        parse_list = [[0x3, 3], [0x2, 6], [0x0, 7], [0x0, self.frame_size_diff], [0x0, 2], [reg_crc, 1], [crc_en, 1], [crc_t, 1], [reset, 1], [wlength, 2], [0x0, 3], [timeout, 1], [drdy_sel, 2], [0x0, 1], [0x0, 1], [0x0, self.frame_size_diff], DATA_PAD_WRITE]124        sendSPI(GenerateSPIFrame(parse_list))125        return sendSPI(GenerateSPIFrame(NULL_FRAME))126    def configureGain1Reg(self, gain0, gain1, gain2, gain3):127        parse_list = [[0x3, 3], [0x4, 6], [0x0, 7], [0x0, self.frame_size_diff], [0x0, 1], [gain3, 3], [0x0, 1], [gain2, 3], [0x0, 1], [gain1, 3], [0x0, 1], [gain0, 3], DATA_PAD_WRITE]128        sendSPI(GenerateSPIFrame(parse_list))...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!!
