Codeforces Better!

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

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

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