Exemplo n.º 1
0
    def handle(self):
        input_data = self.request.recv(1024 * 1024).strip()
        print('Connection from: ' + str(self.client_address))
        self.request.close()

        data = json.loads(input_data.decode('UTF-8'))
        submit_id = data['submit_id']
        problem = data['problem']
        code = data['code']
        custom = data['custom']
        custom_input = data['custom_input']
        user_id = data['user_id']
        print('Handling submit:', submit_id, ' problem:', problem, ' custom:',
              custom, ' user:'******'protokol')

        os.makedirs('submits/%s/' % submit_id)

        with open('submits/%s/data.code' % submit_id, 'w') as out:
            for content, lang in code:
                out.write('%s: %s\n' % (lang, content))

        master = MasterRunner(code,
                              prefix=str(submit_id),
                              variables=load_variables(problem))
        result = master.prepare()
        if result is not None:
            add_compile(protokol, result)
        elif not custom:
            run_tests(problem, master, protokol)
        else:
            input_path = 'submits/%s/data.custom' % submit_id
            init = InitRunner(variables=load_variables(problem),
                              codename=str(submit_id))
            init.prepare_memory(custom_input, input_path)
            run_custom(master, protokol, input_path)

        protocol_data = tostring(protokol)

        with open('submits/%s/data.protocol' % submit_id, 'w') as out:
            out.write('%s' % protocol_data)

        data = urllib.parse.urlencode({
            'submit_id': int(submit_id),
            'protocol': protocol_data
        }).encode('utf-8')
        url = 'http://127.0.0.1:8000/submit/receive_protocol/'

        req = urllib.request.Request(url, data)
        urllib.request.urlopen(req)
Exemplo n.º 2
0
    def run(self, input_file):
        counter = 0
        line = 0
        last_memory = input_file
        init_runner = InitRunner(self.variables)
        while line < len(self.runners):
            counter += 1
            if counter > self.limit:
                return "TLE", line + 1, "Counter exceesed limit " + str(
                    self.limit)

            runner = self.runners[line]
            if runner is None:
                line += 1
            elif not isinstance(runner, tuple):
                self.logger.info('Line %d, counter %d, runner %s code %s',
                                 line + 1, counter, runner.NAME, runner.code)
                out_memory = self.location.format("_mem_" + str(counter))
                self.logger.info('From: %s, To: %s', last_memory, out_memory)
                execute_result = self.runners[line].execute(
                    last_memory, out_memory)
                execute_status, execute_message = execute_result
                if execute_status != 0:
                    return "EXEC", line + 1, execute_message
                last_memory = out_memory
                line += 1
            else:
                self.logger.info('Line %d, counter %d, runner %s', line + 1,
                                 counter, "jump")
                self.logger.info('Jupming on line: %d', line + 1)
                variable = runner[0]
                to_line = runner[1] - 1
                memory = init_runner.load_memory(last_memory)
                self.logger.info('Memory: %s = %d', variable, memory[variable])

                if memory[variable] != 0:
                    line = to_line
                else:
                    line += 1

        self.logger.info('Reading final memory: %s', last_memory)
        memory = init_runner.load_memory(last_memory)
        return memory
Exemplo n.º 3
0
def main(generate, test, test_sample, clean, config_path):
    exec(open(config_path).read(), globals())
    task_path = os.path.dirname(config_path)
    if generate:
        json.dump(variables, open(task_path+'/variables.json', 'w'))

        init = InitRunner(variables)
        samples_names = "abcdefgh"
        # generate samples
        for i, (sample_input, sample_output) in enumerate(sample_input_output_pairs):
            init.prepare_memory(sample_input, task_path+"/00.{}.sample.in".format(samples_names[i]))
            json.dump(sample_output, open(task_path+"/00.{}.sample.out".format(samples_names[i]), 'w'))

        for i, (sample_input, sample_output) in enumerate(real_input_output_pairs):
            init.prepare_memory(sample_input, task_path+"/{0:02d}.in".format(i+1))
            json.dump(sample_output, open(task_path+"/{0:02d}.out".format(i+1), 'w'))
    else:
        print('Not generating anything, --generate')

    if test or test_sample is not None:
        master = MasterRunner(vzorak, prefix='_tmp_', variables=variables)
        result = master.prepare()
        print(result)
        count_ok = 0
        all_results = []
        for input_path in glob.glob(task_path + '/*.in'):
            if test_sample is not None and test_sample not in input_path:
                continue
            base = os.path.splitext(input_path)[0]
            result = master.run(input_path)
            print(result)
            message, line, diff = 'OK', 0, {}
            if isinstance(result, tuple):
                message = 'EXC'
                line = result[1]
            elif isinstance(result, dict):
                memory = result

                with open('%s.out' % base, 'r') as out_file:
                    output = json.loads(out_file.read())
                    ok = True
                    for premenna, hodnota in output.items():
                        # TODO: floaty su meh
                        if not compare(memory, premenna, hodnota, variables):
                            ok = False
                            diff[premenna] = (hodnota, memory[premenna])
                    if ok:
                        message = 'OK'
                        count_ok += 1
                    else:
                        message = 'WA'
            print(message, line)
            all_results.append((input_path, message, line))
            if len(diff) > 0:
                s = ''
                for premenna, (nasa, tvoja) in diff.items():
                    s += 'nas %s: %s\n' % (premenna, nasa)
                    s += 'tvoj %s: %s\n' % (premenna, tvoja)
                print(s)
        for result in all_results:
            print(result)

        print(all([x[1]=='OK' for x in all_results]))

    else:
        print('Not testing anything, --test')

    if clean:
        files = [fname for fname in glob.glob(task_path+"/*") if '_tmp' in fname]
        for f in files:
            os.remove(f)
    else:
        print('Not cleaning anything, --clean')
