Ejemplo n.º 1
0
def run_evosuite(evosuite_jar_path,
                 strategy,
                 projectCP,
                 class_name,
                 criterion,
                 epa_path,
                 inferred_epa_xml_path,
                 stopping_condition,
                 search_budget,
                 test_dir='test',
                 report_dir='report'):
    #is_JDBCResultSet = "JDBCResultSet" in class_name
    #extra_parameters = "-Dassertions=\"false\" -Dminimize=\"false\"" if is_JDBCResultSet else ""
    #extra_parameters = "-Dminimize=\"false\""
    extra_parameters = "-Dminimize=\"true\" -Dstop_zero=\"false\" -Djunit_allow_restricted_libraries=true -Duse_separate_classloader=\"false\" -Dwrite_covered_goals_file=\"false\" -Dwrite_all_goals_file=\"false\" -Dtest_archive=\"true\" -Dprint_missed_goals=\"true\" -Dno_runtime_dependency=\"true\" -Dshow_progress=\"false\" -Dassertions=\"true\" -Dcoverage=\"true\" -Dallows_actions_violates_precondition=\"false\""
    output_parameters = "-Doutput_variables=\"TARGET_CLASS,criterion,Coverage,Total_Goals,Covered_Goals,Generations,Total_Time\""
    #-Dextra_timeout=\"600\" for subjects as strbuilder
    timeout_parameters = "-Dtimeout=\"4000\" -Djunit_check_timeout=\"600\" -Dassertion_timeout=\"600\" -Dminimization_timeout=\"600\" -Dextra_timeout=\"600\""
    command = 'java -jar {} -projectCP {} -class {} -criterion {} -mem=\"4096\" -Dstopping_condition={} -Dsearch_budget={} {} -Dp_functional_mocking=\"0.0\" -Dfunctional_mocking_percent=\"0.0\" -Dvirtual_fs=\"false\" -Dp_reflection_on_private=\"0.0\" -Dtest_dir={} -Dreport_dir={} -Depa_xml_path={} -Dinferred_epa_xml_path={} {} {} {} > {}gen_out.txt 2> {}gen_err.txt'.format(
        evosuite_jar_path, projectCP, class_name, criterion,
        stopping_condition, search_budget, strategy, test_dir, report_dir,
        epa_path, inferred_epa_xml_path, extra_parameters, output_parameters,
        timeout_parameters, test_dir, test_dir)
    utils.print_command(command)
    try:
        subprocess.check_output(command, shell=True)
    except Exception as e:
        print(
            "Error al correr evosuite en la generacion de test con el comando '{}'. Error {}"
            .format(command, e))
Ejemplo n.º 2
0
def run_randoop(projectCP, class_name, randoop_jar_path, testdir,
                search_budget):
    def remove_randoop_error_test(testdir):
        for test in os.listdir(testdir):
            if "ErrorTest" in test:
                test_file = os.path.join(testdir, test)
                os.unlink(test_file)

            #if not test_file.endswith(".java"):
            #    continue
            #if not test[-1:].isdigit(): # Randoop generates a test file without tests.
            #    continue

    """def change_class_name(test_dir, new_classname):
        utils.rename_class(test_dir, "RegressionTest", new_classname)"""

    utils.make_dirs_if_not_exist(testdir)
    sep = os.path.pathsep
    err_file = os.path.join(testdir, "err.txt")
    out_file = os.path.join(testdir, "out.txt")
    package = class_name.split(".")[0:-1]
    packages_dir = utils.get_package_dir(package)
    command = 'java -classpath {}{}{} randoop.main.Main gentests --testclass={} --time-limit={} --usethreads=true --junit-package-name={} --npe-on-non-null-input=expected --junit-output-dir={} > {} 2> {}'.format(
        projectCP, sep, randoop_jar_path, class_name, search_budget,
        packages_dir.replace(os.path.sep, ".")[:-1], testdir, out_file,
        err_file)
    utils.print_command(command)
    try:
        subprocess.check_output(command, shell=True)
    except Exception as e:
        print("Error al correr randoop con el comando '{}'".format(command, e))
    testdir_full = os.path.join(testdir, packages_dir)
    remove_randoop_error_test(testdir_full)
