示例#1
0
def run(logfile, loglevel):

    if logfile is None or len(logfile) == 0:
        print ("Missing log file specification", file=sys.stderr)
        return 4

    # Configure the root logger and set up own logger
    #
    set_logging_paradigm(logfile, loglevel)

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    print ("%s version %s" % (program_name, __version__), file=sys.stdout)
    sys.stdout.flush()

    logger.info("%s version %s" % (program_name, __version__))

    main.execute()

    # We always log start and stop.
    #
    logger.info("%s complete\n" % program_name)
    print ("%s complete\n" % program_name)
    return 0
示例#2
0
    def test_variable_not_defined(self, mocked_print):
        program = """ run away with a;"""
        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "VariableNotDefinedException line 1: The variable a is not defined."
        )
示例#3
0
    def test_missing_semicolon(self, mocked_print):
        program = """ run away with "string" + 5"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "SyntaxException in line 1:27 missing ';' at '<EOF>'")
示例#4
0
    def test_division_by_zero(self, mocked_print):
        program = """ 7/0;"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "DivisionByZeroException line 1: Division by 0")
示例#5
0
    def process(self):
        """
        should take in filename, # of lanes, # of lines per group,
        use those to iterate through each entry and collect points.
        Use point data with vid_x, vid_y size to get ratio
        Send to other video processing function for process.
        """
        # Loop to create data locations
        start_row = 3
        start_col = 6
        direction_and_lines = []
        for group in range(self.num_of_groups):
            # collect the locations of lines
            lines = []
            for line_num in range(self.num_of_lines_per_group):
                one_line = [int(num.strip()) for num in self.entry_strvars[group][line_num].get().split(',')]
                one_line[0] /= vid_x
                one_line[1] /= vid_y
                one_line[2] /= vid_x
                one_line[3] /= vid_y
                lines.append(one_line)

            direction_and_lines.append({"direction": self.direction_vars[group].get(), "lines": lines})

        # TODO: add an entry to enter the output file name
        execute(os.getcwd(), self.filename, "result.txt", 0, direction_and_lines)
示例#6
0
def test(path, verbose=False):
    with open(path, "r") as f:
        _, source, expected = f.read().split("###", 2)
        expected = expected.strip()

        old_stdout = sys.stdout
        sys.stdout = actual = StringIO()

        opt = False
        if expected.startswith("OPTIMIZE"):
            opt = True
            expected = expected[8:].strip()

        lexer_output = expected.startswith("LEXER OUTPUT")
        execute(Scope(),
                source,
                draw=False,
                lexer_output=lexer_output,
                opt=opt)

        sys.stdout = old_stdout
        actual = actual.getvalue().strip()

        path = str(path)

        print(path + Fore.BLUE + "." * (40 - len(path)), end="")
        if actual == expected:
            print(Fore.GREEN + "PASS" + Style.RESET_ALL)
        else:
            print(Fore.RED + "FAIL" + Style.RESET_ALL)
            if verbose:
                print("=" * 10 + "Expected" + "=" * 10)
                print(Fore.GREEN + expected + Style.RESET_ALL)
                print("=" * 10 + " Actual " + "=" * 10)
                print(Fore.YELLOW + actual + Style.RESET_ALL)
示例#7
0
def run(logfile, loglevel):

    if logfile is None or len(logfile) == 0:
        print("Missing log file specification", file=sys.stderr)
        return 4

    # Configure the root logger and set up own logger
    #
    set_logging_paradigm(logfile, loglevel)

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    print("%s version %s" % (program_name, __version__), file=sys.stdout)
    sys.stdout.flush()

    logger.info("%s version %s" % (program_name, __version__))

    main.execute()

    # We always log start and stop.
    #
    logger.info("%s complete\n" % program_name)
    print("%s complete\n" % program_name)
    return 0
示例#8
0
def run(event, arg):

    # Verify input Word document
    if not input_doc_entry.get().endswith('.docx'):
        log.log_data("Error: Expected Word file extension \
                     '.docx' for first argument")
        showinfo(
            "Window", "Expected Word file extension \
                 '.docx' for first argument")
        return

    # Verify BibTeX database
    if not input_bib_entry.get().endswith('.bib'):
        log.log_data("Error: Expected BibTeX file extension \
                     '.bib' for second argument")
        showinfo(
            "Window", "Expected BibTeX file extension \
                 '.bib' for second argument")
        return

    # Verify output Word document
    if not output_doc_entry.get().endswith('.docx'):
        log.log_data("Error: Expected Word file extension \
                     '.docx' for fourth argument")
        showinfo(
            "Window", "Expected Word file extension \
                 '.docx' for fourth argument")
        return

    main.execute(input_bib_entry.get(), input_doc_entry.get(), initial.get(),
                 output_doc_entry.get(), log)
    showinfo("Window", "Execution is complete! :)")
    return
