Best Python code snippet using stestr_python
chain.py
Source:chain.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3#4# OpenBCI - framework for Brain-Computer Interfaces based on EEG signal5# Project was initiated by Magdalena Michalska and Krzysztof Kulewski6# as part of their MSc theses at the University of Warsaw.7# Copyright (C) 2008-2009 Krzysztof Kulewski and Magdalena Michalska8#9# This program is free software: you can redistribute it and/or modify10# it under the terms of the GNU General Public License as published by11# the Free Software Foundation, either version 3 of the License, or12# (at your option) any later version.13#14# This program is distributed in the hope that it will be useful,15# but WITHOUT ANY WARRANTY; without even the implied warranty of16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the17# GNU General Public License for more details.18#19# You should have received a copy of the GNU General Public License20# along with this program. If not, see <http://www.gnu.org/licenses/>.21#22# Author:23# Mateusz KruszyÅski <mateusz.kruszynski@gmail.com>24import traceback25import classification_logging as logger26LOGGER = logger.get_logger("chain", "debug")27class ChainElement(object):28 """Represents an element for Chain object."""29 def __init__(self, class_template, params_sets):30 """Init object, parameters:31 - class_template - a class responding to .process(data) method32 - params_sets - a dictionary with keys contaning every33 class_template`s __init__ parameters and values representing34 alternative values for corresponding parameter, eg:35 for class:36 class A(object):37 def __init__(x,y):38 ...39 where x is a number and y is a string, we would have:40 ChainElement(A, {'x':[1,2,3], 'y':['a', 'b']})41 For that ChainElement Chain object will create 6 A objects42 with every permutation of init parameters:43 A(1,'a'), A(1,'b'), A(2,'a'), A(2,'b'), A(3,'a'), A(3,'b')44 """45 self.class_template = class_template46 try:47 keys = params_sets.keys()48 except AttributeError:49 self.params = params_sets50 else:51 self.params = []52 self._init_params(params_sets, {}, keys)53 def _init_params(self, params_sets, init_set, keys):54 """Initialize self.params list.55 After that operation self.params should look like:56 [{'x':1, 'y':'a'}, {'x':1, 'y':'b'},..., {'x':3, 'y':'b'}]57 """58 if len(keys) == 0:59 self.params.append(init_set)60 return 61 for i_value in params_sets[keys[0]]:62 d = init_set.copy()63 d[keys[0]] = i_value64 self._init_params(params_sets, d, keys[1:])65 66class Chain(object):67 def __init__(self, *chain_elements):68 self.elements = chain_elements69 self.candidates = None70 self.results = None71 self.errors = []72 self.gather_errors = True73 def process(self, data_set=None, 74 select_winner=True, gather_errors=True):75 self.gather_errors = gather_errors76 self.candidates, self.results = self._process(data_set, 0)77 if select_winner:78 return self._select_winner(self.candidates, self.results)79 else:80 return None, None81 def _select_winner(self, candidates, results):82 best_result = max(results)83 ind = results.index(best_result)84 return candidates[ind], best_result85 def _process(self, data_set, element_index):86 try:87 current_element = self.elements[element_index]88 except IndexError:89 # data_set is a result of process method90 # of the last element in the chain91 return [[]], [data_set]92 ret_candidates = []93 ret_results = []94 for i_params_set in current_element.params:95 obj = current_element.class_template(**i_params_set)96 LOGGER.debug("Start processing with: "+str(obj.__class__)+"("+str(i_params_set)+")")97 if self.gather_errors:98 try:99 new_data_set = obj.process(data_set)100 except Exception, e:101 self.errors.append(traceback.format_exc())102 else:103 candidates, results = self._process(new_data_set, element_index + 1)104 for i_cand in candidates:105 # prepend to every list of candidate a current object106 i_cand.insert(0, obj)107 ret_candidates += candidates108 ret_results += results109 else: #dont gather errors110 new_data_set = obj.process(data_set)111 candidates, results = self._process(new_data_set, element_index + 1)112 for i_cand in candidates:113 # prepend to every list of candidate a current object114 i_cand.insert(0, obj)115 ret_candidates += candidates116 ret_results += results117 118 return ret_candidates, ret_results119 def print_errors(self):120 print("****************************************************")121 print("*************** Start printing errors **************")122 for er in self.errors:123 print("*********** NEXT ERROR *****************")124 for l in er.splitlines():125 print(l)126 print("*************** End printing errors ****************")127 print("****************************************************")128 def print_candidate(self, candidate):129 print("****************************************************")130 print("*************** Start printing candidate ***********")131 for cnd in candidate:132 c = eval(str(cnd))133 print("****** next candidate **********")134 print("CLASS: "+c['CLASS'])135 for k, v in c.iteritems():136 print(k, ": ", v)137 print("*************** End printing candidate**************")138 print("****************************************************")139 140 ...
package_loader.py
Source:package_loader.py
1# Copyright (c) 2017-2018 The University of Manchester2#3# This program is free software: you can redistribute it and/or modify4# it under the terms of the GNU General Public License as published by5# the Free Software Foundation, either version 3 of the License, or6# (at your option) any later version.7#8# This program is distributed in the hope that it will be useful,9# but WITHOUT ANY WARRANTY; without even the implied warranty of10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11# GNU General Public License for more details.12#13# You should have received a copy of the GNU General Public License14# along with this program. If not, see <http://www.gnu.org/licenses/>.15import os16import sys17import traceback18def all_modules(directory, prefix, remove_pyc_files=False):19 """ List all the python files found in this directory giving then the\20 prefix.21 Any file that ends in either ``.py`` or ``.pyc`` is assume a python module22 and added to the result set.23 :param str directory: path to check for python files24 :param str prefix: package prefix top add to the file name25 :return: set of python package names26 :rtype: set(str)27 """28 results = set()29 for module in os.listdir(directory):30 if module == "__init__.py":31 results.add(prefix)32 elif module == "__init__.pyc":33 results.add(prefix)34 if remove_pyc_files: # pragma: no cover35 full_path = os.path.join(directory, module)36 print("Deleting: " + full_path)37 os.remove(full_path)38 elif module[-3:] == ".py":39 results.add(prefix + "." + module[:-3])40 elif module[-4:] == ".pyc":41 results.add(prefix + "." + module[:-4])42 if remove_pyc_files: # pragma: no cover43 full_path = os.path.join(directory, module)44 print("Deleting: " + full_path)45 os.remove(full_path)46 elif module != "__pycache__":47 full_path = os.path.join(directory, module)48 if os.path.isdir(full_path):49 results.update(all_modules(50 full_path, prefix + "." + module, remove_pyc_files))51 return results52def load_modules(53 directory, prefix, remove_pyc_files=False, exclusions=None,54 gather_errors=True):55 """ Loads all the python files found in this directory, giving them the\56 specified prefix57 Any file that ends in either ``.py`` or ``.pyc`` is assume a python module58 and added to the result set.59 :param str directory: path to check for python files60 :param str prefix: package prefix top add to the file name61 :param bool remove_pyc_files: True if ``.pyc`` files should be deleted62 :param list(str) exclusions: a list of modules to exclude63 :param bool gather_errors:64 True if errors should be gathered, False to report on first error65 :return: None66 """67 if exclusions is None:68 exclusions = []69 modules = all_modules(directory, prefix, remove_pyc_files)70 errors = list()71 for module in modules:72 if module in exclusions:73 print("SKIPPING " + module)74 continue75 print(module)76 try:77 __import__(module)78 except Exception: # pylint: disable=broad-except79 if gather_errors:80 errors.append((module, sys.exc_info()))81 else:82 raise83 for module, (exc_type, exc_value, exc_traceback) in errors:84 print("Error importing {}:".format(module))85 for line in traceback.format_exception(86 exc_type, exc_value, exc_traceback):87 for line_line in line.split("\n"):88 if line_line:89 print(" ", line_line.rstrip())90 if errors:91 raise Exception("Error when importing, starting at {}".format(prefix))92def load_module(93 name, remove_pyc_files=False, exclusions=None, gather_errors=True):94 """ Loads this modules and all its children.95 :param str name: name of the modules96 :param bool remove_pyc_files: True if ``.pyc`` files should be deleted97 :param list(str) exclusions: a list of modules to exclude98 :param bool gather_errors:99 True if errors should be gathered, False to report on first error100 :return: None101 """102 if exclusions is None:103 exclusions = []104 module = __import__(name)105 path = module.__file__106 directory = os.path.dirname(path)107 load_modules(directory, name, remove_pyc_files, exclusions, gather_errors)108if __name__ == '__main__': # pragma: no cover...
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!!