Ejemplo n.º 3
0
def get_file_path_jncss(strategy, class_name, test_dir, results_dir_name,
                        bug_type, stopping_condition, search_budget, criterion,
                        runid, javancss_jar_path):
    package = class_name.split(".")[0:-1]
    package_dir = utils.get_package_dir(package)

    if "randoop".upper() in criterion.upper():
        only_class_name = "RegressionTest?.java"  #Randoop genera varios .java, c/u con 500 tests
    else:
        only_class_name = class_name.split(".")[-1] + "_ESTest.java"
    test_suite_file_path = os.path.join(test_dir, package_dir, only_class_name)

    result_jncss_temp = os.path.join(
        results_dir_name, "javancss_temp",
        "{}_{}_{}_{}_{}_{}".format(strategy, bug_type, stopping_condition,
                                   search_budget, class_name, criterion))
    utils.make_dirs_if_not_exist(result_jncss_temp)

    result_jncss_temp = os.path.join(result_jncss_temp, "{}.txt".format(runid))
    command = "java -jar {} {} > {}".format(javancss_jar_path,
                                            test_suite_file_path,
                                            result_jncss_temp)
    utils.print_command(command)
    utils.lock_if_windows()
    try:
        subprocess.check_output(command, shell=True)
    except Exception as e:
        print("Error al ejecutar el comando '{}'. Error {}".format(command, e))
    finally:
        utils.release_if_windows()
    return result_jncss_temp
Ejemplo n.º 4
0
def run_pitest(workdir):
    command = "mvn clean install org.pitest:pitest-maven:mutationCoverage > {}out.txt 2> {}err.txt".format(
        workdir, workdir)
    #Si quiero evitar limpiar lo generado (util para dejar algunas classya generados y usar eso para correr PIT
    #command = "mvn install org.pitest:pitest-maven:mutationCoverage > {}out.txt 2> {}err.txt".format(workdir, workdir)
    utils.print_command(command, workdir)
    try:
        subprocess.check_output(command, cwd=workdir, shell=True)
    except Exception as e:
        print("Error al correr pitest con el comando '{}'. Error {}".format(
            command, e))
Ejemplo n.º 5
0
def solve(stage):
    position, label = get_position_or_label(stage, display(stage))
    if position is not None:
        print_command(f'position {position}')
    else:
        print_command(f'label {label}')
    if stage < 5:
        if label is None:
            label = input_number('Label: ', size=1)
        else:
            position = input_number('Position: ', size=1)
        next_button(position, label)
        print()
Ejemplo n.º 6
0
def measure_evosuite(evosuite_jar_path, projectCP, testCP, class_name,
                     epa_path, report_dir, criterion):
    utils.make_dirs_if_not_exist(report_dir)
    err_file = os.path.join(report_dir,
                            criterion.replace(":", "_") + "_err.txt")
    out_file = os.path.join(report_dir,
                            criterion.replace(":", "_") + "_out.txt")
    sep = os.path.pathsep
    command = 'java -jar {}evosuite-master-1.0.4-SNAPSHOT.jar -projectCP {}{}{} -class {} -Depa_xml_path={} -criterion {} -Dwrite_covered_goals_file=\"true\" -Dwrite_all_goals_file=\"true\" -Dreport_dir={} -measureCoverage > {} 2> {}'.format(
        evosuite_jar_path, projectCP, sep, testCP, class_name, epa_path,
        criterion, report_dir, out_file, err_file)
    utils.print_command(command)
    subprocess.check_output(command, shell=True)