示例#9
0
    def test_function_not_defined(self, mocked_print):
        program = """ run away with pipo();"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "FunctionNotDefinedException line 1: Function pipo not defined.")
示例#10
0
def get_latest():
    # set_path()
    if version.get() == "":
        hintLabel["text"] = "必须填写Version! 请按照当前版本填,如0.6.0"
        hintLabel["fg"] = "red"
        return

    global done_flag
    if done_flag:
        hintLabel["text"] = ""
        a = tkinter.messagebox.askokcancel(
            '警告', '您已成功生成了一次表格,再次生成可能会覆盖修改的颜色提示信息,确认要生成吗?')
        if not a:
            return

    error.Error.set_code(-1, "")
    hintLabel["text"] = ""
    main.execute(gl.csv_dir, gl.index_file, gl.trans_file, version.get())
    error_code = error.Error.get_code()
    if error_code == -1:
        hintLabel["text"] = "Success!"
        hintLabel["fg"] = "green"
        done_flag = True
    else:
        hintLabel["text"] = "[Error " + str(
            error_code) + "] " + error.Error.get_info(error_code)
        hintLabel["fg"] = "red"
    def insert_data(self):
        output.append(False)

        if self.kmeans_state:
            if self.optimized1:
                clust_param.get('KMeans').append(self.optimized1)
            else:
                clust_param.get('KMeans').append(self.num_clusters)
                clust_param.get('KMeans').append(self.optimized1)
        else:
            pass

        if self.dbscan_state:
            if self.optimized2:
                clust_param.get('DBSCAN').append(self.optimized2)
            else:
                clust_param.get('DBSCAN').append(self.eps)
                clust_param.get('DBSCAN').append(self.min_samples)
                clust_param.get('DBSCAN').append(self.optimized2)
        else:
            pass

        global is_kmeans
        is_kmeans = self.kmeans_state
        global is_dbscan
        is_dbscan = self.dbscan_state

        output.append(clust_param)

        if self.kmeans_state and not self.dbscan_state:
            kmeanstext = open("KMeans.txt", "w+")
            label1list = execute(output)

            for i in label1list:
                kmeanstext.write(i)
            kmeanstext.close()

        if self.dbscan_state and not self.kmeans_state:
            dbscantext = open("DBSCAN.txt", "w+")
            label1list = execute(output)

            for i in label1list:
                dbscantext.write(i)
            dbscantext.close()

        if self.dbscan_state and self.kmeans_state:
            kmeanstext = open("KMeans.txt", "w+")
            dbscantext = open("DBSCAN.txt", "w+")
            labellist = execute(output)
            label1list = labellist[0]
            label2list = labellist[1:]

            for i in label1list:
                kmeanstext.write(i)
            kmeanstext.close()

            for i in label2list:
                dbscantext.write(i)
            dbscantext.close()
示例#12
0
    def test_function_not_callable(self, mocked_print):
        program = """ a == 3;
                         a();"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "NotCallableException line 2: The variable a is not callable.")
示例#13
0
    def test_operation_not_supported(self, mocked_print):
        program = """ run away with "string" * 5;"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "OperationNotSupportedException line 1: Operation * can't be applied to STRING and NUMBER"
        )
示例#14
0
    def test_method_not_defined(self, mocked_print):
        program = """ a == 3;
                      a.platypus();"""

        execute(InputStream(program), False)
        mocked_print.assert_called_once_with(
            "AttributeNotDefinedException line 2: Object a of type NUMBER doesn't have an attribute platypus."
        )
示例#15
0
    def test_evaluate_y_none(self, mocked_print):
        program = """ 
                          evalY(None);"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "ValueException line 2: Cannot evaluate a non quantic value.")
示例#16
0
 def test_search_name_success_2(self):
     """
     searching a name in trie which exists in it.
     """
     inserting_name = execute(1, ['Alex'], self.trie_obj)
     res = execute(2, ['Alex'], self.trie_obj)
     correct_res = ['Alex']
     self.assertEqual(res, correct_res)
