Best Python code snippet using prospector_python
profile.py
Source:profile.py  
...131def _simple_merge_dict(priority, base):132    out = dict(base.items())133    out.update(dict(priority.items()))134    return out135def _merge_tool_config(priority, base):136    out = dict(base.items())137    for key, value in priority.items():138        # pep8 has extra 'full' and 'none' options139        # pylint has extra 'load-plugins' option140        if key in ("run", "full", "none", "load-plugins"):141            out[key] = value142        elif key in ("options",):143            out[key] = _simple_merge_dict(value, base.get(key, {}))144    # anything enabled in the 'priority' dict is removed145    # from 'disabled' in the base dict and vice versa146    base_disabled = base.get("disable") or []147    base_enabled = base.get("enable") or []148    pri_disabled = priority.get("disable") or []149    pri_enabled = priority.get("enable") or []150    out["disable"] = list(set(pri_disabled) | (set(base_disabled) - set(pri_enabled)))151    out["enable"] = list(set(pri_enabled) | (set(base_enabled) - set(pri_disabled)))152    return out153def _merge_profile_dict(priority, base):154    # copy the base dict into our output155    out = dict(base.items())156    for key, value in priority.items():157        if key in (158            "strictness",159            "doc-warnings",160            "test-warnings",161            "member-warnings",162            "output-format",163            "autodetect",164            "max-line-length",165        ):166            # some keys are simple values which are overwritten167            out[key] = value168        elif key in (169            "ignore",170            "ignore-patterns",171            "ignore-paths",172            "uses",173            "requirements",174            "python-targets",175            "output-target",176        ):177            # some keys should be appended178            out[key] = _ensure_list(value) + _ensure_list(base.get(key, []))179        elif key in TOOLS.keys():180            # this is tool config!181            out[key] = _merge_tool_config(value, base.get(key, {}))182    return out183def _determine_strictness(profile_dict, inherits):184    for profile in inherits:185        if profile.startswith("strictness_"):186            return None, False187    strictness = profile_dict.get("strictness")188    if strictness is None:189        return None, False190    return ("strictness_%s" % strictness), True191def _determine_pep8(profile_dict):192    pep8 = profile_dict.get("pep8", {})193    if pep8.get("full", False):194        return "full_pep8", True195    elif pep8.get("none", False):...tool.py
Source:tool.py  
...8class Options(NamedTuple):9    release: bool10    test_only: List[str]11DEFAULT_TOOL_CONFIG = {"cpp_std": "c++17", "type": "generic"}12def _merge_tool_config(base: Dict[str, Any], local: Dict[str, Any]) -> Dict[str, Any]:13    rv = dict(base)14    rv.update(local)15    return rv16def compute_tool_config(file_path: Path) -> Dict[str, str]:17    root_dir = Path(__file__).parent.resolve()18    found_config_paths = []19    current_dir = file_path.resolve()20    while True:21        current_dir = current_dir.parent22        candidate_path = current_dir / "toolconfig.json"23        if candidate_path.is_file():24            found_config_paths.append(candidate_path)25        if current_dir in root_dir.parents:26            break27    found_config_paths = found_config_paths[::-1]28    tool_config = DEFAULT_TOOL_CONFIG29    for config_path in found_config_paths:30        with open(config_path, "r") as f:31            local_config = json.load(f)32        tool_config = _merge_tool_config(tool_config, local_config)33    return tool_config34def autofix_usaco_header(file_path: Path) -> None:35    contents = file_path.read_text("utf-8")36    problem_name = _get_base_path(file_path).name37    if "ID:" not in contents[:30]:38        if file_path.suffix == ".py":39            contents = (40                f'''\41"""42ID: cesarka243LANG: PYTHON344TASK: {problem_name}45"""46'''47                + contents48            )49        elif file_path.suffix == ".cpp":50            contents = (51                f"""\52/*53ID: cesarka254LANG: C++1455TASK: {problem_name}56*/57"""58                + contents59            )60        file_path.write_text(contents, "utf-8")61def autofix_usaco_input(file_path: Path) -> None:62    problem_name = _get_base_path(file_path).name63    magic_string = problem_name + ".in"64    if magic_string not in file_path.read_text("utf-8"):65        print(66            f"Looks like {magic_string} was found nowhere in {file_path}, but this is usaco!"67        )68        print(69            """\70Monkey:71#ifndef LOCAL72    std::freopen("PROBLEM.in", "r", stdin);73    std::freopen("PROBLEM.out", "w", stdout);74#endif75"""76        )77        sys.exit(1)78def autofix(options: Options, file_path: Path) -> None:79    tool_config = compute_tool_config(file_path)80    if tool_config["type"] == "usaco":81        autofix_usaco_header(file_path)82        autofix_usaco_input(file_path)83def build(options: Options, file_path: Path) -> None:84    tool_config = compute_tool_config(file_path)85    if file_path.suffix == ".py":86        return87    elif file_path.suffix == ".cpp":88        mode_args = (89            ["-O3"]90            if options.release == "release"91            else ["-fsanitize=address,undefined"]92        )93        output = file_path.with_suffix(".run")94        p = subprocess.run(95            [96                "clang++",97                "-DLOCAL",98                "-Wall",99                "-g",100                f"-std={tool_config['cpp_std']}",101                *mode_args,102                "-o",103                str(output),104                str(file_path),105            ],106        )107        if p.returncode != 0:108            print(f"Compiler failed with code: {p.returncode}")109            sys.exit(1)110    else:111        print(f"Unrecognized suffix: {file_path.suffix}")112        sys.exit(1)113    print("Compilation successful!")114def _get_base_path(file_path: Path) -> Path:115    base_path = file_path.with_suffix("")116    if "-" in base_path.name:117        new_name, _ = base_path.name.split("-", 1)118        base_path = base_path.with_name(new_name)119    return base_path120def test(options: Options, file_path: Path) -> None:121    base_path = _get_base_path(file_path)122    for path in base_path.parent.glob(base_path.name + ".cand*"):123        path.unlink()124    if not options.test_only:125        input_files = list(base_path.parent.glob(base_path.name + ".in*"))126        input_files = [x for x in input_files if not x.name.endswith("debug")]127    else:128        input_files = [129            base_path.parent / (base_path.name + ".in" + x) for x in options.test_only130        ]131    input_files.sort()132    if not input_files:133        print("No input files found!")134        sys.exit(1)135    for input_file in input_files:136        output_file = input_file.with_name(input_file.name.replace(".in", ".cand"))137        with open(input_file, "r") as fin, open(output_file, "w") as fout:138            timeout_prefix = ["timeout", "-s9", "5"]139            if file_path.suffix == ".py":140                p = subprocess.run(141                    [*timeout_prefix, "python3", str(file_path)], stdin=fin, stdout=fout142                )143            elif file_path.suffix == ".cpp":144                p = subprocess.run(145                    [*timeout_prefix, str(file_path.with_suffix(".run"))],146                    stdin=fin,147                    stdout=fout,148                )149            else:150                print(f"Unrecognized suffix: {file_path.suffix}")151                sys.exit(1)152            if p.returncode != 0:153                print(f">>> Failure exit code: {p.returncode} ! <<<")154def compare(options: Options, file_path: Path) -> None:155    base_path = _get_base_path(file_path)156    candidates = list(base_path.parent.glob(base_path.name + ".cand*"))157    candidates = [x for x in candidates if not x.name.endswith('debug')]158    candidates.sort()159    different_files_count = 0160    for candidate in candidates:161        output = candidate.with_name(candidate.name.replace(".cand", ".out"))162        print()163        print(f">>> {candidate} vs {output} <<<")164        p = subprocess.run(165            ["diff", "--color=always", "-ysN", str(candidate), str(output)]166        )167        if p.returncode != 0:168            different_files_count += 1169    print()170    if different_files_count:171        print(172            f">>> {different_files_count} out of {len(candidates)} files different <<<"173        )174    else:175        print(">>> All files identical! <<<")176def _generate_compilation_database_entry(177    path: Path, tool_config: Dict[str, Any]178) -> Dict[str, str]:179    std = tool_config["cpp_std"]180    return {181        "directory": str(Path(__file__).parent.resolve()),182        "command": f"clang++ -DLOCAL -std={std} {str(path)}",183        "file": str(path),184    }185def _recursive_generate_compilation_database(186    dir: Path, parent_tool_config: Dict[str, Any]187) -> List[Dict[str, str]]:188    local_tool_config_path = dir / "toolconfig.json"189    current_tool_config = parent_tool_config190    if local_tool_config_path.exists():191        with open(local_tool_config_path, "r") as f:192            local_tool_config = json.load(f)193        current_tool_config = _merge_tool_config(parent_tool_config, local_tool_config)194    rv = []195    for path in dir.iterdir():196        if path.is_file() and path.suffix == ".cpp":197            entry = _generate_compilation_database_entry(path, current_tool_config)198            rv.append(entry)199        elif path.is_dir():200            sub_entries = _recursive_generate_compilation_database(201                path, current_tool_config202            )203            rv.extend(sub_entries)204    return rv205def generate_compilation_database(options: Options, file_path: Path) -> None:206    base_dir = Path(__file__).parent207    compilation_database = _recursive_generate_compilation_database(...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!!