Ejemplo n.º 7
0
def copy_pitest_csv(name, workdir, all_report_dir):
    command = utils.find_and_save_command("*.csv", "sources.txt")
    utils.print_command(command, workdir)

    utils.lock_if_windows()
    subprocess.check_output(command, cwd=workdir, shell=True)
    utils.release_if_windows()

    with open(os.path.join(workdir, "sources.txt")) as file:
        for line in file:
            file_path = os.path.join(workdir, line[2:-1])
            if 'mutations' in line:
                copy_csv(file_path, '{}_mutations'.format(name),
                         all_report_dir)
            elif 'jacoco' in line:
                copy_csv(file_path, '{}_jacoco'.format(name), all_report_dir)
Ejemplo n.º 8
0
def settings():
    global direction, PIN

    DIRECTIONS = {'0': 'North', '1': 'East', '2': 'South', '3': 'West'}

    def get_direction():
        serial = ''
        while len(serial) < 2:
            serial = input('First 2 characters of Serial#: ')
        serial = serial[:2]
        if serial[0].isdigit():
            if serial[1].isdigit():
                return 3
            return 2
        if serial[1].isdigit():
            return 1
        return 0

    if direction is None:
        # Obtain direction
        direction = get_direction()
        if ask('Parallel port?'):
            direction = ((direction - 1) + 4) % 4  # move counter-clockwise
        elif ask('Serial port?'):
            direction = (direction + 1) % 4  # move clockwise
    direction_name = DIRECTIONS[str(direction)]
    print_info(direction_name)

    def append_pin_digit(apps, msg):
        global PIN
        print_apps(apps)
        app = input_app(apps, msg)
        PIN += str(APPS[app])
        apps.remove(app)

    remaining = remaining_apps()
    if len(remaining) == 1 and remaining[0] == 'Settings':
        # Determine order of submission
        apps = set(APPS.keys())
        append_pin_digit(apps, f'App ({direction_name} from center)')
        while len(apps) > 1:
            append_pin_digit(apps, 'Next App (Clockwise)')
        if len(apps) == 1:
            PIN += str(APPS[apps.pop()])
        print_command(f'submit {PIN}')
    else:
        print_info('Solve remaining apps before submit')
Ejemplo n.º 9
0
def run_evosuite(evosuite_jar_path,
                 projectCP,
                 class_name,
                 criterion,
                 epa_path,
                 stopping_condition,
                 search_budget,
                 test_dir='test',
                 report_dir='report'):
    #is_JDBCResultSet = "JDBCResultSet" in class_name
    #extra_parameters = "-Dassertions=\"false\" -Dminimize=\"false\"" if is_JDBCResultSet else ""
    command = 'java -jar {}evosuite-master-1.0.4-SNAPSHOT.jar -projectCP {} -class {} -criterion {} -Dstopping_condition={} -Dsearch_budget={} -Djunit_allow_restricted_libraries=true -Dp_functional_mocking=\"0.0\" -Dp_reflection_on_private=\"0.0\" -Duse_separate_classloader=\"false\" -Dwrite_covered_goals_file=\"false\" -Dwrite_all_goals_file=\"false\" -Dprint_missed_goals=\"true\" -Dtest_dir={} -Dreport_dir={} -Depa_xml_path={} -Dno_runtime_dependency=\"true\" -Dshow_progress=\"false\" -Dtimeout="300" -Doutput_variables=\"TARGET_CLASS,criterion,Coverage,Total_Goals,Covered_Goals,Generations,Total_Time\" -Dassertions=\"true\" -Dminimize=\"true\" -Dcoverage=\"true\" -Djunit_check_timeout="600" -Dassertion_timeout="600" > {}gen_out.txt 2> {}gen_err.txt'.format(
        evosuite_jar_path, projectCP, class_name, criterion,
        stopping_condition, search_budget, test_dir, report_dir, epa_path,
        test_dir, test_dir)
    utils.print_command(command)
    subprocess.check_output(command, shell=True)
