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.

936 lines
74 KiB

4 years ago
5 years ago
3 years ago
1 year ago
2 years ago
5 years ago
2 years ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
5 years ago
2 years ago
1 year ago
2 years ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
4 years ago
4 years ago
4 years ago
3 years ago
2 years ago
1 year ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
1 year ago
3 years ago
1 year ago
2 years ago
1 year ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
1 year ago
1 year ago
2 years ago
1 year ago
1 year ago
1 year ago
1 year ago
3 years ago
1 year ago
2 years ago
1 year ago
2 years ago
4 years ago
2 years ago
2 years ago
4 years ago
2 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1 year ago
1 year ago
3 years ago
1 year ago
3 years ago
3 years ago
1 year ago
3 years ago
2 years ago
1 year ago
3 years ago
1 year ago
3 years ago
2 years ago
6 years ago
2 years ago
2 years ago
2 years ago
6 years ago
6 years ago
5 years ago
5 years ago
6 years ago
5 years ago
1 year ago
2 years ago
5 years ago
2 years ago
2 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
2 years ago
  1. #!/usr/bin/env node
  2. // Usage: node parse.js
  3. //
  4. // Script that creates index.html out of web/template.html and README.md.
  5. //
  6. // It is written in JS because this code used to be executed on the client side.
  7. // To install the Node.js and npm run:
  8. // $ sudo apt install nodejs npm # On macOS use `brew install ...` instead.
  9. //
  10. // To install dependencies globally, run:
  11. // $ npm install -g jsdom jquery showdown highlightjs@9.12.0
  12. //
  13. // If running on macOS and modules can't be found after installation add:
  14. // export NODE_PATH=/usr/local/lib/node_modules
  15. // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'.
  16. //
  17. // To avoid problems with permissions and path variables, install modules
  18. // into project's directory using:
  19. // $ npm install jsdom jquery showdown highlightjs@9.12.0
  20. //
  21. // It is also advisable to add a Bash script into .git/hooks directory, that will
  22. // run this script before every commit. It should be named 'pre-commit' and it
  23. // should contain the following line: `./parse.js`.
  24. const fs = require('fs');
  25. const jsdom = require('jsdom');
  26. const showdown = require('showdown');
  27. const hljs = require('highlightjs');
  28. const TOC =
  29. '<br>' +
  30. '<h2 id="toc">Contents</h2>\n' +
  31. '<pre><code class="hljs bash" style="line-height: 1.3em;"><strong>ToC</strong> = {\n' +
  32. ' <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' +
  33. ' <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' +
  34. ' <strong><span class="hljs-string">\'3. Syntax\'</span></strong>: [<a href="#arguments">Args</a>, <a href="#inline">Inline</a>, <a href="#imports">Import</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">Exception</a>],\n' +
  35. ' <strong><span class="hljs-string">\'4. System\'</span></strong>: [<a href="#exit">Exit</a>, <a href="#print">Print</a>, <a href="#input">Input</a>, <a href="#commandlinearguments">Command_Line_Arguments</a>, <a href="#open">Open</a>, <a href="#paths">Path</a>, <a href="#oscommands">OS_Commands</a>],\n' +
  36. ' <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">Memory_View</a>, <a href="#deque">Deque</a>],\n' +
  37. ' <strong><span class="hljs-string">\'6. Advanced\'</span></strong>: [<a href="#threading">Threading</a>, <a href="#operator">Operator</a>, <a href="#matchstatement">Match_Stmt</a>, <a href="#introspection">Introspection</a>, <a href="#logging">Logging</a>, <a href="#coroutines">Coroutines</a>],\n' +
  38. ' <strong><span class="hljs-string">\'7. Libraries\'</span></strong>: [<a href="#progressbar">Progress_Bar</a>, <a href="#plot">Plots</a>, <a href="#table">Tables</a>, <a href="#curses">Curses</a>, <a href="#pysimplegui">GUIs</a>, <a href="#scraping">Scraping</a>, <a href="#web">Web</a>, <a href="#profiling">Profiling</a>],\n' +
  39. ' <strong><span class="hljs-string">\'8. Multimedia\'</span></strong>: [<a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#animation">Animation</a>, <a href="#audio">Audio</a>, <a href="#synthesizer">Synthesizer</a>, <a href="#pygame">Pygame</a>, <a href="#pandas">Pandas</a>, <a href="#plotly">Plotly</a>]\n' +
  40. '}\n' +
  41. '</code></pre>\n';
  42. const BIN_HEX =
  43. '&lt;int&gt; = ±<span class="hljs-number">0b</span>&lt;bin&gt; <span class="hljs-comment"># Or: ±0x&lt;hex&gt;</span>\n' +
  44. '&lt;int&gt; = int(<span class="hljs-string">\'±&lt;bin&gt;\'</span>, <span class="hljs-number">2</span>) <span class="hljs-comment"># Or: int(\'±&lt;hex&gt;\', 16)</span>\n' +
  45. '&lt;int&gt; = int(<span class="hljs-string">\'±0b&lt;bin&gt;\'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int(\'±0x&lt;hex&gt;\', 0)</span>\n' +
  46. '&lt;str&gt; = bin(&lt;int&gt;) <span class="hljs-comment"># Returns \'[-]0b&lt;bin&gt;\'.</span>\n';
  47. const LRU_CACHE =
  48. '<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> lru_cache\n' +
  49. '\n' +
  50. '<span class="hljs-meta">@lru_cache(maxsize=None)</span>\n' +
  51. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>\n' +
  52. ' <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';
  53. const PARAMETRIZED_DECORATOR =
  54. '<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps\n' +
  55. '\n' +
  56. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(print_result=<span class="hljs-keyword">False</span>)</span>:</span>\n' +
  57. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span><span class="hljs-params">(func)</span>:</span>\n' +
  58. '<span class="hljs-meta"> @wraps(func)</span>\n' +
  59. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>\n' +
  60. ' result = func(*args, **kwargs)\n' +
  61. ' print(func.__name__, result <span class="hljs-keyword">if</span> print_result <span class="hljs-keyword">else</span> <span class="hljs-string">\'\'</span>)\n' +
  62. ' <span class="hljs-keyword">return</span> result\n' +
  63. ' <span class="hljs-keyword">return</span> out\n' +
  64. ' <span class="hljs-keyword">return</span> decorator\n' +
  65. '\n' +
  66. '<span class="hljs-meta">@debug(print_result=True)</span>\n' +
  67. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>\n' +
  68. ' <span class="hljs-keyword">return</span> x + y\n';
  69. const REPR_USE_CASES =
  70. 'print/str/repr([&lt;el&gt;])\n' +
  71. 'print/str/repr({&lt;el&gt;: &lt;el&gt;})\n' +
  72. '<span class="hljs-string">f\'<span class="hljs-subst">{&lt;el&gt;!r}</span>\'</span>\n' +
  73. 'Z = dataclasses.make_dataclass(<span class="hljs-string">\'Z\'</span>, [<span class="hljs-string">\'a\'</span>]); print/str/repr(Z(&lt;el&gt;))\n' +
  74. '<span class="hljs-meta">&gt;&gt;&gt; </span>&lt;el&gt;\n';
  75. const CONSTRUCTOR_OVERLOADING =
  76. '<span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">name</span>&gt;:</span>\n' +
  77. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a=<span class="hljs-keyword">None</span>)</span>:</span>\n' +
  78. ' self.a = a\n';
  79. const DATACLASS =
  80. '<span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass\n' +
  81. '&lt;class&gt; = make_dataclass(<span class="hljs-string">\'&lt;class_name&gt;\'</span>, &lt;coll_of_attribute_names&gt;)\n' +
  82. '&lt;class&gt; = make_dataclass(<span class="hljs-string">\'&lt;class_name&gt;\'</span>, &lt;coll_of_tuples&gt;)\n' +
  83. '&lt;tuple&gt; = (<span class="hljs-string">\'&lt;attr_name&gt;\'</span>, &lt;type&gt; [, &lt;default_value&gt;])';
  84. const SHUTIL_COPY =
  85. 'shutil.copy(from, to) <span class="hljs-comment"># Copies the file. \'to\' can exist or be a dir.</span>\n' +
  86. 'shutil.copy2(from, to) <span class="hljs-comment"># Also copies creation and modification time.</span>\n' +
  87. 'shutil.copytree(from, to) <span class="hljs-comment"># Copies the directory. \'to\' must not exist.</span>\n';
  88. const OS_RENAME =
  89. 'os.rename(from, to) <span class="hljs-comment"># Renames/moves the file or directory.</span>\n' +
  90. 'os.replace(from, to) <span class="hljs-comment"># Same, but overwrites file \'to\' even on Windows.</span>\n' +
  91. 'shutil.move(from, to) <span class="hljs-comment"># Rename() that moves into \'to\' if it\'s a dir.</span>\n';
  92. const STRUCT_FORMAT =
  93. '<span class="hljs-section">\'&lt;n&gt;s\'</span><span class="hljs-attribute"></span>';
  94. const MATCH =
  95. '<span class="hljs-keyword">match</span> &lt;object/expression&gt;:\n' +
  96. ' <span class="hljs-keyword">case</span> &lt;pattern&gt; [<span class="hljs-keyword">if</span> &lt;condition&gt;]:\n' +
  97. ' &lt;code&gt;\n' +
  98. ' ...\n';
  99. const MATCH_EXAMPLE =
  100. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path\n' +
  101. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">match</span> Path(<span class="hljs-string">\'/home/gto/python-cheatsheet/README.md\'</span>):\n' +
  102. '<span class="hljs-meta">... </span> <span class="hljs-keyword">case</span> Path(\n' +
  103. '<span class="hljs-meta">... </span> parts=[<span class="hljs-string">\'/\'</span>, <span class="hljs-string">\'home\'</span>, user, *_],\n' +
  104. '<span class="hljs-meta">... </span> stem=stem,\n' +
  105. '<span class="hljs-meta">... </span> suffix=(<span class="hljs-string">\'.md\'</span> | <span class="hljs-string">\'.txt\'</span>) <span class="hljs-keyword">as</span> suffix\n' +
  106. '<span class="hljs-meta">... </span> ) <span class="hljs-keyword">if</span> stem.lower() == <span class="hljs-string">\'readme\'</span>:\n' +
  107. '<span class="hljs-meta">... </span> print(<span class="hljs-string">f\'<span class="hljs-subst">{stem}</span><span class="hljs-subst">{suffix}</span> is a readme file that belongs to user <span class="hljs-subst">{user}</span>.\'</span>)\n' +
  108. '<span class="hljs-string">\'README.md is a readme file that belongs to user gto.\'</span>\n';
  109. const COROUTINES =
  110. '<span class="hljs-keyword">import</span> asyncio, collections, curses, curses.textpad, enum, random, time\n' +
  111. '\n' +
  112. 'P = collections.namedtuple(<span class="hljs-string">\'P\'</span>, <span class="hljs-string">\'x y\'</span>) <span class="hljs-comment"># Position</span>\n' +
  113. 'D = enum.Enum(<span class="hljs-string">\'D\'</span>, <span class="hljs-string">\'n e s w\'</span>) <span class="hljs-comment"># Direction</span>\n' +
  114. 'W, H = <span class="hljs-number">15</span>, <span class="hljs-number">7</span> <span class="hljs-comment"># Width, Height</span>\n' +
  115. '\n' +
  116. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span>\n' +
  117. ' curses.curs_set(<span class="hljs-number">0</span>) <span class="hljs-comment"># Makes cursor invisible.</span>\n' +
  118. ' screen.nodelay(<span class="hljs-keyword">True</span>) <span class="hljs-comment"># Makes getch() non-blocking.</span>\n' +
  119. ' asyncio.run(main_coroutine(screen)) <span class="hljs-comment"># Starts running asyncio code.</span>\n' +
  120. '\n' +
  121. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main_coroutine</span><span class="hljs-params">(screen)</span>:</span>\n' +
  122. ' moves = asyncio.Queue()\n' +
  123. ' state = {<span class="hljs-string">\'*\'</span>: P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), **{id_: P(W//<span class="hljs-number">2</span>, H//<span class="hljs-number">2</span>) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)}}\n' +
  124. ' ai = [random_controller(id_, moves) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)]\n' +
  125. ' mvc = [human_controller(screen, moves), model(moves, state), view(state, screen)]\n' +
  126. ' tasks = [asyncio.create_task(cor) <span class="hljs-keyword">for</span> cor <span class="hljs-keyword">in</span> ai + mvc]\n' +
  127. ' <span class="hljs-keyword">await</span> asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)\n' +
  128. '\n' +
  129. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">random_controller</span><span class="hljs-params">(id_, moves)</span>:</span>\n' +
  130. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:\n' +
  131. ' d = random.choice(list(D))\n' +
  132. ' moves.put_nowait((id_, d))\n' +
  133. ' <span class="hljs-keyword">await</span> asyncio.sleep(random.triangular(<span class="hljs-number">0.01</span>, <span class="hljs-number">0.65</span>))\n' +
  134. '\n' +
  135. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">human_controller</span><span class="hljs-params">(screen, moves)</span>:</span>\n' +
  136. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:\n' +
  137. ' key_mappings = {<span class="hljs-number">258</span>: D.s, <span class="hljs-number">259</span>: D.n, <span class="hljs-number">260</span>: D.w, <span class="hljs-number">261</span>: D.e}\n' +
  138. ' ch = screen.getch()\n' +
  139. ' <span class="hljs-keyword">if</span> d := key_mappings.get(ch):\n' +
  140. ' moves.put_nowait((<span class="hljs-string">\'*\'</span>, d))\n' +
  141. ' <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.005</span>)\n' +
  142. '\n' +
  143. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">model</span><span class="hljs-params">(moves, state)</span>:</span>\n' +
  144. ' <span class="hljs-keyword">while</span> state[<span class="hljs-string">\'*\'</span>] <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> (state[id_] <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)):\n' +
  145. ' id_, d = <span class="hljs-keyword">await</span> moves.get()\n' +
  146. ' x, y = state[id_]\n' +
  147. ' deltas = {D.n: P(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>), D.e: P(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>), D.s: P(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), D.w: P(<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>)}\n' +
  148. ' dx, dy = deltas[d]\n' +
  149. ' state[id_] = P((x + dx) % W, (y + dy) % H)\n' +
  150. '\n' +
  151. '<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">view</span><span class="hljs-params">(state, screen)</span>:</span>\n' +
  152. ' offset = P(curses.COLS//<span class="hljs-number">2</span> - W//<span class="hljs-number">2</span>, curses.LINES//<span class="hljs-number">2</span> - H//<span class="hljs-number">2</span>)\n' +
  153. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:\n' +
  154. ' screen.erase()\n' +
  155. ' curses.textpad.rectangle(screen, offset.y-<span class="hljs-number">1</span>, offset.x-<span class="hljs-number">1</span>, offset.y+H, offset.x+W)\n' +
  156. ' <span class="hljs-keyword">for</span> id_, p <span class="hljs-keyword">in</span> state.items():\n' +
  157. ' screen.addstr(\n' +
  158. ' offset.y + (p.y - state[<span class="hljs-string">\'*\'</span>].y + H//<span class="hljs-number">2</span>) % H,\n' +
  159. ' offset.x + (p.x - state[<span class="hljs-string">\'*\'</span>].x + W//<span class="hljs-number">2</span>) % W,\n' +
  160. ' str(id_)\n' +
  161. ' )\n' +
  162. ' screen.refresh()\n' +
  163. ' <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.005</span>)\n' +
  164. '\n' +
  165. '<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">\'__main__\'</span>:\n' +
  166. ' start_time = time.perf_counter()\n' +
  167. ' curses.wrapper(main)\n' +
  168. ' print(<span class="hljs-string">f\'You survived <span class="hljs-subst">{time.perf_counter() - start_time:<span class="hljs-number">.2</span>f}</span> seconds.\'</span>)\n';
  169. const CURSES =
  170. '<span class="hljs-comment"># $ pip3 install windows-curses</span>\n' +
  171. '<span class="hljs-keyword">import</span> curses, os\n' +
  172. '<span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> A_REVERSE, KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_ENTER\n' +
  173. '\n' +
  174. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span>\n' +
  175. ' ch, first, selected, paths = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, os.listdir()\n' +
  176. ' <span class="hljs-keyword">while</span> ch != ord(<span class="hljs-string">\'q\'</span>):\n' +
  177. ' height, width = screen.getmaxyx()\n' +
  178. ' screen.erase()\n' +
  179. ' <span class="hljs-keyword">for</span> y, filename <span class="hljs-keyword">in</span> enumerate(paths[first : first+height]):\n' +
  180. ' color = A_REVERSE <span class="hljs-keyword">if</span> filename == paths[selected] <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>\n' +
  181. ' screen.addnstr(y, <span class="hljs-number">0</span>, filename, width-<span class="hljs-number">1</span>, color)\n' +
  182. ' ch = screen.getch()\n' +
  183. ' selected += (ch == KEY_DOWN) - (ch == KEY_UP)\n' +
  184. ' selected = max(<span class="hljs-number">0</span>, min(len(paths)-<span class="hljs-number">1</span>, selected))\n' +
  185. ' first += (selected &gt;= first + height) - (selected &lt; first)\n' +
  186. ' <span class="hljs-keyword">if</span> ch <span class="hljs-keyword">in</span> [KEY_LEFT, KEY_RIGHT, KEY_ENTER, ord(<span class="hljs-string">\'\\n\'</span>), ord(<span class="hljs-string">\'\\r\'</span>)]:\n' +
  187. ' new_dir = <span class="hljs-string">\'..\'</span> <span class="hljs-keyword">if</span> ch == KEY_LEFT <span class="hljs-keyword">else</span> paths[selected]\n' +
  188. ' <span class="hljs-keyword">if</span> os.path.isdir(new_dir):\n' +
  189. ' os.chdir(new_dir)\n' +
  190. ' first, selected, paths = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, os.listdir()\n' +
  191. '\n' +
  192. '<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">\'__main__\'</span>:\n' +
  193. ' curses.wrapper(main)\n';
  194. const PROGRESS_BAR =
  195. '<span class="hljs-comment"># $ pip3 install tqdm</span>\n' +
  196. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> tqdm, time\n' +
  197. '<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> tqdm.tqdm([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], desc=<span class="hljs-string">\'Processing\'</span>):\n' +
  198. '<span class="hljs-meta">... </span> time.sleep(<span class="hljs-number">1</span>)\n' +
  199. 'Processing: 100%|████████████████████| 3/3 [00:03&lt;00:00, 1.00s/it]\n';
  200. const LOGGING_EXAMPLE =
  201. '<span class="hljs-meta">&gt;&gt;&gt; </span>logger = logging.getLogger(<span class="hljs-string">\'my_module\'</span>)\n' +
  202. '<span class="hljs-meta">&gt;&gt;&gt; </span>handler = logging.FileHandler(<span class="hljs-string">\'test.log\'</span>, encoding=<span class="hljs-string">\'utf-8\'</span>)\n' +
  203. '<span class="hljs-meta">&gt;&gt;&gt; </span>formatter = logging.Formatter(<span class="hljs-string">\'%(asctime)s %(levelname)s:%(name)s:%(message)s\'</span>)\n' +
  204. '<span class="hljs-meta">&gt;&gt;&gt; </span>handler.setFormatter(formatter)\n' +
  205. '<span class="hljs-meta">&gt;&gt;&gt; </span>logger.addHandler(handler)\n' +
  206. '<span class="hljs-meta">&gt;&gt;&gt; </span>logging.basicConfig(level=<span class="hljs-string">\'DEBUG\'</span>)\n' +
  207. '<span class="hljs-meta">&gt;&gt;&gt; </span>logging.root.handlers[<span class="hljs-number">0</span>].setLevel(<span class="hljs-string">\'WARNING\'</span>)\n' +
  208. '<span class="hljs-meta">&gt;&gt;&gt; </span>logger.critical(<span class="hljs-string">\'Running out of disk space.\'</span>)\n' +
  209. 'CRITICAL:my_module:Running out of disk space.\n' +
  210. '<span class="hljs-meta">&gt;&gt;&gt; </span>print(open(<span class="hljs-string">\'test.log\'</span>).read())\n' +
  211. '2023-02-07 23:21:01,430 CRITICAL:my_module:Running out of disk space.\n';
  212. const AUDIO =
  213. '<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> pi, sin\n' +
  214. 'samples_f = (sin(i * <span class="hljs-number">2</span> * pi * <span class="hljs-number">440</span> / <span class="hljs-number">44100</span>) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100_000</span>))\n' +
  215. 'write_to_wav_file(<span class="hljs-string">\'test.wav\'</span>, samples_f)\n';
  216. const MARIO =
  217. '<span class="hljs-keyword">import</span> collections, dataclasses, enum, io, itertools <span class="hljs-keyword">as</span> it, pygame <span class="hljs-keyword">as</span> pg, urllib.request\n' +
  218. '<span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> randint\n' +
  219. '\n' +
  220. 'P = collections.namedtuple(<span class="hljs-string">\'P\'</span>, <span class="hljs-string">\'x y\'</span>) <span class="hljs-comment"># Position</span>\n' +
  221. 'D = enum.Enum(<span class="hljs-string">\'D\'</span>, <span class="hljs-string">\'n e s w\'</span>) <span class="hljs-comment"># Direction</span>\n' +
  222. 'W, H, MAX_S = <span class="hljs-number">50</span>, <span class="hljs-number">50</span>, P(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>) <span class="hljs-comment"># Width, Height, Max speed</span>\n' +
  223. '\n' +
  224. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>\n' +
  225. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_screen</span><span class="hljs-params">()</span>:</span>\n' +
  226. ' pg.init()\n' +
  227. ' <span class="hljs-keyword">return</span> pg.display.set_mode((W*<span class="hljs-number">16</span>, H*<span class="hljs-number">16</span>))\n' +
  228. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_images</span><span class="hljs-params">()</span>:</span>\n' +
  229. ' url = <span class="hljs-string">\'https://gto76.github.io/python-cheatsheet/web/mario_bros.png\'</span>\n' +
  230. ' img = pg.image.load(io.BytesIO(urllib.request.urlopen(url).read()))\n' +
  231. ' <span class="hljs-keyword">return</span> [img.subsurface(get_rect(x, <span class="hljs-number">0</span>)) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(img.get_width() // <span class="hljs-number">16</span>)]\n' +
  232. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_mario</span><span class="hljs-params">()</span>:</span>\n' +
  233. ' Mario = dataclasses.make_dataclass(<span class="hljs-string">\'Mario\'</span>, <span class="hljs-string">\'rect spd facing_left frame_cycle\'</span>.split())\n' +
  234. ' <span class="hljs-keyword">return</span> Mario(get_rect(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-keyword">False</span>, it.cycle(range(<span class="hljs-number">3</span>)))\n' +
  235. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_tiles</span><span class="hljs-params">()</span>:</span>\n' +
  236. ' border = [(x, y) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(W) <span class="hljs-keyword">for</span> y <span class="hljs-keyword">in</span> range(H) <span class="hljs-keyword">if</span> x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, W-<span class="hljs-number">1</span>] <span class="hljs-keyword">or</span> y <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, H-<span class="hljs-number">1</span>]]\n' +
  237. ' platforms = [(randint(<span class="hljs-number">1</span>, W-<span class="hljs-number">2</span>), randint(<span class="hljs-number">2</span>, H-<span class="hljs-number">2</span>)) <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(W*H // <span class="hljs-number">10</span>)]\n' +
  238. ' <span class="hljs-keyword">return</span> [get_rect(x, y) <span class="hljs-keyword">for</span> x, y <span class="hljs-keyword">in</span> border + platforms]\n' +
  239. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_rect</span><span class="hljs-params">(x, y)</span>:</span>\n' +
  240. ' <span class="hljs-keyword">return</span> pg.Rect(x*<span class="hljs-number">16</span>, y*<span class="hljs-number">16</span>, <span class="hljs-number">16</span>, <span class="hljs-number">16</span>)\n' +
  241. ' run(get_screen(), get_images(), get_mario(), get_tiles())\n' +
  242. '\n' +
  243. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run</span><span class="hljs-params">(screen, images, mario, tiles)</span>:</span>\n' +
  244. ' clock = pg.time.Clock()\n' +
  245. ' pressed = set()\n' +
  246. ' <span class="hljs-keyword">while</span> <span class="hljs-keyword">not</span> pg.event.get(pg.QUIT) <span class="hljs-keyword">and</span> clock.tick(<span class="hljs-number">28</span>):\n' +
  247. ' keys = {pg.K_UP: D.n, pg.K_RIGHT: D.e, pg.K_DOWN: D.s, pg.K_LEFT: D.w}\n' +
  248. ' pressed |= {keys.get(e.key) <span class="hljs-keyword">for</span> e <span class="hljs-keyword">in</span> pg.event.get(pg.KEYDOWN)}\n' +
  249. ' pressed -= {keys.get(e.key) <span class="hljs-keyword">for</span> e <span class="hljs-keyword">in</span> pg.event.get(pg.KEYUP)}\n' +
  250. ' update_speed(mario, tiles, pressed)\n' +
  251. ' update_position(mario, tiles)\n' +
  252. ' draw(screen, images, mario, tiles, pressed)\n' +
  253. '\n' +
  254. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_speed</span><span class="hljs-params">(mario, tiles, pressed)</span>:</span>\n' +
  255. ' x, y = mario.spd\n' +
  256. ' x += <span class="hljs-number">2</span> * ((D.e <span class="hljs-keyword">in</span> pressed) - (D.w <span class="hljs-keyword">in</span> pressed))\n' +
  257. ' x += (x &lt; <span class="hljs-number">0</span>) - (x &gt; <span class="hljs-number">0</span>)\n' +
  258. ' y += <span class="hljs-number">1</span> <span class="hljs-keyword">if</span> D.s <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> get_boundaries(mario.rect, tiles) <span class="hljs-keyword">else</span> (D.n <span class="hljs-keyword">in</span> pressed) * <span class="hljs-number">-10</span>\n' +
  259. ' mario.spd = P(x=max(-MAX_S.x, min(MAX_S.x, x)), y=max(-MAX_S.y, min(MAX_S.y, y)))\n' +
  260. '\n' +
  261. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_position</span><span class="hljs-params">(mario, tiles)</span>:</span>\n' +
  262. ' x, y = mario.rect.topleft\n' +
  263. ' n_steps = max(abs(s) <span class="hljs-keyword">for</span> s <span class="hljs-keyword">in</span> mario.spd)\n' +
  264. ' <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(n_steps):\n' +
  265. ' mario.spd = stop_on_collision(mario.spd, get_boundaries(mario.rect, tiles))\n' +
  266. ' mario.rect.topleft = x, y = x + (mario.spd.x / n_steps), y + (mario.spd.y / n_steps)\n' +
  267. '\n' +
  268. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_boundaries</span><span class="hljs-params">(rect, tiles)</span>:</span>\n' +
  269. ' deltas = {D.n: P(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>), D.e: P(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>), D.s: P(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), D.w: P(<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>)}\n' +
  270. ' <span class="hljs-keyword">return</span> {d <span class="hljs-keyword">for</span> d, delta <span class="hljs-keyword">in</span> deltas.items() <span class="hljs-keyword">if</span> rect.move(delta).collidelist(tiles) != <span class="hljs-number">-1</span>}\n' +
  271. '\n' +
  272. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">stop_on_collision</span><span class="hljs-params">(spd, bounds)</span>:</span>\n' +
  273. ' <span class="hljs-keyword">return</span> P(x=<span class="hljs-number">0</span> <span class="hljs-keyword">if</span> (D.w <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.x &lt; <span class="hljs-number">0</span>) <span class="hljs-keyword">or</span> (D.e <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.x &gt; <span class="hljs-number">0</span>) <span class="hljs-keyword">else</span> spd.x,\n' +
  274. ' y=<span class="hljs-number">0</span> <span class="hljs-keyword">if</span> (D.n <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.y &lt; <span class="hljs-number">0</span>) <span class="hljs-keyword">or</span> (D.s <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.y &gt; <span class="hljs-number">0</span>) <span class="hljs-keyword">else</span> spd.y)\n' +
  275. '\n' +
  276. '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw</span><span class="hljs-params">(screen, images, mario, tiles, pressed)</span>:</span>\n' +
  277. ' <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_marios_image_index</span><span class="hljs-params">()</span>:</span>\n' +
  278. ' <span class="hljs-keyword">if</span> D.s <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> get_boundaries(mario.rect, tiles):\n' +
  279. ' <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>\n' +
  280. ' <span class="hljs-keyword">return</span> next(mario.frame_cycle) <span class="hljs-keyword">if</span> {D.w, D.e} &amp; pressed <span class="hljs-keyword">else</span> <span class="hljs-number">6</span>\n' +
  281. ' screen.fill((<span class="hljs-number">85</span>, <span class="hljs-number">168</span>, <span class="hljs-number">255</span>))\n' +
  282. ' mario.facing_left = (D.w <span class="hljs-keyword">in</span> pressed) <span class="hljs-keyword">if</span> {D.w, D.e} &amp; pressed <span class="hljs-keyword">else</span> mario.facing_left\n' +
  283. ' screen.blit(images[get_marios_image_index() + mario.facing_left * <span class="hljs-number">9</span>], mario.rect)\n' +
  284. ' <span class="hljs-keyword">for</span> t <span class="hljs-keyword">in</span> tiles:\n' +
  285. ' screen.blit(images[<span class="hljs-number">18</span> <span class="hljs-keyword">if</span> t.x <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, (W-<span class="hljs-number">1</span>)*<span class="hljs-number">16</span>] <span class="hljs-keyword">or</span> t.y <span class="hljs-keyword">in</span> [<span class="hljs-number">0</span>, (H-<span class="hljs-number">1</span>)*<span class="hljs-number">16</span>] <span class="hljs-keyword">else</span> <span class="hljs-number">19</span>], t)\n' +
  286. ' pg.display.flip()\n' +
  287. '\n' +
  288. '<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">\'__main__\'</span>:\n' +
  289. ' main()\n';
  290. const PLOTLY =
  291. '<span class="hljs-meta">&gt;&gt;&gt; </span>gb = df.groupby(<span class="hljs-string">\'z\'</span>); gb.apply(print)\n' +
  292. ' x y z\n' +
  293. 'a <span class="hljs-number">1</span> <span class="hljs-number">2</span> <span class="hljs-number">3</span>\n' +
  294. ' x y z\n' +
  295. 'b <span class="hljs-number">4</span> <span class="hljs-number">5</span> <span class="hljs-number">6</span>\n' +
  296. 'c <span class="hljs-number">7</span> <span class="hljs-number">8</span> <span class="hljs-number">6</span>';
  297. const INDEX =
  298. '<li><strong>Only available in the <a href="https://transactions.sendowl.com/products/78175486/4422834F/view">PDF</a>.</strong></li>\n' +
  299. '<li><strong>Ctrl+F / ⌘F is usually sufficient.</strong></li>\n' +
  300. '<li><strong>Searching <code class="python hljs"><span class="hljs-string">\'#&lt;title&gt;\'</span></code> will limit the search to the titles.</strong></li>\n';
  301. const DIAGRAM_1_A =
  302. '+------------------+------------+------------+------------+\n' +
  303. '| | Iterable | Collection | Sequence |\n' +
  304. '+------------------+------------+------------+------------+\n';
  305. const DIAGRAM_1_B =
  306. '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' +
  307. '┃ │ Iterable │ Collection │ Sequence ┃\n' +
  308. '┠──────────────────┼────────────┼────────────┼────────────┨\n' +
  309. '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' +
  310. '┃ dict, set │ ✓ │ ✓ │ ┃\n' +
  311. '┃ iter │ ✓ │ │ ┃\n' +
  312. '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n';
  313. const DIAGRAM_2_A =
  314. '+--------------------+----------+----------+----------+----------+----------+\n' +
  315. '| | Number | Complex | Real | Rational | Integral |\n' +
  316. '+--------------------+----------+----------+----------+----------+----------+\n';
  317. const DIAGRAM_2_B =
  318. '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' +
  319. '┃ │ Number │ Complex │ Real │ Rational │ Integral ┃\n' +
  320. '┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' +
  321. '┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  322. '┃ fractions.Fraction │ ✓ │ ✓ │ ✓ │ ✓ │ ┃\n' +
  323. '┃ float │ ✓ │ ✓ │ ✓ │ │ ┃\n' +
  324. '┃ complex │ ✓ │ ✓ │ │ │ ┃\n' +
  325. '┃ decimal.Decimal │ ✓ │ │ │ │ ┃\n' +
  326. '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n';
  327. const DIAGRAM_3_A =
  328. '+---------------+----------+----------+----------+----------+----------+\n';
  329. const DIAGRAM_3_B =
  330. '┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' +
  331. '┃ │ [ !#$%…] │ [a-zA-Z] │ [¼½¾] │ [²³¹] │ [0-9] ┃\n' +
  332. '┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' +
  333. '┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  334. '┃ isalnum() │ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  335. '┃ isnumeric() │ │ │ ✓ │ ✓ │ ✓ ┃\n' +
  336. '┃ isdigit() │ │ │ │ ✓ │ ✓ ┃\n' +
  337. '┃ isdecimal() │ │ │ │ │ ✓ ┃\n' +
  338. '┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n';
  339. const DIAGRAM_4_A =
  340. "+--------------+----------------+----------------+----------------+----------------+\n" +
  341. "| | {<float>} | {<float>:f} | {<float>:e} | {<float>:%} |\n" +
  342. "+--------------+----------------+----------------+----------------+----------------+\n";
  343. const DIAGRAM_4_B =
  344. "┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓\n" +
  345. "┃ │ {&lt;float&gt;} │ {&lt;float&gt;:f} │ {&lt;float&gt;:e} │ {&lt;float&gt;:%} ┃\n" +
  346. "┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨\n" +
  347. "┃ 0.000056789 │ '5.6789e-05' │ '0.000057' │ '5.678900e-05' │ '0.005679%' ┃\n" +
  348. "┃ 0.00056789 │ '0.00056789' │ '0.000568' │ '5.678900e-04' │ '0.056789%' ┃\n" +
  349. "┃ 0.0056789 │ '0.0056789' │ '0.005679' │ '5.678900e-03' │ '0.567890%' ┃\n" +
  350. "┃ 0.056789 │ '0.056789' │ '0.056789' │ '5.678900e-02' │ '5.678900%' ┃\n" +
  351. "┃ 0.56789 │ '0.56789' │ '0.567890' │ '5.678900e-01' │ '56.789000%' ┃\n" +
  352. "┃ 5.6789 │ '5.6789' │ '5.678900' │ '5.678900e+00' │ '567.890000%' ┃\n" +
  353. "┃ 56.789 │ '56.789' │ '56.789000' │ '5.678900e+01' │ '5678.900000%' ┃\n" +
  354. "┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛\n" +
  355. "\n" +
  356. "┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓\n" +
  357. "┃ │ {&lt;float&gt;:.2} │ {&lt;float&gt;:.2f} │ {&lt;float&gt;:.2e} │ {&lt;float&gt;:.2%} ┃\n" +
  358. "┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨\n" +
  359. "┃ 0.000056789 │ '5.7e-05' │ '0.00' │ '5.68e-05' │ '0.01%' ┃\n" +
  360. "┃ 0.00056789 │ '0.00057' │ '0.00' │ '5.68e-04' │ '0.06%' ┃\n" +
  361. "┃ 0.0056789 │ '0.0057' │ '0.01' │ '5.68e-03' │ '0.57%' ┃\n" +
  362. "┃ 0.056789 │ '0.057' │ '0.06' │ '5.68e-02' │ '5.68%' ┃\n" +
  363. "┃ 0.56789 │ '0.57' │ '0.57' │ '5.68e-01' │ '56.79%' ┃\n" +
  364. "┃ 5.6789 │ '5.7' │ '5.68' │ '5.68e+00' │ '567.89%' ┃\n" +
  365. "┃ 56.789 │ '5.7e+01' │ '56.79' │ '5.68e+01' │ '5678.90%' ┃\n" +
  366. "┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛\n";
  367. const DIAGRAM_5_A =
  368. "+--------------+----------------+----------------+----------------+----------------+\n" +
  369. "| | {<float>:.2} | {<float>:.2f} | {<float>:.2e} | {<float>:.2%} |\n" +
  370. "+--------------+----------------+----------------+----------------+----------------+\n";
  371. const DIAGRAM_6_A =
  372. '+------------+------------+------------+------------+--------------+\n' +
  373. '| | Iterable | Collection | Sequence | abc.Sequence |\n' +
  374. '+------------+------------+------------+------------+--------------+\n';
  375. const DIAGRAM_6_B =
  376. '┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓\n' +
  377. '┃ │ Iterable │ Collection │ Sequence │ abc.Sequence ┃\n' +
  378. '┠────────────┼────────────┼────────────┼────────────┼──────────────┨\n' +
  379. '┃ iter() │ ! │ ! │ ✓ │ ✓ ┃\n' +
  380. '┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' +
  381. '┃ len() │ │ ! │ ! │ ! ┃\n' +
  382. '┃ getitem() │ │ │ ! │ ! ┃\n' +
  383. '┃ reversed() │ │ │ ✓ │ ✓ ┃\n' +
  384. '┃ index() │ │ │ │ ✓ ┃\n' +
  385. '┃ count() │ │ │ │ ✓ ┃\n' +
  386. '┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n';
  387. const DIAGRAM_7_A =
  388. 'BaseException\n' +
  389. ' +-- SystemExit';
  390. const DIAGRAM_7_B =
  391. "BaseException\n" +
  392. " ├── SystemExit <span class='hljs-comment'># Raised by the sys.exit() function.</span>\n" +
  393. " ├── KeyboardInterrupt <span class='hljs-comment'># Raised when the user hits the interrupt key (ctrl-c).</span>\n" +
  394. " └── Exception <span class='hljs-comment'># User-defined exceptions should be derived from this class.</span>\n" +
  395. " ├── ArithmeticError <span class='hljs-comment'># Base class for arithmetic errors such as ZeroDivisionError.</span>\n" +
  396. " ├── AssertionError <span class='hljs-comment'># Raised by `assert &lt;exp&gt;` if expression returns false value.</span>\n" +
  397. " ├── AttributeError <span class='hljs-comment'># Raised when object doesn't have requested attribute/method.</span>\n" +
  398. " ├── EOFError <span class='hljs-comment'># Raised by input() when it hits an end-of-file condition.</span>\n" +
  399. " ├── LookupError <span class='hljs-comment'># Base class for errors when a collection can't find an item.</span>\n" +
  400. " │ ├── IndexError <span class='hljs-comment'># Raised when a sequence index is out of range.</span>\n" +
  401. " │ └── KeyError <span class='hljs-comment'># Raised when a dictionary key or set element is missing.</span>\n" +
  402. " ├── MemoryError <span class='hljs-comment'># Out of memory. Could be too late to start deleting vars.</span>\n" +
  403. " ├── NameError <span class='hljs-comment'># Raised when nonexistent name (variable/func/class) is used.</span>\n" +
  404. " │ └── UnboundLocalError <span class='hljs-comment'># Raised when local name is used before it's being defined.</span>\n" +
  405. " ├── OSError <span class='hljs-comment'># Errors such as FileExistsError/PermissionError (see #Open).</span>\n" +
  406. " │ └── ConnectionError <span class='hljs-comment'># Errors such as BrokenPipeError/ConnectionAbortedError.</span>\n" +
  407. " ├── RuntimeError <span class='hljs-comment'># Raised by errors that don't fall into other categories.</span>\n" +
  408. " │ ├── NotImplementedErr <span class='hljs-comment'># Can be raised by abstract methods or by unfinished code.</span>\n" +
  409. " │ └── RecursionError <span class='hljs-comment'># Raised when the maximum recursion depth is exceeded.</span>\n" +
  410. " ├── StopIteration <span class='hljs-comment'># Raised by next() when run on an empty iterator.</span>\n" +
  411. " ├── TypeError <span class='hljs-comment'># Raised when an argument is of the wrong type.</span>\n" +
  412. " └── ValueError <span class='hljs-comment'># When argument has the right type but inappropriate value.</span>\n";
  413. const DIAGRAM_8_A =
  414. '+-----------+------------+------------+------------+\n' +
  415. '| | List | Set | Dict |\n' +
  416. '+-----------+------------+------------+------------+\n';
  417. const DIAGRAM_8_B =
  418. '┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' +
  419. '┃ │ List │ Set │ Dict ┃\n' +
  420. '┠───────────┼────────────┼────────────┼────────────┨\n' +
  421. '┃ getitem() │ IndexError │ │ KeyError ┃\n' +
  422. '┃ pop() │ IndexError │ KeyError │ KeyError ┃\n' +
  423. '┃ remove() │ ValueError │ KeyError │ ┃\n' +
  424. '┃ index() │ ValueError │ │ ┃\n' +
  425. '┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n';
  426. const DIAGRAM_9_A =
  427. '+------------------+--------------+--------------+--------------+\n' +
  428. '| | excel | excel-tab | unix |\n' +
  429. '+------------------+--------------+--------------+--------------+\n';
  430. const DIAGRAM_9_B =
  431. "┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓\n" +
  432. "┃ │ excel │ excel-tab │ unix ┃\n" +
  433. "┠──────────────────┼──────────────┼──────────────┼──────────────┨\n" +
  434. "┃ delimiter │ ',' │ '\\t' │ ',' ┃\n" +
  435. "┃ quotechar │ '\"' │ '\"' │ '\"' ┃\n" +
  436. "┃ doublequote │ True │ True │ True ┃\n" +
  437. "┃ skipinitialspace │ False │ False │ False ┃\n" +
  438. "┃ lineterminator │ '\\r\\n' │ '\\r\\n' │ '\\n' ┃\n" +
  439. "┃ quoting │ 0 │ 0 │ 1 ┃\n" +
  440. "┃ escapechar │ None │ None │ None ┃\n" +
  441. "┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n";
  442. const DIAGRAM_95_A =
  443. '+------------+--------------+----------+----------------------------------+\n' +
  444. '| Dialect | pip3 install | import | Dependencies |\n' +
  445. '+------------+--------------+----------+----------------------------------+\n';
  446. const DIAGRAM_95_B =
  447. '┏━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n' +
  448. '┃ Dialect │ pip3 install │ import │ Dependencies ┃\n' +
  449. '┠────────────┼──────────────┼──────────┼──────────────────────────────────┨\n' +
  450. '┃ mysql │ mysqlclient │ MySQLdb │ www.pypi.org/project/mysqlclient ┃\n' +
  451. '┃ postgresql │ psycopg2 │ psycopg2 │ www.pypi.org/project/psycopg2 ┃\n' +
  452. '┃ mssql │ pyodbc │ pyodbc │ www.pypi.org/project/pyodbc ┃\n' +
  453. '┃ oracle │ oracledb │ oracledb │ www.pypi.org/project/oracledb ┃\n' +
  454. '┗━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n';
  455. const DIAGRAM_10_A =
  456. '+-------------+-------------+\n' +
  457. '| Classes | Metaclasses |\n' +
  458. '+-------------+-------------|\n' +
  459. '| MyClass <-- MyMetaClass |\n';
  460. const DIAGRAM_10_B =
  461. '┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
  462. '┃ Classes │ Metaclasses ┃\n' +
  463. '┠─────────────┼─────────────┨\n' +
  464. '┃ MyClass ←──╴MyMetaClass ┃\n' +
  465. '┃ │ ↑ ┃\n' +
  466. '┃ object ←─────╴type ←╮ ┃\n' +
  467. '┃ │ │ ╰──╯ ┃\n' +
  468. '┃ str ←─────────╯ ┃\n' +
  469. '┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛\n';
  470. const DIAGRAM_11_A =
  471. '+-------------+-------------+\n' +
  472. '| Classes | Metaclasses |\n' +
  473. '+-------------+-------------|\n' +
  474. '| MyClass | MyMetaClass |\n';
  475. const DIAGRAM_11_B =
  476. '┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
  477. '┃ Classes │ Metaclasses ┃\n' +
  478. '┠─────────────┼─────────────┨\n' +
  479. '┃ MyClass │ MyMetaClass ┃\n' +
  480. '┃ ↑ │ ↑ ┃\n' +
  481. '┃ object╶─────→ type ┃\n' +
  482. '┃ ↓ │ ┃\n' +
  483. '┃ str │ ┃\n' +
  484. '┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛\n';
  485. const DIAGRAM_115_A =
  486. '+--------------+----------+------------+-------------------------------+------+\n' +
  487. '| pip3 install | Type | Target | How to run | Live |\n' +
  488. '+--------------+----------+------------+-------------------------------+------+\n';
  489. const DIAGRAM_115_B =
  490. '┏━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━┓\n' +
  491. '┃ pip3 install │ Type │ Target │ How to run │ Live ┃\n' +
  492. '┠──────────────┼──────────┼────────────┼───────────────────────────────┼──────┨\n' +
  493. '┃ pyinstrument │ Sampling │ CPU │ pyinstrument test.py │ × ┃\n' +
  494. '┃ py-spy │ Sampling │ CPU │ py-spy top -- python3 test.py │ ✓ ┃\n' +
  495. '┃ scalene │ Sampling │ CPU+Memory │ scalene test.py │ × ┃\n' +
  496. '┃ memray │ Tracing │ Memory │ memray run --live test.py │ ✓ ┃\n' +
  497. '┗━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━┛\n';
  498. const DIAGRAM_12_A =
  499. '+-----------+-----------+------+-----------+\n' +
  500. '| sampwidth | min | zero | max |\n' +
  501. '+-----------+-----------+------+-----------+\n';
  502. const DIAGRAM_12_B =
  503. '┏━━━━━━━━━━━┯━━━━━━━━━━━┯━━━━━━┯━━━━━━━━━━━┓\n' +
  504. '┃ sampwidth │ min │ zero │ max ┃\n' +
  505. '┠───────────┼───────────┼──────┼───────────┨\n' +
  506. '┃ 1 │ 0 │ 128 │ 255 ┃\n' +
  507. '┃ 2 │ -32768 │ 0 │ 32767 ┃\n' +
  508. '┃ 3 │ -8388608 │ 0 │ 8388607 ┃\n' +
  509. '┗━━━━━━━━━━━┷━━━━━━━━━━━┷━━━━━━┷━━━━━━━━━━━┛\n';
  510. const DIAGRAM_13_A =
  511. '| sr.apply(…) | 5 | sum 5 | s 5 |';
  512. const DIAGRAM_13_B =
  513. "┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  514. "┃ │ 'sum' │ ['sum'] │ {'s': 'sum'} ┃\n" +
  515. "┠───────────────┼─────────────┼─────────────┼───────────────┨\n" +
  516. "┃ sr.apply(…) │ 5 │ sum 5 │ s 5 ┃\n" +
  517. "┃ sr.agg(…) │ │ │ ┃\n" +
  518. "┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n" +
  519. "\n" +
  520. "┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  521. "┃ │ 'rank' │ ['rank'] │ {'r': 'rank'} ┃\n" +
  522. "┠───────────────┼─────────────┼─────────────┼───────────────┨\n" +
  523. "┃ sr.apply(…) │ │ rank │ ┃\n" +
  524. "┃ sr.agg(…) │ x 1 │ x 1 │ r x 1 ┃\n" +
  525. "┃ │ y 2 │ y 2 │ y 2 ┃\n" +
  526. "┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n";
  527. const DIAGRAM_14_A =
  528. "| | 'rank' | ['rank'] | {'r': 'rank'} |";
  529. const DIAGRAM_15_A =
  530. '+------------------------+---------------+------------+------------+--------------------------+';
  531. const DIAGRAM_15_B =
  532. "┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n" +
  533. "┃ │ 'outer' │ 'inner' │ 'left' │ Description ┃\n" +
  534. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  535. "┃ l.merge(r, on='y', │ x y z │ x y z │ x y z │ Merges on column if 'on' ┃\n" +
  536. "┃ how=…) │ 0 1 2 . │ 3 4 5 │ 1 2 . │ or 'left/right_on' are ┃\n" +
  537. "┃ │ 1 3 4 5 │ │ 3 4 5 │ set, else on shared cols.┃\n" +
  538. "┃ │ 2 . 6 7 │ │ │ Uses 'inner' by default. ┃\n" +
  539. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  540. "┃ l.join(r, lsuffix='l', │ x yl yr z │ │ x yl yr z │ Merges on row keys. ┃\n" +
  541. "┃ rsuffix='r', │ a 1 2 . . │ x yl yr z │ 1 2 . . │ Uses 'left' by default. ┃\n" +
  542. "┃ how=…) │ b 3 4 4 5 │ 3 4 4 5 │ 3 4 4 5 │ If r is a Series, it is ┃\n" +
  543. "┃ │ c . . 6 7 │ │ │ treated as a column. ┃\n" +
  544. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  545. "┃ pd.concat([l, r], │ x y z │ y │ │ Adds rows at the bottom. ┃\n" +
  546. "┃ axis=0, │ a 1 2 . │ 2 │ │ Uses 'outer' by default. ┃\n" +
  547. "┃ join=…) │ b 3 4 . │ 4 │ │ A Series is treated as a ┃\n" +
  548. "┃ │ b . 4 5 │ 4 │ │ column. To add a row use ┃\n" +
  549. "┃ │ c . 6 7 │ 6 │ │ pd.concat([l, DF([sr])]).┃\n" +
  550. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  551. "┃ pd.concat([l, r], │ x y y z │ │ │ Adds columns at the ┃\n" +
  552. "┃ axis=1, │ a 1 2 . . │ x y y z │ │ right end. Uses 'outer' ┃\n" +
  553. "┃ join=…) │ b 3 4 4 5 │ 3 4 4 5 │ │ by default. A Series is ┃\n" +
  554. "┃ │ c . . 6 7 │ │ │ treated as a column. ┃\n" +
  555. "┠────────────────────────┼───────────────┼────────────┼────────────┼──────────────────────────┨\n" +
  556. "┃ l.combine_first(r) │ x y z │ │ │ Adds missing rows and ┃\n" +
  557. "┃ │ a 1 2 . │ │ │ columns. Also updates ┃\n" +
  558. "┃ │ b 3 4 5 │ │ │ items that contain NaN. ┃\n" +
  559. "┃ │ c . 6 7 │ │ │ Argument r must be a DF. ┃\n" +
  560. "┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n";
  561. const DIAGRAM_16_A =
  562. '| df.apply(…) | x 4 | x y | x 4 |';
  563. const DIAGRAM_16_B =
  564. "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  565. "┃ │ 'sum' │ ['sum'] │ {'x': 'sum'} ┃\n" +
  566. "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" +
  567. "┃ df.apply(…) │ x 4 │ x y │ x 4 ┃\n" +
  568. "┃ df.agg(…) │ y 6 │ sum 4 6 │ ┃\n" +
  569. "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n" +
  570. "\n" +
  571. "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  572. "┃ │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" +
  573. "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" +
  574. "┃ df.apply(…) │ │ x y │ ┃\n" +
  575. "┃ df.agg(…) │ x y │ rank rank │ x ┃\n" +
  576. "┃ df.transform(…) │ a 1 1 │ a 1 1 │ a 1 ┃\n" +
  577. "┃ │ b 2 2 │ b 2 2 │ b 2 ┃\n" +
  578. "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n";
  579. const DIAGRAM_17_A =
  580. "| | 'rank' | ['rank'] | {'x': 'rank'} |";
  581. const DIAGRAM_18_A =
  582. '| gb.agg(…) | x y | | x y | |';
  583. const DIAGRAM_18_B =
  584. "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" +
  585. "┃ │ 'sum' │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" +
  586. "┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" +
  587. "┃ gb.agg(…) │ x y │ │ x y │ ┃\n" +
  588. "┃ │ z │ x y │ rank rank │ x ┃\n" +
  589. "┃ │ 3 1 2 │ a 1 1 │ a 1 1 │ a 1 ┃\n" +
  590. "┃ │ 6 11 13 │ b 1 1 │ b 1 1 │ b 1 ┃\n" +
  591. "┃ │ │ c 2 2 │ c 2 2 │ c 2 ┃\n" +
  592. "┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" +
  593. "┃ gb.transform(…) │ x y │ x y │ │ ┃\n" +
  594. "┃ │ a 1 2 │ a 1 1 │ │ ┃\n" +
  595. "┃ │ b 11 13 │ b 1 1 │ │ ┃\n" +
  596. "┃ │ c 11 13 │ c 2 2 │ │ ┃\n" +
  597. "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n";
  598. const MENU = '<a href="https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md">Download text file</a>, <a href="https://transactions.sendowl.com/products/78175486/4422834F/view">Buy PDF</a>, <a href="https://github.com/gto76/python-cheatsheet">Fork me on GitHub</a>, <a href="https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions">Check out FAQ</a> or <a href="index.html?theme=dark3">Switch to dark theme</a>.\n';
  599. const DARK_THEME_SCRIPT =
  600. '<script>\n' +
  601. ' // Changes the image and link to theme if URL ends with "index.html?theme=dark". \n' +
  602. ' if (window.location.search.search(/[?&]theme=dark/) !== -1) {\n' +
  603. '\n' +
  604. ' var link_to_theme = document.createElement("a")\n' +
  605. ' link_to_theme.href = "index.html"\n' +
  606. ' link_to_theme.text = "Switch to light theme"\n' +
  607. ' document.getElementsByClassName("banner")[0].firstChild.children[4].replaceWith(link_to_theme)\n' +
  608. '\n' +
  609. ' var img_dark = document.createElement("img");\n' +
  610. ' img_dark.src = "web/image_orig_blue6.png";\n' +
  611. ' img_dark.alt = "Monthy Python";\n' +
  612. ' if ((window.location.search.search(/[?&]theme=dark2/) !== -1) ||\n' +
  613. ' (window.location.search.search(/[?&]theme=dark3/) !== -1)) {\n' +
  614. ' img_dark.style = "width: 910px;";\n' +
  615. ' } else {\n' +
  616. ' img_dark.style = "width: 960px;";\n' +
  617. ' }\n' +
  618. ' document.getElementsByClassName("banner")[1].firstChild.replaceWith(img_dark);\n' +
  619. ' }\n' +
  620. '</script>';
  621. function main() {
  622. const html = getMd();
  623. initDom(html);
  624. modifyPage();
  625. var template = readFile('web/template.html');
  626. template = updateDate(template);
  627. const tokens = template.split('<div id=main_container></div>');
  628. const text = `${tokens[0]} ${document.body.innerHTML} ${tokens[1]}`;
  629. writeToFile('index.html', text);
  630. }
  631. function getMd() {
  632. var readme = readFile('README.md');
  633. var readme = readme.replace("#semaphore-event-barrier", "#semaphoreeventbarrier");
  634. var readme = readme.replace("#semaphore-event-barrier", "#semaphoreeventbarrier");
  635. var readme = readme.replace("#dataframe-plot-encode-decode", "#dataframeplotencodedecode");
  636. const converter = new showdown.Converter();
  637. return converter.makeHtml(readme);
  638. }
  639. function initDom(html) {
  640. const { JSDOM } = jsdom;
  641. const dom = new JSDOM(html);
  642. const $ = (require('jquery'))(dom.window);
  643. global.$ = $;
  644. global.document = dom.window.document;
  645. }
  646. function modifyPage() {
  647. changeMenu();
  648. addDarkThemeScript();
  649. removeOrigToc();
  650. addToc();
  651. insertLinks();
  652. unindentBanner();
  653. updateDiagrams();
  654. highlightCode();
  655. fixPandasDiagram();
  656. removePlotImages();
  657. fixABCSequenceDiv();
  658. fixStructFormatDiv();
  659. }
  660. function changeMenu() {
  661. $('sup').first().html(MENU)
  662. }
  663. function addDarkThemeScript() {
  664. $('#main').before(DARK_THEME_SCRIPT);
  665. }
  666. function removeOrigToc() {
  667. const headerContents = $('#contents');
  668. const contentsList = headerContents.next();
  669. headerContents.remove();
  670. contentsList.remove();
  671. }
  672. function addToc() {
  673. const nodes = $.parseHTML(TOC);
  674. $('#main').before(nodes);
  675. }
  676. function insertLinks() {
  677. $('h2').each(function() {
  678. const aId = $(this).attr('id');
  679. const text = $(this).text();
  680. const line = `<a href="#${aId}" name="${aId}">#</a>${text}`;
  681. $(this).html(line);
  682. });
  683. }
  684. function unindentBanner() {
  685. const montyImg = $('img').first();
  686. montyImg.parent().addClass('banner');
  687. const downloadPraragrapth = $('p').first();
  688. downloadPraragrapth.addClass('banner');
  689. }
  690. function updateDiagrams() {
  691. $(`code:contains(${DIAGRAM_1_A})`).html(DIAGRAM_1_B);
  692. $(`code:contains(${DIAGRAM_2_A})`).html(DIAGRAM_2_B);
  693. $(`code:contains(${DIAGRAM_3_A})`).html(DIAGRAM_3_B);
  694. $(`code:contains(${DIAGRAM_4_A})`).html(DIAGRAM_4_B);
  695. $(`code:contains(${DIAGRAM_5_A})`).parent().remove();
  696. $(`code:contains(${DIAGRAM_6_A})`).html(DIAGRAM_6_B);
  697. $(`code:contains(${DIAGRAM_7_A})`).html(DIAGRAM_7_B);
  698. $(`code:contains(${DIAGRAM_8_A})`).html(DIAGRAM_8_B);
  699. $(`code:contains(${DIAGRAM_9_A})`).html(DIAGRAM_9_B);
  700. $(`code:contains(${DIAGRAM_95_A})`).html(DIAGRAM_95_B);
  701. $(`code:contains(${DIAGRAM_10_A})`).html(DIAGRAM_10_B);
  702. $(`code:contains(${DIAGRAM_11_A})`).html(DIAGRAM_11_B);
  703. $(`code:contains(${DIAGRAM_115_A})`).html(DIAGRAM_115_B);
  704. $(`code:contains(${DIAGRAM_12_A})`).html(DIAGRAM_12_B).removeClass("text").removeClass("language-text").addClass("python");
  705. $(`code:contains(${DIAGRAM_13_A})`).html(DIAGRAM_13_B).removeClass("text").removeClass("language-text").addClass("python");
  706. $(`code:contains(${DIAGRAM_14_A})`).parent().remove();
  707. $(`code:contains(${DIAGRAM_15_A})`).html(DIAGRAM_15_B).removeClass("text").removeClass("language-text").addClass("python");
  708. $(`code:contains(${DIAGRAM_16_A})`).html(DIAGRAM_16_B).removeClass("text").removeClass("language-text").addClass("python");
  709. $(`code:contains(${DIAGRAM_17_A})`).parent().remove();
  710. $(`code:contains(${DIAGRAM_18_A})`).html(DIAGRAM_18_B).removeClass("text").removeClass("language-text").addClass("python");
  711. }
  712. function highlightCode() {
  713. changeCodeLanguages();
  714. $('code').each(function(index) {
  715. hljs.highlightBlock(this);
  716. });
  717. fixClasses();
  718. fixHighlights();
  719. preventPageBreaks();
  720. fixPageBreaksFile();
  721. fixPageBreaksStruct();
  722. insertPageBreaks();
  723. }
  724. function changeCodeLanguages() {
  725. setApaches(['<D>', '<T>', '<DT>', '<TD>', '<a>', '<n>']);
  726. $('code').not('.python').not('.text').not('.bash').not('.apache').addClass('python');
  727. $('code:contains(<el> = <2d_array>[row_index, column_index])').removeClass().addClass('bash');
  728. $('code:contains(<2d_array> = <2d_array>[row_indexes])').removeClass().addClass('bash');
  729. $('code:contains(<2d_bools> = <2d_array> > <el/1d/2d_array>)').removeClass().addClass('bash');
  730. $('code.perl').removeClass().addClass('python');
  731. }
  732. function setApaches(elements) {
  733. for (el of elements) {
  734. $(`code:contains(${el})`).addClass('apache');
  735. }
  736. }
  737. function fixClasses() {
  738. // Changes class="hljs-keyword" to class="hljs-title" of 'class' keyword.
  739. $('.hljs-class').filter(':contains(class \')').find(':first-child').removeClass('hljs-keyword').addClass('hljs-title')
  740. }
  741. function fixHighlights() {
  742. $(`code:contains(<int> = ±0b<bin>)`).html(BIN_HEX);
  743. $(`code:contains(@lru_cache(maxsize=None))`).html(LRU_CACHE);
  744. $(`code:contains(@debug(print_result=True))`).html(PARAMETRIZED_DECORATOR);
  745. $(`code:contains(print/str/repr([<el>]))`).html(REPR_USE_CASES);
  746. $(`code:contains((self, a=None):)`).html(CONSTRUCTOR_OVERLOADING);
  747. $(`code:contains(make_dataclass(\'<class_name>\')`).html(DATACLASS);
  748. $(`code:contains(shutil.copy)`).html(SHUTIL_COPY);
  749. $(`code:contains(os.rename)`).html(OS_RENAME);
  750. $(`code:contains(\'<n>s\')`).html(STRUCT_FORMAT);
  751. $(`code:contains(match <object/expression>:)`).html(MATCH);
  752. $(`code:contains(>>> match Path)`).html(MATCH_EXAMPLE);
  753. $(`code:contains(import asyncio, collections, curses, curses.textpad, enum, random)`).html(COROUTINES);
  754. $(`code:contains(import curses, os)`).html(CURSES);
  755. $(`code:contains(pip3 install tqdm)`).html(PROGRESS_BAR);
  756. $(`code:contains(>>> logging.basicConfig(level=)`).html(LOGGING_EXAMPLE);
  757. $(`code:contains(samples_f = (sin(i *)`).html(AUDIO);
  758. $(`code:contains(collections, dataclasses, enum, io, itertools)`).html(MARIO);
  759. $(`code:contains(>>> gb = df.groupby)`).html(PLOTLY);
  760. $(`ul:contains(Only available in)`).html(INDEX);
  761. }
  762. function preventPageBreaks() {
  763. $(':header').each(function(index) {
  764. var el = $(this)
  765. var untilPre = el.nextUntil('pre')
  766. var untilH2 = el.nextUntil('h2')
  767. if ((untilPre.length < untilH2.length) || el.prop('tagName') === 'H1') {
  768. untilPre.add(el).next().add(el).wrapAll("<div></div>");
  769. } else {
  770. untilH2.add(el).wrapAll("<div></div>");
  771. }
  772. });
  773. }
  774. function fixPageBreaksFile() {
  775. const modesDiv = $('#file').parent().parent().parent()
  776. move(modesDiv, 'file')
  777. move(modesDiv, 'exceptions-1')
  778. }
  779. function fixPageBreaksStruct() {
  780. const formatDiv = $('#floatingpointtypesstructalwaysusesstandardsizes').parent().parent().parent().parent()
  781. move(formatDiv, 'floatingpointtypesstructalwaysusesstandardsizes')
  782. move(formatDiv, 'integertypesuseacapitalletterforunsignedtypeminimumandstandardsizesareinbrackets')
  783. move(formatDiv, 'forstandardsizesstartformatstringwith')
  784. }
  785. function move(anchor_el, el_id) {
  786. const el = $('#'+el_id).parent()
  787. anchor_el.after(el)
  788. }
  789. function insertPageBreaks() {
  790. insertPageBreakBefore('#decorator')
  791. // insertPageBreakBefore('#print')
  792. }
  793. function insertPageBreakBefore(an_id) {
  794. $('<div class="pagebreak"></div>').insertBefore($(an_id).parent())
  795. }
  796. function fixPandasDiagram() {
  797. const diagram_15 = '┏━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━┓';
  798. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(and)").after("and");
  799. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(as)").after("as");
  800. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(is)").after("is");
  801. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(if)").after("if");
  802. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(or)").after("or");
  803. $(`code:contains(${diagram_15})`).find(".hljs-keyword:contains(else)").after("else");
  804. $(`code:contains(${diagram_15})`).find(".hljs-keyword").remove();
  805. }
  806. function removePlotImages() {
  807. $('img[alt="Covid Deaths"]').remove();
  808. $('img[alt="Covid Cases"]').remove();
  809. }
  810. function fixABCSequenceDiv() {
  811. $('#abcsequence').parent().insertBefore($('#tableofrequiredandautomaticallyavailablespecialmethods').parent())
  812. }
  813. function fixStructFormatDiv() {
  814. const div = $('#format-2').parent()
  815. $('#format-2').insertBefore(div)
  816. $('#forstandardtypesizesandmanualalignmentpaddingstartformatstringwith').parent().insertBefore(div)
  817. }
  818. function updateDate(template) {
  819. const date = new Date();
  820. const date_str = date.toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'});
  821. template = template.replace('May 20, 2021', date_str);
  822. template = template.replace('May 20, 2021', date_str);
  823. return template;
  824. }
  825. // UTIL
  826. function readFile(filename) {
  827. try {
  828. return fs.readFileSync(filename, 'utf8');
  829. } catch(e) {
  830. console.error('Error:', e.stack);
  831. }
  832. }
  833. function writeToFile(filename, text) {
  834. try {
  835. return fs.writeFileSync(filename, text, 'utf8');
  836. } catch(e) {
  837. console.error('Error:', e.stack);
  838. }
  839. }
  840. main();