Best Python code snippet using tappy_python
graphgenerator.py
Source:graphgenerator.py  
1# Copyright 2021 Wechat Group, Tencent2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14import logging15import numpy as np16import ir.framework17from backend.cppcode.namemanager import NameManager18from backend.cppcode.common import get_symbol_cpp_dtype, symbol_to_cpp_type19from backend.cppcode.nodegenerator import get_all_node_generators20class GraphGenerator(object):21    def __init__(self, graph: ir.framework.Graph, cls_name: str, model_generator):22        self._graph = graph23        self._cls_name = model_generator.name_manager.get_symbol_name(graph, cls_name)24        self._scope_name = self._cls_name25        self._model_generator = model_generator26    @property27    def graph(self):28        return self._graph29    @property30    def cls_name(self):31        return self._cls_name32    @property33    def model_generator(self):34        return self._model_generator35    @property36    def name_manager(self):37        return self.model_generator.name_manager38    @property39    def input_symbol_names(self):40        names = []41        for name in self.graph.inputs:42            symbol = self.graph.get_symbol(name)43            symbol_name = self.name_manager.get_symbol_name(symbol, symbol.name)44            names.append(symbol_name)45        return names46    @property47    def declaration(self):48        symbol_declarations = ""49        for symbol in sorted(self.graph.symbols.values(), key=lambda a: a.name):50            if symbol.name not in self.graph.keep_symbol_names:51                continue52            assert symbol.is_constant() and symbol.stype == symbol.origin_stype53            symbol_name = self.name_manager.get_symbol_name(symbol)54            symbol_declarations += "    {symbol} {name};\n".format(55                symbol=symbol_to_cpp_type(symbol, False), name=symbol_name56            )57        for name in self.graph.inputs:58            symbol = self.graph.get_symbol(name)59            symbol_name = self.name_manager.get_symbol_name(symbol, symbol.name)60            symbol_declarations += "    {symbol} {name};\n".format(61                symbol=symbol_to_cpp_type(symbol, False), name=symbol_name62            )63        function_declarations = "    {cls_name}();\n".format(cls_name=self._cls_name)64        for name in self.graph.inputs:65            symbol = self.graph.get_symbol(name)66            symbol_name = self.name_manager.get_symbol_name(symbol, symbol.name)67            function_declarations += "    /**\n"68            function_declarations += (69                "     * @param v_{name} {origin_name} {shape}\n".format(70                    name=symbol_name, origin_name=symbol.name, shape=symbol.shape71                )72            )73            function_declarations += "     */\n"74            function_declarations += (75                "    void set_{name}(const {symbol}& v_{name});\n".format(76                    name=symbol_name, symbol=symbol_to_cpp_type(symbol, True)77                )78            )79        return_types = []80        for name in self.graph.outputs:81            symbol = self.graph.get_symbol(name)82            return_types.append(symbol_to_cpp_type(symbol, False, True))83        processFunctionDeclaration = ""84        processFunctionDeclaration += "    /**\n"85        processFunctionDeclaration += "     * @return\n"86        for i, name in enumerate(self.graph.outputs):87            symbol = self.graph.get_symbol(name)88            processFunctionDeclaration += "     * output:{i} {name} {shape}\n".format(89                i=i, name=symbol.name, shape=symbol.shape90            )91        processFunctionDeclaration += "     */\n"92        processFunctionDeclaration += "    std::tuple<{types}> process();\n".format(93            types=", ".join(return_types)94        )95        format_str = """96class {cls_name}97{{98{symbols}99public:100{functions}101{process}102}};103"""104        return format_str.format(105            cls_name=self._cls_name,106            symbols=symbol_declarations,107            functions=function_declarations,108            process=processFunctionDeclaration,109        )110    @property111    def define(self):112        construct_function = "{cls_name}::{cls_name}()\n".format(113            cls_name=self._cls_name114        )115        construct_function += "{\n"116        construct_function += (117            '    auto scopeG = tfcc::Scope::scope("{scope}");\n'.format(118                scope=self._scope_name119            )120        )121        for symbol in sorted(self.graph.symbols.values(), key=lambda a: a.name):122            if symbol.name not in self.graph.keep_symbol_names:123                continue124            assert symbol.is_constant() and symbol.stype == symbol.origin_stype125            symbol_name = self.name_manager.get_symbol_name(symbol)126            if symbol.is_tensor():127                construct_function += '    {name} = tfcc::View<{dtype}>(tfcc::Constant<{dtype}>::getConstant("{name}"));\n'.format(128                    name=symbol_name, dtype=get_symbol_cpp_dtype(symbol)129                )130            elif symbol.is_value() and symbol.dtype != ir.framework.DataType.BOOL:131                construct_function += '    {name} = tfcc::Configure<{dtype}>::getConfigure("{name}");\n'.format(132                    name=symbol_name, dtype=get_symbol_cpp_dtype(symbol)133                )134            elif symbol.is_value() and symbol.dtype == ir.framework.DataType.BOOL:135                construct_function += '    {name} = tfcc::Configure<uint8_t>::getConfigure("{name}");\n'.format(136                    name=symbol_name, dtype=get_symbol_cpp_dtype(symbol)137                )138            elif symbol.is_vector():139                assert symbol.dtype != ir.framework.DataType.BOOL140                construct_function += '    {name} = tfcc::data::get(tfcc::Constant<{dtype}>::getConstant("{name}"));\n'.format(141                    name=symbol_name, dtype=get_symbol_cpp_dtype(symbol)142                )143            else:144                raise RuntimeError("Unknow constant symbol")145        construct_function += "}\n"146        setter_function = ""147        for name in self.graph.inputs:148            symbol = self.graph.get_symbol(name)149            symbol_name = self.name_manager.get_symbol_name(symbol, symbol.name)150            setter_function += (151                "void {cls_name}::set_{name}(const {symbol}& v_{name})\n".format(152                    cls_name=self._cls_name,153                    name=symbol_name,154                    symbol=symbol_to_cpp_type(symbol, True),155                )156            )157            setter_function += "{\n"158            if symbol.is_tensor():159                setter_function += (160                    "    {name} = tfcc::View<{dtype}>(v_{name});\n".format(161                        name=symbol_name, dtype=get_symbol_cpp_dtype(symbol)162                    )163                )164            elif symbol.is_value():165                setter_function += "    {name} = v_{name};\n".format(name=symbol_name)166            elif symbol.is_vector():167                setter_function += "    {name} = v_{name};\n".format(name=symbol_name)168            else:169                raise RuntimeError("Unknow stype")170            setter_function += "}\n"171        return_types = []172        for name in self.graph.outputs:173            symbol = self.graph.get_symbol(name)174            return_types.append(symbol_to_cpp_type(symbol, False, True))175        generator_classes = get_all_node_generators()176        process_function = "std::tuple<{types}> {cls_name}::process()\n".format(177            cls_name=self._cls_name, types=", ".join(return_types)178        )179        process_function += "{\n"180        all_succ = True181        for node in self.graph.nodes:182            generator = None183            for generator_class in generator_classes:184                if generator_class.accept(node):185                    generator = generator_class(node, self)186            if generator:187                process_function += generator.comment188                process_function += "    " + generator.code189                # process_function += generator.debug_code190            else:191                all_succ = False192                logging.debug(node.__class__)193        if not all_succ:194            raise RuntimeError("Node to code error")195        return_codes = []196        for name in self.graph.outputs:197            if (198                self.graph.get_symbol(name).is_tensor()199                and self.graph.get_symbol(name).stype200                != ir.framework.SymbolType.VARIABLE201            ):202                return_codes.append(203                    "tfcc::data::copy({symbol})".format(204                        symbol=self.name_manager.get_symbol_name(205                            self.graph.get_symbol(name)206                        )207                    )208                )209            else:210                return_codes.append(211                    "std::move({symbol})".format(212                        symbol=self.name_manager.get_symbol_name(213                            self.graph.get_symbol(name)214                        )215                    )216                )217        outputs_vals = ", ".join(return_codes)218        process_function += "    return std::make_tuple({vals});\n".format(219            vals=outputs_vals220        )221        process_function += "}\n"222        format_str = """223{constructer}224{setter}225{processer}226"""227        return format_str.format(228            cls_name=self._cls_name,229            constructer=construct_function,230            setter=setter_function,231            processer=process_function,232        )233    @property234    def data(self):235        symbols = {}236        for symbol in sorted(self.graph.symbols.values(), key=lambda a: a.name):237            if not symbol.is_constant():238                continue239            symbol_name = self.name_manager.get_symbol_name(symbol)240            key = "{scope}/{name}".format(scope=self._scope_name, name=symbol_name)241            if symbol.dtype == ir.framework.DataType.BOOL:242                symbols[key] = symbol.data.astype(np.uint8)243            else:244                symbols[key] = symbol.data245        return symbols246    @property247    def demo(self):248        constructer_body = ""249        constructer_body += "        {\n"250        constructer_body += '            auto scopeG = tfcc::Scope::scope("model");\n'251        constructer_body += "            _model = std::unique_ptr<{cls_name}>(new {cls_name});\n".format(252            cls_name=self._cls_name253        )254        constructer_body += "        }\n"255        constructer_body += "        {\n"256        constructer_body += '            auto scopeG = tfcc::Scope::scope("sample");\n'257        for name in self.graph.inputs:258            symbol = self.graph.get_symbol(name)259            symbol_name = self.name_manager.get_symbol_name(symbol)260            fmtDict = {261                "name": name,262                "symbol_name": symbol_name,263                "dtype": get_symbol_cpp_dtype(symbol),264            }265            if symbol.is_tensor():266                constructer_body += '            _model->set_{symbol_name}(tfcc::Constant<{dtype}>::getConstant("{name}"));\n'.format(267                    **fmtDict268                )269            elif symbol.is_value() and symbol.dtype != ir.framework.DataType.BOOL:270                constructer_body += '            _model->set_{symbol_name}(tfcc::Configure<{dtype}>::getConfigure("{name}"));\n'.format(271                    **fmtDict272                )273            elif symbol.is_value() and symbol.dtype == ir.framework.DataType.BOOL:274                constructer_body += '            _model->set_{symbol_name}(tfcc::Configure<uint8_t>::getConfigure("{name}"));\n'.format(275                    **fmtDict276                )277            elif symbol.is_vector():278                assert symbol.dtype != ir.framework.DataType.BOOL279                constructer_body += '            _model->set_{symbol_name}(tfcc::data::get(tfcc::Constant<{dtype}>::getConstant("{name}")));\n'.format(280                    **fmtDict281                )282            else:283                raise RuntimeError("Unknow constant symbol")284        constructer_body += "        }\n"285        run_once_body = ""286        run_once_body += "        _model->process();\n"287        run_once_body += "        tfcc::MKLDevice* device = static_cast<tfcc::MKLDevice*>(tfcc::Device::getThreadDefault());\n"288        run_once_body += "        device->clearStatistics();\n"289        run_once_body += "        tfcc::Session::getThreadDefault()->sync();\n"290        run_once_body += "        auto result = _model->process();\n"291        run_once_body += "        tfcc::Session::getThreadDefault()->sync();\n"292        run_once_body += "        device->getStatistics().print();\n"293        for i, name in enumerate(self.graph.outputs):294            symbol = self.graph.get_symbol(name)295            if symbol.is_tensor() or symbol.is_value():296                run_once_body += '        std::cout << "{name}: " << std::get<{i}>(result) << std::endl;\n'.format(297                    name=name, i=i298                )299            elif symbol.is_vector():300                assert symbol.dtype != ir.framework.DataType.BOOL301                run_once_body += '        std::cout << "{name}: " << tfcc::data::set(std::get<{i}>(result), {static_cast<unsigned>(std::get<{i}>(result).size())}) << std::endl;\n'.format(302                    name=name, i=i303                )304            else:305                raise RuntimeError("Unknow constant symbol")306        code_fmt = """307class Demo308{{309    std::unique_ptr<{cls_name}> _model;310public:311    struct Statistics312    {{313        std::atomic<size_t> processCnt;314        std::atomic<size_t> totalCost;315    }};316public:317    Demo()318    {{319{constructer_body}320    }}321    void runOnce()322    {{323        auto scopeG = tfcc::Scope::scope("model");324{run_once_body}325    }}326    void run(Statistics& statistics)327    {{328        auto scopeG = tfcc::Scope::scope("model");329        while (true)330        {{331            tfcc::Coster coster;332            _model->process();333            tfcc::Session::getThreadDefault()->sync();334            ++statistics.processCnt;335            statistics.totalCost += coster.lap().microseconds();336        }}337    }}338}};339"""340        return code_fmt.format(341            cls_name=self._cls_name,342            constructer_body=constructer_body,343            run_once_body=run_once_body,344        )345    @property346    def demo_data(self):347        data = {}348        for name in self.graph.inputs:349            symbol = self.graph.get_symbol(name)350            shape = [1 if isinstance(s, str) else s for s in symbol.shape]351            if symbol.is_integer():352                data[name] = np.ones(shape)353            else:354                data[name] = np.zeros(shape) + 0.1...gameentity.py
Source:gameentity.py  
1from pathlib import Path2from engine.funcs import *3class GameEntity:4    """5    Base class of all game entities. Each game entity as access to the engine.6    If the Engine was not initialized, no objects will be created. Each game entity7    has an automatic distributed ID.8    Each entity is added in a dictionary with their entity id.9    """10    engine = None11    _nbentity = 012    _register = 113    _subclassdict = {}14    _cls_name = None15    _entities = {}16    def __init_subclass__(cls, **kwargs):17        cls._cls_name = cls.__name__18        if cls._register:19            cls._subclassdict[cls._cls_name]=cls20        cls.init_class()21    def __new__(cls, *args, **kwargs):22        if GameEntity.engine is None:23            return None24        else:25            return super().__new__(cls)26    def __init__(self, *args, **kwargs):27        self.entityID = GameEntity._nbentity28        GameEntity._nbentity += 129        GameEntity.add_entity(self)30        self._update = False31        if "update" in dir(self):32            self.set_update(True)33        self.init(*args, **kwargs)34    def init(self, *args, **kwargs):35        pass36    def set_update(self, value:bool):37        """38        if value is true, the entity is added to the engine update list39        :param value:40        :return:41        """42        if value:43            self.engine.e_add_updatedentity(self)44            self._update = True45        if not value:46            self.engine.e_del_updatedentity(self)47            self._update = False48    def delete(self):49        pass50    def __del__(self):51        self.engine.log("info","Gamentity deleted:", str(type(self)))52        if self._update:53            self.engine.e_del_updatedentity(self)54    @classmethod55    def init_class(cls):56        pass57    @classmethod58    def set_subclasses(cls):59        """60        Gets all the classes that inherits from class. This function can be called in61        """62        cls.subclassdict = get_subclasses(cls)63    @classmethod64    def get_subclasses(cls):65        return cls._subclassdict66    @classmethod67    def e_set_engine(cls, engine):68        cls.engine = engine69    @classmethod70    def get_engine(cls):71        return cls.engine72    @classmethod73    def set_name(cls, name):74        """75        Sets the name of the class for the engine76        """77        if name not in cls._subclassdict:78            if cls._register:79                del cls._subclassdict[cls._cls_name]80                cls._cls_name = name81                cls._subclassdict[cls._cls_name] = cls82            else:83                cls._cls_name = name84        else:85            cls.engine.log("error", "can't set name, class name already exists.")86    @classmethod87    def add_entity(cls, entity):88        cls._entities[entity.entityID] = entity89    @classmethod90    def get_entity(cls, entityid):91        return cls._entities[entityid]92    @staticmethod93    def get_datapath(pathname):94        return Path().joinpath(*pathname.split("|"))95class GameEntityContainer:...foo.py
Source:foo.py  
1#coding: UTF-82def foo():3    n = 14    def bar():5        print n # å¼ç¨éå
¨å±çå¤é¨åénï¼æé ä¸ä¸ªéå
6    n = 27    return bar8closure = foo()9# print closure.func_closure10# 使ç¨dir()å¾ç¥cell对象æä¸ä¸ªcell_contents屿§å¯ä»¥è·å¾å¼11#print closure.func_closure[0].cell_contents # 212'''''13æ¥æ¾å建对象14 _cls_name='LoginError'15 _packet_name = 'home.cates.'16'''17def get_cate_obj(_packet_name,_cls_name):18    _module_home = __import__(_packet_name,globals(),locals(),[_cls_name])19    obj =  getattr(_module_home,_cls_name)20    return obj()21# cls = get_cate_obj("reflection.foo","bar")22# print(cls.bar())23print (getattr(closure,"bar"))...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!!
