You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

231 lines
10 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. #!/usr/bin/env node
  2. // Usage: node test.js
  3. // Script that creates index.html out of web/template.html and README.md.
  4. // It is written in JS because this code used to be executed on the client side.
  5. // To install dependencies run:
  6. // $ npm install -g jsdom jquery showdown highlightjs
  7. // If running on Mac and modules can't be found after installation add:
  8. // export NODE_PATH=/usr/local/lib/node_modules
  9. // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'.
  10. const fs = require('fs');
  11. const jsdom = require('jsdom');
  12. const showdown = require('showdown');
  13. const hljs = require('highlightjs');
  14. const PDF_BUTTON =
  15. '<a href="https://transactions.sendowl.com/products/78175486/4422834F/view" rel="nofollow"><img src="web/button.png" style="max-width: none; min-width: 0;"/></a>\n';
  16. const TOC =
  17. '<br>' +
  18. '<h2 id="toc">Contents</h2>\n' +
  19. '<pre><code class="hljs bash"><strong>ToC</strong> = {\n' +
  20. ' <strong><span class="hljs-string">\'1. Collections\'</span></strong>: [<a href="#list">List</a>, <a href="#dictionary">Dictionary</a>, <a href="#set">Set</a>, <a href="#tuple">Tuple</a>, <a href="#range">Range</a>, <a href="#enumerate">Enumerate</a>, <a href="#iterator">Iterator</a>, <a href="#generator">Generator</a>],\n' +
  21. ' <strong><span class="hljs-string">\'2. Types\'</span></strong>: [<a href="#type">Type</a>, <a href="#string">String</a>, <a href="#regex">Regular_Exp</a>, <a href="#format">Format</a>, <a href="#numbers">Numbers</a>, <a href="#combinatorics">Combinatorics</a>, <a href="#datetime">Datetime</a>],\n' +
  22. ' <strong><span class="hljs-string">\'3. Syntax\'</span></strong>: [<a href="#arguments">Args</a>, <a href="#inline">Inline</a>, <a href="#closure">Closure</a>, <a href="#decorator">Decorator</a>, <a href="#class">Class</a>, <a href="#ducktypes">Duck_Types</a>, <a href="#enum">Enum</a>, <a href="#exceptions">Exceptions</a>],\n' +
  23. ' <strong><span class="hljs-string">\'4. System\'</span></strong>: [<a href="#print">Print</a>, <a href="#input">Input</a>, <a href="#commandlinearguments">Command_Line_Arguments</a>, <a href="#open">Open</a>, <a href="#path">Path</a>, <a href="#oscommands">Command_Execution</a>],\n' +
  24. ' <strong><span class="hljs-string">\'5. Data\'</span></strong>: [<a href="#json">JSON</a>, <a href="#pickle">Pickle</a>, <a href="#csv">CSV</a>, <a href="#sqlite">SQLite</a>, <a href="#bytes">Bytes</a>, <a href="#struct">Struct</a>, <a href="#array">Array</a>, <a href="#memoryview">MemoryView</a>, <a href="#deque">Deque</a>],\n' +
  25. ' <strong><span class="hljs-string">\'6. Advanced\'</span></strong>: [<a href="#threading">Threading</a>, <a href="#operator">Operator</a>, <a href="#introspection">Introspection</a>, <a href="#metaprograming">Metaprograming</a>, <a href="#eval">Eval</a>, <a href="#coroutines">Coroutine</a>],\n' +
  26. ' <strong><span class="hljs-string">\'7. Libraries\'</span></strong>: [<a href="#progressbar">Progress_Bar</a>, <a href="#plot">Plot</a>, <a href="#table">Table</a>, <a href="#curses">Curses</a>, <a href="#logging">Logging</a>, <a href="#scraping">Scraping</a>, <a href="#web">Web</a>, <a href="#profiling">Profile</a>,\n' +
  27. ' <a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#animation">Animation</a>, <a href="#audio">Audio</a>]\n' +
  28. '}\n' +
  29. '</code></pre>\n';
  30. const OS_RENAME =
  31. 'os.rename(from, to) <span class="hljs-comment"># Renames/moves the file or directory.</span>\n' +
  32. 'os.replace(from, to) <span class="hljs-comment"># Same, but overwrites \'to\' if it exists.</span>\n';
  33. const SHUTIL_COPY =
  34. 'shutil.copy(from, to) <span class="hljs-comment"># Copies the file. \'to\' can be a directory.</span>\n' +
  35. 'shutil.copytree(from, to) <span class="hljs-comment"># Copies the directory. \'to\' must not exist.</span>\n';
  36. const EVAL =
  37. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> ast <span class="hljs-keyword">import</span> literal_eval\n' +
  38. '<span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">\'1 + 2\'</span>)\n' +
  39. '<span class="hljs-number">3</span>\n' +
  40. '<span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">\'[1, 2, 3]\'</span>)\n' +
  41. '[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]\n' +
  42. '<span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">\'abs(1)\'</span>)\n' +
  43. 'ValueError: malformed node or string\n';
  44. const LRU_CACHE =
  45. '<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> lru_cache\n' +
  46. '\n' +
  47. '<span class="hljs-meta">@lru_cache(maxsize=None)</span>\n' +
  48. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>\n' +
  49. ' <span class="hljs-keyword">return</span> n <span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">2</span> <span class="hljs-keyword">else</span> fib(n-<span class="hljs-number">2</span>) + fib(n-<span class="hljs-number">1</span>)\n';
  50. const TYPE =
  51. '<code class="python language-python hljs">&lt;class&gt; = type(<span class="hljs-string">\'&lt;class_name&gt;\'</span>, &lt;parents_tuple&gt;, &lt;attributes_dict&gt;)</code>';
  52. const DATACLASS =
  53. '<code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass\n' +
  54. '&lt;class&gt; = make_dataclass(<span class="hljs-string">\'&lt;class_name&gt;\'</span>, &lt;coll_of_attribute_names&gt;)\n' +
  55. '&lt;class&gt; = make_dataclass(<span class="hljs-string">\'&lt;class_name&gt;\'</span>, &lt;coll_of_tuples&gt;)\n' +
  56. '&lt;tuple&gt; = (<span class="hljs-string">\'&lt;attr_name&gt;\'</span>, &lt;type&gt; [, &lt;default_value&gt;])</code>';
  57. const DATETIME =
  58. '<code class="python language-python hljs"><span class="hljs-string">\'&lt;DT&gt; = resolve_imaginary(&lt;DT&gt;)\'</span></code>';
  59. function main() {
  60. const html = getMd();
  61. initDom(html);
  62. modifyPage();
  63. const template = readFile('web/template.html');
  64. const tokens = template.split('<div id=main_container></div>');
  65. const text = `${tokens[0]} ${document.body.innerHTML} ${tokens[1]}`;
  66. writeToFile('index.html', text);
  67. }
  68. function initDom(html) {
  69. const { JSDOM } = jsdom;
  70. const dom = new JSDOM(html);
  71. const $ = (require('jquery'))(dom.window);
  72. global.$ = $;
  73. global.document = dom.window.document;
  74. }
  75. function getMd() {
  76. var readme = readFile('README.md');
  77. var readme = readme.replace("#semaphore-event-barrier", "#semaphoreeventbarrier");
  78. const converter = new showdown.Converter();
  79. return converter.makeHtml(readme);
  80. }
  81. function modifyPage() {
  82. // addPdfButton()
  83. removeOrigToc();
  84. addToc();
  85. insertLinks();
  86. unindentBanner();
  87. highlightCode();
  88. }
  89. function addPdfButton() {
  90. const nodes = $.parseHTML(PDF_BUTTON);
  91. $('img').first().parent().before(nodes);
  92. }
  93. function removeOrigToc() {
  94. const headerContents = $('#contents');
  95. const contentsList = headerContents.next();
  96. headerContents.remove();
  97. contentsList.remove();
  98. }
  99. function addToc() {
  100. const nodes = $.parseHTML(TOC);
  101. $('#main').before(nodes);
  102. }
  103. function insertLinks() {
  104. $('h2').each(function() {
  105. const aId = $(this).attr('id');
  106. const text = $(this).text();
  107. const line = `<a href="#${aId}" name="${aId}">#</a>${text}`;
  108. $(this).html(line);
  109. });
  110. }
  111. function unindentBanner() {
  112. const montyImg = $('img').first();
  113. montyImg.parent().addClass('banner');
  114. const downloadPraragrapth = $('p').first();
  115. downloadPraragrapth.addClass('banner');
  116. }
  117. function highlightCode() {
  118. setApaches(['<D>', '<T>', '<DT>', '<TD>', '<a>', '<n>']);
  119. $('code').not('.python').not('.text').not('.bash').not('.apache').addClass('python');
  120. $('code').each(function(index) {
  121. hljs.highlightBlock(this);
  122. });
  123. fixClasses();
  124. fixHighlights();
  125. preventPageBreaks();
  126. fixPageBreaksFile();
  127. fixPageBreaksStruct();
  128. insertPageBreaks();
  129. }
  130. function setApaches(elements) {
  131. for (el of elements) {
  132. $(`code:contains(${el})`).addClass('apache');
  133. }
  134. }
  135. function fixClasses() {
  136. // Changes class="hljs-keyword" to class="hljs-title" of 'class' keyword.
  137. $('.hljs-class').filter(':contains(class \')').find(':first-child').removeClass('hljs-keyword').addClass('hljs-title')
  138. }
  139. function fixHighlights() {
  140. $(`code:contains(os.rename)`).html(OS_RENAME);
  141. $(`code:contains(shutil.copy)`).html(SHUTIL_COPY);
  142. $(`code:contains(ValueError: malformed node)`).html(EVAL);
  143. $(`code:contains(@lru_cache(maxsize=None))`).html(LRU_CACHE);
  144. $(`code:contains(\'<class_name>\', <parents_tuple>, <attributes_dict>)`).html(TYPE);
  145. $(`code:contains(make_dataclass(\'<class_name>\')`).html(DATACLASS);
  146. $(`code:contains((<DT>))`).html(DATETIME)
  147. }
  148. function preventPageBreaks() {
  149. $(':header').each(function(index) {
  150. var el = $(this)
  151. var untilPre = el.nextUntil('pre')
  152. var untilH2 = el.nextUntil('h2')
  153. if ((untilPre.length < untilH2.length) || el.prop('tagName') === 'H1') {
  154. untilPre.add(el).next().add(el).wrapAll("<div></div>");
  155. } else {
  156. untilH2.add(el).wrapAll("<div></div>");
  157. }
  158. });
  159. }
  160. function fixPageBreaksFile() {
  161. const modesDiv = $('#file').parent().parent().parent()
  162. move(modesDiv, 'file')
  163. move(modesDiv, 'exceptions-1')
  164. }
  165. function fixPageBreaksStruct() {
  166. const formatDiv = $('#floatingpointtypes').parent().parent().parent().parent()
  167. move(formatDiv, 'floatingpointtypes')
  168. move(formatDiv, 'integertypesuseacapitalletterforunsignedtypestandardsizesareinbrackets')
  169. move(formatDiv, 'forstandardsizesstartformatstringwith')
  170. }
  171. function move(anchor_el, el_id) {
  172. const el = $('#'+el_id).parent()
  173. anchor_el.after(el)
  174. }
  175. function insertPageBreaks() {
  176. // insertPageBreakBefore('#libraries')
  177. insertPageBreakBefore('#print')
  178. }
  179. function insertPageBreakBefore(an_id) {
  180. $('<div class="pagebreak"></div>').insertBefore($(an_id).parent())
  181. }
  182. function readFile(filename) {
  183. try {
  184. return fs.readFileSync(filename, 'utf8');
  185. } catch(e) {
  186. console.error('Error:', e.stack);
  187. }
  188. }
  189. function writeToFile(filename, text) {
  190. try {
  191. return fs.writeFileSync(filename, text, 'utf8');
  192. } catch(e) {
  193. console.error('Error:', e.stack);
  194. }
  195. }
  196. main();