Ejemplo n.º 10
0
def measure_evosuite(evosuite_jar_path, projectCP, testCP, class_name,
                     epa_path, report_dir, criterion, inferred_epa_xml_path,
                     force_inferred_epa):
    utils.make_dirs_if_not_exist(report_dir)
    err_file = os.path.join(report_dir,
                            criterion.replace(":", "_") + "_err.txt")
    out_file = os.path.join(report_dir,
                            criterion.replace(":", "_") + "_out.txt")
    sep = "" if projectCP[-1] == os.path.pathsep else os.path.pathsep
    command = 'java -jar {} -projectCP {}{}{} -class {} -Depa_xml_path={} -criterion {} -Dwrite_covered_goals_file=\"true\" -Dwrite_all_goals_file=\"true\" -Dreport_dir={} -Dforce_inferred_epa={} -Dinferred_epa_xml_path={} -Dallows_actions_violates_precondition=\"false\" -measureCoverage > {} 2> {}'.format(
        evosuite_jar_path, projectCP, sep, testCP, class_name, epa_path,
        criterion, report_dir, force_inferred_epa, inferred_epa_xml_path,
        out_file, err_file)
    utils.print_command(command)
    try:
        subprocess.check_output(command, shell=True)
    except Exception as e:
        print(
            "Error al correr evosuite en la medicion de cobertura con el comando '{}'"
            .format(command, e))
Ejemplo n.º 11
0
def pitest_measure(pitest_dir, targetClasses, targetTests, class_dir,
                   test_dir):
    generate_pitest_workdir(pitest_dir)
    edit_pit_pom('pit_pom.xml', targetClasses, targetTests,
                 os.path.join(pitest_dir, "pom.xml"))

    pitest_dir_src_main_java = os.path.join(pitest_dir, "src", "main", "java")
    command_copy_source = 'cp -r {}/* {}'.format(class_dir,
                                                 pitest_dir_src_main_java)
    utils.print_command(command_copy_source)
    # Si existe el directorio lo elimino (sino tira error shutil.copytree)
    if os.path.exists(pitest_dir_src_main_java):
        shutil.rmtree(pitest_dir_src_main_java)
    shutil.copytree(class_dir, pitest_dir_src_main_java)

    pitest_dir_src_test_java = os.path.join(pitest_dir, "src", "test", "java")
    command_copy_test = 'cp -r {}/* {}'.format(test_dir,
                                               pitest_dir_src_test_java)
    utils.print_command(command_copy_test)
    if os.path.exists(pitest_dir_src_test_java):
        shutil.rmtree(pitest_dir_src_test_java)
    shutil.copytree(test_dir, pitest_dir_src_test_java)

    run_pitest(os.path.join(pitest_dir, ""))
Ejemplo n.º 12
0
            current = prev
            prev = previous[current[0]][current[1]]
        path.append(('S', start_pos))
        path.reverse()
        return path

    # BFS
    q = deque()
    q.append(start_pos)

    while len(q) > 0:
        pos = q.popleft()
        for neighbour in get_neighbours(pos):
            if previous[neighbour[0]][neighbour[1]] is None:
                previous[neighbour[0]][neighbour[1]] = pos
                if neighbour == end_pos:
                    return build_path()
                q.append(neighbour)


if __name__ == "__main__":
    start = input('Display: ')
    end = input('Last digit of Serial#: ')
    path = get_path(start, end)
    if path:
        dir_path = ''.join(list(map(lambda dir_pos: dir_pos[0], path[1:])))
        dir_path = dir_path[::2]  # Remove wall rows/cols
        print_command(dir_path)
    else:
        print_info('No solution. Please check input.')
Ejemplo n.º 13
0
def run_pitest(workdir):
    command = "mvn clean install org.pitest:pitest-maven:mutationCoverage > {}out.txt 2> {}err.txt".format(
        workdir, workdir)
    utils.print_command(command, workdir)
    subprocess.check_output(command, cwd=workdir, shell=True)