Exemplo n.º 4
0
    def prepare(self):
        code_file = open(self.codename + ".pl", "w")
        code_file.write(self.generate())
        code_file.close()
        return 0, ''

    def execute(self, in_memory, out_memory):
        log_fname = "{}.log_file".format(self.codename)
        cmd = 'perl {}.pl {} {} 2> {}'.format(self.codename, in_memory,
                                              out_memory, log_fname)
        return os.system(self.timeout(cmd)), open(log_fname).read()


if __name__ == '__main__':
    from runners.init_runner import InitRunner
    init = InitRunner()
    init.create_init_memory('tmp/memory.txt')
    init.create_init_memory('tmp/memory2_pl.txt')
    runner = PerlRunner(
        '@' + init.SOME_STR_VECTOR + '=("a","bb","dss");\n' + '@' +
        init.SOME_INT_VECTOR + '=(1,2,3);\n' + '@' + init.SOME_FLOAT_VECTOR +
        '=(11.0,21.0,31);\n' + '$' + init.SOME_INT + ' += $' +
        init.SOME_INT_VECTOR + '[1];\n', 'tmp/tmp')
    runner.simple_full_run('tmp/memory.txt', 'tmp/memory2_pl.txt')
    mem = init.load_memory('tmp/memory2_pl.txt')
    assert mem[init.SOME_STR_VECTOR] == ["a", "bb", "dss"]
    assert mem[init.SOME_INT_VECTOR] == [1, 2, 3]
    assert mem[init.SOME_FLOAT_VECTOR] == [11.0, 21.0, 31]
    assert mem[init.SOME_INT] == 2
Exemplo n.º 5
0
                self.logger.info('Memory: %s = %d', variable, memory[variable])

                if memory[variable] != 0:
                    line = to_line
                else:
                    line += 1

        self.logger.info('Reading final memory: %s', last_memory)
        memory = init_runner.load_memory(last_memory)
        return memory


if __name__ == "__main__":
    # Custom Variables
    variables = {'INTS': ['int1'], 'STRS': ['str1']}
    custom_init = InitRunner(variables)
    code2 = [
        [custom_init.SOME_INT + '=5', 'Python'],
        [custom_init.SOME_STR + '="loool";', 'C++'],
    ]

    custom_init.create_init_memory('tmp/memory.txt')
    master = MasterRunner(code2, '2', variables)
    master.prepare()
    memory = master.run('tmp/memory.txt')
    print(memory)
    assert len(memory) == 2
    assert memory['int1'] == 5
    assert memory['str1'] == "loool"

    # Basic multilanguage
Exemplo n.º 6
0
    def prepare(self):
        code_file = open(self.codename + ".r", "w")
        code_file.write(self.generate())
        code_file.close()
        return 0, ''

    def execute(self, in_memory, out_memory):
        log_fname = "{}.log_file".format(self.codename)
        cmd = 'Rscript {}.r {} {} 2> {}'.format(self.codename, in_memory,
                                                out_memory, log_fname)
        return os.system(self.timeout(cmd)), open(log_fname).read()


if __name__ == '__main__':
    from runners.init_runner import InitRunner
    init = InitRunner()
    init.create_init_memory('tmp/memory.txt')
    init.create_init_memory('tmp/memory2.txt')  # just to be sure
    init.create_init_memory('tmp/memory3.txt')  # just to be sure
    runner = RRunner(
        '{} <- c({}, "f");\n'.format(init.SOME_STR_VECTOR,
                                     init.SOME_STR_VECTOR) +
        '{} <- c({}, 0.112, 0.4652);\n'.format(init.SOME_FLOAT_VECTOR,
                                               init.SOME_FLOAT_VECTOR) +
        '{} <- ({}+5)*5;\n'.format(init.SOME_INT, init.SOME_INT), 'tmp/tmp')
    runner.simple_full_run('tmp/memory.txt', 'tmp/memory2.txt')
    mem = init.load_memory('tmp/memory2.txt')
    print(mem)
    assert mem[init.SOME_FLOAT_VECTOR] == [0.112, 0.4652]
    assert mem[init.SOME_STR_VECTOR] == ['1', '0', 'f']
    assert mem[init.SOME_INT] == 25