Search in sources :

Example 1 with Language

use of cn.edu.zjnu.acm.judge.domain.Language in project judge by zjnu-acm.

the class ContestStatisticsController method contestStatistics.

@GetMapping(value = "/conteststatistics", produces = TEXT_HTML_VALUE)
public String contestStatistics(HttpServletRequest request, Model model, @RequestParam("contest_id") long contestId) throws SQLException {
    Instant now = Instant.now();
    Contest contest = contestService.findOneByIdAndNotDisabled(contestId);
    String title = contest.getTitle();
    Instant endTime = contest.getEndTime();
    model.addAttribute("contestId", contestId);
    model.addAttribute("title", "Contest Statistics");
    StringBuilder sb = new StringBuilder("<p align=center><font size=5 color=blue>Contest Statistics--");
    sb.append(HtmlEscape.escapeHtml4Xml(title));
    if (!contest.isEnded()) {
        if (endTime != null) {
            sb.append("<br/>Time to go:").append(JudgeUtils.formatTime(now, endTime));
        } else {
            sb.append("<br/>Time to go Infinity");
        }
    }
    sb.append("</font></p>" + "<TABLE align=center cellSpacing=0 cellPadding=0 width=600 border=1 class=table-back style=\"border-collapse: collapse\" bordercolor=#FFF>" + "<tr bgcolor=#6589D1><th>&nbsp;</th><th>100</th><th>99~70</th><th>69~31</th><th>30~1</th><th>0</th><th>CE</th><th>Others</th><th>Total</th>");
    Map<Integer, Language> languages = languageService.getAvailableLanguages();
    int languageCount = languages.size();
    StringBuilder sql = new StringBuilder(600).append("select ");
    for (int i : languages.keySet()) {
        sql.append("sum(if(language=").append(i).append(",1,0)) g").append(i).append(",");
    }
    sql.append("s.problem_id,sum(if(score=100,1,0)) A,sum(if(score<100 and score >=70,1,0)) B,sum(if(score<70 and score >30,1,0)) D,sum(if(score>0 and score <=30,1,0)) C,sum(if(score=0,1,0)) E,sum(if(score=-7,1,0)) F,sum(if(score<-7 or score > 100,1,0)) G,count(*) Total from contest_problem cp left join solution s on cp.problem_id=s.problem_id and cp.contest_id=s.contest_id where s.contest_id=? group by cp.problem_id order by cp.num");
    String[] judgeStatus = { "A", "B", "C", "D", "E", "F", "G", "Total" };
    long[] byScore = new long[judgeStatus.length];
    long[] byLanguage = new long[languageCount];
    sb.append("<th>&nbsp;</th>");
    languages.values().stream().map(Language::getName).map(HtmlEscape::escapeHtml4Xml).forEach(languageName -> sb.append("<th>").append(languageName).append("</th>"));
    sb.append("</tr>");
    log.debug("{}", sql);
    Map<Long, long[]> problemsMap = contestService.getProblemsMap(contestId);
    try (Connection conn = dataSource.getConnection();
        PreparedStatement ps = conn.prepareStatement(sql.toString())) {
        ps.setLong(1, contestId);
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                long problemId = rs.getLong("problem_id");
                long[] num = problemsMap.get(problemId);
                if (num != null) {
                    sb.append("<tr><th><a href=contests/").append(contestId).append("/problems/").append(num[1]).append(".html>").append(contestService.toProblemIndex(num[0])).append("</a></th>");
                }
                for (int i = 0; i < judgeStatus.length; ++i) {
                    long value = rs.getLong(judgeStatus[i]);
                    byScore[i] += value;
                    if (value == 0) {
                        sb.append("<td>&nbsp;</td>");
                    } else if (i == judgeStatus.length - 1) {
                        sb.append("<th><a href=status?contest_id=").append(contestId).append("&problem_id=").append(problemId).append(">").append(value).append("</a></th>");
                    } else {
                        sb.append("<td>").append(value).append("</td>");
                    }
                }
                sb.append("<td>&nbsp;</td>");
                for (int i = 0; i < languageCount; ++i) {
                    long value = rs.getLong(i + 1);
                    byLanguage[i] += value;
                    if (value == 0) {
                        sb.append("<td>&nbsp;</td>");
                    } else {
                        sb.append("<td>").append(value).append("</td>");
                    }
                }
                sb.append("</tr>");
            }
        }
    }
    sb.append("<tr><th>Total</th>");
    for (int i = 0; i < judgeStatus.length; ++i) {
        if (byScore[i] == 0) {
            sb.append("<td>&nbsp;</td>");
        } else if (i == judgeStatus.length - 1) {
            sb.append("<th>").append(byScore[i]).append("</th>");
        } else {
            sb.append("<td>").append(byScore[i]).append("</td>");
        }
    }
    sb.append("<td>&nbsp;</td>");
    for (int i = 0; i < languageCount; ++i) {
        if (byLanguage[i] == 0) {
            sb.append("<td>&nbsp;</td>");
        } else {
            sb.append("<td>").append(byLanguage[i]).append("</td>");
        }
    }
    sb.append("</tr></table>");
    model.addAttribute("content", sb.toString());
    return "legacy";
}
Also used : Instant(java.time.Instant) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Language(cn.edu.zjnu.acm.judge.domain.Language) ResultSet(java.sql.ResultSet) Contest(cn.edu.zjnu.acm.judge.domain.Contest) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 2 with Language