Ejemplo n.º 14
0
    def run(self):
        if self.method in [
                EpatestingMethod.ONLY_TESTGEN.value,
                EpatestingMethod.BOTH.value,
                EpatestingMethod.BOTH_WITHOUT_MUJAVA.value
        ]:
            print('GENERATING TESTS')
            code_dir = self.instrumented_code_dir if "epa" in self.criterion else self.original_code_dir
            bin_code_dir = self.bin_instrumented_code_dir if "epa" in self.criterion else self.bin_original_code_dir

            # if exists testsuite in other bug_type, copy it!
            testsuite_exists = False
            curr_bug_type = self.bug_type
            try:
                lock.acquire()
                testsuite_exists = cp_testsuite_if_exists_in_other_results(
                    curr_bug_type, self.subdir_testgen,
                    self.generated_test_report_evosuite_dir, self.class_name,
                    self.class_name.split(".")[-1])
            except:
                testsuite_exists = False
                print("error copying from other bug_type folder to {}".format(
                    self.subdir_testgen))
            finally:
                lock.release()

            if (not testsuite_exists):
                run_evosuite(
                    evosuite_jar_path=self.evosuite_jar_path,
                    projectCP=bin_code_dir,
                    class_name=self.class_name,
                    criterion=self.criterion,
                    epa_path=self.epa_path,
                    test_dir=self.generated_test_dir,
                    stopping_condition=self.stopping_condition,
                    search_budget=self.search_budget,
                    report_dir=self.generated_test_report_evosuite_dir)

            add_fails = False
            if (self.bug_type.upper() == BugType.ERRPROT.name):
                # If is run in errprot mode, then always remove asserts and specific exceptions
                self.assert_type = AssertType.NO_ASSERT_EXCEPTION.name
                #if("JDBCResultSet" in self.name):
                #add_fails= True;
            if self.assert_type.upper() in [
                    AssertType.NO_ASSERT.name,
                    AssertType.NO_ASSERT_EXCEPTION.name
            ]:
                workaround_test(
                    self.generated_test_dir, self.class_name,
                    self.class_name.split(".")[-1] + "_ESTest.java", add_fails,
                    self.assert_type)

            utils.compile_test_workdir(self.generated_test_dir, code_dir,
                                       self.junit_jar, self.evosuite_classes,
                                       self.evosuite_runtime_jar_path)

        if self.method in [
                EpatestingMethod.ONLY_METRICS.value,
                EpatestingMethod.BOTH.value,
                EpatestingMethod.BOTH_WITHOUT_MUJAVA.value,
                EpatestingMethod.ONLY_METRICS_WITHOUT_MUJAVA.value
        ]:
            print('GENERATING METRICS')
            if not os.path.exists(self.subdir_testgen):
                print("not found testgen folder ! '{}'".format(
                    self.subdir_testgen))
                exit(1)

            measure_evosuite(evosuite_jar_path=self.evosuite_jar_path,
                             projectCP=self.bin_instrumented_code_dir,
                             testCP=self.generated_test_dir,
                             class_name=self.class_name,
                             epa_path=self.epa_path,
                             report_dir=self.generated_report_evosuite_dir,
                             criterion="epatransition")
            measure_evosuite(evosuite_jar_path=self.evosuite_jar_path,
                             projectCP=self.bin_instrumented_code_dir,
                             testCP=self.generated_test_dir,
                             class_name=self.class_name,
                             epa_path=self.epa_path,
                             report_dir=self.generated_report_evosuite_dir,
                             criterion="epaexception")
            measure_evosuite(evosuite_jar_path=self.evosuite_jar_path,
                             projectCP=self.bin_instrumented_code_dir,
                             testCP=self.generated_test_dir,
                             class_name=self.class_name,
                             epa_path=self.epa_path,
                             report_dir=self.generated_report_evosuite_dir,
                             criterion="epaadjacentedges")

            # Run Pitest to measure
            pitest_measure(self.generated_report_pitest_dir, self.class_name,
                           "{}_ESTest".format(self.class_name),
                           self.original_code_dir, self.generated_test_dir)

            if self.method in [
                    EpatestingMethod.ONLY_METRICS.value,
                    EpatestingMethod.BOTH.value
            ]:
                mujava_measure(self.bug_type, self.name, self.criterion,
                               self.subdir_mutants, self.error_prot_list,
                               self.ignore_mutants_list,
                               self.bin_original_code_dir,
                               self.generated_test_dir, self.class_name,
                               self.junit_jar, self.hamcrest_jar_path,
                               self.generated_report_mujava)

            # Resume the reports generated
            all_report_dir = os.path.join(self.subdir_metrics, 'all_reports')
            command_mkdir_report = 'mkdir {}'.format(all_report_dir)
            utils.print_command(command_mkdir_report)
            if not os.path.exists(all_report_dir):
                os.makedirs(all_report_dir)

            copy_pitest_csv(self.name, self.generated_report_pitest_dir,
                            all_report_dir)

            statistics_csv = os.path.join(self.generated_report_evosuite_dir,
                                          "statistics.csv")
            copy_csv(statistics_csv, 'epacoverage_{}'.format(self.name),
                     all_report_dir)
            statistics_testgen_csv = os.path.join(
                self.generated_test_report_evosuite_dir, "statistics.csv")
            copy_csv(statistics_testgen_csv,
                     'statistics_testgen_{}'.format(self.name), all_report_dir)

            mujava_csv = os.path.join(self.generated_report_mujava,
                                      "mujava_report.csv")
            if os.path.exists(mujava_csv):
                copy_csv(mujava_csv, 'mujava_{}'.format(self.name),
                         all_report_dir)
            else:
                print("Does not exists mujava file {}".format(mujava_csv))

            epacoverage_csv = os.path.join(
                all_report_dir, "epacoverage_{}.csv".format(self.name))
            statistics_testgen_csv = os.path.join(
                all_report_dir, "statistics_testgen_{}.csv".format(self.name))
            jacoco_csv = os.path.join(all_report_dir,
                                      "{}_jacoco.csv".format(self.name))
            mutations_csv = os.path.join(all_report_dir,
                                         "{}_mutations.csv".format(self.name))
            resume_csv = os.path.join(self.subdir_metrics, 'resume.csv')
            criterion = get_alternative_criterion_names(self.criterion)

            #if self.bug_type.upper() == BugType.ALL.name:
            pit_mutants_histogram(self.criterion, self.search_budget,
                                  self.stopping_condition, mutations_csv,
                                  self.generated_test_dir,
                                  self.generated_pitest_killer_test,
                                  self.runid)

            make_report_resume(self.class_name, epacoverage_csv,
                               statistics_testgen_csv, jacoco_csv,
                               mutations_csv, resume_csv, self.runid,
                               self.stopping_condition, self.search_budget,
                               criterion, self.bug_type, mujava_csv)

        if self.method in [EpatestingMethod.ONLY_PIT_MUTANTS_HISTOGRAM.value]:
            mutations_csv = get_mutation_csv_pit(
                self.generated_report_pitest_dir)
            pit_mutants_histogram(self.criterion, self.search_budget,
                                  self.stopping_condition, mutations_csv,
                                  self.generated_test_dir,
                                  self.generated_pitest_killer_test,
                                  self.runid)