示例#17
0
 def test_search_name_fail(self):
     """
     searching a name in trie which does not exists in it.
     """
     inserting_name = execute(1, ['Donald'], self.trie_obj)
     res = execute(2, ['Trump'], self.trie_obj)
     correct_res = []  # empty List
     self.assertEqual(res, correct_res)
示例#18
0
    def test_list_get_index_out_of_range(self, mocked_print):
        program = """
                      list == [3,4];
                      list.get(9);
                  """
        execute(InputStream(program))

        mocked_print.assert_called_once_with(
            "ValueException line 3: Index 9 out of range (length of list = 2).")
示例#19
0
    def test_quantic_boolean_to_float(self, mocked_print):
        program = """ 
                      float(yTrue);"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "EvaluateQuanticBooleanException line 2: Quantic booleans can't be evaluated or operated as regular booleans. Use evalX() or evalY() to evaluate them first."
        )
示例#20
0
    def test_range_end_not_a_number(self, mocked_print):
        program = """
                              range(6,"Hey listen");

                              """

        execute(InputStream(program), False)
        mocked_print.assert_called_once_with(
            "ValueException line 2: The start and end in range() must be integers."
        )
示例#21
0
    def test_list_remove_not_contained(self, mocked_print):
        program = """
                          e == [];
                          e.remove(9);
                          run away with e;
                   """
        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "ElementNotContainedException line 3: The list e doesn't contain 9")
示例#22
0
    def test_range_end_not_integer_but_number(self, mocked_print):
        program = """
                          range(3,6.3);

                          """

        execute(InputStream(program), False)
        mocked_print.assert_called_once_with(
            "ValueException line 2: The end value in range() must be an integer."
        )
示例#23
0
    def test_random_string_to_integer(self, mocked_print):
        program = """
                        int("ehenistl y");

                 """

        execute(InputStream(program), False)
        mocked_print.assert_called_once_with(
            "ValueException line 2: The string/variable 'ehenistl y' can't be transformed to integer."
        )
示例#24
0
    def test_object_to_integer(self, mocked_print):
        program = """
                          int(object());

                   """

        execute(InputStream(program), False)
        mocked_print.assert_called_once_with(
            "ValueException line 2: Cannot transform an object of type OBJECT to integer."
        )
示例#25
0
    def test_import_file_not_found(self, mocked_print):
        program = """
                   import "./thisfileshouldntexist/nope/pizza" as smth;

                   run away with [imported.value, imported.plus6(4)];
               """

        execute(InputStream(program), False)
        mocked_print.assert_called_with(
            "FileNotFoundException line 2: File .\\./thisfileshouldntexist/nope/pizza not found."
        )
示例#26
0
    def test_evaluate_quantic_boolean_in_condition(self, mocked_print):
        program = """ 
                    if not xTrue{
                        run away with 6;
                    }"""

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "EvaluateQuanticBooleanException line 2: Quantic booleans can't be evaluated or operated as regular booleans. Use evalX() or evalY() to evaluate them first."
        )
示例#27
0
    def test_variables_cant_start_with_number(self):
        program = """
                         6a == 3;
                         """

        with self.assertRaises(ConfProlSyntaxError) as e:
            execute(InputStream(program), True)

        self.assertIn(
            "SyntaxException in line 2:25 mismatched input '6a' expecting",
            e.exception.get_message())
示例#28
0
    def test_list_insert_first_argument_not_integer(self,mocked_print):
        program = """
                            list == [3,4];
                            list.insert(3.1,"VALUE");
                            run away with list;

                                      """
        execute(InputStream(program))

        mocked_print.assert_called_once_with(
            "ValueException line 3: The first argument of the method 'insert' must be an integer")
示例#29
0
    def test_import_directory(self, mocked_print):
        program = """
                           import "REPLACE_PATH" as foo;
                       """

        path = os.path.join(self.test_path, "samples")
        program = program.replace("REPLACE_PATH", path)
        execute(InputStream(program), False)
        mocked_print.assert_called_with(
            f"CannotOpenDirectoryException line 2: The directory {path} can't be opened or imported."
        )
示例#30
0
    def test_has_attribute_second_argument_not_string(self, mocked_print):
        program = """
                            a == object();
                            has_attribute(a,3.0);              

                            """

        execute(InputStream(program), False)
        mocked_print.assert_called_once_with(
            "ValueException line 3: The second argument of the function 'has_attribute' must be a string"
        )
示例#31
0
    def test_duplicated_parameters(self, mocked_print):
        program = """ funko thisIsAFunction(param,param){

                        }
                  """

        execute(InputStream(program), False)

        mocked_print.assert_called_once_with(
            "SyntaxException in line 1:1 Duplicated parameter {'param'} in function thisIsAFunction."
        )
示例#32
0
def _event_cb(topic, msg):
  # msg is storage ident
  path = os.path.join(__ROOT__, __MOUNT_BASE__, msg)
  logging.info("Event topic : %s, msg : %s, path : %s", topic, msg, path)

  if topic == __MOUNT_ADD_TOPIC__:
    if path not in __DATA__.storage_list:
      __DATA__.storage_list.append(path)
      main.execute(path)
    logging.info("Success mount add event.")
  elif topic == __MOUNT_REMOVE_TOPIC__:
    if path in __DATA__.storage_list:
      __DATA__.storage_list.remove(path)
    logging.info("Success mount remove event.")
 def testEquivalence(self):
   targets = [RBMOneSide, SumAmultA, RBM, SumAAT, SumAB, Sym]
   for target in targets:
     manage.config.EXPR_IMPL = ExprZp
     scheduler = NgramScheduler
     params = {'depth': 5, 'trials': 1}
     matlab = execute(scheduler, params, target, maxpower=4, record_it=False)[0]["matlab"]
     for i, m in enumerate(matlab):
       f = open('code.m', 'w')
       original = target(i + 1).GetTargetExpression()
       code = ""
       code += original.comp[MATLAB] + "\n"
       code += "optimized = "
       expr = ""
       for w, c in m:
         if len(expr) > 0:
           expr += " + "
         expr += "%s * (%s)" % (ExprZp.ToFrac(w), c)
       if target == RBM:
         expr = "2^(n + m - %d) * (%s)" % (manage.config.N + manage.config.M, expr)
       if target == RBMOneSide:
         expr = "2^(n - %d) * (%s)" % (manage.config.M, expr)
       code += expr + ";\n"
       code += "assert(sum(abs(original(:) - optimized(:))) / sum(abs(original(:))) < 1e-8);"
       f.write(code)
       f.close()
       print "Executing matlab code: \n%s\n" % code
       ret = os.system("matlab -nodesktop -nodisplay -nojvm -nosplash -r \"try run('code.m');catch exit(-1); end; exit(0) \" > /dev/null")
       if ret == 0:
         print "Passed matlab verification\n"
       else:
         self.assertEquals(ret, 0)
       os.remove('code.m')
示例#34
0
def process():
    for i in range(len(request.files)):
        f = request.files['file'+str(i)]
        if f and allowed_file(f.filename):
            now = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
            noExt, ext = os.path.splitext(f.filename);
            filename = os.path.join(app.config['UPLOAD_FOLDER'], noExt+now+ext)
            f.save(str(filename));
            main.execute(filename)
            outputFile = noExt+now+".txt"
            r = make_response(send_file(app.config['OUTPUT_FOLDER'] + outputFile), 200, {"file": outputFile} );
            return r;
        elif f:
            return "wrong file extension"

    return "No files were uploaded"
示例#35
0
def process():
    for i in range(len(request.files)):
        f = request.files['file'+str(i)]
        if f:
            now = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
            noExt, ext = os.path.splitext(f.filename);
            filename = os.path.join(app.config['UPLOAD_FOLDER'], noExt+now+ext)
            f.save(filename)
            main.execute(filename)
            outputFile = noExt+now+".txt"
            r = make_response(send_file(app.config['OUTPUT_FOLDER'] + outputFile), 200, {"file": outputFile} );
            #k = os.urandom(24);
            #app.config['COOKIE LIST'][]
            #r.set_cookie('username', k)
            return r;


    return "No files were uploaded";
示例#36
0
def exeY86():
    main.execute()
示例#37
0
文件: csm_au.py 项目: ommaurya/csm
        options.preupgradeset = True

    elif ctx.requested_action == 'Activate':
        options.upgradeset = True

    elif ctx.requested_action == 'Post-Upgrade':
        options.postupgradeset = True

    elif ctx.requested_action == 'Get-Package':
        options.pkg_state = True

    elif ctx.requested_action == 'Install Commit':
        options.commitset = True

    options.ctx = ctx
    status = main.execute(options, args, oparser)
    print "AUT Execution completed with status :",status
    options.stdoutfile.close()
    if testing_csm :
        return options.ctx 
    return status


class Host(object):
    """
    Host class
    """
    def __init__(self):
        self.urls = []

示例#38
0
def exeY86():#执行一次
    main.execute()