use of cn.edu.zjnu.acm.judge.domain.Language in project judge by zjnu-acm.

the class StatusController method status.

@GetMapping(value = { "/status", "/submissions" }, produces = TEXT_HTML_VALUE)
@SuppressWarnings("AssignmentToMethodParameter")
public String status(HttpServletRequest request, @RequestParam(value = "problem_id", defaultValue = "") String pid, @RequestParam(value = "contest_id", required = false) Long contestId, @RequestParam(value = "language", defaultValue = "-1") int language, @RequestParam(value = "size", defaultValue = "20") int size, @RequestParam(value = "bottom", required = false) final Long bottom, @RequestParam(value = "score", required = false) Integer sc, @RequestParam(value = "user_id", defaultValue = "") String userId, @RequestParam(value = "top", required = false) final Long top, Authentication authentication, Model model) {
    long problemId = 0;
    String query = URLBuilder.fromRequest(request).replaceQueryParam("top").replaceQueryParam("bottom").toString();
    log.debug("query={}", query);
    Map<Long, long[]> problemsMap = Collections.emptyMap();
    if (contestId != null) {
        problemsMap = contestService.getProblemsMap(contestId);
    }
    try {
        problemId = Long.parseLong(pid);
    } catch (NumberFormatException ex) {
        if (contestId != null && pid.length() == 1) {
            // TODO the character is the index in the list.
            int x = Character.toUpperCase(pid.charAt(0)) - 'A';
            for (Map.Entry<Long, long[]> entry : problemsMap.entrySet()) {
                long key = entry.getKey();
                long[] value = entry.getValue();
                if (x == value[0]) {
                    problemId = key;
                    break;
                }
            }
        }
    }
    SubmissionQueryForm form = SubmissionQueryForm.builder().problem(problemId == 0 ? null : problemId).contest(contestId).score(sc).size(Math.max(Math.min(size, 500), 0)).top(top).bottom(bottom).user(StringUtils.hasText(userId) ? userId : null).language(language != -1 ? language : null).build();
    log.debug("{}", form);
    List<Submission> submissions = submissionMapper.findAllByCriteria(form);
    OptionalLong min = submissions.stream().mapToLong(Submission::getId).min();
    OptionalLong max = submissions.stream().mapToLong(Submission::getId).max();
    model.addAttribute("contestId", contestId);
    model.addAttribute("title", "Problem Status List");
    StringBuilder sb = new StringBuilder("<p align=center><font size=4 color=#339>Problem Status List</font></p>" + "<form method=get action='status'/><label for='pid'>Problem ID:</label><input id='pid' type=text name=problem_id size=8 value=\"").append(HtmlEscape.escapeHtml4Xml(pid)).append("\"/> <label for='uid'>User ID:</label><input id='uid' type=text name=user_id size=15 value=\"").append(HtmlEscape.escapeHtml4Xml(userId)).append("\"/>" + " <label for='languag'>Language:</label>" + "<select id='languag' size=\"1\" name=\"language\">" + "<option value=\"\">All</option>");
    for (Map.Entry<Integer, Language> entry : languageService.getAvailableLanguages().entrySet()) {
        int key = entry.getKey();
        Language value = entry.getValue();
        sb.append("<option value=\"").append(key).append("\"").append(key == language ? " selected" : "").append(">").append(HtmlEscape.escapeHtml4Xml(value.getName())).append("</option>");
    }
    sb.append("</select>");
    if (contestId != null) {
        sb.append("<input type=hidden name=contest_id value='").append(contestId).append("' />");
    }
    sb.append(" <button type=submit>Go</button></form>" + "<TABLE cellSpacing=0 cellPadding=0 width=100% border=1 class=table-back style=\"border-collapse: collapse\" bordercolor=#FFF>" + "<tr bgcolor=#6589D1><td align=center width=8%><b>Run ID</b></td><td align=center width=10%><b>User</b></td><td align=center width=6%><b>Problem</b></td>" + "<td align=center width=10%><b>Result</b></td><td align=center width=10%><b>Score</b></td><td align=center width=7%><b>Memory</b></td><td align=center width=7%><b>Time</b></td><td align=center width=7%><b>Language</b></td><td align=center width=7%><b>Code Length</b></td><td align=center width=17%><b>Submit Time</b></td></tr>");
    boolean admin = UserDetailsServiceImpl.isAdminLoginned(request);
    boolean sourceBrowser = UserDetailsServiceImpl.isSourceBrowser(request);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    for (Submission submission : submissions) {
        long id = submission.getId();
        String user_id1 = submission.getUser();
        long problem_id1 = submission.getProblem();
        Long contest_id1 = submission.getContest();
        long[] num = problemsMap.getOrDefault(problem_id1, new long[] { -1 });
        int score = submission.getScore();
        Instant inDate = submission.getInDate();
        String language1 = languageService.getLanguageName(submission.getLanguage());
        String color;
        if (score == 100) {
            color = "blue";
        } else {
            color = "red";
        }
        sb.append("<tr align=center><td>").append(id).append("</td>");
        sb.append("<td><a href=userstatus?user_id=").append(user_id1).append(">").append(user_id1).append("</a></td>");
        if (contestId == null || num[0] == -1) {
            sb.append("<td><a href=showproblem?problem_id=").append(problem_id1).append(">").append(problem_id1).append("</a></td>");
        } else {
            sb.append("<td><a href=contests/").append(contestId).append("/problems/").append(num[1]).append(".html>").append(contestService.toProblemIndex(num[0])).append("</a></td>");
        }
        if (score == ResultType.COMPILE_ERROR) {
            if (submissionService.canView(request, submission)) {
                sb.append("<td><a href=\"showcompileinfo?solution_id=").append(id).append("\" target=_blank><font color=green>").append(ResultType.getResultDescription(score)).append("</font></a></td>");
            } else {
                sb.append("<td><font color=green>").append(ResultType.getResultDescription(score)).append("</font></td>");
            }
        } else if (submissionService.canView(request, submission)) {
            sb.append("<td><a href=showsolutiondetails?solution_id=").append(id).append(" target=_blank><strong><font color=").append(color).append(">").append(ResultType.getResultDescription(score)).append("</font></strong></a></td>");
        } else {
            sb.append("<td><font color=").append(color).append(">").append(ResultType.getResultDescription(score)).append("</font></a></td>");
        }
        if (score <= 100 && score >= 0) {
            sb.append("<td>").append(score).append("</td>");
        } else {
            sb.append("<td>&nbsp;</td>");
        }
        boolean ended = true;
        if (!admin && contest_id1 != null) {
            ended = contestMapper.findOne(contest_id1).isEnded();
        }
        if (score == 100 && ended) {
            sb.append("<td>").append(submission.getMemory()).append("K</td><td>").append(submission.getTime()).append("MS</td>");
        } else {
            sb.append("<td>&nbsp;</td><td>&nbsp;</td>");
        }
        if (admin || sourceBrowser || UserDetailsServiceImpl.isUser(authentication, user_id1)) {
            sb.append("<td><a href=showsource?solution_id=").append(id).append(" target=_blank>").append(language1).append("</a></td>");
        } else {
            sb.append("<td>").append(language1).append("</td>");
        }
        if (ended) {
            int sourceLength = submission.getSourceLength();
            String t = sourceLength > 2048 ? new DecimalFormat("0.00").format(sourceLength / 1024.) + " KB" : sourceLength + " B";
            sb.append("<td>").append(t).append("</td>");
        } else {
            sb.append("<td>&nbsp;</td>");
        }
        sb.append("<td>").append(sdf.format(Timestamp.from(inDate))).append("</td></tr>");
    }
    query = request.getContextPath() + query;
    sb.append("</table><p align=center>[<a href=\"").append(query).append("\">Top</a>]&nbsp;&nbsp;");
    query += query.contains("?") ? '&' : '?';
    sb.append("[<a href=\"").append(query).append("bottom=").append(max.isPresent() ? max.getAsLong() : "").append("\"><font color=blue>Previous Page</font></a>]" + "&nbsp;&nbsp;[<a href=\"").append(query).append("top=").append(min.isPresent() ? min.getAsLong() : "").append("\"><font color=blue>Next Page</font></a>]&nbsp;&nbsp;</p>" + "<script>!function(w){setTimeout(function(){w.location.reload()},60000)}(this)</script>");
    model.addAttribute("content", sb.toString());
    return "legacy";
}
Also used : Submission(cn.edu.zjnu.acm.judge.domain.Submission) Instant(java.time.Instant) DecimalFormat(java.text.DecimalFormat) Language(cn.edu.zjnu.acm.judge.domain.Language) SubmissionQueryForm(cn.edu.zjnu.acm.judge.data.form.SubmissionQueryForm) OptionalLong(java.util.OptionalLong) OptionalLong(java.util.OptionalLong) Map(java.util.Map) SimpleDateFormat(java.text.SimpleDateFormat) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 3 with Language