Ejemplo n.º 15
0
def copy_csv(file_path, file_name, all_report_dir):
    dest = os.path.join(all_report_dir, "{}.csv".format(file_name))
    command = 'cp {} {}'.format(file_path, dest)
    utils.print_command(command)
    shutil.copyfile(file_path, dest)
Ejemplo n.º 16
0
def generate_pitest_workdir(pitest_dir):
    # To generate the pitest workdir we need the following hierachy:
    # pom.xml
    # src/main/java/ < source code we want to test
    # src/test/java/ < testsuite
    command_mkdir_home = "mkdir {}".format(pitest_dir)
    utils.print_command(command_mkdir_home)
    if not os.path.exists(pitest_dir):
        os.makedirs(pitest_dir)
    pitest_dir_src = os.path.join(pitest_dir, "src")
    command_mkdir_src = "mkdir {}".format(pitest_dir_src)
    utils.print_command(command_mkdir_src)
    if not os.path.exists(pitest_dir_src):
        os.makedirs(pitest_dir_src)

    pitest_dir_src_main = os.path.join(pitest_dir, "src", "main")
    command_mkdir_src_main = "mkdir {}".format(pitest_dir_src_main)
    utils.print_command(command_mkdir_src_main)
    if not os.path.exists(pitest_dir_src_main):
        os.makedirs(pitest_dir_src_main)

    pitest_dir_src_main_java = os.path.join(pitest_dir, "src", "main", "java")
    command_mkdir_src_main_java = "mkdir {}".format(pitest_dir_src_main_java)
    utils.print_command(command_mkdir_src_main_java)
    if not os.path.exists(pitest_dir_src_main_java):
        os.makedirs(pitest_dir_src_main_java)

    pitest_dir_src_test = os.path.join(pitest_dir, "src", "test")
    command_mkdir_src_test = "mkdir {}".format(pitest_dir_src_test)
    utils.print_command(command_mkdir_src_test)
    if not os.path.exists(pitest_dir_src_test):
        os.makedirs(pitest_dir_src_test)

    pitest_dir_src_test_java = os.path.join(pitest_dir, "src", "test", "java")
    command_mkdir_src_test_java = "mkdir {}".format(pitest_dir_src_test_java)
    utils.print_command(command_mkdir_src_test_java)
    if not os.path.exists(pitest_dir_src_test_java):
        os.makedirs(pitest_dir_src_test_java)
