Best Python code snippet using autotest_python
cca_cluster.py
Source:cca_cluster.py  
...226            # As the function seeks to minimizes we convert to minus area227            loss_function = -sum(true_corr[perm_good] - median_corr[perm_good])228        gp_dict['x_iters'].append([audio_reg, visual_reg])229        gp_dict['func_vals'].append(loss_function)230        save_as_pickle(gp_dict, path_joiner('gp_dict'))231        df = pd.DataFrame(gp_dict)232        df.to_csv(path_joiner('gp_dict') + '.csv', index=False)233        if loss_function <= min(gp_dict['func_vals']):234            print('Save because it is best')235            save_as_pickle(cca, path_joiner('best_cca'))236            perm_dict['significant_comp'] = perm_good237            perm_dict['min_func'] = loss_function238            perm_dict['perm_corr'] = perm_corr239            perm_dict['true_corr'] = true_corr240            save_as_pickle(perm_dict, path_joiner('perm_dict'))241        objective_count.append(1)242        return loss_function243    n_calls = 10244    n_random_starts = 5245    try:246        gp_dict = load_pickle_file(path_joiner('gp_dict'))247        perm_dict = load_pickle_file(path_joiner('perm_dict'))248        x0 = gp_dict['x_iters']249        y0 = gp_dict['func_vals']250        function_gp = gp_minimize(objective, space, x0=x0, y0=y0, n_calls=n_calls, n_jobs=1, verbose=False,251                                  n_random_starts=n_random_starts, random_state=0)252    except FileNotFoundError:253        # Description of bayesian optimization https://distill.pub/2020/bayesian-optimization/254        function_gp = gp_minimize(objective, space, n_calls=n_calls, n_jobs=1, verbose=False,255                                  n_random_starts=n_random_starts, random_state=0)256    print('Best corr: ' + str(-function_gp['fun']) + '\n')257    print('with audio reg = ' + str(function_gp['x'][0]) + ', visual reg = ' + str(function_gp['x'][1]) + '\n\n')258    audio_reg = function_gp['x'][0]259    visual_reg = function_gp['x'][1]260    if save_fig:261        all_cv['reg_audio'].append(audio_reg)262        all_cv['reg_visual'].append(visual_reg)263        all_cv['largest_area'].append(-function_gp['fun'])264        all_cv['significant_comp'].append(perm_dict['significant_comp'])265        df = pd.DataFrame(all_cv)266        df.to_csv(path_joiner('area') + '.csv', index=False)267        save_as_pickle(perm_dict, path_joiner('perm_dict'))268    # Plot the permutations269    cca_perm_plot(audio_feature, visual_feature, audio_reg, visual_reg, save_kwargs, **perm_dict)270    return271def cca_perm_plot(audio_feature, visual_feature, audio_reg, visual_reg, save_kwargs,272                  perm_corr, true_corr, significant_comp, min_func):273    """274    Plots the correlation for each component along with the corresponding permutations. Further, the significant275    components are highlighted.276    :param audio_feature:277    :param visual_feature:278    :param audio_reg:279    :param visual_reg:280    :param save_kwargs:281    :param perm_corr:...test_jinjawalk.py
Source:test_jinjawalk.py  
...3import os4from jinjawalk import JinjaWalk5from typing import Callable, Dict6import shutil7def path_joiner(base: str) -> Callable[[str], str]:8    return lambda s: os.path.join(base, s)9def dump_string(file_path: str, s: str):10    with open(file_path, "w") as of:11        print(s, file=of)12def read_file(file_path: str) -> str:13    with open(file_path, "r") as f:14        content = f.read()15    return content16class TestJinjaWalk(TestCase):17    @staticmethod18    def write_dummy_template(destination: str,19                             conf: Dict[str, str],20                             section_name: str = 'section_name',21                             namespace: str = 'config') -> str:22        s = '\n'.join(["line" + str(i+1) + " with {{ " + namespace + "['" + section_name + "']['" + k + "'] }}"23                       for i, k in enumerate(conf)])24        dump_string(destination, s)25        expected_render = '\n'.join([f"line{i+1} with {conf[k]}" for i, k in enumerate(conf)])26        return expected_render27    @staticmethod28    def write_dummy_conf_file(destination: str, conf: Dict[str, str], section_name='section_name'):29        s = f"[{section_name}]\n" + '\n'.join([f"{k} = {conf[k]}" for k in conf])30        dump_string(destination, s)31class TestMultipleInPlace(TestJinjaWalk):32    def setUp(self) -> None:33        self.work_dir = tempfile.mkdtemp()34        conf1 = {"key1": "value1"}35        conf2 = {"key2": "value2"}36        conf3 = {"key3": "value3"}37        self.conf_file_path1 = path_joiner(self.work_dir)('conf1.ini')38        self.conf_file_path2 = path_joiner(self.work_dir)('conf2.ini')39        self.conf_file_path3 = path_joiner(self.work_dir)('conf3.ini')40        self.write_dummy_conf_file(self.conf_file_path1, conf1)41        self.write_dummy_conf_file(self.conf_file_path2, conf2)42        self.write_dummy_conf_file(self.conf_file_path3, conf3)43        self.expected_render = self.write_dummy_template(path_joiner(self.work_dir)('template.txt'),44                                                         {**conf1, **conf2, **conf3})45    def tearDown(self) -> None:46        shutil.rmtree(self.work_dir)47    def test_multiple_in_place(self):48        walker = JinjaWalk()49        walker.walk([self.conf_file_path1, self.conf_file_path2, self.conf_file_path3], self.work_dir, self.work_dir)50        rendered_template = read_file(path_joiner(self.work_dir)('template.txt'))51        self.assertEqual(self.expected_render, rendered_template.strip('\n'))52class TestDefaults(TestJinjaWalk):53    conf = {"key1": "value1", "key2": "value2"}54    list_of_dummy_subdirs = ['.', 'subdir1', 'subdir2']55    list_of_dummy_templates = ['template1.txt', 'template2.txt']56    def setUp(self) -> None:57        self.source_dir = tempfile.mkdtemp()58        self.conf_file_path = path_joiner(self.source_dir)('conf.ini')59        self.write_dummy_conf_file(self.conf_file_path, self.conf)60        subdirs_to_populate = map(path_joiner(self.source_dir), self.list_of_dummy_subdirs)61        for subdir in subdirs_to_populate:62            os.makedirs(subdir, exist_ok=True)63            templates_to_create = map(path_joiner(subdir), self.list_of_dummy_templates)64            for template_path in templates_to_create:65                self.expected_render = self.write_dummy_template(template_path, self.conf)66        self.output_dir = tempfile.mkdtemp()67    def tearDown(self) -> None:68        shutil.rmtree(self.source_dir)69        shutil.rmtree(self.output_dir)70    def test_subdirs(self):71        walker = JinjaWalk()72        walker.walk(self.conf_file_path, self.source_dir, self.output_dir)73        subdirs_to_check = map(path_joiner(self.output_dir), self.list_of_dummy_subdirs)74        for subdir in subdirs_to_check:75            rendered_templates_to_check = map(path_joiner(subdir), self.list_of_dummy_templates)76            for template_path in rendered_templates_to_check:77                with self.subTest(template=template_path):78                    rendered_template = read_file(template_path)...main.py
Source:main.py  
...39def create_python_package(40    path_joiner: Callable[..., Path],41    dirs: Sequence[str],42) -> None:43    dir_path = path_joiner(*dirs)44    dir_path.mkdir(parents=True, exist_ok=True)45    convert_dir_to_python_package(dir_path)46def render_with_ctx(47    jinja_env: Environment,48    template_data: TemplateData,49    context: dict[str, Any],50) -> str:51    return jinja_env.get_template(template_data.name).render(52        **extract_keys(context, template_data.context_keys)53    )54def create_from_template(55    path_joiner: Callable[..., Path],56    name_transformer: Callable[[str], str],57    jinja_env: Environment,58    template_data: TemplateData,59    context: dict[str, Any],60) -> None:61    actual = name_transformer(template_data.name)62    target_dir = template_data.target.format(**context)63    with path_joiner(target_dir, actual).open("w", encoding="utf-8") as f:64        f.write(render_with_ctx(jinja_env, template_data, context))65        f.write("\n")66@click.command()67@click.option(68    "--target-dir",69    "-t",70    default=".",71    type=str,72    show_default=True,73    help="Desired destination of the scaffolding.",74)75@click.option(76    "--line-length",77    "-l",...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!!
