Codeforces Better!

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

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

  1. // ==UserScript==
  2. // @name Codeforces Better!
  3. // @namespace https://greasyfork.org/users/747162
  4. // @version 1.24
  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: 'Add to favourites', replace: '添加到收藏' },
  466. { match: 'Submit', replace: '提交' },
  467. ],
  468. '.datatable': [
  469. { match: 'Virtual participation', replace: '参加虚拟重现赛' },
  470. { match: 'Enter', replace: '进入' },
  471. { match: 'Final standings', replace: '榜单' },
  472. { match: 'School/University/City/Region Championship', replace: '学校/大学/城市/区域比赛' },
  473. { match: 'Official School Contest', replace: '学校官方比赛' },
  474. { match: 'Training Contest', replace: '训练赛' },
  475. { match: 'Training Camp Contest', replace: '训练营比赛' },
  476. { match: 'Official ICPC Contest', replace: 'ICPC官方比赛' },
  477. { match: 'Official International Personal Contest', replace: '官方国际个人赛' },
  478. { match: 'China', replace: '中国' },
  479. { match: 'Statements', replace: '题目描述' },
  480. { match: 'in Chinese', replace: '中文' },
  481. { match: 'Trainings', replace: '训练' },
  482. { match: 'Prepared by', replace: '编写人' },
  483. { match: 'Current or upcoming contests', replace: '当前或即将举行的比赛' },
  484. { match: 'Past contests', replace: '过去的比赛' },
  485. { match: 'Exclusions', replace: '排除' },
  486. { match: 'Before start', replace: '还有' },
  487. { match: 'Before registration', replace: '报名还有' },
  488. { match: 'Until closing ', replace: '结束报名' },
  489. { match: 'Register', replace: '报名' },
  490. { match: 'Registration completed', replace: '已报名' },
  491. { match: 'Questions about problems', replace: '关于题目的提问' },
  492. ],
  493. '.ask-question-link': [
  494. { match: 'Ask a question', replace: '提一个问题' },
  495. ],
  496. '.contests-table': [
  497. { match: 'Contest history', replace: '比赛历史' },
  498. ],
  499. '.roundbox.sidebox.borderTopRound ': [
  500. { match: 'Register now', replace: '现在报名' },
  501. ],
  502. '.icon-eye-close.icon-large': [
  503. { match: 'Add to exclusions', replace: '添加到排除列表' },
  504. ],
  505. '._ContestFilterExclusionsManageFrame_addExclusionLink': [
  506. { match: 'Add to exclusions for gym contests filter', replace: '添加训练营过滤器的排除项' },
  507. ],
  508. '.roundbox.sidebox.sidebar-menu.borderTopRound ': [
  509. { match: 'Announcement', replace: '公告' },
  510. { match: 'Statements', replace: '统计报表' },
  511. { match: 'Tutorial', replace: '题解' },
  512. ],
  513. '.second-level-menu ': [
  514. { match: 'Problems', replace: '问题' },
  515. { match: 'Submit Code', replace: '提交代码' },
  516. { match: 'My Submissions', replace: '我的提交' },
  517. { match: 'Status', replace: '状态' },
  518. { match: 'Standings', replace: '榜单' },
  519. { match: 'Custom Invocation', replace: '自定义调试' },
  520. { match: 'Common standings', replace: '全部排行' },
  521. { match: 'Friends standings', replace: '只看朋友' },
  522. { match: 'Submit', replace: '提交' },
  523. { match: 'Custom test', replace: '自定义测试' },
  524. { match: 'Blog', replace: '博客' },
  525. { match: 'Teams', replace: '队伍' },
  526. { match: 'Submissions', replace: '提交' },
  527. { match: 'Groups', replace: '团体' },
  528. { match: 'Contests', replace: '比赛' },
  529. { match: '问题etting', replace: '参与编写的问题' },
  530. { match: 'Gym', replace: '训练营' },
  531. { match: 'Mashups', replace: '组合混搭' },
  532. { match: 'Posts', replace: '帖子' },
  533. { match: '>Comments<', replace: '>回复<' },
  534. { match: 'Main', replace: '主要' },
  535. { match: 'Settings', replace: '设置' },
  536. { match: 'Lists', replace: '列表' },
  537. ],
  538. '.topic-toggle-collapse': [
  539. { match: 'Expand', replace: '展开' },
  540. ],
  541. '.topic-read-more': [
  542. { match: 'Full text and comments', replace: '阅读全文/评论' },
  543. ],
  544. '.toggleEditorCheckboxLabel': [
  545. { match: 'Switch off editor', replace: '关闭编辑器语法高亮' },
  546. ],
  547. '.submit': [
  548. { match: 'Registration for the contest', replace: '比赛报名' },
  549. ],
  550. };
  551. for (const className in classData) {
  552. const elements = document.querySelectorAll(className);
  553. elements.forEach((element) => {
  554. let html = element.outerHTML;
  555. const parent = element.parentNode;
  556. const childIndex = Array.from(parent.children).indexOf(element);
  557. let matched = false;
  558. classData[className].forEach((rule) => {
  559. if (html.match(new RegExp(rule.match, 'g'))) {
  560. matched = true;
  561. html = html.replace(new RegExp(rule.match, 'g'), rule.replace);
  562. const temp = document.createElement('div');
  563. temp.innerHTML = html.trim();
  564. const newElement = element.cloneNode(true);
  565. newElement.innerHTML = temp.firstChild.innerHTML;
  566. parent.replaceChild(newElement, parent.children[childIndex]);
  567. }
  568. });
  569. });
  570. }
  571.  
  572. // 元素选择替换
  573. // 侧栏titled汉化
  574. (function () {
  575. var translations = {
  576. "Pay attention": "→ 注意",
  577. "Top rated": "→ 积分排行",
  578. "Top contributors": "→ 贡献者排行",
  579. "Find user": "→ 查找用户",
  580. "Recent actions": "→ 最近热帖",
  581. "Training filter": "→ 过滤筛选",
  582. "Find training": "→ 搜索比赛/问题",
  583. "Virtual participation": "→ 什么是虚拟参赛",
  584. "Contest materials": "→ 比赛相关资料",
  585. "Settings": "→ 设置",
  586. "Clone Contest to Mashup": "→ Clone比赛到组合混搭",
  587. "Submit": "→ 提交",
  588. "Practice": "→ 练习",
  589. "Problem tags": "→ 问题标签",
  590. "Filter Problems": "→ 过滤问题",
  591. "Attention": "→ 注意",
  592. "About Contest": "→ 关于比赛",
  593. };
  594.  
  595. $(".caption.titled").each(function () {
  596. var tag = $(this).text();
  597. for (var property in translations) {
  598. if (tag.match(property)) {
  599. $(this).addClass(property);
  600. $(this).text(translations[property]);
  601. break;
  602. }
  603. }
  604. });
  605. })();
  606. // 题目Tag汉化
  607. (function () {
  608. var parentElement = $('._FilterByTagsFrame_addTagLabel');
  609. var selectElement = parentElement.find('select');
  610. var translations = {
  611. "*combine tags by OR": "*按逻辑或组合我选择的标签",
  612. "combine-tags-by-or": "*按逻辑或组合我选择的标签(combine-tags-by-or)",
  613. "2-sat": "二分图可满足性问题(2-sat)",
  614. "binary search": "二分搜索(binary search)",
  615. "bitmasks": "位掩码(bitmasks)",
  616. "brute force": "暴力枚举(brute force)",
  617. "chinese remainder theorem": "中国剩余定理(chinese remainder theorem)",
  618. "combinatorics": "组合数学(combinatorics)",
  619. "constructive algorithms": "构造算法(constructive algorithms)",
  620. "data structures": "数据结构(data structures)",
  621. "dfs and similar": "深度优先搜索及其变种(dfs and similar)",
  622. "divide and conquer": "分治算法(divide and conquer)",
  623. "dp": "动态规划(dp)",
  624. "dsu": "并查集(dsu)",
  625. "expression parsing": "表达式解析(expression parsing)",
  626. "fft": "快速傅里叶变换(fft)",
  627. "flows": "流(flows)",
  628. "games": "博弈论(games)",
  629. "geometry": "计算几何(geometry)",
  630. "graph matchings": "图匹配(graph matchings)",
  631. "graphs": "图论(graphs)",
  632. "greedy": "贪心策略(greedy)",
  633. "hashing": "哈希表(hashing)",
  634. "implementation": "实现问题,编程技巧,模拟(implementation)",
  635. "interactive": "交互性问题(interactive)",
  636. "math": "数学(math)",
  637. "matrices": "矩阵(matrices)",
  638. "meet-in-the-middle": "meet-in-the-middle算法(meet-in-the-middle)",
  639. "number theory": "数论(number theory)",
  640. "probabilities": "概率论(probabilities)",
  641. "schedules": "调度算法(schedules)",
  642. "shortest paths": "最短路算法(shortest paths)",
  643. "sortings": "排序算法(sortings)",
  644. "string suffix structures": "字符串后缀结构(string suffix structures)",
  645. "strings": "字符串处理(strings)",
  646. "ternary search": "三分搜索(ternary search)",
  647. "trees": "树形结构(trees)",
  648. "two pointers": "双指针算法(two pointers)"
  649. };
  650. selectElement.find("option").each(function () {
  651. var optionValue = $(this).val();
  652. if (translations[optionValue]) {
  653. $(this).text(translations[optionValue]);
  654. }
  655. });
  656. $("._FilterByTagsFrame_tagBoxCaption").each(function () {
  657. var tag = $(this).text();
  658. if (tag in translations) {
  659. $(this).text(translations[tag]);
  660. }
  661. });
  662. $(".notice").each(function () {
  663. var tag = $(this).text();
  664. if (tag in translations) {
  665. $(this).text(translations[tag]);
  666. }
  667. });
  668. $(".tag-box").each(function () {
  669. var tag = $(this).text();
  670. for (var property in translations) {
  671. property = property.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
  672. if (tag.match(property)) {
  673. $(this).text(translations[property]);
  674. break;
  675. }
  676. }
  677. });
  678. })();
  679. // 题目过滤器选项汉化
  680. (function () {
  681. var parentElement = $('#gym-filter-form');
  682. var selectElement = parentElement.find('div');
  683. var translations = {
  684. "Contest type:": "比赛类型:",
  685. "ICPC region:": "ICPC地区:",
  686. "Contest format:": "比赛形式:",
  687. "Order by:": "排序方式:",
  688. "Secondary order by:": "次要排序方式:",
  689. "Hide, if participated:": "隐藏我参加过的:",
  690. };
  691. selectElement.find("label").each(function () {
  692. var optionValue = $(this).text();
  693. if (translations[optionValue]) {
  694. $(this).text(translations[optionValue]);
  695. }
  696. });
  697. translations = {
  698. "Season:": "时间范围(年度)",
  699. "Duration, hours:": "持续时间(小时):",
  700. "Difficulty:": "难度:"
  701. };
  702. selectElement.each(function () {
  703. var optionValue = $(this).text();
  704. if (translations[optionValue]) {
  705. $(this).text(translations[optionValue]);
  706. }
  707. });
  708. })();
  709. (function () {
  710. var parentElement = $('.setting-value');
  711. var selectElement = parentElement.find('select');
  712. var translations = {
  713. "Official ACM-ICPC Contest": "ICPC官方比赛",
  714. "Official School Contest": "学校官方比赛",
  715. "Opencup Contest": "Opencup比赛",
  716. "School/University/City/Region Championship": "学校/大学/城市/地区锦标赛",
  717. "Training Camp Contest": "训练营比赛",
  718. "Official International Personal Contest": "官方国际个人赛",
  719. "Training Contest": "训练比赛",
  720. "ID_ASC": "创建时间(升序)",
  721. "ID_DESC": "创建时间(降序)",
  722. "RATING_ASC": "评分(升序)",
  723. "RATING_DESC": "评分(降序)",
  724. "DIFFICULTY_ASC": "难度(升序)",
  725. "DIFFICULTY_DESC": "难度(降序)",
  726. "START_TIME_ASC": "开始时间(升序)",
  727. "START_TIME_DESC": "开始时间(降序)",
  728. "DURATION_ASC": "持续时间(升序)",
  729. "DURATION_DESC": "持续时间(降序)",
  730. "POPULARITY_ASC": "热度(升序)",
  731. "POPULARITY_DESC": "热度(降序)",
  732. "UPDATE_TIME_ASC": "更新时间(升序)",
  733. "UPDATE_TIME_DESC": "更新时间(降序)"
  734. };
  735. selectElement.find("option").each(function () {
  736. var optionValue = $(this).val();
  737. if (translations[optionValue]) {
  738. $(this).text(translations[optionValue]);
  739. }
  740. });
  741. parentElement = $('.setting-last-value');
  742. selectElement = parentElement.find('select');
  743. selectElement.find("option").each(function () {
  744. var optionValue = $(this).val();
  745. if (translations[optionValue]) {
  746. $(this).text(translations[optionValue]);
  747. }
  748. });
  749. })();
  750. // 右侧sidebox通用汉化
  751. (function () {
  752. var parentElement = $('.sidebox');
  753. var selectElement = parentElement.find('div');
  754. var translations = {
  755. "Show tags for unsolved problems": "显示未解决问题的标签",
  756. "Hide solved problems": "隐藏已解决的问题",
  757. };
  758. selectElement.find("label").each(function () {
  759. var optionValue = $(this).text();
  760. if (translations[optionValue]) {
  761. $(this).text(translations[optionValue]);
  762. }
  763. });
  764. })();
  765. // 题目提交/报名页汉化
  766. (function () {
  767. var translations = {
  768. "Problem:": "题目:",
  769. "Language:": "语言:",
  770. "Source code:": "源代码:",
  771. "Or choose file:": "或者选择文件:",
  772. "Choose file:": "选择文件:",
  773. "Notice:": "注意:",
  774. "virtual participation:": "虚拟参与:",
  775. "Registration for the contest:": "比赛报名:",
  776. "Terms of agreement:": "协议条款:",
  777. "Take part:": "参与:",
  778. "as individual participant:": "作为个人参与者:",
  779. "as a team member:": "作为团队成员:",
  780. "Virtual start time:": "虚拟开始时间:",
  781. "Complete problemset:": "完整的问题集:"
  782. };
  783. $(".field-name").each(function () {
  784. var optionValue = $(this).text();
  785. if (translations[optionValue]) {
  786. $(this).text(translations[optionValue]);
  787. }
  788. });
  789. })();
  790. // 按钮汉化
  791. (function () {
  792. var translations = {
  793. "Register for virtual participation": "报名虚拟参赛"
  794. };
  795. $(".submit").each(function () {
  796. var optionValue = $(this).val();
  797. if (translations[optionValue]) {
  798. $(this).val(translations[optionValue]);
  799. }
  800. });
  801. })();
  802. // 杂项汉化
  803. (function () {
  804. var translations = {
  805. "(standard input\/output)": "标准输入/输出",
  806. };
  807. $("div.notice").each(function () {
  808. var tag = $(this).children().eq(0).text();
  809. for (var property in translations) {
  810. if (tag.match(property)) {
  811. $(this).children().eq(0).text(translations[property]);
  812. break;
  813. }
  814. }
  815. });
  816. })();
  817.  
  818. })();
  819.  
  820. // **设置面板**
  821. $("div[class='lang-chooser']").each(function () {
  822. $(this).before(
  823. "<button class='html2mdButton CFBetter_setting'>CodeforcesBetter设置</button>"
  824. );
  825. });
  826. $(document).ready(function () {
  827. $(".CFBetter_setting").click(function () {
  828. $(".CFBetter_setting").attr("disabled", true);
  829. $(".CFBetter_setting").css("background-color", "#e6e6e6");
  830. $(".CFBetter_setting").css("color", "#727378");
  831. $(".CFBetter_setting").css("cursor", "not-allowed");
  832. $("body").append(`
  833. <div id='CFBetter_setting_menu'>
  834. <div class="tool-box">
  835. <button class="btn-close">×</button>
  836. </div>
  837. <h3>基本设置</h3>
  838. <hr>
  839. <div class='CFBetter_setting_list'>
  840. <input type="checkbox" id="bottomZh_CN" name="bottomZh_CN" checked>
  841. <label for="bottomZh_CN">界面汉化</label>
  842. </div>
  843. <h3>翻译设置</h3>
  844. <hr>
  845. <label>
  846. <input type='radio' name='translation' value='deepl'>
  847. <span class='CFBetter_setting_menu_label_text'>deepl翻译</span>
  848. </label>
  849. <label>
  850. <input type='radio' name='translation' value='youdao'>
  851. <span class='CFBetter_setting_menu_label_text'>有道翻译</span>
  852. </label>
  853. <label>
  854. <input type='radio' name='translation' value='openai'>
  855. <span class='CFBetter_setting_menu_label_text'>使用ChatGPT翻译(API)</span>
  856. </label>
  857. <label>
  858. <input type='radio' name='translation' value='api2d'>
  859. <span class='CFBetter_setting_menu_label_text'>使用api2d翻译(API)</span>
  860. </label><br>
  861. <div class='CFBetter_setting_menu_input' id='baidu' style='display: none;'>
  862. <label for='baidu_uid'>APP ID:</label><input type='text' id='baidu_uid'>
  863. <label for='baidu_key'>KEY:</label><input type='text' id='baidu_key'>
  864. </div>
  865. <div class='CFBetter_setting_menu_input' id='openai' style='display: none;'>
  866. <span class ='tip'>提示:<br>请确保你能够正常访问OpenAIapi<br></span>
  867. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成,</span>
  868. <span class ='tip'>你需要输入自己的OpenAI KEY,<a target="_blank" href="https://platform.openai.com/account/usage">官网</a></span>
  869. <label for='openai_key'>KEY:</label><input type='text' id='openai_key'>
  870. </div>
  871. <div class='CFBetter_setting_menu_input' id='api2d' style='display: none;'>
  872. <span class ='tip'>提示:<br>api2d是国内的一家提供代理直连访问OpenAIapi的服务商,相当于OpenAIapi的套壳<br></span>
  873. <span class ='tip'>使用ChatGPT-3.5进行翻译,脚本的所有请求均在本地完成<br></span>
  874. <span class ='tip'>你需要输入自己的api2d KEY,<a target="_blank" href="https://api2d.com/profile">官网</a></span>
  875. <label for='api2d_key'>KEY:</label><input type='text' id='api2d_key'>
  876. </div>
  877. <br>
  878. <button id='save'>保存</button>
  879. </div>
  880. `);
  881. var translation = getCookie("translation");
  882. $("#bottomZh_CN").prop("checked", getCookie("bottomZh_CN") === "true");
  883. if (translation === 'undefined' || translation === '') {
  884. setCookie("translation", "deepl", 3650);
  885. $("input[name='translation'][value='deepl']").prop("checked", true);
  886. } else {
  887. $("input[name='translation'][value='" + translation + "']").prop("checked", true);
  888. $("input[name='translation']").css("color", "gray");
  889. if (translation == "baidu") {
  890. $("#baidu").show();
  891. $("#baidu_uid").val(getCookie("baidu_uid"));
  892. $("#baidu_key").val(getCookie("baidu_key"));
  893. $("#baidu_uid").css("color", "gray");
  894. $("#baidu_key").css("color", "gray");
  895. } else if (translation == "openai") {
  896. $("#openai").show();
  897. $("#openai_key").val(getCookie("openai_key"));
  898. $("#openai_key").css("color", "gray");
  899. } else if (translation == "api2d") {
  900. $("#api2d").show();
  901. $("#api2d_key").val(getCookie("api2d_key"));
  902. $("#api2d_key").css("color", "gray");
  903. }
  904. }
  905.  
  906. // 当单选框被选中时,显示对应的输入框,同时隐藏其他输入框
  907. $("input[name='translation']").change(function () {
  908. var selected = $(this).val(); // 获取当前选中的值
  909. if (selected === 'baidu') {
  910. $("#baidu").show();
  911. $("#baidu_uid").val(getCookie("baidu_uid"));
  912. $("#baidu_key").val(getCookie("baidu_key"));
  913. $("#openai, #api2d").hide();
  914. } else if (selected === 'openai') {
  915. $("#openai").show();
  916. $("#openai_key").val(getCookie("openai_key"));
  917. $("#baidu, #api2d").hide();
  918. } else if (selected === 'api2d') {
  919. $("#api2d").show();
  920. $("#api2d_key").val(getCookie("api2d_key"));
  921. $("#baidu, #openai").hide();
  922. } else {
  923. $("#baidu, #openai, #api2d").hide();
  924. }
  925. });
  926.  
  927. $("#save").click(function () {
  928. setCookie("bottomZh_CN", $("#bottomZh_CN").prop("checked"), 3650);
  929. var translation = $("input[name='translation']:checked").val();
  930. var baidu_uid = $("#baidu_uid").val();
  931. var baidu_key = $("#baidu_key").val();
  932. var openai_key = $("#openai_key").val();
  933. var api2d_key = $("#api2d_key").val();
  934. setCookie("translation", translation, 3650);
  935. if (translation == "baidu") {
  936. setCookie("baidu_uid", baidu_uid, 3650);
  937. setCookie("baidu_key", baidu_key, 3650);
  938. } else if (translation == "openai") {
  939. setCookie("openai_key", openai_key, 3650);
  940. } else if (translation == "api2d") {
  941. setCookie("api2d_key", api2d_key, 3650);
  942. }
  943. location.reload();
  944. });
  945. // 关闭
  946. $("#CFBetter_setting_menu .btn-close").click(function () {
  947. $("#CFBetter_setting_menu").remove();
  948. $(".CFBetter_setting").attr("disabled", false);
  949. $(".CFBetter_setting").css("background-color", "#60a5fa");
  950. $(".CFBetter_setting").css("color", "white");
  951. $(".CFBetter_setting").css("cursor", "pointer");
  952. });
  953. });
  954. });
  955.  
  956. // 是否为旧的latex渲染
  957. var is_oldLatex = false;
  958. if ($('.tex-span').length) {
  959. is_oldLatex = true;
  960. var newElement = $("<div></div>").addClass("alert alert-warning").html(`
  961. 注意:当前页面存在使用非 MathJax 库渲染为 HTML Latex 公式(这通常是一道古老的题目),这导致 CodeforcesBetter 无法将其还原回 Latex,因此当前页面部分功能不适用。
  962. <br>此外当前页面的翻译功能采用了特别的实现方式,因此可能会出现排版错位的情况。
  963. `).css({
  964. "margin": "1em",
  965. "text-align": "center",
  966. "position": "relative"
  967. });
  968. $(".menu-box:first").next().after(newElement);
  969. }
  970.  
  971. // 题目markdown转换/翻译面板
  972. function addButtonPanel(parent, suffix, type, is_simple = false) {
  973. if (type === "upper_level_2" || type === "problem") {
  974. $(parent).children(':eq(1)').before(
  975. "<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>");
  976. } else if (is_simple) {
  977. $(parent).before(
  978. "<div class='html2md-panel'><button class='html2mdButton translateButton" + suffix + "'>翻译</button> </div>");
  979. } else {
  980. $(parent).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. }
  983. }
  984. function addButtonWithHTML2MD(parent, suffix, type) {
  985. if(is_oldLatex){
  986. $(".html2md-view" + suffix).css({
  987. "cursor": "not-allowed",
  988. "background-color": "#e6e6e638",
  989. "color": "#72737896",
  990. });
  991. $(".html2md-view" + suffix).prop("disabled", true);
  992. }
  993. $(".html2md-view" + suffix).click(function () {
  994. var target, removedChildren;
  995. if (type === "problem") {
  996. target = $(parent).children().next().next().get(0);
  997. } else if (type === "problem_QA") {
  998. target = $(this).parent().parent().get(0);
  999. removedChildren = $(this).parent().parent().children().eq(0).detach();
  1000. } else if (type === "upper_level_2") {
  1001. target = parent;
  1002. removedChildren = $(parent).children().slice(0, 2).detach();
  1003. } else {
  1004. target = parent;
  1005. }
  1006. if (target.viewmd) {
  1007. target.viewmd = false;
  1008. $(this).text("MarkDown视图");
  1009. $(this).removeClass("mdViewed");
  1010. $(target).html(target.original_html);
  1011. } else {
  1012. target.viewmd = true;
  1013. if (!target.original_html) {
  1014. target.original_html = $(target).html();
  1015. }
  1016. if (!target.markdown) {
  1017. target.markdown = turndownService.turndown($(target).html());
  1018. }
  1019. $(this).text("原始内容");
  1020. $(this).addClass("mdViewed");
  1021. $(target).html(`<span class="mdViewContent" oninput="$(this).parent().get(0).markdown=this.value;" style="width:auto; height:auto;">${target.markdown}</span>`);
  1022. }
  1023. // 恢复删除的元素
  1024. if (type === "problem_QA" || type === "upper_level_2") $(target).prepend(removedChildren);
  1025. });
  1026. }
  1027.  
  1028. function addButtonWithCopy(parent, suffix, type) {
  1029. if(is_oldLatex){
  1030. $(".html2md-cb" + suffix).css({
  1031. "cursor": "not-allowed",
  1032. "background-color": "#e6e6e638",
  1033. "color": "#72737896",
  1034. });
  1035. $(".html2md-cb" + suffix).prop("disabled", true);
  1036. }
  1037. $(".html2md-cb" + suffix).click(function () {
  1038. var target, removedChildren;
  1039. if (type === "problem") {
  1040. target = $($(parent).children().next().next().get(0)).clone();
  1041. } else if (type === "problem_QA") {
  1042. target = $(this).parent().parent().eq(0).clone();
  1043. $(target).children(':first').remove();
  1044. } else if (type === "upper_level_2") {
  1045. target = $(parent).clone();
  1046. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1047. $(target).children(':first').remove();
  1048. } else {
  1049. target = $(parent).clone();
  1050. }
  1051. if (!target.markdown) {
  1052. target.markdown = turndownService.turndown($(target).html());
  1053. }
  1054. const textarea = document.createElement('textarea');
  1055. textarea.value = target.markdown;
  1056. document.body.appendChild(textarea);
  1057. textarea.select();
  1058. document.execCommand('copy');
  1059. document.body.removeChild(textarea);
  1060. $(this).addClass("copied");
  1061. $(this).text("Copied");
  1062. // 更新复制按钮文本
  1063. setTimeout(() => {
  1064. $(this).removeClass("copied");
  1065. $(this).text("Copy");
  1066. }, 2000);
  1067. $(target).remove();
  1068. });
  1069. }
  1070.  
  1071. function addButtonWithTranslation(parent, suffix, type) {
  1072. $(".translateButton" + suffix).click(async function () {
  1073. var target, removedChildren;
  1074. if (type === "problem") {
  1075. target = $($(parent).children().next().next().get(0)).clone();
  1076. } else if (type === "problem_QA") {
  1077. target = $(this).parent().parent().eq(0).clone();
  1078. $(target).children(':first').remove();
  1079. } else if (type === "upper_level_2") {
  1080. target = $(parent).clone();
  1081. $(target).children(':first').remove(); // 删除前两个元素(标题和按钮面板)
  1082. $(target).children(':first').remove();
  1083. } else {
  1084. target = $(parent).clone();
  1085. }
  1086. if (is_oldLatex) {
  1087. target.markdown = $(target).html();
  1088. } else if (!target.markdown) {
  1089. target.markdown = turndownService.turndown($(target).html());
  1090. }
  1091. const textarea = document.createElement('textarea');
  1092. textarea.value = target.markdown;
  1093. // 翻译处理
  1094. $(this).removeClass("translated");
  1095. $(this).text("翻译中");
  1096. $(this).css("cursor", "not-allowed");
  1097. var element_node;
  1098. if (type === "problem") {
  1099. element_node = $(parent).children()[2]; // 题面特殊处理
  1100. } else if (type === "problem_QA") {
  1101. element_node = $(parent).children().last().get(0);
  1102. } else {
  1103. element_node = parent;
  1104. }
  1105. var translateDiv = await translateProblemStatement(textarea.value, element_node);
  1106. //
  1107. $(this).addClass("translated");
  1108. $(this).text("已翻译");
  1109. $(this).prop("disabled", true);
  1110. $(target).remove();
  1111. // 重新翻译
  1112. if ($(this).next('.reTranslation').length === 0) {
  1113. const reTranslateBtn = $('<button>').addClass('html2mdButton reTranslation').html('&circlearrowright;').attr('title', '重新翻译');
  1114. reTranslateBtn.on('click', function() {
  1115. $(translateDiv).remove();
  1116. $(this).prev().click();
  1117. });
  1118. $(this).after(reTranslateBtn);
  1119. }else {
  1120. const reTranslateBtn = $(this).next('.reTranslation');
  1121. reTranslateBtn.off('click').on('click', function() {
  1122. $(translateDiv).remove();
  1123. $(this).prev().click();
  1124. });
  1125. }
  1126. });
  1127. }
  1128.  
  1129. var turndownService = new TurndownService();
  1130. window.onload = function () {
  1131. turndownService.keep(['del']);
  1132.  
  1133. // 处理规则
  1134. // 忽略
  1135. turndownService.addRule('ignore-sample-tests', {
  1136. filter: function (node) {
  1137. return node.classList.contains('sample-tests') || node.classList.contains('header');
  1138. },
  1139. replacement: function (content, node) {
  1140. return "";
  1141. }
  1142. });
  1143.  
  1144. // remove <script> math
  1145. turndownService.addRule('remove-script', {
  1146. filter: function (node, options) {
  1147. return node.tagName.toLowerCase() == "script" && node.type.startsWith("math/tex");
  1148. },
  1149. replacement: function (content, node) {
  1150. return "";
  1151. }
  1152. });
  1153.  
  1154. // inline math
  1155. turndownService.addRule('inline-math', {
  1156. filter: function (node, options) {
  1157. return node.tagName.toLowerCase() == "span" && node.className == "MathJax";
  1158. },
  1159. replacement: function (content, node) {
  1160. return "$ " + $(node).next().text() + " $";
  1161. }
  1162. });
  1163.  
  1164. // block math
  1165. turndownService.addRule('block-math', {
  1166. filter: function (node, options) {
  1167. return node.tagName.toLowerCase() == "div" && node.className == "MathJax_Display";
  1168. },
  1169. replacement: function (content, node) {
  1170. return "\n$$\n" + $(node).next().text() + "\n$$\n";
  1171. }
  1172. });
  1173.  
  1174. // bordertable
  1175. turndownService.addRule('bordertable', {
  1176. filter: 'table',
  1177. replacement: function (content, node) {
  1178. if (node.classList.contains('bordertable')) {
  1179. var output = [],
  1180. thead = '',
  1181. trs = node.querySelectorAll('tr');
  1182. if (trs.length > 0) {
  1183. var ths = trs[0].querySelectorAll('th');
  1184. if (ths.length > 0) {
  1185. thead = '| ' + Array.from(ths).map(th => turndownService.turndown(th.innerHTML.trim())).join(' | ') + ' |\n'
  1186. + '| ' + Array.from(ths).map(() => ' --- ').join('|') + ' |\n';
  1187. }
  1188. }
  1189. var rows = node.querySelectorAll('tr');
  1190. Array.from(rows).forEach(function (row, i) {
  1191. if (i > 0) {
  1192. var cells = row.querySelectorAll('td,th');
  1193. var trow = '| ' + Array.from(cells).map(cell => turndownService.turndown(cell.innerHTML.trim())).join(' | ') + ' |';
  1194. output.push(trow);
  1195. }
  1196. });
  1197. return thead + output.join('\n');
  1198. } else {
  1199. return content;
  1200. }
  1201. }
  1202. });
  1203.  
  1204.  
  1205. // 添加按钮到题面部分
  1206. $("div[class='problem-statement']").each(function () {
  1207. var problem_id = "_comment_" + getRandomNumber(8);
  1208. addButtonPanel(this, problem_id, "problem");
  1209. addButtonWithHTML2MD(this, problem_id, "problem");
  1210. addButtonWithCopy(this, problem_id, "problem");
  1211. addButtonWithTranslation(this, problem_id, "problem");
  1212. });
  1213.  
  1214. // 添加按钮到input部分
  1215. $("div[class='input-specification']").each(function () {
  1216. var id = "_" + getRandomNumber(8);
  1217. addButtonPanel(this, id, "upper_level_2");
  1218. addButtonWithHTML2MD(this, id, "upper_level_2");
  1219. addButtonWithCopy(this, id, "upper_level_2");
  1220. addButtonWithTranslation(this, id, "upper_level_2");
  1221. });
  1222.  
  1223. // 添加按钮到output部分
  1224. $("div[class='output-specification']").each(function () {
  1225. var id = "_" + getRandomNumber(8);
  1226. addButtonPanel(this, id, "upper_level_2");
  1227. addButtonWithHTML2MD(this, id, "upper_level_2");
  1228. addButtonWithCopy(this, id, "upper_level_2");
  1229. addButtonWithTranslation(this, id, "upper_level_2");
  1230. });
  1231.  
  1232. // 添加按钮到note部分
  1233. $("div[class='note']").each(function () {
  1234. var id = "_" + getRandomNumber(8);
  1235. addButtonPanel(this, id, "upper_level_2");
  1236. addButtonWithHTML2MD(this, id, "upper_level_2");
  1237. addButtonWithCopy(this, id, "upper_level_2");
  1238. addButtonWithTranslation(this, id, "upper_level_2");
  1239. });
  1240.  
  1241. // 添加按钮到ttypography部分
  1242. $(".ttypography").each(function () {
  1243. // 题目页特判
  1244. if (!$(this).parent().hasClass('problemindexholder')) {
  1245. var comment_id = "_comment_" + getRandomNumber(8);
  1246. addButtonPanel(this, comment_id, "this_level");
  1247. addButtonWithHTML2MD(this, comment_id, "this_level");
  1248. addButtonWithCopy(this, comment_id, "this_level");
  1249. addButtonWithTranslation(this, comment_id, "this_level");
  1250. }
  1251. });
  1252.  
  1253. // 添加按钮到titled部分
  1254. (function () {
  1255. var elements = [".Virtual.participation", ".Attention", ".Practice"];//只为部分titled添加
  1256. $.each(elements, function (index, value) {
  1257. $(value).each(function () {
  1258. var titled_id = "_titled_" + getRandomNumber(8);
  1259. var $nextDiv = $(this).next().get(0);
  1260. addButtonPanel($nextDiv, titled_id, "this_level", true);
  1261. addButtonWithTranslation($nextDiv, titled_id, "this_level");
  1262. });
  1263. });
  1264. })();
  1265.  
  1266. // 添加按钮到比赛QA部分
  1267. $(".question-requestText-td").each(function () {
  1268. var $nextDiv = $(this).children().get(0);
  1269. var question_id = "_question_" + getRandomNumber(8);
  1270. addButtonPanel($nextDiv, question_id, "problem_QA", true);
  1271. addButtonWithTranslation(this, question_id, "problem_QA");
  1272. });
  1273. };
  1274.  
  1275. // 翻译框/翻译处理器
  1276. var translatedText = "";
  1277. async function translateProblemStatement(text, element_node) {
  1278. let id = Math.floor(Date.now() / 1000);
  1279. let matches = [];
  1280. let replacements = {};
  1281. // 创建元素并放在element_node的后面
  1282. const translateDiv = document.createElement('div');
  1283. translateDiv.setAttribute('id', id);
  1284. translateDiv.classList.add('translate-problem-statement');
  1285. const spanElement = document.createElement('span');
  1286. translateDiv.appendChild(spanElement);
  1287. element_node.insertAdjacentElement('afterend', translateDiv);
  1288. // 替换latex公式
  1289. if (is_oldLatex) {
  1290. //去除开头结尾的<p>标签
  1291. text = text.replace(/^<p>/i, "");
  1292. text = text.replace(/<\/p>$/i, "");
  1293. //
  1294. let i = 0;
  1295. let regex = /<span\s+class="tex-span">.*?<\/span>/gi;
  1296. matches = text.match(regex);
  1297. try {
  1298. for (i; i < matches.length; i++) {
  1299. let match = matches[i];
  1300. text = text.replace(match, `【${i + 1}】`);
  1301. replacements[`【${i + 1}】`] = match;
  1302. }
  1303. } catch (e) { }
  1304. } else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1305. // 使用GPT翻译时不必替换latex公式
  1306. let i = 0;
  1307. // 块公式
  1308. matches = matches.concat(text.match(/\$\$([\s\S]*?)\$\$/g));
  1309. try {
  1310. for (i; i < matches.length; i++) {
  1311. let match = matches[i];
  1312. text = text.replace(match, `【${i + 1}】`);
  1313. replacements[`【${i + 1}】`] = match;
  1314. }
  1315. } catch (e) { }
  1316. // 行内公式
  1317. matches = matches.concat(text.match(/\$(.*?)\$/g));
  1318. try {
  1319. for (i; i < matches.length; i++) {
  1320. let match = matches[i];
  1321. text = text.replace(match, `【${i + 1}】`);
  1322. replacements[`【${i + 1}】`] = match;
  1323. }
  1324. } catch (e) { }
  1325. }
  1326. // 翻译
  1327. var translation = getCookie("translation");
  1328. if (translation === 'undefined' || translation === '') {
  1329. setCookie("translation", "deepl", 3650);
  1330. translation = "deepl";
  1331. }
  1332. if (translation == "deepl") {
  1333. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1334. translatedText = await translate_deepl(text);
  1335. } else if (translation == "youdao") {
  1336. translateDiv.textContent = "正在翻译中……请耐心等待,\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1337. translatedText = await translate_youdao_mobile(text);
  1338. } else if (translation == "baidu") {
  1339. var baidu_appid = getCookie("baidu_uid");
  1340. var baidu_key = getCookie("baidu_key");
  1341. } else if (translation == "openai") {
  1342. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1343. translatedText = await translate_openai(text);
  1344. } else if (translation == "api2d") {
  1345. translateDiv.textContent = "正在翻译中……请稍等\n\n使用GPT(ChatGPT/api2d)进行翻译通常需要很长的时间,请耐心等待\n\n如果长时间无变化,请尝试刷新页面重试或者查看控制台的报错信息";
  1346. translatedText = await translate_api2d(text);
  1347. }
  1348. // 还原latex公式
  1349. if (is_oldLatex) {
  1350. translatedText = "<p>" + translatedText;
  1351. translatedText += "</p>";
  1352. try {
  1353. for (let i = 0; i < matches.length; i++) {
  1354. let match = matches[i];
  1355. let replacement = replacements[`【${i + 1}】`];
  1356. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1357. }
  1358. } catch (e) { }
  1359. }
  1360. else if (getCookie("translation") != "api2d" && getCookie("translation") != "openai") {
  1361. try {
  1362. for (let i = 0; i < matches.length; i++) {
  1363. let match = matches[i];
  1364. let replacement = replacements[`【${i + 1}】`];
  1365. translatedText = translatedText.replace(`【${i + 1}】`, replacement);
  1366. }
  1367. } catch (e) { }
  1368. }
  1369. // 使符合mathjx的转换语法
  1370. translatedText = translatedText.replace(/(\$\$)/g, "");
  1371. translatedText = translatedText.replace(/(?<!\$)\$(?!\$)/g, "$$$$$");
  1372. // 更新
  1373. if (is_oldLatex) {
  1374. // oldlatex
  1375. translatedText = $.parseHTML(translatedText);
  1376. $(translateDiv).empty().append($(translatedText));
  1377. } else {
  1378. translateDiv.innerHTML = translatedText;
  1379. // 渲染MarkDown
  1380. var md = window.markdownit();
  1381. var html = md.render(translateDiv.innerText);
  1382. translateDiv.innerHTML = html;
  1383. // 渲染Latex
  1384. MathJax.Hub.Queue(["Typeset", MathJax.Hub, document.getElementById(id)]);
  1385. }
  1386. return translateDiv;
  1387. }
  1388.  
  1389. // ChatGPT
  1390. async function translate_openai(raw) {
  1391. var openai_key = getCookie("openai_key");
  1392. var openai_retext = "";
  1393. var data;
  1394. if (is_oldLatex) {
  1395. data = {
  1396. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1397. max_tokens: 2048,
  1398. model: "text-davinci-003",
  1399. };
  1400. } else {
  1401. data = {
  1402. prompt: "(You:请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n" + raw + ")",
  1403. max_tokens: 2048,
  1404. model: "text-davinci-003",
  1405. };
  1406. };
  1407. return new Promise(function (resolve, reject) {
  1408. GM_xmlhttpRequest({
  1409. method: 'POST',
  1410. url: 'https://api.openai.com/v1/completions',
  1411. data: JSON.stringify(data),
  1412. headers: {
  1413. 'Content-Type': 'application/json',
  1414. 'Authorization': 'Bearer ' + getCookie("openai_key") + ''
  1415. },
  1416. responseType: 'json',
  1417. onload: function (res) {
  1418. if (res.status === 200) {
  1419. openai_retext = res.response.choices[0].text;
  1420. openai_retext = openai_retext.replace(/^\s+/, '');
  1421. resolve(openai_retext);
  1422. }
  1423. else {
  1424. console.error(res.statusText);
  1425. reject(res.statusText);
  1426. }
  1427. }
  1428. });
  1429. });
  1430. }
  1431.  
  1432. // api2d
  1433. async function translate_api2d(raw) {
  1434. var api2d_key = getCookie("api2d_key");
  1435. var api2d_retext = "";
  1436. var postData;
  1437. if (is_oldLatex) {
  1438. postData = JSON.stringify({
  1439. model: 'gpt-3.5-turbo',
  1440. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的【】、HTML标签本身以及其中的内容不翻译不变动,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1441. });
  1442. } else {
  1443. postData = JSON.stringify({
  1444. model: 'gpt-3.5-turbo',
  1445. messages: [{ role: 'user', content: '请帮我将下面的文本翻译为中文,这是一个编程竞赛题描述的一部分,注意术语的翻译,注意保持其中的latex公式不翻译,你只需要回复翻译后的内容即可,不要回复任何其他内容:\n\n' + raw }],
  1446. });
  1447. }
  1448. const options = {
  1449. method: 'POST',
  1450. headers: {
  1451. 'Content-Type': 'application/json',
  1452. Authorization: 'Bearer ' + api2d_key,
  1453. },
  1454. data: postData,
  1455. };
  1456.  
  1457. return new Promise(function (resolve, reject) {
  1458. GM_xmlhttpRequest({
  1459. method: options.method,
  1460. url: `https://openai.api2d.net/v1/chat/completions`,
  1461. headers: options.headers,
  1462. data: options.data,
  1463. responseType: 'json',
  1464. onload: function (response) {
  1465. api2d_retext = response.response.choices[0].message.content;
  1466. resolve(api2d_retext);
  1467. },
  1468. onerror: function (response) {
  1469. console.error(response.statusText);
  1470. reject(response.statusText);
  1471. },
  1472. });
  1473. });
  1474. }
  1475. //
  1476.  
  1477. //--有道翻译m--start
  1478. async function translate_youdao_mobile(raw) {
  1479. const options = {
  1480. method: "POST",
  1481. url: 'http://m.youdao.com/translate',
  1482. data: "inputtext=" + encodeURIComponent(raw) + "&type=AUTO",
  1483. anonymous: true,
  1484. headers: {
  1485. "Content-Type": "application/x-www-form-urlencoded"
  1486. }
  1487. }
  1488. return await BaseTranslate('有道翻译mobile', raw, options, res => /id="translateResult">\s*?<li>([\s\S]*?)<\/li>\s*?<\/ul/.exec(res)[1])
  1489. }
  1490. //--有道翻译m--end
  1491.  
  1492. //--Deepl翻译--start
  1493. function getTimeStamp(iCount) {
  1494. const ts = Date.now();
  1495. if (iCount !== 0) {
  1496. iCount = iCount + 1;
  1497. return ts - (ts % iCount) + iCount;
  1498. } else {
  1499. return ts;
  1500. }
  1501. }
  1502.  
  1503. async function translate_deepl(raw) {
  1504. const id = (Math.floor(Math.random() * 99999) + 100000) * 1000;
  1505. const data = {
  1506. jsonrpc: '2.0',
  1507. method: 'LMT_handle_texts',
  1508. id,
  1509. params: {
  1510. splitting: 'newlines',
  1511. lang: {
  1512. source_lang_user_selected: 'auto',
  1513. target_lang: 'ZH',
  1514. },
  1515. texts: [{
  1516. text: raw,
  1517. requestAlternatives: 3
  1518. }],
  1519. timestamp: getTimeStamp(raw.split('i').length - 1)
  1520. }
  1521. }
  1522. let postData = JSON.stringify(data);
  1523. if ((id + 5) % 29 === 0 || (id + 3) % 13 === 0) {
  1524. postData = postData.replace('"method":"', '"method" : "');
  1525. } else {
  1526. postData = postData.replace('"method":"', '"method": "');
  1527. }
  1528. const options = {
  1529. method: 'POST',
  1530. url: 'https://www2.deepl.com/jsonrpc',
  1531. data: postData,
  1532. headers: {
  1533. 'Content-Type': 'application/json',
  1534. 'Host': 'www.deepl.com',
  1535. 'Origin': 'https://www.deepl.com',
  1536. 'Referer': 'https://www.deepl.com/'
  1537. },
  1538. anonymous: true,
  1539. nocache: true,
  1540. }
  1541. return await BaseTranslate('Deepl翻译', raw, options, res => JSON.parse(res).result.texts[0].text)
  1542. }
  1543.  
  1544. //--Deepl翻译--end
  1545.  
  1546. // Cookie Get/Set
  1547. function setCookie(cname, cvalue, exdays) {
  1548. var d = new Date();
  1549. d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  1550. var expires = "expires=" + d.toUTCString();
  1551. document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  1552. }
  1553.  
  1554. function getCookie(cname) {
  1555. var name = cname + "=";
  1556. var decodedCookie = decodeURIComponent(document.cookie);
  1557. var ca = decodedCookie.split(';');
  1558. for (var i = 0; i < ca.length; i++) {
  1559. var c = ca[i];
  1560. while (c.charAt(0) == ' ') {
  1561. c = c.substring(1);
  1562. }
  1563. if (c.indexOf(name) == 0) {
  1564. return c.substring(name.length, c.length);
  1565. }
  1566. }
  1567. return "";
  1568. }
  1569.  
  1570.  
  1571. //--异步请求包装工具--start
  1572. async function PromiseRetryWrap(task, options, ...values) {
  1573. const { RetryTimes, ErrProcesser } = options || {};
  1574. let retryTimes = RetryTimes || 5;
  1575. const usedErrProcesser = ErrProcesser || (err => { throw err });
  1576. if (!task) return;
  1577. while (true) {
  1578. try {
  1579. return await task(...values);
  1580. } catch (err) {
  1581. if (!--retryTimes) {
  1582. console.log(err);
  1583. return usedErrProcesser(err);
  1584. }
  1585. }
  1586. }
  1587. }
  1588.  
  1589. async function BaseTranslate(name, raw, options, processer) {
  1590. const toDo = async () => {
  1591. var tmp;
  1592. try {
  1593. const data = await Request(options);
  1594. tmp = data.responseText;
  1595. const result = await processer(tmp);
  1596. if (result) sessionStorage.setItem(name + '-' + raw, result);
  1597. return result
  1598. } catch (err) {
  1599. throw {
  1600. responseText: tmp,
  1601. err: err
  1602. }
  1603. }
  1604. }
  1605. return await PromiseRetryWrap(toDo, { RetryTimes: 3, ErrProcesser: () => "翻译出错" })
  1606. }
  1607.  
  1608. function Request(options) {
  1609. return new Promise((reslove, reject) => GM_xmlhttpRequest({ ...options, onload: reslove, onerror: reject }))
  1610. }
  1611.  
  1612. //--异步请求包装工具--end
  1613.  
  1614. // 随机数生成
  1615. function getRandomNumber(numDigits) {
  1616. let min = Math.pow(10, numDigits - 1);
  1617. let max = Math.pow(10, numDigits) - 1;
  1618. return Math.floor(Math.random() * (max - min + 1)) + min;
  1619. }