Ejemplo n.º 17
0
  if len(set(buttons)) != len(buttons):
    return []
  def get_order(pressed):
    adjacents = get_available_adjacents(buttons, pressed)
    candidates = adjacents if pressed else buttons
    for candidate in candidates:
      if not pressed or is_next(pressed[-1], candidate):
        order = get_order(pressed + [candidate])
        if len(order) == len(buttons):
          return order
    return pressed
  return get_order([])

def get_positions(order, buttons):
  return map(lambda button: order.index(button) + 1, buttons)

def get_sin_list(buttons):
  return ' '.join(map(lambda n: SINS[n].colored_name(), list(buttons)))

if __name__ == "__main__":
  print_info('Input buttons order going clockwise starting from the top left.')
  print_info('\n'.join(map(lambda sin: f'{sin[0]}: {sin[1]!r}', SINS.items())))
  buttons = input('Current buttons order: ').replace(' ', '')
  print_info(get_sin_list(buttons))
  solution = solve(buttons)
  if solution:
    print_command(f"press {' '.join(list(map(str, get_positions(buttons, solution))))}")
    print(get_sin_list(solution))
  else:
    print_info('No solution. Please check input.')
Ejemplo n.º 18
0
def create_project(project_name, default, helloworld, api, spa):
    """
    This function is responsible for interacting user with file creation.
    Args:
        project_name (string): This is the project name that will be used for project creation.
        api (bool): This flag says if project is going to have api-like boilerplate structure.
        spa (bool): This flag says if project is going to have spa-like boilerplate structure.

    Raises:
        FileExistsError: If project_name param has the same value as some of the directories in the current directory.

    """
    # getting arguments and options from the locals() function
    options = locals()
    # project_name is removed since we want to browse through options and project_name isn't necessary
    options.pop('project_name')

    # if none of the options was selected, fall back to default
    if [i for i in options.values()].count(True) == 0:
        options['default'] = True

    # seeing if there are more than 2 options selected
    elif [i for i in options.values()].count(True) > 1:
        error_exit("Please make sure only 1 option is selected and try again.")

    # seeing if project_name matches any of directories in the current directory
    try:
        create_folder(project_name)

    except FileExistsError:
        error_exit(
            'That directory already exists. Please check your project name and try again.'
        )

    # printing when project creation is starting
    click.echo(NEWLINE + 'Creating a new Flask app in ' +
               colored(f'~/{project_name}', 'green') + '.')
    click.echo(NEWLINE)

    # create venv if helloworld option is not selected
    if not helloworld:
        create_venv(f'./{project_name}/venv/')

    # deciding which boilerplate to choose and creating it based on argument choice
    base_dir = os.path.dirname(__file__)

    # iterating over names and values in options dictionary
    for name, value in options.items():
        if value:
            choice = os.path.join(base_dir, name)
    # copy the boilerplate filetree to the project folder
    try:
        copy_filetree(choice, f"./{project_name}/")
    except Exception as e:
        error_exit(e)

    # output hell starts here
    click.echo(f'Success! Created app {project_name} in {os.getcwd()}' +
               f'/{project_name}')
    click.echo('Inside that directory you can run several commands:')
    click.echo(NEWLINE)

    # print commands and descriptions
    print_command('python run.py',
                  'Starts the server, default config is set to development.')
    if not helloworld:

        print_command('export secret_key=STRING',
                      'Sets the secret key for your app.')

        print_command(
            'export PRODUCTION=True',
            'Sets production config for your app. Setting it to False will set the development config.'
        )

        print_command(
            'source venv/bin/activate (unix) \n\t./venv/Scripts/activate  (windows)',
            'Activate the virtual enviroment for the app.')

        print_command(
            'pip install -r requirements.txt',
            'Install the packages listed in requirements.txt into the venv.')

        click.echo('We suggest that you start by typing:')
        click.echo(colored('\tcd ', 'cyan') + colored(project_name, 'white'))
        click.echo(
            colored(
                '\tsource venv/bin/activate' if not system() == 'Windows' else
                '\t./venv/Scripts/activate', 'cyan'))
        click.echo(
            colored('\tpip install -r ', 'cyan') +
            colored('requirements.txt', 'white'))
        click.echo(colored('\tpython run.py', 'cyan'))
    else:
        click.echo('We suggest that you start by typing:')
        click.echo(colored('\tcd ', 'cyan') + colored(project_name, 'white'))
        click.echo(colored('\tpip install flask ', 'cyan'))
        click.echo(colored('\tpython app.py'))

    click.echo(NEWLINE + 'Happy hacking!')
