AtCoder Easy Test v2

Make testing sample cases easy

Ekde 2021/10/23. Vidu La ĝisdata versio.

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