use of cn.edu.zjnu.acm.judge.domain.Language in project judge by zjnu-acm.

the class JudgeRunnerTest method test.

@ParameterizedTest(name = "{index}: {0}")
@MethodSource("data")
public void test(String key, Checker checker, Path path) throws IOException {
    Path work = Files.createDirectories(Paths.get("target/work/judgeRunnerTest").resolve(key));
    Path[] groovyJars = GroovyHolder.getPaths();
    assertThat(groovyJars).isNotEmpty();
    for (Path groovyJar : groovyJars) {
        Files.copy(groovyJar, work.resolve(groovyJar.getFileName().toString()));
    }
    String cp = Arrays.stream(groovyJars).map(p -> p.getFileName().toString()).collect(Collectors.joining(File.pathSeparator));
    String executeCommand = build("java", "-cp", cp, groovy.ui.GroovyMain.class.getName(), "Main.groovy");
    Language groovy = Language.builder().name("groovy").sourceExtension("groovy").executeCommand(executeCommand).executableExtension("groovy").description("").timeFactor(2).build();
    log.warn("Language groovy: {}", groovy);
    languageMapper.save(groovy);
    String extension = getExtension(path);
    int languageId = findFirstLanguageByExtension(EXTENSION_MAP.get(extension));
    Language language = languageMapper.findOne(languageId);
    Objects.requireNonNull(language, "language " + languageId + " not exists");
    String source = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
    RunRecord runRecord = RunRecord.builder().source(source).timeLimit(timeLimit).memoryLimit(memoryLimit).language(language).build();
    RunResult runResult = judgeRunner.run(runRecord, work, judgeData, validator, false);
    int expectScore = SPECIAL_SCORE.getOrDefault(key, checker.getScore());
    String expectedCaseResult = ResultType.getCaseScoreDescription(checker.getStatus());
    Status resultStatus = runResult.getType();
    if (resultStatus != null) {
        assertThat(resultStatus).describedAs("type will either be null or COMPILATION_ERROR," + " if got other result, please modify this file").isEqualTo(Status.COMPILATION_ERROR);
    }
    String detail1 = runResult.getDetail();
    if (resultStatus == Status.COMPILATION_ERROR) {
        assertThat(detail1).describedAs("submission detail").isNull();
    } else {
        List<SubmissionDetailDTO> details = detail1 != null ? submissionService.parseSubmissionDetail(detail1) : null;
        String msg = "%s %s %s";
        Object[] param = { key, details, expectedCaseResult };
        assertThat(runResult.getScore()).describedAs(msg, param).isEqualTo(expectScore);
        assertThat(details).describedAs(msg, param).anyMatch(detail -> expectedCaseResult.equals(detail.getResult()));
    }
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) URISyntaxException(java.net.URISyntaxException) PlatformAssuming.assumingWindows(cn.edu.zjnu.acm.judge.test.PlatformAssuming.assumingWindows) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RunWith(org.junit.runner.RunWith) Status(cn.edu.zjnu.acm.judge.core.Status) Autowired(org.springframework.beans.factory.annotation.Autowired) ArrayList(java.util.ArrayList) Language(cn.edu.zjnu.acm.judge.domain.Language) Validator(cn.edu.zjnu.acm.judge.core.Validator) SubmissionDetailDTO(cn.edu.zjnu.acm.judge.data.dto.SubmissionDetailDTO) StringTokenizer(java.util.StringTokenizer) Map(java.util.Map) Arguments.arguments(org.junit.jupiter.params.provider.Arguments.arguments) Path(java.nio.file.Path) Application(cn.edu.zjnu.acm.judge.Application) MethodSource(org.junit.jupiter.params.provider.MethodSource) WebAppConfiguration(org.springframework.test.context.web.WebAppConfiguration) ImmutableMap(com.google.common.collect.ImmutableMap) Files(java.nio.file.Files) RunResult(cn.edu.zjnu.acm.judge.support.RunResult) GroovyHolder(cn.edu.zjnu.acm.judge.core.GroovyHolder) IOException(java.io.IOException) RunRecord(cn.edu.zjnu.acm.judge.support.RunRecord) Arguments(org.junit.jupiter.params.provider.Arguments) Collectors(java.util.stream.Collectors) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Paths(java.nio.file.Paths) ResultType(cn.edu.zjnu.acm.judge.util.ResultType) SimpleValidator(cn.edu.zjnu.acm.judge.core.SimpleValidator) LanguageMapper(cn.edu.zjnu.acm.judge.mapper.LanguageMapper) JUnitPlatform(org.junit.platform.runner.JUnitPlatform) JudgeData(cn.edu.zjnu.acm.judge.support.JudgeData) Transactional(org.springframework.transaction.annotation.Transactional) Status(cn.edu.zjnu.acm.judge.core.Status) RunRecord(cn.edu.zjnu.acm.judge.support.RunRecord) Language(cn.edu.zjnu.acm.judge.domain.Language) SubmissionDetailDTO(cn.edu.zjnu.acm.judge.data.dto.SubmissionDetailDTO) RunResult(cn.edu.zjnu.acm.judge.support.RunResult) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 4 with Language