Ejemplo n.º 19
0
    funni -= len(get_divisors(n, UNFUNNY))
    # If the number is even subtract one funni point, otherwise add 1 funni point.
    if n % 2 == 0:
        funni -= 1
    else:
        funni += 1
    # If the number is prime, add 2 funni points.
    if is_prime(n):
        funni += 2
    # If the number is a perfect square, subtract 2 funni points.
    root = sqrt(n)
    if root == int(root):
        funni -= 2
        # If the number is the square of a prime, subtract another 2 funni points.
        if is_prime(root):
            funni -= 2
    print_info(funni)
    return funni > 0


if __name__ == "__main__":
    try:
        print_info('Press Ctrl+C to cancel')
        for i in range(5):
            if is_funny(input_number('Number: ')):
                print_command('funny')
            else:
                print_command('unfunny')
    except KeyboardInterrupt:
        pass
Ejemplo n.º 20
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-

# https://ktane.timwi.de/HTML/Prime%20Checker.html

from math_utils import is_prime
from utils import input_number, print_info, print_command

if __name__ == "__main__":
    try:
        print_info('Press Ctrl+C to cancel')
        while True:
            n = input_number('Number: ')
            if is_prime(n):
                print_command('prime')
            else:
                print_command('not prime')
    except KeyboardInterrupt:
        pass