示例#1
0
    def compile_no_main(self):
        # Modify the program
        util.copy_file(self.name + '.R', 'modified.R')
        ori = util.read_file('modified.R')
        main = util.read_file('main.R')
        util.write_file('modified.R', '%s\n%s\n' % (ori, main))
        try:
            s = util.read_file("modified.R")
            util.write_file("wrapper.R", """
wrapper_R <- function() {

%s

}
""" % s)
            util.write_file(
                "compiler.R", """
library("codetools")

source("wrapper.R")

checkUsage(wrapper_R)
        """ % s)
            self.execute_compiler('Rscript compiler.R 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False
        util.del_file("compiler.R")
        util.del_file("wrapper.R")
        util.del_file("modified.R")
        return True
示例#2
0
    def execute(self, tst, correct, iterations=1):
        if 'source_modifier' in self.handler and (
                self.handler['source_modifier'] == 'no_main'
                or self.handler['source_modifier'] == 'structs'):
            util.copy_file(self.name + '.py', 'modified.py')
            ori = util.read_file(self.name + '.py')
            main = util.read_file('main.py')
            util.write_file('modified.py', '%s\n%s\n' % (ori, main))

            exec = 'modified.py'
        else:
            exec = self.executable()

        if correct:
            ext = 'cor'
            print("python3 %s < %s.inp > %s.%s" % (exec, tst, tst, ext),
                  end='')
        else:
            ext = 'py.out'
        """func.system("python3 %s < %s.inp > %s.%s" % (exec, tst, tst, ext))"""
        func = 'import os; os.system("python3 %s < %s.inp > %s.%s")' % (
            exec, tst, tst, ext)
        time = timeit.timeit(func, number=iterations) / iterations

        util.del_file('modified.py')
        util.del_dir('__pycache__')

        return time
示例#3
0
def build_q(fname, title):

    py_name = str(fname) + ".py"
    yml_name = str(fname) + ".yml"

    # read the python code
    if os.path.exists(py_name):
        code = util.read_file(py_name)
    else:
        code = ""

    # read the question description
    q = util.read_file(yml_name)

    # execute the code, using new global and local dictionaries
    def all_different(*x):
        return len(x) == len(set(x))

    ldict = {'all_different': all_different}
    exec(code, globals(), ldict)

    # modify the question description with the local dictionary
    subs = string.Template(q).substitute(ldict)

    # get the text back to data
    output = yaml.load(subs, Loader=yaml.FullLoader)
    # make sure we have the mandatory attributes
    text = output.get("text")
    if text == None:
        error(title, "Missing text!")
    check_not_dict_list(text, title, "Text", "string")

    qtype = output.get("type")
    if qtype == None:
        error(title, "Missing type!")
    check_not_dict_list(text, title, "Question type", "just a word")

    # fix fields according to type
    if output["type"] == "SingleChoice":
        return build_sc(output, title)
    elif output["type"] == "MultipleChoice":
        return build_mc(output, title)
    elif output["type"] == "Ordering":
        return build_o(output, title)
    elif output["type"] == "FillIn":
        return build_fi(output, title)
    elif output["type"] == "Matching":
        return build_m(output, title)
    elif output["type"] == "OpenQuestion":
        return build_oq(output, title)
    else:
        error(title, "Incorrect question type!")
示例#4
0
    def compile_normal(self):
        try:
            s = util.read_file(self.name + ".R")
            util.write_file("wrapper.R", """
wrapper_R <- function() {

%s

}
""" % s)
            util.write_file(
                "compiler.R", """
library("codetools")

source("wrapper.R")

checkUsage(wrapper_R)
            """)
            self.execute_compiler('Rscript compiler.R 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False
        util.del_file("compiler.R")
        util.del_file("wrapper.R")
        return True
示例#5
0
def make_quiz(seed):
    try:
        quiz = yaml.load(util.read_file("quiz.yml"), Loader=yaml.FullLoader)
    except Exception:
        print(Fore.RED +
              'No quiz was found on this folder (quiz.yml is missing)!' +
              Style.RESET_ALL,
              file=sys.stderr)
        sys.exit(0)

    random.seed(seed)

    if quiz.get('shuffle', True):
        random.shuffle(quiz['questions'])

    sample = quiz.get('sample', None)
    if sample != None:
        if sample <= 0:
            print(
                Style.BRIGHT + Fore.RED +
                '--- ERROR --- Sample number must be a natural number bigger than 0!'
                + Style.RESET_ALL,
                file=sys.stderr)
            sys.exit(0)
        else:
            question_num = len(quiz['questions'])
            if sample <= question_num:
                quiz['questions'] = quiz['questions'][:-question_num + sample]
            else:
                warning(
                    'Sample number is bigger than the number of questions! All questions will be used.'
                )

    quiz['seed'] = seed
    quiz['time-generation'] = time.ctime(
    )  # !!! posar format YYYY-MM-DD HH:MM:SS

    # Check types
    check_not_dict_list(quiz.get("statement"), "Quiz", "Statement", "text")

    score_sum = 0
    for question in quiz['questions']:
        score = question.get("score", 0)
        weight = question.get("weight", 1)
        if not isinstance(score, int) or score <= 0:
            error("quiz", "All scores must be positive integers")
        if not isinstance(weight, int) or weight <= 0:
            error("quiz", "All weights must be positive integers")
        score_sum += score
        if not question.get("file", False) or not question.get("title", False):
            error("quiz", "All questions need a file and a title!")
        question['q'] = build_q(question['file'], question['title'])
        question['a'] = {}
        question['points'] = 0
    if score_sum != 100:
        error("quiz", "Scores don't add to 100!!!")

    json.dump(quiz, sys.stdout, indent=4)
示例#6
0
    def compile_no_main(self):
        # Modify the program
        util.copy_file(self.name + '.cc', 'modified.cc')
        ori = util.read_file('modified.cc')
        main = util.read_file('main.cc')
        util.write_file(
            'modified.cc', """
#define main main__3

%s

#undef main
#define main main__2

%s

#undef main

int main() {
    return main__2();
}

""" % (ori, main))

        # Compile modified program
        util.del_file(self.executable())
        try:
            self.execute_compiler('g++ ' + self.flags2() + ' modified.cc -o ' +
                                  self.executable())
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            util.del_file(self.executable())
            util.del_file('modified.cc')
            return False

        # We are almost there
        util.del_file('modified.cc')
        if util.file_exists(self.executable()):
            return True
        else:
            print(Style.BRIGHT + Fore.RED + 'Unreported error.' +
                  Style.RESET_ALL)
            util.del_file(self.executable())
            return False
示例#7
0
    def compile_no_main(self):
        if not self.compile_normal():
            return False

        # Modify the program
        util.copy_file(self.name + '.py', 'modified.py')
        ori = util.read_file(self.name + '.py')
        main = util.read_file('main.py')
        util.write_file('modified.py', '%s\n%s\n' % (ori, main))

        # Compile modified program
        try:
            self.gen_wrapper()
            self.execute_compiler('python3 py3c.py modified.py 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False
        self.del_wrapper()
        return True
示例#8
0
 def compile(self):
     try:
         self.gen_wrapper()
         code = util.read_file(self.name + '.py')
         util.write_file(self.name + '.py', code)
         self.execute_compiler('python3 py3c.py ' + self.name +
                               '.py 1> /dev/null')
     except CompilationTooLong:
         print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
               Style.RESET_ALL)
         return False
     self.del_wrapper()
     return True
示例#9
0
    def compile_no_main(self):
        util.copy_file(self.name + '.hs', 'modified.hs')
        ori = util.read_file('modified.hs')
        main = util.read_file('main.hs')
        util.write_file('modified.hs', """
%s

%s
""" % (ori, main))

        util.del_file(self.executable())
        try:
            self.execute_compiler('ghc ' + self.flags1() + ' modified.hs -o ' +
                                  self.executable() + ' 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            util.del_file(self.executable())
            return False

        util.del_file('modified.hs')
        util.del_file('modified.hi')
        util.del_file('modified.o')
        return util.file_exists(self.executable())
示例#10
0
    def compile_normal(self):
        try:
            self.gen_wrapper()
            code = util.read_file(self.name + '.py')
            util.write_file(self.name + '.py', code)
            util.write_file(
                'py3c.py', """#!/usr/bin/python3

import py_compile, sys

py_compile.compile(sys.argv[1])""")
            self.execute_compiler('python3 py3c.py ' + self.name +
                                  '.py 1> /dev/null')
        except CompilationTooLong:
            print(Style.BRIGHT + Fore.RED + 'Compilation time exceeded!' +
                  Style.RESET_ALL)
            return False
        self.del_wrapper()
        return True