use of cn.edu.zjnu.acm.judge.domain.Language in project judge by zjnu-acm.

the class LanguageControllerTest method testUpdate.

/**
 * Test of update method, of class LanguageController.
 *
 * {@link LanguageController#update(long, Language)}
 */
@Test
public void testUpdate() throws Exception {
    log.info("update");
    long id = anyId();
    Language request = Language.builder().name("mock language").sourceExtension("tmp").executableExtension("dummy").build();
    MvcResult result = mvc.perform(put("/api/languages/{id}?_format=json", id).content(objectMapper.writeValueAsString(request)).contentType(MediaType.APPLICATION_JSON)).andExpect(status().isNoContent()).andReturn();
}
Also used : Language(cn.edu.zjnu.acm.judge.domain.Language) MvcResult(org.springframework.test.web.servlet.MvcResult) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 5 with Language

use of cn.edu.zjnu.acm.judge.domain.Language in project judge by zjnu-acm.

the class JudgeRunnerImpl method run.

@Override
public RunResult run(RunRecord runRecord, Path workDirectory, JudgeData judgeData, Validator validator, boolean cleanDirectory) {
    Objects.requireNonNull(runRecord);
    Objects.requireNonNull(workDirectory);
    try {
        RunResult.Builder builder = RunResult.builder();
        String source = runRecord.getSource();
        if (!StringUtils.hasLength(source)) {
            return builder.type(Status.COMPILATION_ERROR).compileInfo("empty source file").build();
        }
        final String main = "Main";
        Files.createDirectories(workDirectory);
        Language language = runRecord.getLanguage();
        // 源码码文件
        Path sourceFile = workDirectory.resolve(main + "." + language.getSourceExtension());
        Files.write(sourceFile, source.getBytes(Platform.getCharset()));
        String compileCommand = language.getCompileCommand();
        log.debug("Compile Command: {}", compileCommand);
        if (StringUtils.hasText(compileCommand)) {
            // create compiling process
            // VC++ will output compiling info to stdout
            // G++ will output compiling info to stderr
            Path compileInfo = workDirectory.resolve("compileInfo.txt");
            @SuppressWarnings("null") Process process = ProcessCreationHelper.execute(new ProcessBuilder(compileCommand.split("\\s+")).directory(workDirectory.toFile()).redirectInput(ProcessBuilder.Redirect.from(NULL_FILE)).redirectOutput(compileInfo.toFile()).redirectErrorStream(true)::start);
            try {
                process.waitFor(1, TimeUnit.MINUTES);
            } catch (InterruptedException ex) {
                process.destroy();
                throw new InterruptedIOException();
            }
            // export compiling information
            String errorInfo;
            if (process.isAlive()) {
                process.destroyForcibly();
                try {
                    process.waitFor();
                } catch (InterruptedException ex) {
                    throw new InterruptedIOException();
                }
                errorInfo = "Compile timeout\nOutput:\n" + collectLines(compileInfo);
            } else {
                errorInfo = collectLines(compileInfo);
            }
            builder.compileInfo(errorInfo);
            log.debug("errorInfo = {}", errorInfo);
            // The executable file after compiling
            Path executable = workDirectory.resolve(main + "." + language.getExecutableExtension());
            log.debug("executable = {}", executable);
            boolean compilePassed = Files.exists(executable);
            if (!compilePassed) {
                return builder.type(Status.COMPILATION_ERROR).build();
            }
        }
        int caseNum = judgeData.getCaseCount();
        ArrayList<String> details = new ArrayList<>(caseNum << 2);
        String command = language.getExecuteCommand();
        // executable command should be absolute
        command = StringUtils.hasText(command) ? command : workDirectory.toAbsolutePath().resolve("Main." + language.getExecutableExtension()).toString();
        long extTime = language.getExtTime();
        long castTimeLimit = runRecord.getTimeLimit() * language.getTimeFactor() + extTime;
        // 内存附加
        long extraMemory = language.getExtMemory();
        long caseMemoryLimit = (runRecord.getMemoryLimit() + extraMemory) * 1024;
        Option[] opts = new Option[caseNum];
        for (int cas = 0; cas < caseNum; cas++) {
            Path[] entry = judgeData.get(cas);
            Path in = entry[0];
            Path standard = entry[1];
            Path progOutput = workDirectory.resolve(standard.getFileName());
            opts[cas] = Option.builder().timeLimit(// time limit
            castTimeLimit).memoryLimit(// memory in bytes
            caseMemoryLimit).outputLimit(// 16M
            16 * 1024 * 1024).command(command).workDirectory(workDirectory).inputFile(in).outputFile(progOutput).standardOutput(standard).errFile(NULL_FILE.toPath()).build();
        }
        String scorePerCase = new DecimalFormat("0.#").format(100.0 / caseNum);
        final ExecuteResult[] ers;
        try {
            ers = judgeBridge.judge(opts, false, validator);
        } catch (NotExecutableException ex) {
            // original command
            if (!StringUtils.hasText(language.getExecuteCommand())) {
                String msg = "fail to execute the binary file";
                Win32Exception cause = ex.getCause();
                if (cause != null) {
                    msg = msg + ": " + cause.getMessage();
                }
                return builder.type(Status.COMPILATION_ERROR).detail(msg).build();
            }
            throw ex.getCause();
        }
        long time = 0;
        long memory = 0;
        // final case whose result is accepted.
        int accept = 0;
        for (ExecuteResult er : ers) {
            long tim1 = Math.max(0, er.getTime() - extTime);
            long mem1 = Math.max(0, er.getMemory() / 1024 - extraMemory);
            String message = er.getMessage();
            boolean success = er.isSuccess();
            time = Math.max(time, tim1);
            memory = Math.max(memory, mem1);
            log.debug("message = {}, time = {}, memory = {}", message, time, memory);
            details.add(String.valueOf(er.getCode().getResult()));
            details.add(success ? scorePerCase : "0");
            details.add(String.valueOf(tim1));
            details.add(String.valueOf(mem1));
            if (success) {
                ++accept;
            }
        }
        log.debug("{}", details);
        int score = accept >= 0 ? (int) Math.round(accept * 100.0 / caseNum) : accept;
        if (score == 0 && accept != 0) {
            ++score;
        } else if (score == 100 && accept != caseNum) {
            --score;
        }
        String msg = details.stream().map(String::valueOf).collect(Collectors.joining(","));
        return builder.score(score).time(time).memory(memory).detail(msg).build();
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    } finally {
        if (cleanDirectory) {
            delete(workDirectory);
        }
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) UncheckedIOException(java.io.UncheckedIOException) Language(cn.edu.zjnu.acm.judge.domain.Language) ExecuteResult(cn.edu.zjnu.acm.judge.core.ExecuteResult) RunResult(cn.edu.zjnu.acm.judge.support.RunResult) Path(java.nio.file.Path) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) Win32Exception(jnc.platform.win32.Win32Exception) NotExecutableException(cn.edu.zjnu.acm.judge.core.NotExecutableException) Option(cn.edu.zjnu.acm.judge.core.Option)

Aggregations

Language (cn.edu.zjnu.acm.judge.domain.Language)8 Instant (java.time.Instant)4 GetMapping (org.springframework.web.bind.annotation.GetMapping)4 Contest (cn.edu.zjnu.acm.judge.domain.Contest)3 DecimalFormat (java.text.DecimalFormat)3 Map (java.util.Map)3 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)3 SubmissionQueryForm (cn.edu.zjnu.acm.judge.data.form.SubmissionQueryForm)2 Submission (cn.edu.zjnu.acm.judge.domain.Submission)2 RunResult (cn.edu.zjnu.acm.judge.support.RunResult)2 IOException (java.io.IOException)2 Path (java.nio.file.Path)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 ArrayList (java.util.ArrayList)2 OptionalLong (java.util.OptionalLong)2 Application (cn.edu.zjnu.acm.judge.Application)1 ExecuteResult (cn.edu.zjnu.acm.judge.core.ExecuteResult)1 GroovyHolder (cn.edu.zjnu.acm.judge.core.GroovyHolder)1