Best Python code snippet using autotest_python
vk_helper_generator.py
Source:vk_helper_generator.py  
...39### format helpers ###40######################41def format_line(line, indent_level=0):42    return INDENT * indent_level + line.replace("\t", INDENT) + "\n"43def format_lines(lines, indent_level=0):44    return [format_line(line, indent_level) for line in lines]45######################46#### ENUM helpers ####47######################48def add_to_enum_list(elist, new_enum):49    if new_enum != None and next((i for i in elist if (i.value == new_enum.value)), None) == None:50        elist.append(new_enum)51def get_enum_value(root, extnumber = None):52    #print(root.tag, root.attrib)53    if "alias" in root.attrib:54        return None55    if "value" in root.attrib:56        return vk_enum_value(name=root.attrib.get("name"), value=root.attrib.get("value"))57    if "extnumber" in root.attrib:58        extnumber = (int(root.attrib.get("extnumber")) - 1) * 100059    offset = int(root.attrib.get("offset"))60    value = 1000000000 + extnumber + offset61    return vk_enum_value(name=root.attrib.get("name"), value=str(value))62def get_sub_enum(root, result, enum_name, ext_num = None):63    for item in root.findall("enum"):64        if item.attrib.get("extends") == enum_name:65            add_to_enum_list(result, get_enum_value(item, ext_num))66def get_enum_from_feature(root, result, enum_name, ext_num = None):67    for require in root.findall("require"):68        if "extension" in require.attrib:69            continue70        get_sub_enum(require, result, enum_name, ext_num)71def get_enum(root, enum_name):72    core_enum = [i for i in root.findall("enums") if i.get("name") == enum_name][0];73    if core_enum.get("type") != "enum":74        raise LookupError("not enum")75    #print(core_enum.tag, core_enum.attrib)76    result = []77    for i in core_enum:78        add_to_enum_list(result, get_enum_value(i))79    features = root.findall("feature");80    for feature in features:81        get_enum_from_feature(feature, result, enum_name)82    extensions = root.find("extensions");83    for ext in extensions:84        if ext.attrib.get("supported") != "disabled":85            tmp = []86            get_enum_from_feature(ext, tmp, enum_name, int(ext.attrib.get("number")))87            platform = [i for i in g_platforms if i.name == str(ext.attrib.get("platform"))][0]88            for value in tmp:89                value.platform = platform90                add_to_enum_list(result, value)91    result.sort(key=lambda e: int(e.value))92    return result93######################94#### func helpers ####95######################96def get_all_funcs(root):97    funcs = []98    child_instance = {'VkInstance', 'VkPhysicalDevice'}99    child_device = {'VkDevice', 'VkCommandBuffer', 'VkQueue'}100    commands = root.find("commands")101    for command in commands.findall("command"):102        name = None103        parent = None104        if command.attrib.get("alias") != None:105            func = [i for i in funcs if i.name == command.attrib.get("alias")][0]106            func.aliases.append(command.attrib.get("name"))107        proto = command.find("proto")108        if proto != None:109            name = proto.find("name").text110        param = command.find("param")111        if param != None:112            if param.find("type").text in child_instance:113                parent = "VkInstance"114            elif param.find("type").text in child_device:115                parent = "VkDevice"116            else:117                continue118        else:119            continue120        funcs.append(vk_func(name, parent))121##    result = []122##    features = root.findall("feature");123##    for feature in features:124##        for require in feature.findall("require"):125##            for command in require.findall("command"):126##                result.append(vk_func(command.attrib.get("name")))127##128    extensions = root.find("extensions");129    for ext in extensions:130        if ext.attrib.get("supported") != "disabled":131            for require in ext.findall("require"):132                platform = [i for i in g_platforms if i.name == str(ext.attrib.get("platform"))][0]133                for command in require.findall("command"):134                    try:135                        func = [i for i in funcs if i.name == command.attrib.get("name")][0]136                        func.platform=platform137                    except:138                        pass139        else:140            for require in ext.findall("require"):141                platform = [i for i in g_platforms if i.name == str(ext.attrib.get("platform"))][0]142                for command in require.findall("command"):143                    try:144                        func = [i for i in funcs if i.name == command.attrib.get("name")][0]145                        funcs.remove(func)146                    except:147                        pass148    #print(funcs)149    return funcs150######################151### sType helpers ####152######################153def convert_sType_to_name(sType: str):154    vendor_parts = ["EXT", "KHR", "KHX", "AMD", "NV", "NVX", "IMG", "AMDX", "ARM", "ANDROID", "FUCHSIA",155                    "GGP", "GOOGLE", "QCOM", "NN", "MVK", "MESA", "INTEL",]156    blacklisted_parts = ["ID", "LOD", "SM", "ASTC", "AABB",]157                        #TODO auto generate + add more158    special_parts = {"8BIT" : "8Bit", "16BIT" : "16Bit", "DIRECTFB" : "DirectFB",}159    special_meaning = {"VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO"   : "VkLayerDeviceCreateInfo",160                       "VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO" : "VkLayerInstanceCreateInfo",161                       "VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TEXTURE_COMPRESSION_ASTC_HDR_FEATURES_EXT" :162                       "VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT",}163    if special_meaning.get(sType) != None:164        return special_meaning[sType];165    struct_parts = sType[len("VK_STRUCTURE_TYPE_"):].split("_")166    struct_name = "Vk"167    for i in range(len(struct_parts)):168        part = struct_parts[i]169        if part in vendor_parts and i == len(struct_parts) - 1:170            struct_name += part171        elif part in blacklisted_parts:172            struct_name += part173        elif special_parts.get(part) != None:174            struct_name += special_parts[part]175        else:176            struct_name += part[0]177            struct_name += part[1:].lower()178    return struct_name179######################180##### generators #####181######################182def write_vulkan_sizeof(sTypes):183    with open("../generated/vulkan_sizeof.h", "w") as file:184        boilerplate_start = ["#pragma once", "",185                             "#ifdef __cplusplus",186                             "extern \"C\" {",187                             "#endif", "",188                             "#include <stddef.h>", "",189                             "//Frog",190                             ]191        vksizeof_start = ["static size_t vksizeof(VkStructureType sType)",192                          "{",193                          "\tswitch (sType)",194                          "\t{",195                          ]196        vksizeof_end = ["\t\tdefault: return 0;",197                        "\t}",198                        "}", "",199                        ]200        boilerplate_end = ["#ifdef __cplusplus",201                           "}",202                           "#endif",203                           ]204        file.writelines(format_lines(boilerplate_start))205        file.writelines(format_lines(vksizeof_start))206        for i in sTypes:207            if i.platform.name != "None":208                file.write(format_line("#ifdef {}".format(i.platform.guard)))209            line = "case {}: return sizeof({});".format(i.name, convert_sType_to_name(i.name))210            file.write(format_line(line, 2))211            if i.platform.name != "None":212                file.write(format_line("#endif"))213        file.writelines(format_lines(vksizeof_end))214        file.writelines(format_lines(boilerplate_end))215def write_vulkan_get_sType(sTypes):216    with open("../generated/vulkan_stype.hpp", "w") as file:217        boilerplate_start = ["#pragma once", "",218                             "#include <type_traits>", "",219                             "//Frog generated",220                             ]221        get_sType_start = ["template <typename T>",222                           "constexpr VkStructureType sTypeFromStruct()",223                           "{",224                           ]225        get_sType_end = ["",226                         "\treturn (VkStructureType) -1;",227                         "}",228                         ]229        boilerplate_end = []230        file.writelines(format_lines(boilerplate_start))231        file.writelines(format_lines(get_sType_start))232        for i in sTypes:233            if i.platform.name != "None":234                file.write(format_line("#ifdef {}".format(i.platform.guard)))235            lines = ["if constexpr (std::is_same<T, {}>::value)".format(convert_sType_to_name(i.name)),236                     "{",237                     "\treturn {};".format(i.name),238                     "}",239                     ]240            file.writelines(format_lines(lines, 1))241            if i.platform.name != "None":242                file.write(format_line("#endif"))243        file.writelines(format_lines(get_sType_end))244        file.writelines(format_lines(boilerplate_end))245def write_vulkan_dispatch_table(funcs):246    with open("../generated/vulkan_dispatch_table.hpp", "w") as file:247        boilerplate_start = ["#pragma once", "",248                             "//Frog generated",249                             ]250        d_table_start = ["struct VulkanDispatchTable",251                         "{",252                         ]253        d_table_end = ["};",254                       "",255                       ]256        init_instance_start = ["static void initInstanceTable(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VulkanDispatchTable* table)",257                               "{",258                               ]259        init_instance_end = ["}", ""]260        init_device_start = ["static void initDeviceTable(PFN_vkGetDeviceProcAddr gdpa, VkDevice device, VulkanDispatchTable* table)",261                             "{",262                             ]263        init_device_end = ["}",]264        boilerplate_end = []265        file.writelines(format_lines(boilerplate_start))266        file.writelines(format_lines(d_table_start))267        for i in funcs:268            if i.platform.name != "None":269                file.write(format_line("#ifdef {}".format(i.platform.guard)))270            line = "PFN_{} {} = nullptr;".format(i.name, i.name[2:])271            file.write(format_line(line, 1))272            if i.platform.name != "None":273                file.write(format_line("#endif"))274        file.writelines(format_lines(d_table_end))275        file.writelines(format_lines(boilerplate_end))276def write_vulkan_dispatch_int(funcs):277    with open("../generated/vulkan_dispatch_init.hpp", "w") as file:278        boilerplate_start = ["#pragma once", "",279                             "//Frog generated",280                             ]281        init_instance_start = ["static void initInstanceTable(PFN_vkGetInstanceProcAddr gipa, VkInstance instance, VulkanDispatchTable* table)",282                               "{",283                               ]284        init_instance_end = ["}", ""]285        init_device_start = ["static void initDeviceTable(PFN_vkGetDeviceProcAddr gdpa, VkDevice device, VulkanDispatchTable* table)",286                             "{",287                             ]288        init_device_end = ["}",]289        boilerplate_end = []290        file.writelines(format_lines(boilerplate_start))291    292        file.writelines(format_lines(init_instance_start))293        for i in [f for f in funcs if f.parent == "VkInstance"]:294            if i.platform.name != "None":295                file.write(format_line("#ifdef {}".format(i.platform.guard)))296            commands = [i.name] + i.aliases297            for command in commands:298                lines = ["if (table->{} == nullptr)".format(i.name[2:]),299                         "\ttable->{} = (PFN_{}) gipa(instance, \"{}\");".format(i.name[2:], i.name, command)]300                file.writelines(format_lines(lines, 1))301            if i.platform.name != "None":302                file.write(format_line("#endif"))303        file.writelines(format_lines(init_instance_end))304        file.writelines(format_lines(init_device_start))305        for i in [f for f in funcs if f.parent == "VkDevice"]:306            if i.platform.name != "None":307                file.write(format_line("#ifdef {}".format(i.platform.guard)))308            commands = [i.name] + i.aliases309            for command in commands:310                lines = ["if (table->{} == nullptr)".format(i.name[2:]),311                         "\ttable->{} = (PFN_{}) gdpa(device, \"{}\");".format(i.name[2:], i.name, command)]312                file.writelines(format_lines(lines, 1))313            if i.platform.name != "None":314                file.write(format_line("#endif"))315        file.writelines(format_lines(init_device_end))316        317        file.writelines(format_lines(boilerplate_end))318def main():319    vk_xml = "vk-{}.xml".format(VK_API_VERSION)320    get_vk_xml(vk_xml, VK_API_VERSION)321    tree = etree.parse(vk_xml)322    get_vk_platforms(tree)323    #print(g_platforms)324    sTypes = get_enum(tree, "VkStructureType")325    #print(sTypes)326    #print([i.name for i in sTypes])327    write_vulkan_sizeof(sTypes)328    write_vulkan_get_sType(sTypes)329    funcs = get_all_funcs(tree)330    write_vulkan_dispatch_table(funcs)331    write_vulkan_dispatch_int(funcs)...formatter.py
Source:formatter.py  
1# This code is part of Qiskit.2#3# (C) Copyright IBM 2021.4#5# This code is licensed under the Apache License, Version 2.0. You may6# obtain a copy of this license in the LICENSE.txt file in the root directory7# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.8#9# Any modifications or derivative works of this code must retain this10# copyright notice, and modified files need to carry a notice indicating11# that they have been altered from the originals.12"""13A class that formats documentation sections.14"""15from typing import List16from .utils import _check_no_indent17class DocstringSectionFormatter:18    """A class that formats parsed docstring lines.19    This formatter formats sections with Google Style Python Docstrings with20    several reStructuredText directives.21    """22    def __init__(self, indent: str):23        self.indent = indent24    def format_header(self, lines: List[str]) -> List[str]:25        """Format header section."""26        format_lines = lines27        format_lines.append("")28        return format_lines29    @_check_no_indent30    def format_overview(self, lines: List[str]) -> List[str]:31        """Format overview section."""32        format_lines = [".. rubric:: Overview", ""]33        format_lines.extend(lines)34        format_lines.append("")35        return format_lines36    @_check_no_indent37    def format_reference(self, lines: List[str]) -> List[str]:38        """Format reference section."""39        format_lines = [".. rubric:: References", ""]40        format_lines.extend(lines)41        format_lines.append("")42        return format_lines43    def format_warning(self, lines: List[str]) -> List[str]:44        """Format warning section."""45        format_lines = [".. warning::", ""]46        for line in lines:47            format_lines.append(self.indent + line)48        format_lines.append("")49        return format_lines50    @_check_no_indent51    def format_example(self, lines: List[str]) -> List[str]:52        """Format example section."""53        format_lines = [".. rubric:: Example", ""]54        format_lines.extend(lines)55        format_lines.append("")56        return format_lines57    def format_note(self, lines: List[str]) -> List[str]:58        """Format notification section."""59        format_lines = [".. note::", ""]60        for line in lines:61            format_lines.append(self.indent + line)62        format_lines.append("")63        return format_lines64    @_check_no_indent65    def format_see_also(self, lines: List[str]) -> List[str]:66        """Format see also section."""67        text = ".. seealso:: Module(s) "68        modules = []69        for line in lines:70            modules.append(f":py:mod:`~{line.lstrip()}`")71        text += ", ".join(modules)72        return [text, ""]73    @_check_no_indent74    def format_tutorial(self, lines: List[str]) -> List[str]:75        """Format tutorial section."""76        format_lines = [".. rubric:: Tutorials", ""]77        format_lines.extend(lines)78        format_lines.append("")79        return format_lines80class ExperimentSectionFormatter(DocstringSectionFormatter):81    """Formatter for experiment class."""82    @_check_no_indent83    def format_analysis_ref(self, lines: List[str]) -> List[str]:84        """Format analysis class reference section."""85        format_lines = [".. rubric:: Analysis Class Reference", ""]86        format_lines.extend(lines)87        format_lines.append("")88        return format_lines89    @_check_no_indent90    def format_experiment_opts(self, lines: List[str]) -> List[str]:91        """Format experiment options section."""92        format_lines = [93            ".. rubric:: Experiment Options",94            "",95            "These options can be set by :py:meth:`set_experiment_options` method.",96            "",97        ]98        format_lines.extend(lines)99        format_lines.append("")100        return format_lines101    @_check_no_indent102    def format_analysis_opts(self, lines: List[str]) -> List[str]:103        """Format analysis options section."""104        format_lines = [105            ".. rubric:: Analysis Options",106            "",107            "These options can be set by :py:meth:`analysis.set_options` method.",108            "",109        ]110        format_lines.extend(lines)111        format_lines.append("")112        return format_lines113    @_check_no_indent114    def format_transpiler_opts(self, lines: List[str]) -> List[str]:115        """Format transpiler options section."""116        format_lines = [117            ".. rubric:: Transpiler Options",118            "",119            "This option can be set by :py:meth:`set_transpile_options` method.",120            "",121        ]122        format_lines.extend(lines)123        format_lines.append("")124        return format_lines125    @_check_no_indent126    def format_run_opts(self, lines: List[str]) -> List[str]:127        """Format run options section."""128        format_lines = [129            ".. rubric:: Backend Run Options",130            "",131            "This option can be set by :py:meth:`set_run_options` method.",132            "",133        ]134        format_lines.extend(lines)135        format_lines.append("")136        return format_lines137class AnalysisSectionFormatter(DocstringSectionFormatter):138    """Formatter for analysis class."""139    @_check_no_indent140    def format_analysis_opts(self, lines: List[str]) -> List[str]:141        """Format analysis options section."""142        format_lines = [143            ".. rubric:: Run Options",144            "",145            "These are the keyword arguments of :py:meth:`run` method.",146            "",147        ]148        format_lines.extend(lines)149        format_lines.append("")150        return format_lines151    @_check_no_indent152    def format_fit_model(self, lines: List[str]) -> List[str]:153        """Format fit model section."""154        format_lines = [155            ".. rubric:: Fit Model",156            "",157            "This is the curve fitting analysis. ",158            "The following equation(s) are used to represent curve(s).",159            "",160        ]161        format_lines.extend(lines)162        format_lines.append("")163        return format_lines164    @_check_no_indent165    def format_fit_parameters(self, lines: List[str]) -> List[str]:166        """Format fit parameter section."""167        format_lines = [168            ".. rubric:: Fit Parameters",169            "",170            "The following fit parameters are estimated during the analysis.",171            "",172        ]173        format_lines.extend(lines)174        format_lines.append("")...plot.py
Source:plot.py  
...4def read_txt_file(file_url: str):5    with open(file_url, "r") as read_file:6        lines = read_file.readlines()7    return lines8def format_lines(lines):9    lines = [line.replace("\n", "") for line in lines]10    formatted_lines = [float(line.replace("\n", "")) for line in lines]11    return formatted_lines12def plot(*args):13    fig = plt.figure()14    for arg in args:15        plt.plot(arg)16    fig.savefig(f"./visualisation/figures/compare.png")17def main():18    ## Exact solution19    lines = read_txt_file(EXACT_SOLUTION_URL)20    formatted_lines_exact = format_lines(lines)21    ## Approximated solution22    lines = read_txt_file(CG_SOLUTION_URL)23    formatted_lines_cg = format_lines(lines)24    ## Plot25    plot(formatted_lines_exact, formatted_lines_cg)26if __name__ == "__main__":...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!!
