AtCoder Easy Test v2

Make testing sample cases easy

As of 2021-10-07. See the latest version.

  1. // ==UserScript==
  2. // @name AtCoder Easy Test v2
  3. // @namespace https://atcoder.jp/
  4. // @version 2.3.2
  5. // @description Make testing sample cases easy
  6. // @author magurofly
  7. // @license MIT
  8. // @supportURL https://github.com/magurofly/atcoder-easy-test/
  9. // @match https://atcoder.jp/contests/*/tasks/*
  10. // @match https://yukicoder.me/problems/no/*
  11. // @grant unsafeWindow
  12. // ==/UserScript==
  13. (function() {
  14. const codeSaver = {
  15. LIMIT: 10,
  16. get() {
  17. // `json` は、ソースコード文字列またはJSON文字列
  18. let json = unsafeWindow.localStorage.AtCoderEasyTest$lastCode;
  19. let data = [];
  20. try {
  21. if (typeof json == "string") {
  22. data.push(...JSON.parse(json));
  23. }
  24. else {
  25. data = [];
  26. }
  27. }
  28. catch (e) {
  29. data.push({
  30. path: unsafeWindow.localStorage.AtCoderEasyTset$lastPage,
  31. code: json,
  32. });
  33. }
  34. return data;
  35. },
  36. set(data) {
  37. unsafeWindow.localStorage.AtCoderEasyTest$lastCode = JSON.stringify(data);
  38. },
  39. save(code) {
  40. let data = codeSaver.get();
  41. const idx = data.findIndex(({ path }) => path == location.pathname);
  42. if (idx != -1)
  43. data.splice(idx, idx + 1);
  44. data.push({
  45. path: location.pathname,
  46. code,
  47. });
  48. while (data.length > codeSaver.LIMIT)
  49. data.shift();
  50. codeSaver.set(data);
  51. },
  52. restore() {
  53. const data = codeSaver.get();
  54. const idx = data.findIndex(({ path }) => path == location.pathname);
  55. if (idx == -1 || !(data[idx] instanceof Object))
  56. return Promise.reject(`No saved code found for ${location.pathname}`);
  57. return Promise.resolve(data[idx].code);
  58. }
  59. };
  60.  
  61. function similarLangs(targetLang, candidateLangs) {
  62. const [targetName, targetDetail] = targetLang.split(" ", 2);
  63. const selectedLangs = candidateLangs.filter(candidateLang => {
  64. const [name, _] = candidateLang.split(" ", 2);
  65. return name == targetName;
  66. }).map(candidateLang => {
  67. const [_, detail] = candidateLang.split(" ", 2);
  68. return [candidateLang, similarity(detail, targetDetail)];
  69. });
  70. return selectedLangs.sort((a, b) => a[1] - b[1]).map(([lang, _]) => lang);
  71. }
  72. function similarity(s, t) {
  73. const n = s.length, m = t.length;
  74. let dp = new Array(m + 1).fill(0);
  75. for (let i = 0; i < n; i++) {
  76. const dp2 = new Array(m + 1).fill(0);
  77. for (let j = 0; j < m; j++) {
  78. const cost = (s.charCodeAt(i) - t.charCodeAt(j)) ** 2;
  79. dp2[j + 1] = Math.min(dp[j] + cost, dp[j + 1] + cost * 0.25, dp2[j] + cost * 0.25);
  80. }
  81. dp = dp2;
  82. }
  83. return dp[m];
  84. }
  85.  
  86. class CodeRunner {
  87. get label() {
  88. return this._label;
  89. }
  90. constructor(label, site) {
  91. this._label = `${label} [${site}]`;
  92. }
  93. async test(sourceCode, input, expectedOutput, options) {
  94. const result = await this.run(sourceCode, input);
  95. if (expectedOutput != null)
  96. result.expectedOutput = expectedOutput;
  97. if (result.status != "OK" || typeof expectedOutput != "string")
  98. return result;
  99. let output = result.output || "";
  100. if (options.trim) {
  101. expectedOutput = expectedOutput.trim();
  102. output = output.trim();
  103. }
  104. let equals = (x, y) => x === y;
  105. if (options.allowableError) {
  106. const floatPattern = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/;
  107. const superEquals = equals;
  108. equals = (x, y) => {
  109. if (floatPattern.test(x) && floatPattern.test(y))
  110. return Math.abs(parseFloat(x) - parseFloat(y)) <= options.allowableError;
  111. return superEquals(x, y);
  112. };
  113. }
  114. if (options.split) {
  115. const superEquals = equals;
  116. equals = (x, y) => {
  117. const xs = x.split(/\s+/);
  118. const ys = y.split(/\s+/);
  119. if (xs.length != ys.length)
  120. return false;
  121. const len = xs.length;
  122. for (let i = 0; i < len; i++) {
  123. if (!superEquals(xs[i], ys[i]))
  124. return false;
  125. }
  126. return true;
  127. };
  128. }
  129. result.status = equals(output, expectedOutput) ? "AC" : "WA";
  130. return result;
  131. }
  132. }
  133.  
  134. class CustomRunner extends CodeRunner {
  135. run;
  136. constructor(label, run) {
  137. super(label, "Browser");
  138. this.run = run;
  139. }
  140. }
  141.  
  142. function buildParams(data) {
  143. return Object.entries(data).map(([key, value]) => encodeURIComponent(key) + "=" + encodeURIComponent(value)).join("&");
  144. }
  145. function sleep(ms) {
  146. return new Promise(done => setTimeout(done, ms));
  147. }
  148. function doneOrFail(p) {
  149. return p.then(() => Promise.resolve(), () => Promise.resolve());
  150. }
  151. function html2element(html) {
  152. const template = document.createElement("template");
  153. template.innerHTML = html;
  154. return template.content.firstChild;
  155. }
  156. const eventListeners = {};
  157. const events = {
  158. on(name, listener) {
  159. const listeners = (name in eventListeners ? eventListeners[name] : eventListeners[name] = []);
  160. listeners.push(listener);
  161. },
  162. trig(name) {
  163. if (name in eventListeners) {
  164. for (const listener of eventListeners[name])
  165. listener();
  166. }
  167. },
  168. };
  169. class ObservableValue {
  170. _value;
  171. _listeners;
  172. constructor(value) {
  173. this._value = value;
  174. this._listeners = new Set();
  175. }
  176. get value() {
  177. return this._value;
  178. }
  179. set value(value) {
  180. this._value = value;
  181. for (const listener of this._listeners)
  182. listener(value);
  183. }
  184. addListener(listener) {
  185. this._listeners.add(listener);
  186. listener(this._value);
  187. }
  188. removeListener(listener) {
  189. this._listeners.delete(listener);
  190. }
  191. map(f) {
  192. const y = new ObservableValue(f(this.value));
  193. this.addListener(x => {
  194. y.value = f(x);
  195. });
  196. return y;
  197. }
  198. }
  199.  
  200. let waitAtCoderCustomTest = Promise.resolve();
  201. const AtCoderCustomTestBase = location.href.replace(/\/tasks\/.+$/, "/custom_test");
  202. const AtCoderCustomTestResultAPI = AtCoderCustomTestBase + "/json?reload=true";
  203. const AtCoderCustomTestSubmitAPI = AtCoderCustomTestBase + "/submit/json";
  204. class AtCoderRunner extends CodeRunner {
  205. languageId;
  206. constructor(languageId, label) {
  207. super(label, "AtCoder");
  208. this.languageId = languageId;
  209. }
  210. async run(sourceCode, input) {
  211. const promise = this.submit(sourceCode, input);
  212. waitAtCoderCustomTest = promise;
  213. return await promise;
  214. }
  215. async submit(sourceCode, input) {
  216. try {
  217. await waitAtCoderCustomTest;
  218. }
  219. catch (error) {
  220. console.error(error);
  221. }
  222. const error = await fetch(AtCoderCustomTestSubmitAPI, {
  223. method: "POST",
  224. credentials: "include",
  225. headers: {
  226. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  227. },
  228. body: buildParams({
  229. "data.LanguageId": String(this.languageId),
  230. sourceCode,
  231. input,
  232. csrf_token: unsafeWindow.csrfToken,
  233. }),
  234. }).then(r => r.text());
  235. if (error) {
  236. throw new Error(error);
  237. }
  238. await sleep(100);
  239. for (;;) {
  240. const data = await fetch(AtCoderCustomTestResultAPI, {
  241. method: "GET",
  242. credentials: "include",
  243. }).then(r => r.json());
  244. if (!("Result" in data))
  245. continue;
  246. const result = data.Result;
  247. if ("Interval" in data) {
  248. await sleep(data.Interval);
  249. continue;
  250. }
  251. return {
  252. status: (result.ExitCode == 0) ? "OK" : (result.TimeConsumption == -1) ? "CE" : "RE",
  253. exitCode: result.ExitCode,
  254. execTime: result.TimeConsumption,
  255. memory: result.MemoryConsumption,
  256. input,
  257. output: data.Stdout,
  258. error: data.Stderr,
  259. };
  260. }
  261. }
  262. }
  263.  
  264. class PaizaIORunner extends CodeRunner {
  265. name;
  266. constructor(name, label) {
  267. super(label, "PaizaIO");
  268. this.name = name;
  269. }
  270. async run(sourceCode, input) {
  271. let id, status, error;
  272. try {
  273. const res = await fetch("https://api.paiza.io/runners/create?" + buildParams({
  274. source_code: sourceCode,
  275. language: this.name,
  276. input,
  277. longpoll: "true",
  278. longpoll_timeout: "10",
  279. api_key: "guest",
  280. }), {
  281. method: "POST",
  282. mode: "cors",
  283. }).then(r => r.json());
  284. id = res.id;
  285. status = res.status;
  286. error = res.error;
  287. }
  288. catch (error) {
  289. return {
  290. status: "IE",
  291. input,
  292. error: String(error),
  293. };
  294. }
  295. while (status == "running") {
  296. const res = await fetch("https://api.paiza.io/runners/get_status?" + buildParams({
  297. id,
  298. api_key: "guest",
  299. }), {
  300. mode: "cors",
  301. }).then(res => res.json());
  302. status = res.status;
  303. error = res.error;
  304. }
  305. const res = await fetch("https://api.paiza.io/runners/get_details?" + buildParams({
  306. id,
  307. api_key: "guest",
  308. }), {
  309. mode: "cors",
  310. }).then(r => r.json());
  311. const result = {
  312. status: "OK",
  313. exitCode: String(res.exit_code),
  314. execTime: +res.time * 1e3,
  315. memory: +res.memory * 1e-3,
  316. input,
  317. };
  318. if (res.build_result == "failure") {
  319. result.status = "CE";
  320. result.exitCode = res.build_exit_code;
  321. result.output = res.build_stdout;
  322. result.error = res.build_stderr;
  323. }
  324. else {
  325. result.status = (res.result == "timeout") ? "TLE" : (res.result == "failure") ? "RE" : "OK";
  326. result.exitCode = res.exit_code;
  327. result.output = res.stdout;
  328. result.error = res.stderr;
  329. }
  330. return result;
  331. }
  332. }
  333.  
  334. class WandboxRunner extends CodeRunner {
  335. name;
  336. options;
  337. constructor(name, label, options = {}) {
  338. super(label, "Wandbox");
  339. this.name = name;
  340. this.options = options;
  341. }
  342. getOptions(sourceCode, input) {
  343. if (typeof this.options == "function")
  344. return this.options(sourceCode, input);
  345. return this.options;
  346. }
  347. run(sourceCode, input) {
  348. const options = this.getOptions(sourceCode, input);
  349. return this.request(Object.assign({
  350. compiler: this.name,
  351. code: sourceCode,
  352. stdin: input,
  353. }, options));
  354. }
  355. async request(body) {
  356. const startTime = Date.now();
  357. let res;
  358. try {
  359. res = await fetch("https://wandbox.org/api/compile.json", {
  360. method: "POST",
  361. mode: "cors",
  362. headers: {
  363. "Content-Type": "application/json",
  364. },
  365. body: JSON.stringify(body),
  366. }).then(r => r.json());
  367. }
  368. catch (error) {
  369. console.error(error);
  370. return {
  371. status: "IE",
  372. input: body.stdin,
  373. error: String(error),
  374. };
  375. }
  376. const endTime = Date.now();
  377. const result = {
  378. status: "OK",
  379. exitCode: String(res.status),
  380. execTime: endTime - startTime,
  381. input: body.stdin,
  382. output: String(res.program_output || ""),
  383. error: String(res.program_error || ""),
  384. };
  385. // 正常終了以外の場合
  386. if (res.status != 0) {
  387. if (res.signal) {
  388. result.exitCode += ` (${res.signal})`;
  389. }
  390. result.output = String(res.compiler_output || "") + String(result.output || "");
  391. result.error = String(res.compiler_error || "") + String(result.error || "");
  392. if (res.compiler_output || res.compiler_error) {
  393. result.status = "CE";
  394. }
  395. else {
  396. result.status = "RE";
  397. }
  398. }
  399. return result;
  400. }
  401. }
  402.  
  403. class WandboxCppRunner extends WandboxRunner {
  404. async run(sourceCode, input) {
  405. // ACL を結合する
  406. const ACLBase = "https://cdn.jsdelivr.net/gh/atcoder/ac-library/";
  407. const files = new Map();
  408. const includeHeader = async (source) => {
  409. const pattern = /^#\s*include\s*[<"]atcoder\/([^>"]+)[>"]/gm;
  410. const loaded = [];
  411. let match;
  412. while (match = pattern.exec(source)) {
  413. const file = "atcoder/" + match[1];
  414. if (files.has(file))
  415. continue;
  416. files.set(file, null);
  417. loaded.push([file, fetch(ACLBase + file, { mode: "cors", cache: "force-cache", }).then(r => r.text())]);
  418. }
  419. const included = await Promise.all(loaded.map(async ([file, r]) => {
  420. const source = await r;
  421. files.set(file, source);
  422. return source;
  423. }));
  424. for (const source of included) {
  425. await includeHeader(source);
  426. }
  427. };
  428. await includeHeader(sourceCode);
  429. const codes = [];
  430. for (const [file, code] of files) {
  431. codes.push({ file, code, });
  432. }
  433. const options = this.getOptions(sourceCode, input);
  434. return await this.request(Object.assign({
  435. compiler: this.name,
  436. code: sourceCode,
  437. stdin: input,
  438. codes,
  439. "compiler-option-raw": "-I.",
  440. }, options));
  441. }
  442. }
  443.  
  444. let brythonRunnerLoaded = false;
  445. const brythonRunner = new CustomRunner("Brython", async (sourceCode, input) => {
  446. if (!brythonRunnerLoaded) {
  447. // BrythonRunner を読み込む
  448. await new Promise((resolve) => {
  449. const script = document.createElement("script");
  450. script.src = "https://cdn.jsdelivr.net/gh/pythonpad/brython-runner/lib/brython-runner.bundle.js";
  451. script.onload = () => {
  452. brythonRunnerLoaded = true;
  453. resolve(null);
  454. };
  455. document.head.appendChild(script);
  456. });
  457. }
  458. let stdout = "";
  459. let stderr = "";
  460. let stdinOffset = 0;
  461. const BrythonRunner = unsafeWindow.BrythonRunner;
  462. const runner = new BrythonRunner({
  463. stdout: { write(content) { stdout += content; }, flush() { } },
  464. stderr: { write(content) { stderr += content; }, flush() { } },
  465. stdin: { async readline() {
  466. let index = input.indexOf("\n", stdinOffset) + 1;
  467. if (index == 0)
  468. index = input.length;
  469. const text = input.slice(stdinOffset, index);
  470. stdinOffset = index;
  471. return text;
  472. } },
  473. });
  474. const timeStart = Date.now();
  475. await runner.runCode(sourceCode);
  476. const timeEnd = Date.now();
  477. return {
  478. status: "OK",
  479. exitCode: "0",
  480. execTime: (timeEnd - timeStart),
  481. input,
  482. output: stdout,
  483. error: stderr,
  484. };
  485. });
  486.  
  487. function pairs(list) {
  488. const pairs = [];
  489. const len = list.length >> 1;
  490. for (let i = 0; i < len; i++)
  491. pairs.push([list[i * 2], list[i * 2 + 1]]);
  492. return pairs;
  493. }
  494. async function init$2() {
  495. if (location.host != "atcoder.jp")
  496. throw "Not AtCoder";
  497. const doc = unsafeWindow.document;
  498. const eLanguage = unsafeWindow.$("#select-lang>select");
  499. const langMap = {
  500. 4001: "C GCC 9.2.1",
  501. 4002: "C Clang 10.0.0",
  502. 4003: "C++ GCC 9.2.1",
  503. 4004: "C++ Clang 10.0.0",
  504. 4005: "Java OpenJDK 11.0.6",
  505. 4006: "Python3 CPython 3.8.2",
  506. 4007: "Bash 5.0.11",
  507. 4008: "bc 1.07.1",
  508. 4009: "Awk GNU Awk 4.1.4",
  509. 4010: "C# .NET Core 3.1.201",
  510. 4011: "C# Mono-mcs 6.8.0.105",
  511. 4012: "C# Mono-csc 3.5.0",
  512. 4013: "Clojure 1.10.1.536",
  513. 4014: "Crystal 0.33.0",
  514. 4015: "D DMD 2.091.0",
  515. 4016: "D GDC 9.2.1",
  516. 4017: "D LDC 1.20.1",
  517. 4018: "Dart 2.7.2",
  518. 4019: "dc 1.4.1",
  519. 4020: "Erlang 22.3",
  520. 4021: "Elixir 1.10.2",
  521. 4022: "F# .NET Core 3.1.201",
  522. 4023: "F# Mono 10.2.3",
  523. 4024: "Forth gforth 0.7.3",
  524. 4025: "Fortran GNU Fortran 9.2.1",
  525. 4026: "Go 1.14.1",
  526. 4027: "Haskell GHC 8.8.3",
  527. 4028: "Haxe 4.0.3",
  528. 4029: "Haxe 4.0.3",
  529. 4030: "JavaScript Node.js 12.16.1",
  530. 4031: "Julia 1.4.0",
  531. 4032: "Kotlin 1.3.71",
  532. 4033: "Lua Lua 5.3.5",
  533. 4034: "Lua LuaJIT 2.1.0",
  534. 4035: "Dash 0.5.8",
  535. 4036: "Nim 1.0.6",
  536. 4037: "Objective-C Clang 10.0.0",
  537. 4038: "Lisp SBCL 2.0.3",
  538. 4039: "OCaml 4.10.0",
  539. 4040: "Octave 5.2.0",
  540. 4041: "Pascal FPC 3.0.4",
  541. 4042: "Perl 5.26.1",
  542. 4043: "Raku Rakudo 2020.02.1",
  543. 4044: "PHP 7.4.4",
  544. 4045: "Prolog SWI-Prolog 8.0.3",
  545. 4046: "Python PyPy2 7.3.0",
  546. 4047: "Python3 PyPy3 7.3.0",
  547. 4048: "Racket 7.6",
  548. 4049: "Ruby 2.7.1",
  549. 4050: "Rust 1.42.0",
  550. 4051: "Scala 2.13.1",
  551. 4052: "Java OpenJDK 1.8.0",
  552. 4053: "Scheme Gauche 0.9.9",
  553. 4054: "ML MLton 20130715",
  554. 4055: "Swift 5.2.1",
  555. 4056: "Text cat 8.28",
  556. 4057: "TypeScript 3.8",
  557. 4058: "Basic .NET Core 3.1.101",
  558. 4059: "Zsh 5.4.2",
  559. 4060: "COBOL Fixed OpenCOBOL 1.1.0",
  560. 4061: "COBOL Free OpenCOBOL 1.1.0",
  561. 4062: "Brainfuck bf 20041219",
  562. 4063: "Ada Ada2012 GNAT 9.2.1",
  563. 4064: "Unlambda 2.0.0",
  564. 4065: "Cython 0.29.16",
  565. 4066: "Sed 4.4",
  566. 4067: "Vim 8.2.0460",
  567. };
  568. const languageId = new ObservableValue(eLanguage.val());
  569. eLanguage.change(() => {
  570. languageId.value = eLanguage.val();
  571. });
  572. const language = languageId.map(lang => langMap[lang]);
  573. function getTestCases() {
  574. const selectors = [
  575. ["#task-statement p+pre.literal-block", ".section"],
  576. ["#task-statement pre.source-code-for-copy", ".part"],
  577. ["#task-statement .lang>*:nth-child(1) .div-btn-copy+pre", ".part"],
  578. ["#task-statement .div-btn-copy+pre", ".part"],
  579. ["#task-statement>.part pre.linenums", ".part"],
  580. ["#task-statement>.part:not(.io-style)>h3+section>pre", ".part"],
  581. ["#task-statement pre", ".part"],
  582. ];
  583. for (const [selector, closestSelector] of selectors) {
  584. let e = [...doc.querySelectorAll(selector)];
  585. e = e.filter(e => !e.closest(".io-style")); // practice2
  586. if (e.length == 0)
  587. continue;
  588. return pairs(e).map(([input, output], index) => ({
  589. title: `Sample ${index + 1}`,
  590. input: input.textContent,
  591. output: output.textContent,
  592. anchor: (input.closest(closestSelector) || input.parentElement).querySelector(".btn-copy"),
  593. }));
  594. }
  595. { // maximum_cup_2018_d
  596. let e = [...doc.querySelectorAll("#task-statement .div-btn-copy+pre")];
  597. e = e.filter(f => !f.childElementCount);
  598. if (e.length) {
  599. return pairs(e).map(([input, output], index) => ({
  600. title: `Sample ${index + 1}`,
  601. input: input.textContent,
  602. output: output.textContent,
  603. anchor: (input.closest(".part") || input.parentElement).querySelector(".btn-copy"),
  604. }));
  605. }
  606. }
  607. return [];
  608. }
  609. return {
  610. name: "AtCoder",
  611. language,
  612. get sourceCode() {
  613. return unsafeWindow.getSourceCode();
  614. },
  615. set sourceCode(sourceCode) {
  616. doc.querySelector(".plain-textarea").value = sourceCode;
  617. unsafeWindow.$(".editor").data("editor").doc.setValue(sourceCode);
  618. },
  619. submit() {
  620. doc.querySelector("#submit").click();
  621. },
  622. get testButtonContainer() {
  623. return doc.querySelector("#submit").parentElement;
  624. },
  625. get sideButtonContainer() {
  626. return doc.querySelector(".editor-buttons");
  627. },
  628. get bottomMenuContainer() {
  629. return doc.getElementById("main-div");
  630. },
  631. get resultListContainer() {
  632. return doc.querySelector(".form-code-submit");
  633. },
  634. get testCases() {
  635. return getTestCases();
  636. }
  637. };
  638. }
  639.  
  640. async function init$1() {
  641. if (location.host != "yukicoder.me")
  642. throw "Not yukicoder";
  643. const $ = unsafeWindow.$;
  644. const doc = unsafeWindow.document;
  645. const editor = unsafeWindow.ace.edit("rich_source");
  646. const eSourceObject = $("#source");
  647. const eLang = $("#lang");
  648. const eSamples = $(".sample");
  649. const langMap = {
  650. "cpp14": "C++ C++14 GCC 11.1.0 + Boost 1.77.0",
  651. "cpp17": "C++ C++17 GCC 11.1.0 + Boost 1.77.0",
  652. "cpp-clang": "C++ C++17 Clang 10.0.0 + Boost 1.76.0",
  653. "cpp23": "C++ C++11 GCC 8.4.1",
  654. "c11": "C++ C++11 GCC 11.1.0",
  655. "c": "C C90 GCC 8.4.1",
  656. "java8": "Java Java16 OpenJDK 16.0.1",
  657. "csharp": "C# CSC 3.9.0",
  658. "csharp_mono": "C# Mono 6.12.0.147",
  659. "csharp_dotnet": "C# .NET 5.0",
  660. "perl": "Perl 5.26.3",
  661. "raku": "Raku Rakudo v2021-07-2-g74d7ff771",
  662. "php": "PHP 7.2.24",
  663. "php7": "PHP 8.0.8",
  664. "python3": "Python3 3.9.6 + numpy 1.14.5 + scipy 1.1.0",
  665. "pypy2": "Python PyPy2 7.3.5",
  666. "pypy3": "Python3 PyPy3 7.3.5",
  667. "ruby": "Ruby 3.0.2p107",
  668. "d": "D DMD 2.097.1",
  669. "go": "Go 1.16.6",
  670. "haskell": "Haskell 8.10.5",
  671. "scala": "Scala 2.13.6",
  672. "nim": "Nim 1.4.8",
  673. "rust": "Rust 1.53.0",
  674. "kotlin": "Kotlin 1.5.21",
  675. "scheme": "Scheme Gauche 0.9.10",
  676. "crystal": "Crystal 1.1.1",
  677. "swift": "Swift 5.4.2",
  678. "ocaml": "OCaml 4.12.0",
  679. "clojure": "Clojure 1.10.2.790",
  680. "fsharp": "F# 5.0",
  681. "elixir": "Elixir 1.7.4",
  682. "lua": "Lua LuaJIT 2.0.5",
  683. "fortran": "Fortran gFortran 8.4.1",
  684. "node": "JavaScript Node.js 15.5.0",
  685. "typescript": "TypeScript 4.3.5",
  686. "lisp": "Lisp Common Lisp sbcl 2.1.6",
  687. "sml": "ML Standard ML MLton 20180207-6",
  688. "kuin": "Kuin KuinC++ v.2021.7.17",
  689. "vim": "Vim v8.2",
  690. "sh": "Bash 4.4.19",
  691. "nasm": "Assembler nasm 2.13.03",
  692. "clay": "cLay 20210917-1",
  693. "bf": "Brainfuck BFI 1.1",
  694. "Whitespace": "Whitespace 0.3",
  695. "text": "Text cat 8.3",
  696. };
  697. const language = new ObservableValue(langMap[eLang.val()]);
  698. eLang.on("change", () => {
  699. language.value = langMap[eLang.val()];
  700. });
  701. return {
  702. name: "yukicoder",
  703. language,
  704. get sourceCode() {
  705. if (eSourceObject.is(":visible"))
  706. return eSourceObject.val();
  707. return editor.getSession().getValue();
  708. },
  709. set sourceCode(sourceCode) {
  710. eSourceObject.val(sourceCode);
  711. editor.getSession().setValue(sourceCode);
  712. },
  713. submit() {
  714. doc.querySelector(`#submit_form input[type="submit"]`).click();
  715. },
  716. get testButtonContainer() {
  717. return doc.querySelector("#submit_form");
  718. },
  719. get sideButtonContainer() {
  720. return doc.querySelector("#toggle_source_editor").parentElement;
  721. },
  722. get bottomMenuContainer() {
  723. return doc.body;
  724. },
  725. get resultListContainer() {
  726. return doc.querySelector("#content");
  727. },
  728. get testCases() {
  729. const testCases = [];
  730. let sampleId = 1;
  731. for (let i = 0; i < eSamples.length; i++) {
  732. const eSample = eSamples.eq(i);
  733. const [eInput, eOutput] = eSample.find("pre");
  734. testCases.push({
  735. title: `Sample ${sampleId++}`,
  736. input: eInput.textContent,
  737. output: eOutput.textContent,
  738. anchor: eSample.find("button")[0],
  739. });
  740. }
  741. return testCases;
  742. },
  743. };
  744. }
  745.  
  746. var pSite = Promise.any([init$2(), init$1()]);
  747.  
  748. const runners = {
  749. "C GCC 10.1.0 Wandbox": new WandboxRunner("gcc-10.1.0-c", "C (GCC 10.1.0)"),
  750. "C C17 Clang 10.0.0 paiza.io": new PaizaIORunner("c", "C (C17 / Clang 10.0.0)"),
  751. "C++ GCC 10.1.0 + Boost 1.73.0 + ACL Wandbox": new WandboxCppRunner("gcc-10.1.0", "C++ (GCC 10.1.0) + ACL", { options: "warning,boost-1.73.0-gcc-9.2.0,gnu++17" }),
  752. "C++ Clang 10.0.0 + ACL Wandbox": new WandboxCppRunner("clang-10.0.0", "C++ (Clang 10.0.0) + ACL", { options: "warning,boost-nothing-clang-10.0.0,c++17" }),
  753. "Python3 CPython 3.8.2 paiza.io": new PaizaIORunner("python3", "Python (3.8.2)"),
  754. "Python3 Brython": brythonRunner,
  755. "Bash 5.0.17 paiza.io": new PaizaIORunner("bash", "Bash (5.0.17)"),
  756. "C# .NET Core 6.0.100-alpha.1.20562.2 Wandbox": new WandboxRunner("csharp", "C# (.NET Core 6.0.100-alpha.1.20562.2)"),
  757. "C# Mono-mcs HEAD Wandbox": new WandboxRunner("mono-head", "C# (Mono-mcs HEAD)"),
  758. "Clojure 1.10.1-1 paiza.io": new PaizaIORunner("clojure", "Clojure (1.10.1-1)"),
  759. "D LDC 1.23.0 paiza.io": new PaizaIORunner("d", "D (LDC 1.23.0)"),
  760. "Erlang 10.6.4 paiza.io": new PaizaIORunner("erlang", "Erlang (10.6.4)"),
  761. "Elixir 1.10.4 paiza.io": new PaizaIORunner("elixir", "Elixir (1.10.4)"),
  762. "F# Interactive 4.0 paiza.io": new PaizaIORunner("fsharp", "F# (Interactive 4.0)"),
  763. "Go 1.14.1 Wandbox": new WandboxRunner("go-1.14.1", "Go (1.14.1)"),
  764. "Haskell GHC HEAD Wandbox": new WandboxRunner("ghc-head", "Haskell (GHC HEAD)"),
  765. "JavaScript Node.js paiza.io": new PaizaIORunner("javascript", "JavaScript (Node.js 12.18.3)"),
  766. "Kotlin 1.4.0 paiza.io": new PaizaIORunner("kotlin", "Kotlin (1.4.0)"),
  767. "Lua 5.3.4 Wandbox": new WandboxRunner("lua-5.3.4", "Lua (Lua 5.3.4)"),
  768. "Lua LuaJIT HEAD Wandbox": new WandboxRunner("luajit-head", "Lua (LuaJIT HEAD)"),
  769. "Nim 1.0.6 Wandbox": new WandboxRunner("nim-1.0.6", "Nim (1.0.6)"),
  770. "Objective-C Clang 10.0.0 paiza.io": new PaizaIORunner("objective-c", "Objective-C (Clang 10.0.0)"),
  771. "Ocaml HEAD Wandbox": new WandboxRunner("ocaml-head", "OCaml (HEAD)"),
  772. "Pascal FPC 3.0.2 Wandbox": new WandboxRunner("fpc-3.0.2", "Pascal (FPC 3.0.2)"),
  773. "Perl 5.30.0 paiza.io": new PaizaIORunner("perl", "Perl (5.30.0)"),
  774. "PHP 7.4.10 paiza.io": new PaizaIORunner("php", "PHP (7.4.10)"),
  775. "PHP 7.3.3 Wandbox": new WandboxRunner("php-7.3.3", "PHP (7.3.3)"),
  776. "Python PyPy HEAD Wandbox": new WandboxRunner("pypy-head", "PyPy2 (HEAD)"),
  777. "Python3 PyPy3 7.2.0 Wandbox": new WandboxRunner("pypy-7.2.0-3", "PyPy3 (7.2.0)"),
  778. "Ruby 2.7.1 paiza.io": new PaizaIORunner("ruby", "Ruby (2.7.1)"),
  779. "Ruby HEAD Wandbox": new WandboxRunner("ruby-head", "Ruby (HEAD)"),
  780. "Ruby 2.7.1 Wandbox": new WandboxRunner("ruby-2.7.1", "Ruby (2.7.1)"),
  781. "Rust 1.42.0 AtCoder": new AtCoderRunner("4050", "Rust (1.42.0)"),
  782. "Rust HEAD Wandbox": new WandboxRunner("rust-head", "Rust (HEAD)"),
  783. "Rust 1.43.0 paiza.io": new PaizaIORunner("rust", "Rust (1.43.0)"),
  784. "Scala 2.13.3 paiza": new PaizaIORunner("scala", "Scala (2.13.3)"),
  785. "Scheme Gauche 0.9.6 paiza.io": new PaizaIORunner("scheme", "Scheme (Gauche 0.9.6)"),
  786. "Swift 5.2.5 paiza.io": new PaizaIORunner("swift", "Swift (5.2.5)"),
  787. "Text local": new CustomRunner("Text", async (sourceCode, input) => {
  788. return {
  789. status: "OK",
  790. exitCode: "0",
  791. input,
  792. output: sourceCode,
  793. };
  794. }),
  795. "Basic Visual Basic .NET Core 4.0.1 paiza.io": new PaizaIORunner("vb", "Visual Basic (.NET Core 4.0.1)"),
  796. "COBOL Free OpenCOBOL 2.2.0 paiza.io": new PaizaIORunner("cobol", "COBOL - Free (OpenCOBOL 2.2.0)"),
  797. "COBOL Fixed OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4060", "COBOL - Fixed (OpenCOBOL 1.1.0)"),
  798. "COBOL Free OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4061", "COBOL - Free (OpenCOBOL 1.1.0)"),
  799. "C++ GCC 9.2.0 + ACL Wandbox": new WandboxCppRunner("gcc-9.2.0", "C++ (GCC 9.2.0) + ACL"),
  800. };
  801. if (pSite.name == "AtCoder") {
  802. // AtCoderRunner がない場合は、追加する
  803. for (const e of document.querySelectorAll("#select-lang option[value]")) {
  804. const m = e.textContent.match(/([^ ]+) \(([^)]+)\)/);
  805. if (m) {
  806. const name = `${m[1]} ${m[2]} AtCoder`;
  807. const languageId = e.value;
  808. runners[name] = new AtCoderRunner(languageId, e.textContent);
  809. }
  810. }
  811. }
  812. console.info("AtCoder Easy Test: codeRunner OK");
  813. var codeRunner = {
  814. // 指定した環境でコードを実行する
  815. run(languageId, sourceCode, input, expectedOutput, options = { trim: true, split: true }) {
  816. // CodeRunner が存在しない言語ID
  817. if (!(languageId in runners))
  818. return Promise.reject("Language not supported");
  819. // 最後に実行したコードを保存
  820. if (sourceCode.length > 0)
  821. codeSaver.save(sourceCode);
  822. // 実行
  823. return runners[languageId].test(sourceCode, input, expectedOutput, options);
  824. },
  825. // 環境の名前の一覧を取得する
  826. async getEnvironment(languageId) {
  827. const langs = similarLangs(languageId, Object.keys(runners));
  828. if (langs.length == 0)
  829. throw `Undefined language: ${languageId}`;
  830. return langs.map(lang => [lang, runners[lang].label]);
  831. },
  832. };
  833.  
  834. var hBottomMenu = "<div id=\"bottom-menu-wrapper\" class=\"navbar navbar-default navbar-fixed-bottom\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button id=\"bottom-menu-key\" type=\"button\" class=\"navbar-toggle collapsed glyphicon glyphicon-menu-down\" data-toggle=\"collapse\" data-target=\"#bottom-menu\"></button>\n </div>\n <div id=\"bottom-menu\" class=\"collapse navbar-collapse\">\n <ul id=\"bottom-menu-tabs\" class=\"nav nav-tabs\"></ul>\n <div id=\"bottom-menu-contents\" class=\"tab-content\"></div>\n </div>\n </div>\n</div>";
  835.  
  836. var hStyle$1 = "<style>\n#bottom-menu-wrapper {\n background: transparent;\n border: none;\n pointer-events: none;\n padding: 0;\n}\n\n#bottom-menu-wrapper>.container {\n position: absolute;\n bottom: 0;\n width: 100%;\n padding: 0;\n}\n\n#bottom-menu-wrapper>.container>.navbar-header {\n float: none;\n}\n\n#bottom-menu-key {\n display: block;\n float: none;\n margin: 0 auto;\n padding: 10px 3em;\n border-radius: 5px 5px 0 0;\n background: #000;\n opacity: 0.5;\n color: #FFF;\n cursor: pointer;\n pointer-events: auto;\n text-align: center;\n}\n\n@media screen and (max-width: 767px) {\n #bottom-menu-key {\n opacity: 0.25;\n }\n}\n\n#bottom-menu-key.collapsed:before {\n content: \"\\e260\";\n}\n\n#bottom-menu-tabs {\n padding: 3px 0 0 10px;\n cursor: n-resize;\n}\n\n#bottom-menu-tabs a {\n pointer-events: auto;\n}\n\n#bottom-menu {\n pointer-events: auto;\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n max-height: unset;\n}\n\n#bottom-menu.collapse:not(.in) {\n display: none !important;\n}\n\n#bottom-menu-tabs>li>a {\n background: rgba(150, 150, 150, 0.5);\n color: #000;\n border: solid 1px #ccc;\n filter: brightness(0.75);\n}\n\n#bottom-menu-tabs>li>a:hover {\n background: rgba(150, 150, 150, 0.5);\n border: solid 1px #ccc;\n color: #111;\n filter: brightness(0.9);\n}\n\n#bottom-menu-tabs>li.active>a {\n background: #eee;\n border: solid 1px #ccc;\n color: #333;\n filter: none;\n}\n\n.bottom-menu-btn-close {\n font-size: 8pt;\n vertical-align: baseline;\n padding: 0 0 0 6px;\n margin-right: -6px;\n}\n\n#bottom-menu-contents {\n padding: 5px 15px;\n max-height: 50vh;\n overflow-y: auto;\n}\n\n#bottom-menu-contents .panel {\n color: #333;\n}\n</style>";
  837.  
  838. async function init() {
  839. const site = await pSite;
  840. const style = html2element(hStyle$1);
  841. const bottomMenu = html2element(hBottomMenu);
  842. unsafeWindow.document.head.appendChild(style);
  843. site.bottomMenuContainer.appendChild(bottomMenu);
  844. const bottomMenuKey = bottomMenu.querySelector("#bottom-menu-key");
  845. const bottomMenuTabs = bottomMenu.querySelector("#bottom-menu-tabs");
  846. const bottomMenuContents = bottomMenu.querySelector("#bottom-menu-contents");
  847. // メニューのリサイズ
  848. {
  849. let resizeStart = null;
  850. const onStart = (event) => {
  851. const target = event.target;
  852. const pageY = event.pageY;
  853. if (target.id != "bottom-menu-tabs")
  854. return;
  855. resizeStart = { y: pageY, height: bottomMenuContents.getBoundingClientRect().height };
  856. };
  857. const onMove = (event) => {
  858. if (!resizeStart)
  859. return;
  860. event.preventDefault();
  861. bottomMenuContents.style.height = `${resizeStart.height - (event.pageY - resizeStart.y)}px`;
  862. };
  863. const onEnd = () => {
  864. resizeStart = null;
  865. };
  866. bottomMenuTabs.addEventListener("mousedown", onStart);
  867. bottomMenuTabs.addEventListener("mousemove", onMove);
  868. bottomMenuTabs.addEventListener("mouseup", onEnd);
  869. bottomMenuTabs.addEventListener("mouseleave", onEnd);
  870. }
  871. let tabs = new Set();
  872. let selectedTab = null;
  873. /** 下メニューの操作 */
  874. const menuController = {
  875. /** タブを選択 */
  876. selectTab(tabId) {
  877. const tab = unsafeWindow.$(`#bottom-menu-tab-${tabId}`);
  878. if (tab && tab[0]) {
  879. tab.tab("show"); // Bootstrap 3
  880. selectedTab = tabId;
  881. }
  882. },
  883. /** 下メニューにタブを追加する */
  884. addTab(tabId, tabLabel, paneContent, options = {}) {
  885. console.log(`AtCoder Easy Test: addTab: ${tabLabel} (${tabId})`, paneContent);
  886. // タブを追加
  887. const tab = document.createElement("a");
  888. tab.textContent = tabLabel;
  889. tab.id = `bottom-menu-tab-${tabId}`;
  890. tab.href = "#";
  891. tab.dataset.target = `#bottom-menu-pane-${tabId}`;
  892. tab.dataset.toggle = "tab";
  893. tab.addEventListener("click", event => {
  894. event.preventDefault();
  895. menuController.selectTab(tabId);
  896. });
  897. const tabLi = document.createElement("li");
  898. tabLi.appendChild(tab);
  899. bottomMenuTabs.appendChild(tabLi);
  900. // 内容を追加
  901. const pane = document.createElement("div");
  902. pane.className = "tab-pane";
  903. pane.id = `bottom-menu-pane-${tabId}`;
  904. pane.appendChild(paneContent);
  905. bottomMenuContents.appendChild(pane);
  906. const controller = {
  907. get id() {
  908. return tabId;
  909. },
  910. close() {
  911. bottomMenuTabs.removeChild(tabLi);
  912. bottomMenuContents.removeChild(pane);
  913. tabs.delete(tab);
  914. if (selectedTab == tabId) {
  915. selectedTab = null;
  916. if (tabs.size > 0) {
  917. menuController.selectTab(tabs.values().next().value.id);
  918. }
  919. }
  920. },
  921. show() {
  922. menuController.show();
  923. menuController.selectTab(tabId);
  924. },
  925. set color(color) {
  926. tab.style.backgroundColor = color;
  927. },
  928. };
  929. // 閉じるボタン
  930. if (options.closeButton) {
  931. const btn = document.createElement("a");
  932. btn.className = "bottom-menu-btn-close btn btn-link glyphicon glyphicon-remove";
  933. btn.addEventListener("click", () => {
  934. controller.close();
  935. });
  936. tab.appendChild(btn);
  937. }
  938. // 選択されているタブがなければ選択
  939. if (!selectedTab)
  940. menuController.selectTab(tabId);
  941. return controller;
  942. },
  943. /** 下メニューを表示する */
  944. show() {
  945. if (bottomMenuKey.classList.contains("collapsed"))
  946. bottomMenuKey.click();
  947. },
  948. /** 下メニューの表示/非表示を切り替える */
  949. toggle() {
  950. bottomMenuKey.click();
  951. },
  952. };
  953. console.info("AtCoder Easy Test: bottomMenu OK");
  954. return menuController;
  955. }
  956.  
  957. var hRowTemplate = "<div class=\"atcoder-easy-test-cases-row alert alert-dismissible\">\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">\n <span aria-hidden=\"true\">×</span>\n </button>\n <div class=\"progress\">\n <div class=\"progress-bar\" style=\"width: 0%;\">0 / 0</div>\n </div>\n <!--div class=\"label label-default label-warning\" style=\"margin: 3px; cursor: pointer;\">WA</div>\n <div class=\"label label-default label-warning\" style=\"margin: 3px; cursor: pointer;\">WA</div>\n <div class=\"label label-default label-warning\" style=\"margin: 3px; cursor: pointer;\">WA</div-->\n</div>";
  958.  
  959. class ResultRow {
  960. _tabs;
  961. _element;
  962. _promise;
  963. constructor(pairs) {
  964. this._tabs = pairs.map(([_, tab]) => tab);
  965. this._element = html2element(hRowTemplate);
  966. const numCases = pairs.length;
  967. let numFinished = 0;
  968. let numAccepted = 0;
  969. const progressBar = this._element.querySelector(".progress-bar");
  970. progressBar.textContent = `${numFinished} / ${numCases}`;
  971. this._promise = Promise.all(pairs.map(([pResult, tab]) => {
  972. const button = html2element(`<div class="label label-default" style="margin: 3px; cursor: pointer;">WJ</div>`);
  973. button.addEventListener("click", async () => {
  974. (await tab).show();
  975. });
  976. this._element.appendChild(button);
  977. return pResult.then(result => {
  978. button.textContent = result.status;
  979. if (result.status == "AC") {
  980. button.classList.add("label-success");
  981. }
  982. else if (result.status != "OK") {
  983. button.classList.add("label-warning");
  984. }
  985. numFinished++;
  986. if (result.status == "AC")
  987. numAccepted++;
  988. progressBar.textContent = `${numFinished} / ${numCases}`;
  989. progressBar.style.width = `${100 * numFinished / numCases}%`;
  990. if (numFinished == numCases) {
  991. if (numAccepted == numCases)
  992. this._element.classList.add("alert-success");
  993. else
  994. this._element.classList.add("alert-warning");
  995. }
  996. }).catch(reason => {
  997. button.textContent = "IE";
  998. button.classList.add("label-danger");
  999. console.error(reason);
  1000. });
  1001. }));
  1002. }
  1003. get element() {
  1004. return this._element;
  1005. }
  1006. onFinish(listener) {
  1007. this._promise.then(listener);
  1008. }
  1009. remove() {
  1010. for (const pTab of this._tabs)
  1011. pTab.then(tab => tab.close());
  1012. const parent = this._element.parentElement;
  1013. if (parent)
  1014. parent.removeChild(this._element);
  1015. }
  1016. }
  1017.  
  1018. var hResultList = "<div class=\"row\"></div>";
  1019.  
  1020. const eResultList = html2element(hResultList);
  1021. pSite.then(site => site.resultListContainer.appendChild(eResultList));
  1022. const resultList = {
  1023. addResult(pairs) {
  1024. const result = new ResultRow(pairs);
  1025. eResultList.insertBefore(result.element, eResultList.firstChild);
  1026. return result;
  1027. },
  1028. };
  1029.  
  1030. let data = {};
  1031. function toString() {
  1032. return JSON.stringify(data);
  1033. }
  1034. function save() {
  1035. localStorage.setItem("AtCoderEasyTest", toString());
  1036. }
  1037. function load() {
  1038. if ("AtCoderEasyTest" in localStorage) {
  1039. data = JSON.parse(localStorage.getItem("AtCoderEasyTest"));
  1040. }
  1041. }
  1042. load();
  1043. /** プロパティ名は camelCase にすること */
  1044. const config = {
  1045. getString(key, defaultValue = "") {
  1046. if (!(key in data))
  1047. config.setString(key, defaultValue);
  1048. return data[key];
  1049. },
  1050. setString(key, value) {
  1051. data[key] = value;
  1052. save();
  1053. },
  1054. has(key) {
  1055. return key in data;
  1056. },
  1057. get(key, defaultValue = null) {
  1058. if (!(key in data))
  1059. config.set(key, defaultValue);
  1060. return JSON.parse(data[key]);
  1061. },
  1062. set(key, value) {
  1063. config.setString(key, JSON.stringify(value));
  1064. },
  1065. save,
  1066. load,
  1067. toString,
  1068. };
  1069.  
  1070. var hPage = "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>AtCoder Easy Test</title>\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css\" rel=\"stylesheet\">\n </head>\n <body>\n <div class=\"container\">\n <div class=\"panel panel-default\">\n <div class=\"panel-heading\">Settings</div>\n <div class=\"panel-body\">\n <form>\n <div class=\"checkbox\">\n <label><input id=\"use-keyboard-shortcut\" type=\"checkbox\">Use Keyboard Shortcuts</label>\n </div>\n </form>\n </div>\n </div>\n </div>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js\"></script>\n </body>\n</html>";
  1071.  
  1072. function bindCheckbox(key, defaultValue, element) {
  1073. element.checked = config.get(key, defaultValue);
  1074. element.addEventListener("change", () => {
  1075. config.set(key, element.checked);
  1076. });
  1077. }
  1078. const settings = {
  1079. /** 設定ページを開く
  1080. * クリックなどのイベント時にしか正しく実行できない
  1081. */
  1082. open() {
  1083. const win = window.open("about:blank");
  1084. const doc = win.document;
  1085. doc.open();
  1086. doc.write(hPage);
  1087. doc.close();
  1088. bindCheckbox("useKeyboardShortcut", true, doc.getElementById("use-keyboard-shortcut"));
  1089. }
  1090. };
  1091.  
  1092. var hTabTemplate = "<div class=\"atcoder-easy-test-result container\">\n <div class=\"row\">\n <div class=\"atcoder-easy-test-result-col-input col-xs-12\" data-if-expected-output=\"col-sm-6 col-sm-push-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Input\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-input form-control\" rows=\"3\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n <div class=\"atcoder-easy-test-result-col-expected-output col-xs-12 col-sm-6 hidden\" data-if-expected-output=\"!hidden col-sm-pull-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Expected Output\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-expected-output form-control\" rows=\"3\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n </div>\n <div class=\"row\"><div class=\"col-sm-6 col-sm-offset-3\">\n <div class=\"panel panel-default\">\n <table class=\"table table-condensed\">\n <tbody>\n <tr>\n <th class=\"text-center\">Exit Code</th>\n <th class=\"text-center\">Exec Time</th>\n <th class=\"text-center\">Memory</th>\n </tr>\n <tr>\n <td class=\"atcoder-easy-test-result-exit-code text-center\"></td>\n <td class=\"atcoder-easy-test-result-exec-time text-center\"></td>\n <td class=\"atcoder-easy-test-result-memory text-center\"></td>\n </tr>\n </tbody>\n </table>\n </div>\n </div></div>\n <div class=\"row\">\n <div class=\"atcoder-easy-test-result-col-output col-xs-12\" data-if-error=\"col-md-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Output\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-output form-control\" rows=\"5\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n <div class=\"atcoder-easy-test-result-col-error col-xs-12 col-md-6 hidden\" data-if-error=\"!hidden\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Error\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-error form-control\" rows=\"5\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n </div>\n</div>";
  1093.  
  1094. function setClassFromData(element, name) {
  1095. const classes = element.dataset[name].split(/\s+/);
  1096. for (let className of classes) {
  1097. let flag = true;
  1098. if (className[0] == "!") {
  1099. className = className.slice(1);
  1100. flag = false;
  1101. }
  1102. element.classList.toggle(className, flag);
  1103. }
  1104. }
  1105. class ResultTabContent {
  1106. _title;
  1107. _uid;
  1108. _element;
  1109. _result;
  1110. constructor() {
  1111. this._uid = Date.now().toString(16);
  1112. this._result = null;
  1113. this._element = html2element(hTabTemplate);
  1114. this._element.id = `atcoder-easy-test-result-${this._uid}`;
  1115. }
  1116. set result(result) {
  1117. this._result = result;
  1118. if (result.status == "AC") {
  1119. this.outputStyle.backgroundColor = "#dff0d8";
  1120. }
  1121. else if (result.status != "OK") {
  1122. this.outputStyle.backgroundColor = "#fcf8e3";
  1123. }
  1124. this.input = result.input;
  1125. if ("expectedOutput" in result)
  1126. this.expectedOutput = result.expectedOutput;
  1127. this.exitCode = result.exitCode;
  1128. if ("execTime" in result)
  1129. this.execTime = `${result.execTime} ms`;
  1130. if ("memory" in result)
  1131. this.memory = `${result.memory} KB`;
  1132. if ("output" in result)
  1133. this.output = result.output;
  1134. if (result.error)
  1135. this.error = result.error;
  1136. }
  1137. get result() {
  1138. return this._result;
  1139. }
  1140. get uid() {
  1141. return this._uid;
  1142. }
  1143. get element() {
  1144. return this._element;
  1145. }
  1146. set title(title) {
  1147. this._title = title;
  1148. }
  1149. get title() {
  1150. return this._title;
  1151. }
  1152. set input(input) {
  1153. this._get("input").value = input;
  1154. }
  1155. get inputStyle() {
  1156. return this._get("input").style;
  1157. }
  1158. set expectedOutput(output) {
  1159. this._get("expected-output").value = output;
  1160. setClassFromData(this._get("col-input"), "ifExpectedOutput");
  1161. setClassFromData(this._get("col-expected-output"), "ifExpectedOutput");
  1162. }
  1163. get expectedOutputStyle() {
  1164. return this._get("expected-output").style;
  1165. }
  1166. set output(output) {
  1167. this._get("output").value = output;
  1168. }
  1169. get outputStyle() {
  1170. return this._get("output").style;
  1171. }
  1172. set error(error) {
  1173. this._get("error").value = error;
  1174. setClassFromData(this._get("col-output"), "ifError");
  1175. setClassFromData(this._get("col-error"), "ifError");
  1176. }
  1177. set exitCode(code) {
  1178. const element = this._get("exit-code");
  1179. element.textContent = code;
  1180. const isSuccess = code == "0";
  1181. element.classList.toggle("bg-success", isSuccess);
  1182. element.classList.toggle("bg-danger", !isSuccess);
  1183. }
  1184. set execTime(time) {
  1185. this._get("exec-time").textContent = time;
  1186. }
  1187. set memory(memory) {
  1188. this._get("memory").textContent = memory;
  1189. }
  1190. _get(name) {
  1191. return this._element.querySelector(`.atcoder-easy-test-result-${name}`);
  1192. }
  1193. }
  1194.  
  1195. var hRoot = "<form id=\"atcoder-easy-test-container\" class=\"form-horizontal\">\n <div class=\"row\">\n <div class=\"col-xs-12 col-lg-8\">\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\">Test Environment</label>\n <div class=\"col-sm-10\">\n <select class=\"form-control\" id=\"atcoder-easy-test-language\"></select>\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-input\">Standard Input</label>\n <div class=\"col-sm-10\">\n <textarea id=\"atcoder-easy-test-input\" name=\"input\" class=\"form-control\" rows=\"3\"></textarea>\n </div>\n </div>\n </div>\n <div class=\"col-xs-12 col-lg-4\">\n <details close>\n <summary>Expected Output</summary>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-allowable-error-check\">Allowable Error</label>\n <div class=\"col-sm-10\">\n <div class=\"input-group\">\n <span class=\"input-group-addon\">\n <input id=\"atcoder-easy-test-allowable-error-check\" type=\"checkbox\" checked=\"checked\">\n </span>\n <input id=\"atcoder-easy-test-allowable-error\" type=\"text\" class=\"form-control\" value=\"1e-6\">\n </div>\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-output\">Expected Output</label>\n <div class=\"col-sm-10\">\n <textarea id=\"atcoder-easy-test-output\" name=\"output\" class=\"form-control\" rows=\"3\"></textarea>\n </div>\n </div>\n </details>\n </div>\n <div class=\"col-xs-12 col-md-6\">\n <div class=\"col-xs-11 col-xs-offset=1\">\n <div class=\"form-group\">\n <a id=\"atcoder-easy-test-run\" class=\"btn btn-primary\">Run</a>\n </div>\n </div>\n </div>\n <div class=\"col-xs-12 col-md-6\">\n <div class=\"col-xs-11 col-xs-offset=1\">\n <div class=\"form-group text-right\">\n <small>AtCoder Easy Test v<span id=\"atcoder-easy-test-version\"></span></small>\n <a id=\"atcoder-easy-test-setting\" class=\"btn btn-xs btn-default\">Setting</a>\n </div>\n </div>\n </div>\n </div>\n <style>\n #atcoder-easy-test-language {\n border: none;\n background: transparent;\n font: inherit;\n color: #fff;\n }\n #atcoder-easy-test-language option {\n border: none;\n color: #333;\n font: inherit;\n }\n </style>\n</form>";
  1196.  
  1197. var hStyle = "<style>\n.atcoder-easy-test-result textarea {\n font-family: monospace;\n font-weight: normal;\n}\n</style>";
  1198.  
  1199. var hRunButton = "<a class=\"btn btn-primary btn-sm\" style=\"vertical-align: top; margin-left: 0.5em\">Run</a>";
  1200.  
  1201. var hTestAndSubmit = "<a id=\"atcoder-easy-test-btn-test-and-submit\" class=\"btn btn-info btn\" style=\"margin-left: 1rem\" title=\"Ctrl+Enter\" data-toggle=\"tooltip\">Test &amp; Submit</a>";
  1202.  
  1203. var hTestAllSamples = "<a id=\"atcoder-easy-test-btn-test-all\" class=\"btn btn-default btn-sm\" style=\"margin-left: 1rem\" title=\"Alt+Enter\" data-toggle=\"tooltip\">Test All Samples</a>";
  1204.  
  1205. (async () => {
  1206. const site = await pSite;
  1207. const doc = unsafeWindow.document;
  1208. // init bottomMenu
  1209. const pBottomMenu = init();
  1210. pBottomMenu.then(bottomMenu => {
  1211. unsafeWindow.bottomMenu = bottomMenu;
  1212. });
  1213. await doneOrFail(pBottomMenu);
  1214. // external interfaces
  1215. unsafeWindow.codeRunner = codeRunner;
  1216. doc.head.appendChild(html2element(hStyle));
  1217. // interface
  1218. const atCoderEasyTest = {
  1219. config,
  1220. codeSaver,
  1221. enableButtons() {
  1222. events.trig("enable");
  1223. },
  1224. disableButtons() {
  1225. events.trig("disable");
  1226. },
  1227. runCount: 0,
  1228. runTest(title, language, sourceCode, input, output = null, options = { trim: true, split: true, }) {
  1229. this.disableButtons();
  1230. const content = new ResultTabContent();
  1231. const pTab = pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test-result-" + content.uid, `#${++this.runCount} ${title}`, content.element, { active: true, closeButton: true }));
  1232. const pResult = codeRunner.run(language, sourceCode, input, output, options);
  1233. pResult.then(result => {
  1234. content.result = result;
  1235. if (result.status == "AC") {
  1236. pTab.then(tab => tab.color = "#dff0d8");
  1237. }
  1238. else if (result.status != "OK") {
  1239. pTab.then(tab => tab.color = "#fcf8e3");
  1240. }
  1241. }).finally(() => {
  1242. this.enableButtons();
  1243. });
  1244. return [pResult, pTab];
  1245. }
  1246. };
  1247. unsafeWindow.atCoderEasyTest = atCoderEasyTest;
  1248. // place "Easy Test" tab
  1249. {
  1250. // declare const hRoot: string;
  1251. const root = html2element(hRoot);
  1252. const E = (id) => root.querySelector(`#atcoder-easy-test-${id}`);
  1253. const eLanguage = E("language");
  1254. const eInput = E("input");
  1255. const eAllowableErrorCheck = E("allowable-error-check");
  1256. const eAllowableError = E("allowable-error");
  1257. const eOutput = E("output");
  1258. const eRun = E("run");
  1259. const eSetting = E("setting");
  1260. E("version").textContent = "2.3.2";
  1261. events.on("enable", () => {
  1262. eRun.classList.remove("disabled");
  1263. });
  1264. events.on("disable", () => {
  1265. eRun.classList.remove("enabled");
  1266. });
  1267. eSetting.addEventListener("click", () => {
  1268. settings.open();
  1269. });
  1270. // 言語選択関係
  1271. {
  1272. eLanguage.addEventListener("change", async () => {
  1273. const langSelection = config.get("langSelection", {});
  1274. langSelection[site.language.value] = eLanguage.value;
  1275. config.set("langSelection", langSelection);
  1276. });
  1277. async function setLanguage() {
  1278. const languageId = site.language.value;
  1279. while (eLanguage.firstChild)
  1280. eLanguage.removeChild(eLanguage.firstChild);
  1281. try {
  1282. const langs = await codeRunner.getEnvironment(languageId);
  1283. console.log(`language: ${langs[1]} (${langs[0]})`);
  1284. // add <option>
  1285. for (const [languageId, label] of langs) {
  1286. const option = document.createElement("option");
  1287. option.value = languageId;
  1288. option.textContent = label;
  1289. eLanguage.appendChild(option);
  1290. }
  1291. // load
  1292. const langSelection = config.get("langSelection", {});
  1293. if (languageId in langSelection) {
  1294. const prev = langSelection[languageId];
  1295. const [lang, _] = langs.find(([lang, label]) => lang == prev);
  1296. if (lang)
  1297. eLanguage.value = lang;
  1298. }
  1299. events.trig("enable");
  1300. }
  1301. catch (error) {
  1302. console.log(`language: ? (${languageId})`);
  1303. console.error(error);
  1304. const option = document.createElement("option");
  1305. option.className = "fg-danger";
  1306. option.textContent = error;
  1307. eLanguage.appendChild(option);
  1308. events.trig("disable");
  1309. }
  1310. }
  1311. site.language.addListener(() => setLanguage());
  1312. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  1313. eAllowableErrorCheck.addEventListener("change", event => {
  1314. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  1315. });
  1316. }
  1317. // テスト実行
  1318. function runTest(title, input, output = null) {
  1319. const options = { trim: true, split: true, };
  1320. if (eAllowableErrorCheck.checked) {
  1321. options.allowableError = parseFloat(eAllowableError.value);
  1322. }
  1323. return atCoderEasyTest.runTest(title, eLanguage.value, site.sourceCode, input, output, options);
  1324. }
  1325. function runAllCases(testcases) {
  1326. const pairs = testcases.map(testcase => runTest(testcase.title, testcase.input, testcase.output));
  1327. resultList.addResult(pairs);
  1328. return Promise.all(pairs.map(([pResult, _]) => pResult.then(result => {
  1329. if (result.status == "AC")
  1330. return Promise.resolve(result);
  1331. else
  1332. return Promise.reject(result);
  1333. })));
  1334. }
  1335. eRun.addEventListener("click", _ => {
  1336. const title = "Run";
  1337. const input = eInput.value;
  1338. const output = eOutput.value;
  1339. runTest(title, input, output || null);
  1340. });
  1341. await doneOrFail(pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test", "Easy Test", root)));
  1342. // place "Run" button on each sample
  1343. for (const testCase of site.testCases) {
  1344. const eRunButton = html2element(hRunButton);
  1345. eRunButton.addEventListener("click", async () => {
  1346. const [pResult, pTab] = runTest(testCase.title, testCase.input, testCase.output);
  1347. await pResult;
  1348. (await pTab).show();
  1349. });
  1350. testCase.anchor.insertAdjacentElement("afterend", eRunButton);
  1351. events.on("disable", () => {
  1352. eRunButton.classList.add("disabled");
  1353. });
  1354. events.on("enable", () => {
  1355. eRunButton.classList.remove("disabled");
  1356. });
  1357. }
  1358. // place "Test & Submit" button
  1359. {
  1360. const button = html2element(hTestAndSubmit);
  1361. site.testButtonContainer.appendChild(button);
  1362. const testAndSubmit = async () => {
  1363. await runAllCases(site.testCases);
  1364. site.submit();
  1365. };
  1366. button.addEventListener("click", testAndSubmit);
  1367. events.on("testAndSubmit", testAndSubmit);
  1368. }
  1369. // place "Test All Samples" button
  1370. {
  1371. const button = html2element(hTestAllSamples);
  1372. site.testButtonContainer.appendChild(button);
  1373. const testAllSamples = () => runAllCases(site.testCases);
  1374. button.addEventListener("click", testAllSamples);
  1375. events.on("testAllSamples", testAllSamples);
  1376. }
  1377. }
  1378. // place "Restore Last Play" button
  1379. try {
  1380. const restoreButton = doc.createElement("a");
  1381. restoreButton.className = "btn btn-danger btn-sm";
  1382. restoreButton.textContent = "Restore Last Play";
  1383. restoreButton.addEventListener("click", async () => {
  1384. try {
  1385. const lastCode = await codeSaver.restore();
  1386. if (site.sourceCode.length == 0 || confirm("Your current code will be replaced. Are you sure?")) {
  1387. site.sourceCode = lastCode;
  1388. }
  1389. }
  1390. catch (reason) {
  1391. alert(reason);
  1392. }
  1393. });
  1394. site.sideButtonContainer.appendChild(restoreButton);
  1395. }
  1396. catch (e) {
  1397. console.error(e);
  1398. }
  1399. // キーボードショートカット
  1400. unsafeWindow.addEventListener("keydown", (event) => {
  1401. if (config.get("useKeyboardShortcut", true)) {
  1402. if (event.key == "Enter" && event.ctrlKey) {
  1403. events.trig("testAndSubmit");
  1404. }
  1405. else if (event.key == "Enter" && event.altKey) {
  1406. events.trig("testAllSamples");
  1407. }
  1408. else if (event.key == "Escape" && event.altKey) {
  1409. pBottomMenu.then(bottomMenu => bottomMenu.toggle());
  1410. }
  1411. }
  1412. });
  1413. })();
  1414. })();