Codeforces Better!

Codeforces界面汉化、题目翻译,markdown视图,一键复制题目

当前为 2023-05-17 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.25
  5. // @description Codeforces界面汉化、题目翻译,markdown视图,一键复制题目
  6. // @author 北极小狐
  7. // @match https://codeforces.com/*
  8. // @connect www2.deepl.com
  9. // @connect m.youdao.com
  10. // @connect openai.api2d.net
  11. // @connect api.openai.com
  12. // @grant GM_xmlhttpRequest
  13. // @grant GM_info
  14. // @connect greasyfork.org
  15. // @icon https://aowuucdn.oss-cn-beijing.aliyuncs.com/codeforces.png
  16. // @require https://cdn.bootcdn.net/ajax/libs/turndown/7.1.1/turndown.min.js
  17. // @require https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js
  18. // @license MIT
  19. // ==/UserScript==
  20. // 样式
  21. function loadCssCode(code) {
  22. var style = document.createElement('style');
  23. style.type = 'text/css';
  24. style.rel = 'stylesheet';
  25. style.appendChild(document.createTextNode(code));
  26. var head = document.getElementsByTagName('head')[0];
  27. head.appendChild(style);
  28. }
  29. loadCssCode(`
  30. span.mdViewContent {
  31. white-space: pre-wrap;
  32. }
  33. /*翻译div*/
  34. .translate-problem-statement {
  35. display: grid;
  36. justify-items: start;
  37. white-space: pre-wrap;
  38. border: 1px dashed #00aeeccc;
  39. border-radius: 0.3rem;
  40. padding: 5px;
  41. margin: 10px 0px;
  42. font-size: 13px;
  43. }
  44. .translate-problem-statement a {
  45. color: #4d87c7;
  46. background: 0 0;
  47. text-decoration: none;
  48. }
  49. .translate-problem-statement a:hover {
  50. background-color: #800;
  51. color: #fff;
  52. text-decoration: none;
  53. }
  54. .html2md-panel {
  55. display: flex;
  56. justify-content: flex-end;
  57. }
  58. button.html2mdButton {
  59. cursor: pointer;
  60. background-color: #e6e6e6;
  61. color: #727378;
  62. height: 22px;
  63. width: auto;
  64. font-size: 13px;
  65. border-radius: 0.3rem;
  66. border: none;
  67. padding: 1px 5px;
  68. margin: 5px;
  69. box-shadow: 0 0 1px #0000004d;
  70. }
  71. button.html2mdButton.copied {
  72. background-color: #07e65196;
  73. color: #104f2b;
  74. }
  75. button.html2mdButton.mdViewed {
  76. background-color: #ff980057;
  77. color: #5a3a0c;
  78. }
  79. button.translated {
  80. cursor: not-allowed;
  81. background-color: #2a6dc296;
  82. color: #fffdfd;
  83. }
  84. button.html2mdButton.reTranslation {
  85. background-color: #faebd7;
  86. }
  87. .translate-problem-statement table {
  88. border: 1px #ccc solid;
  89. border-collapse: collapse;
  90. margin: 1.3571em 0 0;
  91. color: #222;
  92. }
  93. .translate-problem-statement table td {
  94. border-right: 1px solid #ccc;
  95. border-top: 1px solid #ccc;
  96. padding: 0.7143em 0.5em;
  97. }
  98. .translate-problem-statement table th {
  99. padding: 0.7143em 0.5em;
  100. }
  101. .translate-problem-statement p:not(:first-child) {
  102. margin: 1.5em 0 0;
  103. }
  104. /*设置面板*/
  105. button.html2mdButton.CFBetter_setting {
  106. float: right;
  107. height: 30px;
  108. background: #60a5fa;
  109. color: white;
  110. box-shadow: 0px 0px 1px 1px #0000004d;
  111. margin: 10px;
  112. }
  113. #CFBetter_setting_menu {
  114. z-index: 9999;
  115. border-radius: 0.5rem;
  116. box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  117. display: grid;
  118. position: fixed;
  119. top: 50%;
  120. left: 50%;
  121. width: 270px;
  122. transform: translate(-50%, -50%);
  123. border-radius: 16px;
  124. background-color: #ecf0ff;
  125. border: 6px solid #ffffff;
  126. color: #697e91;
  127. padding: 10px 20px 20px 20px;
  128. }
  129.  
  130. /*设置面板-关闭按钮*/
  131. #CFBetter_setting_menu .tool-box {
  132. position: absolute;
  133. display: flex;
  134. align-items: center;
  135. justify-content: center;
  136. width: 2.5rem;
  137. height: 2.5rem;
  138. top: 3px;
  139. right: 3px;
  140. }
  141.  
  142. #CFBetter_setting_menu .btn-close {
  143. display: flex;
  144. align-items: center;
  145. justify-content: center;
  146. text-align: center;
  147. width: 2rem;
  148. height: 2rem;
  149. color: transparent;
  150. font-size: 0;
  151. cursor: pointer;
  152. background-color: #ff000080;
  153. border: none;
  154. border-radius: 10px;
  155. transition: .2s ease all;
  156. }
  157.  
  158. #CFBetter_setting_menu .btn-close:hover {
  159. width: 2rem;
  160. height: 2rem;
  161. font-size: 1rem;
  162. color: #ffffff;
  163. background-color: #ff0000cc;
  164. box-shadow: 0 5px 5px 0 #00000026;
  165. }
  166.  
  167. #CFBetter_setting_menu .btn-close:active {
  168. width: .9rem;
  169. height: .9rem;
  170. font-size: .9rem;
  171. color: #ffffffde;
  172. --shadow-btn-close: 0 3px 3px 0 #00000026;
  173. box-shadow: var(--shadow-btn-close);
  174. }
  175.  
  176. /*设置面板-checkbox*/
  177. #CFBetter_setting_menu input[type=checkbox]:focus {
  178. outline: 0px;
  179. }
  180.  
  181. #CFBetter_setting_menu input[type="checkbox"] {
  182. margin: 0px;
  183. appearance: none;
  184. width: 48px;
  185. height: 24px;
  186. border: 2px solid #6b8092;
  187. border-radius: 20px;
  188. background: #f1e1e1;
  189. position: relative;
  190. box-sizing: border-box;
  191. }
  192.  
  193. #CFBetter_setting_menu input[type="checkbox"]::before {
  194. content: "";
  195. width: 16px;
  196. height: 16px;
  197. background: #6b80927a;
  198. border: 2px solid #6b8092;
  199. border-radius: 50%;
  200. position: absolute;
  201. top: 0;
  202. left: 0;
  203. transform: translate(0%, 0%);
  204. transition: all 0.3s ease-in-out;
  205. }
  206.  
  207. #CFBetter_setting_menu input[type="checkbox"]::after {
  208. content: url("data:image/svg+xml,%3Csvg xmlns='://www.w3.org/2000/svg' width='23' height='23' viewBox='0 0 23 23' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M6.55021 5.84315L17.1568 16.4498L16.4497 17.1569L5.84311 6.55026L6.55021 5.84315Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M17.1567 6.55021L6.55012 17.1568L5.84302 16.4497L16.4496 5.84311L17.1567 6.55021Z' fill='%23EA0707' fill-opacity='0.89'/%3E%3C/svg%3E");
  209. position: absolute;
  210. top: 0;
  211. left: 24px;
  212. }
  213.  
  214. #CFBetter_setting_menu input[type="checkbox"]:checked {
  215. border: 2px solid #02c202;
  216. background: #e2f1e1;
  217. }
  218.  
  219. #CFBetter_setting_menu input[type="checkbox"]:checked::before {
  220. background: rgba(2, 194, 2, 0.5);
  221. border: 2px solid #02c202;
  222. transform: translate(119%, 0%);
  223. transition: all 0.3s ease-in-out;
  224. }
  225.  
  226. #CFBetter_setting_menu input[type="checkbox"]:checked::after {
  227. content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='15' height='13' viewBox='0 0 15 13' fill='none'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M14.8185 0.114533C15.0314 0.290403 15.0614 0.605559 14.8855 0.818454L5.00187 12.5L0.113036 6.81663C-0.0618274 6.60291 -0.0303263 6.2879 0.183396 6.11304C0.397119 5.93817 0.71213 5.96967 0.886994 6.18339L5.00187 11L14.1145 0.181573C14.2904 -0.0313222 14.6056 -0.0613371 14.8185 0.114533Z' fill='%2302C202' fill-opacity='0.9'/%3E%3C/svg%3E");
  228. position: absolute;
  229. top: 3px;
  230. left: 4px;
  231. }
  232.  
  233. #CFBetter_setting_menu input[type="checkbox"] + label {
  234. margin: 0px 0px 0px 10px !important;
  235. font-size: 16px;
  236. }
  237.  
  238. .CFBetter_setting_list {
  239. display: flex;
  240. align-items: center;
  241. margin-bottom: 18px;
  242. }
  243.  
  244. /*设置面板-radio*/
  245. #CFBetter_setting_menu>label {
  246. display: flex;
  247. list-style-type: none;
  248. padding-inline-start: 0px;
  249. overflow-x: auto;
  250. max-width: 100%;
  251. margin: 0px;
  252. align-items: center;
  253. margin: 3px 0px;
  254. }
  255.  
  256. .CFBetter_setting_menu_label_text {
  257. border: 1px dashed #00aeeccc;
  258. display: block;
  259. height: 20px;
  260. width: 100%;
  261. color: gray;
  262. font-weight: 300;
  263. font-size: 14px;
  264. letter-spacing: 2px;
  265. padding: 7px;
  266. }
  267.  
  268. input[type="radio"]:checked+.CFBetter_setting_menu_label_text {
  269. background: #41e49930;
  270. border: 1px solid green;
  271. color: green;
  272. font-weight: 500;
  273. }
  274.  
  275. #CFBetter_setting_menu>label input[type="radio"] {
  276. -webkit-appearance: none;
  277. appearance: none;
  278. list-style: none;
  279. margin: 0px;
  280. }
  281.  
  282. #CFBetter_setting_menu input[type="text"] {
  283. display: block;
  284. height: 25px;
  285. background-color: #ffffff;
  286. color: #727378;
  287. font-size: 10px;
  288. border-radius: 0.3rem;
  289. padding: 1px 5px;
  290. margin: 5px 0px 5px 0px;
  291. border: 1px solid #00aeeccc;
  292. box-shadow: 0 0 1px #0000004d;
  293. }
  294.  
  295. .CFBetter_setting_menu_input {
  296. width: 100%;
  297. display: grid;
  298. justify-content: start;
  299. }
  300.  
  301. #CFBetter_setting_menu #save {
  302. cursor: pointer;
  303. display: inline-flex;
  304. padding: 0.5rem 1rem;
  305. background-color: #1aa06d;
  306. color: #ffffff;
  307. font-size: 1rem;
  308. line-height: 1.5rem;
  309. font-weight: 500;
  310. justify-content: center;
  311. width: 100%;
  312. border-radius: 0.375rem;
  313. border: none;
  314. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  315. }
  316.  
  317. #CFBetter_setting_menu span.tip {
  318. color: red;
  319. font-size: 2px;
  320. font-weight: 500;
  321. padding: 0px 0px 10px 0px;
  322. }
  323. /*更新检查*/
  324. div#update_panel {
  325. position: fixed;
  326. top: 50%;
  327. left: 50%;
  328. width: 240px;
  329. transform: translate(-50%, -50%);
  330. background-color: #fdfdfd;
  331. border: 1px solid #00aeeccc;
  332. border-radius: 5px;
  333. box-shadow: 2px 2px 3px 1px #0000004d;
  334. padding: 10px 20px 20px 20px;
  335. color: #444242;
  336. background-color: #ecf0ff;
  337. border: 6px solid #ffffff;
  338. border-radius: 16px;
  339. }
  340. div#update_panel #updating {
  341. cursor: pointer;
  342. display: inline-flex;
  343. padding: 0px;
  344. background-color: #1aa06d;
  345. color: #ffffff;
  346. font-size: 1rem;
  347. line-height: 1.5rem;
  348. font-weight: 500;
  349. justify-content: center;
  350. width: 100%;
  351. border-radius: 0.375rem;
  352. border: none;
  353. box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  354. }
  355. div#update_panel #updating a {
  356. text-decoration: none;
  357. color: white;
  358. display: flex;
  359. position: inherit;
  360. top: 0;
  361. left: 0;
  362. width: 100%;
  363. height: 22px;
  364. font-size: 14px;
  365. justify-content: center;
  366. align-items: center;
  367. }
  368. `);
  369.  
  370. // 更新检查
  371. (function checkScriptVersion() {
  372. function compareVersions(version1 = "0", version2 = "0") {
  373. const v1Array = String(version1).split(".");
  374. const v2Array = String(version2).split(".");
  375. const minLength = Math.min(v1Array.length, v2Array.length);
  376. let result = 0;
  377. for (let i = 0; i < minLength; i++) {
  378. const curV1 = Number(v1Array[i]);
  379. const curV2 = Number(v2Array[i]);
  380. if (curV1 > curV2) {
  381. result = 1;
  382. break;
  383. } else if (curV1 < curV2) {
  384. result = -1;
  385. break;
  386. }
  387. }
  388. if (result === 0 && v1Array.length !== v2Array.length) {
  389. const v1IsBigger = v1Array.length > v2Array.length;
  390. const maxLenArray = v1IsBigger ? v1Array : v2Array;
  391. for (let i = minLength; i < maxLenArray.length; i++) {
  392. const curVersion = Number(maxLenArray[i]);
  393. if (curVersion > 0) {
  394. v1IsBigger ? result = 1 : result = -1;
  395. break;
  396. }
  397. }
  398. }
  399. return result;
  400. }
  401.  
  402. GM_xmlhttpRequest({
  403. method: "GET",
  404. url: "https://greasyfork.org/zh-CN/scripts/465777.json",
  405. timeout: 10 * 1e3,
  406. onload: function (response) {
  407. const scriptData = JSON.parse(response.responseText);
  408. if (scriptData.name === GM_info.script.name && compareVersions(scriptData.version, GM_info.script.version) === 1) {
  409. $("body").append(`
  410. <div id='update_panel'>
  411. <h3>${GM_info.script.name}有新版本!</h3>
  412. <hr>
  413. <div class='update_panel_menu'>
  414. <span class ='tip'>版本信息:${GM_info.script.version} ${scriptData.version}</span>
  415. </div>
  416. <br>
  417. <button id='updating'><a target="_blank" href="${scriptData.url}">更新</a></button>
  418. </div>
  419. `);
  420. }
  421. }
  422. });
  423. })();
  424.  
  425. // 汉化替换
  426. (function () {
  427. if (getCookie("bottomZh_CN") === '') setCookie("bottomZh_CN", "true", 3650);
  428. if (getCookie("bottomZh_CN") != "true") return;
  429. // 设置语言为zh
  430. var htmlTag = document.getElementsByTagName("html")[0];
  431. htmlTag.setAttribute("lang", "zh-CN");
  432.  
  433. // 暴力html替换
  434. const classData = {
  435. '.menu-list.main-menu-list': [
  436. { match: 'Help', replace: '帮助' },
  437. { match: 'Calendar', replace: '日历' },
  438. { match: 'Edu', replace: '培训' },
  439. { match: 'Rating', replace: '积分榜' },
  440. { match: 'Groups', replace: '团体' },
  441. { match: 'Problemset', replace: '题单' },
  442. { match: 'Gym', replace: '训练营(过去的大型比赛)' },
  443. { match: 'Contests', replace: '比赛' },
  444. { match: 'Catalog', replace: '指南目录' },
  445. { match: 'Top', replace: '热门' },
  446. { match: 'Home', replace: '主页' },
  447. ],
  448. '.personal-sidebar ': [
  449. { match: 'Contribution', replace: '贡献' },
  450. { match: 'Settings', replace: '设置' },
  451. { match: 'Blog', replace: '博客' },
  452. { match: 'Teams', replace: '队伍' },
  453. { match: 'Submissions', replace: '提交' },
  454. { match: 'Talks', replace: '私信' },
  455. { match: 'Contests', replace: '比赛' },
  456. ],
  457. '.contest-state-phase': [
  458. { match: 'Before contest', replace: '即将进行的比赛' },
  459. ],
  460. '.notice': [
  461. { match: 'has extra registration', replace: '有额外的报名时期' },
  462. { match: 'If you are late to register in 5 minutes before the start, you can register later during the extra registration. Extra registration opens 10 minutes after the contest starts and lasts 25 minutes.', replace: '如果您在比赛开始前5分钟前还未报名,您可以在额外的报名期间稍后报名。额外的报名将在比赛开始后10分钟开放,并持续25分钟。' },
  463. ],
  464. '.act-item': [
  465. { match: 'Submit', replace: '提交' },
  466. ],
  467. '.datatable': [
  468. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  469. { match: 'Enter', replace: '进入' },
  470. { match: 'Final standings', replace: '榜单' },
  471. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  472. { match: 'Official School Contest', replace: '学校官方比赛' },
  473. { match: 'Training Contest', replace: '训练赛' },
  474. { match: 'Training Camp Contest', replace: '训练营比赛' },
  475. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  476. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  477. { match: 'China', replace: '中国' },
  478. { match: 'Statements', replace: '题目描述' },
  479. { match: 'in Chinese', replace: '中文' },
  480. { match: 'Trainings', replace: '训练' },
  481. { match: 'Prepared by', replace: '编写人' },
  482. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  483. { match: 'Past contests', replace: '过去的比赛' },
  484. { match: 'Exclusions', replace: '排除' },
  485. { match: 'Before start', replace: '还有' },
  486. { match: 'Before registration', replace: '报名还有' },
  487. { match: 'Until closing ', replace: '结束报名' },
  488. { match: 'Register', replace: '报名' },
  489. { match: 'Registration completed', replace: '已报名' },
  490. ],
  491. '.contests-table': [
  492. { match: 'Contest history', replace: '比赛历史' },
  493. ],
  494. '.roundbox.sidebox.borderTopRound ': [
  495. { match: 'Register now', replace: '现在报名' },
  496. ],
  497. '.icon-eye-close.icon-large': [
  498. { match: 'Add to exclusions', replace: '添加到排除列表' },
  499. ],
  500. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  501. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  502. ],
  503. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  504. { match: 'Announcement', replace: '公告' },
  505. { match: 'Statements', replace: '统计报表' },
  506. { match: 'Tutorial', replace: '题解' },
  507. ],
  508. '.second-level-menu ': [
  509. { match: 'Problems', replace: '问题' },
  510. { match: 'Submit Code', replace: '提交代码' },
  511. { match: 'My Submissions', replace: '我的提交' },
  512. { match: 'Status', replace: '状态' },
  513. { match: 'Standings', replace: '榜单' },
  514. { match: 'Custom Invocation', replace: '自定义调试' },
  515. { match: 'Common standings', replace: '全部排行' },
  516. { match: 'Friends standings', replace: '只看朋友' },
  517. { match: 'Submit', replace: '提交' },
  518. { match: 'Custom test', replace: '自定义测试' },
  519. { match: 'Blog', replace: '博客' },
  520. { match: 'Teams', replace: '队伍' },
  521. { match: 'Submissions', replace: '提交' },
  522. { match: 'Groups', replace: '团体' },
  523. { match: 'Contests', replace: '比赛' },
  524. { match: '问题etting', replace: '参与编写的问题' },
  525. { match: 'Gym', replace: '训练营' },
  526. { match: 'Mashups', replace: '组合混搭' },
  527. { match: 'Posts', replace: '帖子' },
  528. { match: '>Comments<', replace: '>回复<' },
  529. { match: 'Main', replace: '主要' },
  530. { match: 'Settings', replace: '设置' },
  531. { match: 'Lists', replace: '列表' },
  532. ],
  533. '.topic-toggle-collapse': [
  534. { match: 'Expand', replace: '展开' },
  535. ],
  536. '.topic-read-more': [
  537. { match: 'Full text and comments', replace: '阅读全文/评论' },
  538. ],
  539. '.toggleEditorCheckboxLabel': [
  540. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  541. ],
  542. '.submit': [
  543. { match: 'Registration for the contest', replace: '比赛报名' },
  544. ],
  545. };
  546. for (const className in classData) {
  547. const elements = document.querySelectorAll(className);
  548. elements.forEach((element) => {
  549. let html = element.outerHTML;
  550. const parent = element.parentNode;
  551. const childIndex = Array.from(parent.children).indexOf(element);
  552. let matched = false;
  553. classData[className].forEach((rule) => {
  554. if (html.match(new RegExp(rule.match, 'g'))) {
  555. matched = true;
  556. html = html.replace(new RegExp(rule.match, 'g'), rule.replace);
  557. const temp = document.createElement('div');
  558. temp.innerHTML = html.trim();
  559. const newElement = element.cloneNode(true);
  560. newElement.innerHTML = temp.firstChild.innerHTML;
  561. parent.replaceChild(newElement, parent.children[childIndex]);
  562. }
  563. });
  564. });
  565. }
  566.  
  567. // 元素选择替换
  568. // 侧栏titled汉化
  569. (function () {
  570. var translations = {
  571. "Pay attention": "→ 注意",
  572. "Top rated": "→ 积分排行",
  573. "Top contributors": "→ 贡献者排行",
  574. "Find user": "→ 查找用户",
  575. "Recent actions": "→ 最近热帖",
  576. "Training filter": "→ 过滤筛选",
  577. "Find training": "→ 搜索比赛/问题",
  578. "Virtual participation": "→ 什么是虚拟参赛",
  579. "Contest materials": "→ 比赛相关资料",
  580. "Settings": "→ 设置",
  581. "Clone Contest to Mashup": "→ Clone比赛到组合混搭",
  582. "Submit": "→ 提交",
  583. "Practice": "→ 练习",
  584. "Problem tags": "→ 问题标签",
  585. "Filter Problems": "→ 过滤问题",
  586. "Attention": "→ 注意",
  587. "About Contest": "→ 关于比赛",
  588. };
  589.  
  590. $(".caption.titled").each(function () {
  591. var tag = $(this).text();
  592. for (var property in translations) {
  593. if (tag.match(property)) {
  594. $(this).addClass(property);
  595. $(this).text(translations[property]);
  596. break;
  597. }
  598. }
  599. });
  600. })();
  601. // 题目Tag汉化
  602. (function () {
  603. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  604. var selectElement = parentElement.find('select');
  605. var translations = {
  606. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  607. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  608. "2-sat": "二分图可满足性问题(2-sat)",
  609. "binary search": "二分搜索(binary search)",
  610. "bitmasks": "位掩码(bitmasks)",
  611. "brute force": "暴力枚举(brute force)",
  612. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  613. "combinatorics": "组合数学(combinatorics)",
  614. "constructive algorithms": "构造算法(constructive algorithms)",
  615. "data structures": "数据结构(data structures)",
  616. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  617. "divide and conquer": "分治算法(divide and conquer)",
  618. "dp": "动态规划(dp)",
  619. "dsu": "并查集(dsu)",
  620. "expression parsing": "表达式解析(expression parsing)",
  621. "fft": "快速傅里叶变换(fft)",
  622. "flows": "流(flows)",
  623. "games": "博弈论(games)",
  624. "geometry": "计算几何(geometry)",
  625. "graph matchings": "图匹配(graph matchings)",
  626. "graphs": "图论(graphs)",
  627. "greedy": "贪心策略(greedy)",
  628. "hashing": "哈希表(hashing)",
  629. "implementation": "实现问题,编程技巧,模拟(implementation)",
  630. "interactive": "交互性问题(interactive)",
  631. "math": "数学(math)",
  632. "matrices": "矩阵(matrices)",
  633. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  634. "number theory": "数论(number theory)",
  635. "probabilities": "概率论(probabilities)",
  636. "schedules": "调度算法(schedules)",
  637. "shortest paths": "最短路算法(shortest paths)",
  638. "sortings": "排序算法(sortings)",
  639. "string suffix structures": "字符串后缀结构(string suffix structures)",
  640. "strings": "字符串处理(strings)",
  641. "ternary search": "三分搜索(ternary search)",
  642. "trees": "树形结构(trees)",
  643. "two pointers": "双指针算法(two pointers)"
  644. };
  645. selectElement.find("option").each(function () {
  646. var optionValue = $(this).val();
  647. if (translations[optionValue]) {
  648. $(this).text(translations[optionValue]);
  649. }
  650. });
  651. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  652. var tag = $(this).text();
  653. if (tag in translations) {
  654. $(this).text(translations[tag]);
  655. }
  656. });
  657. $(".notice").each(function () {
  658. var tag = $(this).text();
  659. if (tag in translations) {
  660. $(this).text(translations[tag]);
  661. }
  662. });
  663. $(".tag-box").each(function () {
  664. var tag = $(this).text();
  665. for (var property in translations) {
  666. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  667. if (tag.match(property)) {
  668. $(this).text(translations[property]);
  669. break;
  670. }
  671. }
  672. });
  673. })();
  674. // 题目过滤器选项汉化
  675. (function () {
  676. var parentElement = $('#gym-filter-form');
  677. var selectElement = parentElement.find('div');
  678. var translations = {
  679. "Contest type:": "比赛类型:",
  680. "ICPC region:": "ICPC地区:",
  681. "Contest format:": "比赛形式:",
  682. "Order by:": "排序方式:",
  683. "Secondary order by:": "次要排序方式:",
  684. "Hide, if participated:": "隐藏我参加过的:",
  685. };
  686. selectElement.find("label").each(function () {
  687. var optionValue = $(this).text();
  688. if (translations[optionValue]) {
  689. $(this).text(translations[optionValue]);
  690. }
  691. });
  692. translations = {
  693. "Season:": "时间范围(年度)",
  694. "Duration, hours:": "持续时间(小时):",
  695. "Difficulty:": "难度:"
  696. };
  697. selectElement.each(function () {
  698. var optionValue = $(this).text();
  699. if (translations[optionValue]) {
  700. $(this).text(translations[optionValue]);
  701. }
  702. });
  703. })();
  704. (function () {
  705. var parentElement = $('.setting-value');
  706. var selectElement = parentElement.find('select');
  707. var translations = {
  708. "Official ACM-ICPC Contest": "ICPC官方比赛",
  709. "Official School Contest": "学校官方比赛",
  710. "Opencup Contest": "Opencup比赛",
  711. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  712. "Training Camp Contest": "训练营比赛",
  713. "Official International Personal Contest": "官方国际个人赛",
  714. "Training Contest": "训练比赛",
  715. "ID_ASC": "创建时间(升序)",
  716. "ID_DESC": "创建时间(降序)",
  717. "RATING_ASC": "评分(升序)",
  718. "RATING_DESC": "评分(降序)",
  719. "DIFFICULTY_ASC": "难度(升序)",
  720. "DIFFICULTY_DESC": "难度(降序)",
  721. "START_TIME_ASC": "开始时间(升序)",
  722. "START_TIME_DESC": "开始时间(降序)",
  723. "DURATION_ASC": "持续时间(升序)",
  724. "DURATION_DESC": "持续时间(降序)",
  725. "POPULARITY_ASC": "热度(升序)",
  726. "POPULARITY_DESC": "热度(降序)",
  727. "UPDATE_TIME_ASC": "更新时间(升序)",
  728. "UPDATE_TIME_DESC": "更新时间(降序)"
  729. };
  730. selectElement.find("option").each(function () {
  731. var optionValue = $(this).val();
  732. if (translations[optionValue]) {
  733. $(this).text(translations[optionValue]);
  734. }
  735. });
  736. parentElement = $('.setting-last-value');
  737. selectElement = parentElement.find('select');
  738. selectElement.find("option").each(function () {
  739. var optionValue = $(this).val();
  740. if (translations[optionValue]) {
  741. $(this).text(translations[optionValue]);
  742. }
  743. });
  744. })();
  745. // 右侧sidebox通用汉化
  746. (function () {
  747. var parentElement = $('.sidebox');
  748. var selectElement = parentElement.find('div');
  749. var translations = {
  750. "Show tags for unsolved problems": "显示未解决问题的标签",
  751. "Hide solved problems": "隐藏已解决的问题",
  752. };
  753. selectElement.find("label").each(function () {
  754. var optionValue = $(this).text();
  755. if (translations[optionValue]) {
  756. $(this).text(translations[optionValue]);
  757. }
  758. });
  759. })();
  760. // 题目提交/报名页汉化
  761. (function () {
  762. var translations = {
  763. "Problem:": "题目:",
  764. "Language:": "语言:",
  765. "Source code:": "源代码:",
  766. "Or choose file:": "或者选择文件:",
  767. "Choose file:": "选择文件:",
  768. "Notice:": "注意:",
  769. "virtual participation:": "虚拟参与:",
  770. "Registration for the contest:": "比赛报名:",
  771. "Terms of agreement:": "协议条款:",
  772. "Take part:": "参与:",
  773. "as individual participant:": "作为个人参与者:",
  774. "as a team member:": "作为团队成员:",
  775. "Virtual start time:": "虚拟开始时间:",
  776. "Complete problemset:": "完整的问题集:",
  777. "Question:": "问题:"
  778. };
  779. $(".field-name").each(function () {
  780. var optionValue = $(this).text();
  781. if (translations[optionValue]) {
  782. $(this).text(translations[optionValue]);
  783. }
  784. });
  785. })();
  786. // 按钮汉化
  787. (function () {
  788. var translations = {
  789. "Register for virtual participation": "报名虚拟参赛"
  790. };
  791. $(".submit").each(function () {
  792. var optionValue = $(this).val();
  793. if (translations[optionValue]) {
  794. $(this).val(translations[optionValue]);
  795. }
  796. });
  797. })();
  798. // 杂项汉化
  799. (function () {
  800. var translations = {
  801. "(standard input\/output)": "标准输入/输出",
  802. };
  803. $("div.notice").each(function () {
  804. var tag = $(this).children().eq(0).text();
  805. for (var property in translations) {
  806. if (tag.match(property)) {
  807. $(this).children().eq(0).text(translations[property]);
  808. break;
  809. }
  810. }
  811. });
  812. })();
  813. (function () {
  814. var translations = {
  815. "Ask a question": "提一个问题",
  816. };
  817. $(".ask-question-link").each(function () {
  818. var optionValue = $(this).text();
  819. if (translations[optionValue]) {
  820. $(this).text(translations[optionValue]);
  821. }
  822. });
  823. })();
  824. })();
  825.  
  826. // **设置面板**
  827. $("div[class='lang-chooser']").each(function () {
  828. $(this).before(
  829. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  830. );
  831. });
  832. $(document).ready(function () {
  833. $(".CFBetter_setting").click(function () {
  834. $(".CFBetter_setting").attr("disabled", true);
  835. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  836. $(".CFBetter_setting").css("color", "#727378");
  837. $(".CFBetter_setting").css("cursor", "not-allowed");
  838. $("body").append(`
  839. <div id='CFBetter_setting_menu'>
  840. <div class="tool-box">
  841. <button class="btn-close">×</button>
  842. </div>
  843. <h3>基本设置</h3>
  844. <hr>
  845. <div class='CFBetter_setting_list'>
  846. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  847. <label for="bottomZh_CN">界面汉化</label>
  848. </div>
  849. <h3>翻译设置</h3>
  850. <hr>
  851. <label>
  852. <input type='radio' name='translation' value='deepl'>
  853. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  854. </label>
  855. <label>
  856. <input type='radio' name='translation' value='youdao'>
  857. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  858. </label>
  859. <label>
  860. <input type='radio' name='translation' value='openai'>
  861. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  862. </label>
  863. <label>
  864. <input type='radio' name='translation' value='api2d'>
  865. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  866. </label><br>
  867. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  868. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  869. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  870. </div>
  871. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  872. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  873. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  874. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  875. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  876. </div>
  877. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  878. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  879. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  880. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  881. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  882. </div>
  883. <br>
  884. <button id='save'>保存</button>
  885. </div>
  886. `);
  887. var translation = getCookie("translation");
  888. $("#bottomZh_CN").prop("checked", getCookie("bottomZh_CN") === "true");
  889. if (translation === 'undefined' || translation === '') {
  890. setCookie("translation", "deepl", 3650);
  891. $("input[name='translation'][value='deepl']").prop("checked", true);
  892. } else {
  893. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  894. $("input[name='translation']").css("color", "gray");
  895. if (translation == "baidu") {
  896. $("#baidu").show();
  897. $("#baidu_uid").val(getCookie("baidu_uid"));
  898. $("#baidu_key").val(getCookie("baidu_key"));
  899. $("#baidu_uid").css("color", "gray");
  900. $("#baidu_key").css("color", "gray");
  901. } else if (translation == "openai") {
  902. $("#openai").show();
  903. $("#openai_key").val(getCookie("openai_key"));
  904. $("#openai_key").css("color", "gray");
  905. } else if (translation == "api2d") {
  906. $("#api2d").show();
  907. $("#api2d_key").val(getCookie("api2d_key"));
  908. $("#api2d_key").css("color", "gray");
  909. }
  910. }
  911.  
  912. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  913. $("input[name='translation']").change(function () {
  914. var selected = $(this).val(); // 获取当前选中的值
  915. if (selected === 'baidu') {
  916. $("#baidu").show();
  917. $("#baidu_uid").val(getCookie("baidu_uid"));
  918. $("#baidu_key").val(getCookie("baidu_key"));
  919. $("#openai, #api2d").hide();
  920. } else if (selected === 'openai') {
  921. $("#openai").show();
  922. $("#openai_key").val(getCookie("openai_key"));
  923. $("#baidu, #api2d").hide();
  924. } else if (selected === 'api2d') {
  925. $("#api2d").show();
  926. $("#api2d_key").val(getCookie("api2d_key"));
  927. $("#baidu, #openai").hide();
  928. } else {
  929. $("#baidu, #openai, #api2d").hide();
  930. }
  931. });
  932.  
  933. $("#save").click(function () {
  934. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  935. var translation = $("input[name='translation']:checked").val();
  936. var baidu_uid = $("#baidu_uid").val();
  937. var baidu_key = $("#baidu_key").val();
  938. var openai_key = $("#openai_key").val();
  939. var api2d_key = $("#api2d_key").val();
  940. setCookie("translation", translation, 3650);
  941. if (translation == "baidu") {
  942. setCookie("baidu_uid", baidu_uid, 3650);
  943. setCookie("baidu_key", baidu_key, 3650);
  944. } else if (translation == "openai") {
  945. setCookie("openai_key", openai_key, 3650);
  946. } else if (translation == "api2d") {
  947. setCookie("api2d_key", api2d_key, 3650);
  948. }
  949. location.reload();
  950. });
  951. // 关闭
  952. $("#CFBetter_setting_menu .btn-close").click(function () {
  953. $("#CFBetter_setting_menu").remove();
  954. $(".CFBetter_setting").attr("disabled", false);
  955. $(".CFBetter_setting").css("background-color", "#60a5fa");
  956. $(".CFBetter_setting").css("color", "white");
  957. $(".CFBetter_setting").css("cursor", "pointer");
  958. });
  959. });
  960. });
  961.  
  962. // 是否为旧的latex渲染
  963. var is_oldLatex = false;
  964. if ($('.tex-span').length) {
  965. is_oldLatex = true;
  966. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  967. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter 无法将其还原回 Latex,因此当前页面部分功能不适用。
  968. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  969. `).css({
  970. "margin": "1em",
  971. "text-align": "center",
  972. "position": "relative"
  973. });
  974. $(".menu-box:first").next().after(newElement);
  975. }
  976.  
  977. // 题目markdown转换/翻译面板
  978. function addButtonPanel(parent, suffix, type, is_simple = false) {
  979. if (type === "upper_level_2" || type === "problem") {
  980. $(parent).children(':eq(1)').before(
  981. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  982. } else if (is_simple) {
  983. $(parent).before(
  984. "<div class='html2md-panel'><button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  985. } else {
  986. $(parent).before(
  987. "<div class='html2md-panel'> <button class='html2mdButton html2md-view" + suffix + "'>MarkDown视图</button> <button class='html2mdButton html2md-cb" + suffix + "'>Copy</button> <button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  988. }
  989. }
  990. function addButtonWithHTML2MD(parent, suffix, type) {
  991. if(is_oldLatex){
  992. $(".html2md-view" + suffix).css({
  993. "cursor": "not-allowed",
  994. "background-color": "#e6e6e638",
  995. "color": "#72737896",
  996. });
  997. $(".html2md-view" + suffix).prop("disabled", true);
  998. }
  999. $(".html2md-view" + suffix).click(function () {
  1000. var target, removedChildren;
  1001. if (type === "problem") {
  1002. target = $(parent).children().next().next().get(0);
  1003. } else if (type === "problem_QA") {
  1004. target = $(this).parent().parent().get(0);
  1005. removedChildren = $(this).parent().parent().children().eq(0).detach();
  1006. } else if (type === "upper_level_2") {
  1007. target = parent;
  1008. removedChildren = $(parent).children().slice(0, 2).detach();
  1009. } else {
  1010. target = parent;
  1011. }
  1012. if (target.viewmd) {
  1013. target.viewmd = false;
  1014. $(this).text("MarkDown视图");
  1015. $(this).removeClass("mdViewed");
  1016. $(target).html(target.original_html);
  1017. } else {
  1018. target.viewmd = true;
  1019. if (!target.original_html) {
  1020. target.original_html = $(target).html();
  1021. }
  1022. if (!target.markdown) {
  1023. target.markdown = turndownService.turndown($(target).html());
  1024. }
  1025. $(this).text("原始内容");
  1026. $(this).addClass("mdViewed");
  1027. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1028. }
  1029. // 恢复删除的元素
  1030. if (type === "problem_QA" || type === "upper_level_2") $(target).prepend(removedChildren);
  1031. });
  1032. }
  1033.  
  1034. function addButtonWithCopy(parent, suffix, type) {
  1035. if(is_oldLatex){
  1036. $(".html2md-cb" + suffix).css({
  1037. "cursor": "not-allowed",
  1038. "background-color": "#e6e6e638",
  1039. "color": "#72737896",
  1040. });
  1041. $(".html2md-cb" + suffix).prop("disabled", true);
  1042. }
  1043. $(".html2md-cb" + suffix).click(function () {
  1044. var target, removedChildren;
  1045. if (type === "problem") {
  1046. target = $($(parent).children().next().next().get(0)).clone();
  1047. } else if (type === "problem_QA") {
  1048. target = $(this).parent().parent().eq(0).clone();
  1049. $(target).children(':first').remove();
  1050. } else if (type === "upper_level_2") {
  1051. target = $(parent).clone();
  1052. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1053. $(target).children(':first').remove();
  1054. } else {
  1055. target = $(parent).clone();
  1056. }
  1057. if (!target.markdown) {
  1058. target.markdown = turndownService.turndown($(target).html());
  1059. }
  1060. const textarea = document.createElement('textarea');
  1061. textarea.value = target.markdown;
  1062. document.body.appendChild(textarea);
  1063. textarea.select();
  1064. document.execCommand('copy');
  1065. document.body.removeChild(textarea);
  1066. $(this).addClass("copied");
  1067. $(this).text("Copied");
  1068. // 更新复制按钮文本
  1069. setTimeout(() => {
  1070. $(this).removeClass("copied");
  1071. $(this).text("Copy");
  1072. }, 2000);
  1073. $(target).remove();
  1074. });
  1075. }
  1076.  
  1077. function addButtonWithTranslation(parent, suffix, type) {
  1078. $(".translateButton" + suffix).click(async function () {
  1079. var target, removedChildren;
  1080. if (type === "problem") {
  1081. target = $($(parent).children().next().next().get(0)).clone();
  1082. } else if (type === "problem_QA") {
  1083. target = $(this).parent().parent().eq(0).clone();
  1084. $(target).children(':first').remove();
  1085. } else if (type === "upper_level_2") {
  1086. target = $(parent).clone();
  1087. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1088. $(target).children(':first').remove();
  1089. } else {
  1090. target = $(parent).clone();
  1091. }
  1092. if (is_oldLatex) {
  1093. target.markdown = $(target).html();
  1094. } else if (!target.markdown) {
  1095. target.markdown = turndownService.turndown($(target).html());
  1096. }
  1097. const textarea = document.createElement('textarea');
  1098. textarea.value = target.markdown;
  1099. // 翻译处理
  1100. $(this).removeClass("translated");
  1101. $(this).text("翻译中");
  1102. $(this).css("cursor", "not-allowed");
  1103. var element_node;
  1104. if (type === "problem") {
  1105. element_node = $(parent).children()[2]; // 题面特殊处理
  1106. } else if (type === "problem_QA") {
  1107. element_node = $(parent).children().last().get(0);
  1108. } else {
  1109. element_node = parent;
  1110. }
  1111. var translateDiv = await translateProblemStatement(textarea.value, element_node);
  1112. //
  1113. $(this).addClass("translated");
  1114. $(this).text("已翻译");
  1115. $(this).prop("disabled", true);
  1116. $(target).remove();
  1117. // 重新翻译
  1118. if ($(this).next('.reTranslation').length === 0) {
  1119. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1120. reTranslateBtn.on('click', function() {
  1121. $(translateDiv).remove();
  1122. $(this).prev().click();
  1123. });
  1124. $(this).after(reTranslateBtn);
  1125. }else {
  1126. const reTranslateBtn = $(this).next('.reTranslation');
  1127. reTranslateBtn.off('click').on('click', function() {
  1128. $(translateDiv).remove();
  1129. $(this).prev().click();
  1130. });
  1131. }
  1132. });
  1133. }
  1134.  
  1135. var turndownService = new TurndownService();
  1136. window.onload = function () {
  1137. turndownService.keep(['del']);
  1138.  
  1139. // 处理规则
  1140. // 忽略
  1141. turndownService.addRule('ignore-sample-tests', {
  1142. filter: function (node) {
  1143. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1144. },
  1145. replacement: function (content, node) {
  1146. return "";
  1147. }
  1148. });
  1149.  
  1150. // remove <script> math
  1151. turndownService.addRule('remove-script', {
  1152. filter: function (node, options) {
  1153. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1154. },
  1155. replacement: function (content, node) {
  1156. return "";
  1157. }
  1158. });
  1159.  
  1160. // inline math
  1161. turndownService.addRule('inline-math', {
  1162. filter: function (node, options) {
  1163. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1164. },
  1165. replacement: function (content, node) {
  1166. return "$ " + $(node).next().text() + " $";
  1167. }
  1168. });
  1169.  
  1170. // block math
  1171. turndownService.addRule('block-math', {
  1172. filter: function (node, options) {
  1173. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1174. },
  1175. replacement: function (content, node) {
  1176. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1177. }
  1178. });
  1179.  
  1180. // bordertable
  1181. turndownService.addRule('bordertable', {
  1182. filter: 'table',
  1183. replacement: function (content, node) {
  1184. if (node.classList.contains('bordertable')) {
  1185. var output = [],
  1186. thead = '',
  1187. trs = node.querySelectorAll('tr');
  1188. if (trs.length > 0) {
  1189. var ths = trs[0].querySelectorAll('th');
  1190. if (ths.length > 0) {
  1191. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1192. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1193. }
  1194. }
  1195. var rows = node.querySelectorAll('tr');
  1196. Array.from(rows).forEach(function (row, i) {
  1197. if (i > 0) {
  1198. var cells = row.querySelectorAll('td,th');
  1199. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1200. output.push(trow);
  1201. }
  1202. });
  1203. return thead + output.join('\n');
  1204. } else {
  1205. return content;
  1206. }
  1207. }
  1208. });
  1209.  
  1210.  
  1211. // 添加按钮到题面部分
  1212. $("div[class='problem-statement']").each(function () {
  1213. var problem_id = "_comment_" + getRandomNumber(8);
  1214. addButtonPanel(this, problem_id, "problem");
  1215. addButtonWithHTML2MD(this, problem_id, "problem");
  1216. addButtonWithCopy(this, problem_id, "problem");
  1217. addButtonWithTranslation(this, problem_id, "problem");
  1218. });
  1219.  
  1220. // 添加按钮到input部分
  1221. $("div[class='input-specification']").each(function () {
  1222. var id = "_" + getRandomNumber(8);
  1223. addButtonPanel(this, id, "upper_level_2");
  1224. addButtonWithHTML2MD(this, id, "upper_level_2");
  1225. addButtonWithCopy(this, id, "upper_level_2");
  1226. addButtonWithTranslation(this, id, "upper_level_2");
  1227. });
  1228.  
  1229. // 添加按钮到output部分
  1230. $("div[class='output-specification']").each(function () {
  1231. var id = "_" + getRandomNumber(8);
  1232. addButtonPanel(this, id, "upper_level_2");
  1233. addButtonWithHTML2MD(this, id, "upper_level_2");
  1234. addButtonWithCopy(this, id, "upper_level_2");
  1235. addButtonWithTranslation(this, id, "upper_level_2");
  1236. });
  1237.  
  1238. // 添加按钮到note部分
  1239. $("div[class='note']").each(function () {
  1240. var id = "_" + getRandomNumber(8);
  1241. addButtonPanel(this, id, "upper_level_2");
  1242. addButtonWithHTML2MD(this, id, "upper_level_2");
  1243. addButtonWithCopy(this, id, "upper_level_2");
  1244. addButtonWithTranslation(this, id, "upper_level_2");
  1245. });
  1246.  
  1247. // 添加按钮到ttypography部分
  1248. $(".ttypography").each(function () {
  1249. // 题目页特判
  1250. if (!$(this).parent().hasClass('problemindexholder')) {
  1251. var comment_id = "_comment_" + getRandomNumber(8);
  1252. addButtonPanel(this, comment_id, "this_level");
  1253. addButtonWithHTML2MD(this, comment_id, "this_level");
  1254. addButtonWithCopy(this, comment_id, "this_level");
  1255. addButtonWithTranslation(this, comment_id, "this_level");
  1256. }
  1257. });
  1258.  
  1259. // 添加按钮到titled部分
  1260. (function () {
  1261. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1262. $.each(elements, function (index, value) {
  1263. $(value).each(function () {
  1264. var titled_id = "_titled_" + getRandomNumber(8);
  1265. var $nextDiv = $(this).next().get(0);
  1266. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1267. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1268. });
  1269. });
  1270. })();
  1271.  
  1272. // 添加按钮到比赛QA部分
  1273. $(".question-requestText-td").each(function () {
  1274. var $nextDiv = $(this).children().get(0);
  1275. var question_id = "_question_" + getRandomNumber(8);
  1276. addButtonPanel($nextDiv, question_id, "problem_QA", true);
  1277. addButtonWithTranslation(this, question_id, "problem_QA");
  1278. });
  1279. };
  1280.  
  1281. // 翻译框/翻译处理器
  1282. var translatedText = "";
  1283. async function translateProblemStatement(text, element_node) {
  1284. let id = Math.floor(Date.now() / 1000);
  1285. let matches = [];
  1286. let replacements = {};
  1287. // 创建元素并放在element_node的后面
  1288. const translateDiv = document.createElement('div');
  1289. translateDiv.setAttribute('id', id);
  1290. translateDiv.classList.add('translate-problem-statement');
  1291. const spanElement = document.createElement('span');
  1292. translateDiv.appendChild(spanElement);
  1293. element_node.insertAdjacentElement('afterend', translateDiv);
  1294. // 替换latex公式
  1295. if (is_oldLatex) {
  1296. //去除开头结尾的<p>标签
  1297. text = text.replace(/^<p>/i, "");
  1298. text = text.replace(/<\/p>$/i, "");
  1299. //
  1300. let i = 0;
  1301. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  1302. matches = text.match(regex);
  1303. try {
  1304. for (i; i < matches.length; i++) {
  1305. let match = matches[i];
  1306. text = text.replace(match, `【${i + 1}】`);
  1307. replacements[`【${i + 1}】`] = match;
  1308. }
  1309. } catch (e) { }
  1310. } else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1311. // 使用GPT翻译时不必替换latex公式
  1312. let i = 0;
  1313. // 块公式
  1314. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1315. try {
  1316. for (i; i < matches.length; i++) {
  1317. let match = matches[i];
  1318. text = text.replace(match, `【${i + 1}】`);
  1319. replacements[`【${i + 1}】`] = match;
  1320. }
  1321. } catch (e) { }
  1322. // 行内公式
  1323. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1324. try {
  1325. for (i; i < matches.length; i++) {
  1326. let match = matches[i];
  1327. text = text.replace(match, `【${i + 1}】`);
  1328. replacements[`【${i + 1}】`] = match;
  1329. }
  1330. } catch (e) { }
  1331. }
  1332. // 翻译
  1333. var translation = getCookie("translation");
  1334. if (translation === 'undefined' || translation === '') {
  1335. setCookie("translation", "deepl", 3650);
  1336. translation = "deepl";
  1337. }
  1338. if (translation == "deepl") {
  1339. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1340. translatedText = await translate_deepl(text);
  1341. } else if (translation == "youdao") {
  1342. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1343. translatedText = await translate_youdao_mobile(text);
  1344. } else if (translation == "baidu") {
  1345. var baidu_appid = getCookie("baidu_uid");
  1346. var baidu_key = getCookie("baidu_key");
  1347. } else if (translation == "openai") {
  1348. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1349. translatedText = await translate_openai(text);
  1350. } else if (translation == "api2d") {
  1351. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1352. translatedText = await translate_api2d(text);
  1353. }
  1354. // 还原latex公式
  1355. if (is_oldLatex) {
  1356. translatedText = "<p>" + translatedText;
  1357. translatedText += "</p>";
  1358. try {
  1359. for (let i = 0; i < matches.length; i++) {
  1360. let match = matches[i];
  1361. let replacement = replacements[`【${i + 1}】`];
  1362. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1363. }
  1364. } catch (e) { }
  1365. }
  1366. else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1367. try {
  1368. for (let i = 0; i < matches.length; i++) {
  1369. let match = matches[i];
  1370. let replacement = replacements[`【${i + 1}】`];
  1371. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1372. }
  1373. } catch (e) { }
  1374. }
  1375. // 使符合mathjx的转换语法
  1376. translatedText = translatedText.replace(/(\$\$)/g, "");
  1377. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1378. // 更新
  1379. if (is_oldLatex) {
  1380. // oldlatex
  1381. translatedText = $.parseHTML(translatedText);
  1382. $(translateDiv).empty().append($(translatedText));
  1383. } else {
  1384. translateDiv.innerHTML = translatedText;
  1385. // 渲染MarkDown
  1386. var md = window.markdownit();
  1387. var html = md.render(translateDiv.innerText);
  1388. translateDiv.innerHTML = html;
  1389. // 渲染Latex
  1390. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1391. }
  1392. return translateDiv;
  1393. }
  1394.  
  1395. // ChatGPT
  1396. async function translate_openai(raw) {
  1397. var openai_key = getCookie("openai_key");
  1398. var openai_retext = "";
  1399. var data;
  1400. if (is_oldLatex) {
  1401. data = {
  1402. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1403. max_tokens: 2048,
  1404. model: "text-davinci-003",
  1405. };
  1406. } else {
  1407. data = {
  1408. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1409. max_tokens: 2048,
  1410. model: "text-davinci-003",
  1411. };
  1412. };
  1413. return new Promise(function (resolve, reject) {
  1414. GM_xmlhttpRequest({
  1415. method: 'POST',
  1416. url: 'https://api.openai.com/v1/completions',
  1417. data: JSON.stringify(data),
  1418. headers: {
  1419. 'Content-Type': 'application/json',
  1420. 'Authorization': 'Bearer ' + getCookie("openai_key") + ''
  1421. },
  1422. responseType: 'json',
  1423. onload: function (res) {
  1424. if (res.status === 200) {
  1425. openai_retext = res.response.choices[0].text;
  1426. openai_retext = openai_retext.replace(/^\s+/, '');
  1427. resolve(openai_retext);
  1428. }
  1429. else {
  1430. console.error(res.statusText);
  1431. reject(res.statusText);
  1432. }
  1433. }
  1434. });
  1435. });
  1436. }
  1437.  
  1438. // api2d
  1439. async function translate_api2d(raw) {
  1440. var api2d_key = getCookie("api2d_key");
  1441. var api2d_retext = "";
  1442. var postData;
  1443. if (is_oldLatex) {
  1444. postData = JSON.stringify({
  1445. model: 'gpt-3.5-turbo',
  1446. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1447. });
  1448. } else {
  1449. postData = JSON.stringify({
  1450. model: 'gpt-3.5-turbo',
  1451. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1452. });
  1453. }
  1454. const options = {
  1455. method: 'POST',
  1456. headers: {
  1457. 'Content-Type': 'application/json',
  1458. Authorization: 'Bearer ' + api2d_key,
  1459. },
  1460. data: postData,
  1461. };
  1462.  
  1463. return new Promise(function (resolve, reject) {
  1464. GM_xmlhttpRequest({
  1465. method: options.method,
  1466. url: `https://openai.api2d.net/v1/chat/completions`,
  1467. headers: options.headers,
  1468. data: options.data,
  1469. responseType: 'json',
  1470. onload: function (response) {
  1471. api2d_retext = response.response.choices[0].message.content;
  1472. resolve(api2d_retext);
  1473. },
  1474. onerror: function (response) {
  1475. console.error(response.statusText);
  1476. reject(response.statusText);
  1477. },
  1478. });
  1479. });
  1480. }
  1481. //
  1482.  
  1483. //--有道翻译m--start
  1484. async function translate_youdao_mobile(raw) {
  1485. const options = {
  1486. method: "POST",
  1487. url: 'http://m.youdao.com/translate',
  1488. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1489. anonymous: true,
  1490. headers: {
  1491. "Content-Type": "application/x-www-form-urlencoded"
  1492. }
  1493. }
  1494. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1495. }
  1496. //--有道翻译m--end
  1497.  
  1498. //--Deepl翻译--start
  1499. function getTimeStamp(iCount) {
  1500. const ts = Date.now();
  1501. if (iCount !== 0) {
  1502. iCount = iCount + 1;
  1503. return ts - (ts % iCount) + iCount;
  1504. } else {
  1505. return ts;
  1506. }
  1507. }
  1508.  
  1509. async function translate_deepl(raw) {
  1510. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1511. const data = {
  1512. jsonrpc: '2.0',
  1513. method: 'LMT_handle_texts',
  1514. id,
  1515. params: {
  1516. splitting: 'newlines',
  1517. lang: {
  1518. source_lang_user_selected: 'auto',
  1519. target_lang: 'ZH',
  1520. },
  1521. texts: [{
  1522. text: raw,
  1523. requestAlternatives: 3
  1524. }],
  1525. timestamp: getTimeStamp(raw.split('i').length - 1)
  1526. }
  1527. }
  1528. let postData = JSON.stringify(data);
  1529. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1530. postData = postData.replace('"method":"', '"method" : "');
  1531. } else {
  1532. postData = postData.replace('"method":"', '"method": "');
  1533. }
  1534. const options = {
  1535. method: 'POST',
  1536. url: 'https://www2.deepl.com/jsonrpc',
  1537. data: postData,
  1538. headers: {
  1539. 'Content-Type': 'application/json',
  1540. 'Host': 'www.deepl.com',
  1541. 'Origin': 'https://www.deepl.com',
  1542. 'Referer': 'https://www.deepl.com/'
  1543. },
  1544. anonymous: true,
  1545. nocache: true,
  1546. }
  1547. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1548. }
  1549.  
  1550. //--Deepl翻译--end
  1551.  
  1552. // Cookie Get/Set
  1553. function setCookie(cname, cvalue, exdays) {
  1554. var d = new Date();
  1555. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  1556. var expires = "expires=" + d.toUTCString();
  1557. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  1558. }
  1559.  
  1560. function getCookie(cname) {
  1561. var name = cname + "=";
  1562. var decodedCookie = decodeURIComponent(document.cookie);
  1563. var ca = decodedCookie.split(';');
  1564. for (var i = 0; i < ca.length; i++) {
  1565. var c = ca[i];
  1566. while (c.charAt(0) == ' ') {
  1567. c = c.substring(1);
  1568. }
  1569. if (c.indexOf(name) == 0) {
  1570. return c.substring(name.length, c.length);
  1571. }
  1572. }
  1573. return "";
  1574. }
  1575.  
  1576.  
  1577. //--异步请求包装工具--start
  1578. async function PromiseRetryWrap(task, options, ...values) {
  1579. const { RetryTimes, ErrProcesser } = options || {};
  1580. let retryTimes = RetryTimes || 5;
  1581. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1582. if (!task) return;
  1583. while (true) {
  1584. try {
  1585. return await task(...values);
  1586. } catch (err) {
  1587. if (!--retryTimes) {
  1588. console.log(err);
  1589. return usedErrProcesser(err);
  1590. }
  1591. }
  1592. }
  1593. }
  1594.  
  1595. async function BaseTranslate(name, raw, options, processer) {
  1596. const toDo = async () => {
  1597. var tmp;
  1598. try {
  1599. const data = await Request(options);
  1600. tmp = data.responseText;
  1601. const result = await processer(tmp);
  1602. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1603. return result
  1604. } catch (err) {
  1605. throw {
  1606. responseText: tmp,
  1607. err: err
  1608. }
  1609. }
  1610. }
  1611. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错" })
  1612. }
  1613.  
  1614. function Request(options) {
  1615. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  1616. }
  1617.  
  1618. //--异步请求包装工具--end
  1619.  
  1620. // 随机数生成
  1621. function getRandomNumber(numDigits) {
  1622. let min = Math.pow(10, numDigits - 1);
  1623. let max = Math.pow(10, numDigits) - 1;
  1624. return Math.floor(Math.random() * (max - min + 1)) + min;
  1625. }