AtCoder Easy Test v2

Make testing sample cases easy

2021-10-23 يوللانغان نەشرى. ئەڭ يېڭى نەشرىنى كۆرۈش.

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