diff --git a/README.md b/README.md index a43225b..eac1b55 100644 --- a/README.md +++ b/README.md @@ -494,64 +494,69 @@ Format Numbers ------- ```python -<int> = int(<float/str/bool>) # Or: math.trunc(<float>) -<float> = float(<int/str/bool>) # Or: <int/float>e±<int> -<complex> = complex(real=0, imag=0) # Or: <int/float> ± <int/float>j -<Fraction> = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1) -<Decimal> = decimal.Decimal(<str/int>) # Or: Decimal((sign, digits, exponent)) +<int> = int(<float/str/bool>) # Or: math.trunc(<float>) +<float> = float(<int/str/bool>) # Or: <int/float>e±<int> +<complex> = complex(real=0, imag=0) # Or: <int/float> ± <int/float>j +<Fraction> = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1) +<Decimal> = decimal.Decimal(<str/int>) # Or: Decimal((sign, digits, exponent)) ``` +* **`'int(<str>)'` and `'float(<str>)'` raise ValueError on malformed strings.** * **Decimal numbers are stored exactly, unlike most floats where `'1.1 + 2.2 != 3.3'`.** * **Floats can be compared with: `'math.isclose(<float>, <float>)'`.** * **Precision of decimal operations is set with: `'decimal.getcontext().prec = <int>'`.** * **Bools can be used anywhere ints can, because bool is a subclass of int: `'True + 1 == 2'`.** -### Basic Functions +### Built-in Functions ```python -<num> = pow(<num>, <num>) # Or: <number> ** <number> -<num> = abs(<num>) # <float> = abs(<complex>) -<num> = round(<num> [, ±ndigits]) # `round(126, -1) == 130` +<num> = pow(<num>, <num>) # Or: <number> ** <number> +<num> = abs(<num>) # <float> = abs(<complex>) +<num> = round(<num> [, ±ndigits]) # Also math.floor/ceil(<number>). +<num> = min(<collection>) # Also max(<num>, <num> [, ...]). +<num> = sum(<collection>) # Also math.prod(<collection>). ``` ### Math ```python -from math import e, pi, inf, nan, isinf, isnan # `<el> == nan` is always False. -from math import sin, cos, tan, asin, acos, atan # Also: degrees, radians. -from math import log, log10, log2 # Log can accept base as second arg. +from math import e, pi, inf, nan, isnan # `inf*0` and `nan+1` return nan. +from math import sqrt, factorial # `sqrt(-1)` raises ValueError. +from math import sin, cos, tan # Also: asin, degrees, radians. +from math import log, log10, log2 # Log accepts base as second arg. ``` ### Statistics ```python -from statistics import mean, median, variance # Also: stdev, quantiles, groupby. +from statistics import mean, median, mode # Mode returns the most common value. +from statistics import variance, stdev # Also: pvariance, pstdev, quantiles. ``` ### Random ```python -from random import random, randint, uniform # Also: gauss, choice, shuffle, seed. +from random import random, randint, uniform # Also: gauss, choice, shuffle, seed. ``` ```python -<float> = random() # Returns a float inside [0, 1). -<num> = randint/uniform(a, b) # Returns an int/float inside [a, b]. -<float> = gauss(mean, stdev) # Also triangular(low, high, mode). -<el> = choice(<sequence>) # Keeps it intact. Also sample(pop, k). -shuffle(<list>) # Shuffles the list in place. +<float> = random() # Returns a float inside [0, 1). +<num> = randint/uniform(a, b) # Returns an int/float inside [a, b]. +<float> = gauss(mean, stdev) # Also triangular(low, high, mode). +<el> = choice(<sequence>) # Keeps it intact. Also sample(pop, k). +shuffle(<list>) # Shuffles the list in place. ``` ### Hexadecimal Numbers ```python -<int> = ±0x<hex> # Or: ±0b<bin> -<int> = int('±<hex>', 16) # Or: int('±<bin>', 2) -<int> = int('±0x<hex>', 0) # Or: int('±0b<bin>', 0) -<str> = hex(<int>) # Returns '[-]0x<hex>'. Also bin(). +<int> = ±0x<hex> # Or: ±0b<bin> +<int> = int('±<hex>', 16) # Or: int('±<bin>', 2) +<int> = int('±0x<hex>', 0) # Or: int('±0b<bin>', 0) +<str> = hex(<int>) # Returns '[-]0x<hex>'. Also bin(). ``` ### Bitwise Operators ```python -<int> = <int> & <int> # And (0b1100 & 0b1010 == 0b1000). -<int> = <int> | <int> # Or (0b1100 | 0b1010 == 0b1110). -<int> = <int> ^ <int> # Xor (0b1100 ^ 0b1010 == 0b0110). -<int> = <int> << n_bits # Left shift. Use >> for right. -<int> = ~<int> # Not. Also -<int> - 1. +<int> = <int> & <int> # And (0b1100 & 0b1010 == 0b1000). +<int> = <int> | <int> # Or (0b1100 | 0b1010 == 0b1110). +<int> = <int> ^ <int> # Xor (0b1100 ^ 0b1010 == 0b0110). +<int> = <int> << n_bits # Left shift. Use >> for right. +<int> = ~<int> # Not. Also -<int> - 1. ``` @@ -562,30 +567,24 @@ import itertools as it ``` ```python ->>> list(it.product([0, 1], repeat=3)) -[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), - (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] +>>> list(it.product('abc', repeat=2)) # a b c +[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x + ('b', 'a'), ('b', 'b'), ('b', 'c'), # b x x x + ('c', 'a'), ('c', 'b'), ('c', 'c')] # c x x x ``` ```python ->>> list(it.product('abc', 'abc')) # a b c -[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x - ('b', 'a'), ('b', 'b'), ('b', 'c'), # b x x x - ('c', 'a'), ('c', 'b'), ('c', 'c')] # c x x x +>>> list(it.permutations('abc', 2)) # a b c +[('a', 'b'), ('a', 'c'), # a . x x + ('b', 'a'), ('b', 'c'), # b x . x + ('c', 'a'), ('c', 'b')] # c x x . ``` ```python ->>> list(it.permutations('abc', 2)) # a b c -[('a', 'b'), ('a', 'c'), # a . x x - ('b', 'a'), ('b', 'c'), # b x . x - ('c', 'a'), ('c', 'b')] # c x x . -``` - -```python ->>> list(it.combinations('abc', 2)) # a b c -[('a', 'b'), ('a', 'c'), # a . x x - ('b', 'c'), # b . . x -] # c . . . +>>> list(it.combinations('abc', 2)) # a b c +[('a', 'b'), ('a', 'c'), # a . x x + ('b', 'c'), # b . . x +] # c . . . ``` @@ -1183,7 +1182,7 @@ class Counter: ### Callable * **All functions and classes have a call() method, hence are callable.** -* **Use `'callable(<obj>)'` or `'isinstance(<obj>, collections.abc.Callable)'` to check if object is callable.** +* **Use `'callable(<obj>)'` or `'isinstance(<obj>, collections.abc.Callable)'` to check if object is callable. Calling an uncallable object raises `'TypeError'`.** * **When this cheatsheet uses `'<function>'` as an argument, it means `'<callable>'`.** ```python class Counter: @@ -2435,7 +2434,7 @@ Console App ```python # $ pip3 install windows-curses import curses, os -from curses import A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER +from curses import A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT def main(screen): ch, first, selected, paths = 0, 0, 0, os.listdir() @@ -2450,7 +2449,7 @@ def main(screen): selected += (ch == KEY_DOWN) and (selected < len(paths)-1) first -= (first > selected) first += (first < selected-(height-1)) - if ch in [KEY_LEFT, KEY_RIGHT, KEY_ENTER, ord('\n'), ord('\r')]: + if ch in [KEY_LEFT, KEY_RIGHT, ord('\n')]: new_dir = '..' if ch == KEY_LEFT else paths[selected] if os.path.isdir(new_dir): os.chdir(new_dir) @@ -2469,9 +2468,9 @@ GUI App # $ pip3 install PySimpleGUI import PySimpleGUI as sg -text_box = sg.Input(default_text='100', enable_events=True, key='-QUANTITY-') -dropdown = sg.InputCombo(['g', 'kg', 't'], 'kg', readonly=True, enable_events=True, k='-UNIT-') -label = sg.Text('100 kg is 220.462 lbs.', key='-OUTPUT-') +text_box = sg.Input(default_text='100', enable_events=True, key='QUANTITY') +dropdown = sg.InputCombo(['g', 'kg', 't'], 'kg', readonly=True, enable_events=True, k='UNIT') +label = sg.Text('100 kg is 220.462 lbs.', key='OUTPUT') button = sg.Button('Close') window = sg.Window('Weight Converter', [[text_box, dropdown], [label], [button]]) @@ -2480,13 +2479,13 @@ while True: if event in [sg.WIN_CLOSED, 'Close']: break try: - quantity = float(values['-QUANTITY-']) + quantity = float(values['QUANTITY']) except ValueError: continue - unit = values['-UNIT-'] + unit = values['UNIT'] factors = {'g': 0.001, 'kg': 1, 't': 1000} lbs = quantity * factors[unit] / 0.45359237 - window['-OUTPUT-'].update(value=f'{quantity} {unit} is {lbs:g} lbs.') + window['OUTPUT'].update(value=f'{quantity} {unit} is {lbs:g} lbs.') window.close() ``` @@ -2552,14 +2551,14 @@ app.run(host=None, port=None, debug=None) # Or: $ flask --app FILE run [--ARG[= * **Install a WSGI server like [Waitress](https://flask.palletsprojects.com/en/latest/deploying/waitress/) and a HTTP server such as [Nginx](https://flask.palletsprojects.com/en/latest/deploying/nginx/) for better security.** * **Debug mode restarts the app whenever script changes and displays errors in the browser.** -### Static Request +### Serving Files ```python @app.route('/img/<path:filename>') def serve_file(filename): return fl.send_from_directory('DIRNAME', filename) ``` -### Dynamic Request +### Serving HTML ```python @app.route('/<sport>') def serve_html(sport): @@ -2570,7 +2569,7 @@ def serve_html(sport): * **`'fl.request.args[<str>]'` returns parameter from query string (URL part right of '?').** * **`'fl.session[<str>] = <obj>'` stores session data. It requires secret key to be set at the startup with `'app.secret_key = <str>'`.** -### REST Request +### Serving JSON ```python @app.post('/<sport>/odds') def serve_json(sport): diff --git a/index.html b/index.html index 89dbbe4..7e80673 100644 --- a/index.html +++ b/index.html @@ -56,7 +56,7 @@ <body> <header> - <aside>April 17, 2025</aside> + <aside>April 22, 2025</aside> <a href="https://gto76.github.io" rel="author">Jure Šorn</a> </header> @@ -455,75 +455,76 @@ Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span> {<span class="hljs-number">90</span>:X} <span class="hljs-comment"># '5A'. Hexadecimal with upper-case letters.</span> </code></pre></div> -<div><h2 id="numbers"><a href="#numbers" name="numbers">#</a>Numbers</h2><pre><code class="python language-python hljs"><int> = int(<float/str/bool>) <span class="hljs-comment"># Or: math.trunc(<float>)</span> -<float> = float(<int/str/bool>) <span class="hljs-comment"># Or: <int/float>e±<int></span> -<complex> = complex(real=<span class="hljs-number">0</span>, imag=<span class="hljs-number">0</span>) <span class="hljs-comment"># Or: <int/float> ± <int/float>j</span> -<Fraction> = fractions.Fraction(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>) <span class="hljs-comment"># Or: Fraction(numerator=0, denominator=1)</span> -<Decimal> = decimal.Decimal(<str/int>) <span class="hljs-comment"># Or: Decimal((sign, digits, exponent))</span> +<div><h2 id="numbers"><a href="#numbers" name="numbers">#</a>Numbers</h2><pre><code class="python language-python hljs"><int> = int(<float/str/bool>) <span class="hljs-comment"># Or: math.trunc(<float>)</span> +<float> = float(<int/str/bool>) <span class="hljs-comment"># Or: <int/float>e±<int></span> +<complex> = complex(real=<span class="hljs-number">0</span>, imag=<span class="hljs-number">0</span>) <span class="hljs-comment"># Or: <int/float> ± <int/float>j</span> +<Fraction> = fractions.Fraction(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>) <span class="hljs-comment"># Or: Fraction(numerator=0, denominator=1)</span> +<Decimal> = decimal.Decimal(<str/int>) <span class="hljs-comment"># Or: Decimal((sign, digits, exponent))</span> </code></pre></div> <ul> +<li><strong><code class="python hljs"><span class="hljs-string">'int(<str>)'</span></code> and <code class="python hljs"><span class="hljs-string">'float(<str>)'</span></code> raise ValueError on malformed strings.</strong></li> <li><strong>Decimal numbers are stored exactly, unlike most floats where <code class="python hljs"><span class="hljs-string">'1.1 + 2.2 != 3.3'</span></code>.</strong></li> <li><strong>Floats can be compared with: <code class="python hljs"><span class="hljs-string">'math.isclose(<float>, <float>)'</span></code>.</strong></li> <li><strong>Precision of decimal operations is set with: <code class="python hljs"><span class="hljs-string">'decimal.getcontext().prec = <int>'</span></code>.</strong></li> <li><strong>Bools can be used anywhere ints can, because bool is a subclass of int: <code class="python hljs"><span class="hljs-string">'True + 1 == 2'</span></code>.</strong></li> </ul> -<div><h3 id="basicfunctions">Basic Functions</h3><pre><code class="python language-python hljs"><num> = pow(<num>, <num>) <span class="hljs-comment"># Or: <number> ** <number></span> -<num> = abs(<num>) <span class="hljs-comment"># <float> = abs(<complex>)</span> -<num> = round(<num> [, ±ndigits]) <span class="hljs-comment"># `round(126, -1) == 130`</span> +<div><h3 id="builtinfunctions">Built-in Functions</h3><pre><code class="python language-python hljs"><num> = pow(<num>, <num>) <span class="hljs-comment"># Or: <number> ** <number></span> +<num> = abs(<num>) <span class="hljs-comment"># <float> = abs(<complex>)</span> +<num> = round(<num> [, ±ndigits]) <span class="hljs-comment"># Also math.floor/ceil(<number>).</span> +<num> = min(<collection>) <span class="hljs-comment"># Also max(<num>, <num> [, ...]).</span> +<num> = sum(<collection>) <span class="hljs-comment"># Also math.prod(<collection>).</span> </code></pre></div> -<div><h3 id="math">Math</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> e, pi, inf, nan, isinf, isnan <span class="hljs-comment"># `<el> == nan` is always False.</span> -<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> sin, cos, tan, asin, acos, atan <span class="hljs-comment"># Also: degrees, radians.</span> -<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2 <span class="hljs-comment"># Log can accept base as second arg.</span> +<div><h3 id="math">Math</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> e, pi, inf, nan, isnan <span class="hljs-comment"># `inf*0` and `nan+1` return nan.</span> +<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> sqrt, factorial <span class="hljs-comment"># `sqrt(-1)` raises ValueError.</span> +<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> sin, cos, tan <span class="hljs-comment"># Also: asin, degrees, radians.</span> +<span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2 <span class="hljs-comment"># Log accepts base as second arg.</span> </code></pre></div> -<div><h3 id="statistics">Statistics</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mean, median, variance <span class="hljs-comment"># Also: stdev, quantiles, groupby.</span> +<div><h3 id="statistics">Statistics</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mean, median, mode <span class="hljs-comment"># Mode returns the most common value.</span> +<span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> variance, stdev <span class="hljs-comment"># Also: pvariance, pstdev, quantiles.</span> </code></pre></div> -<div><h3 id="random">Random</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> random, randint, uniform <span class="hljs-comment"># Also: gauss, choice, shuffle, seed.</span> +<div><h3 id="random">Random</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> random, randint, uniform <span class="hljs-comment"># Also: gauss, choice, shuffle, seed.</span> </code></pre></div> -<pre><code class="python language-python hljs"><float> = random() <span class="hljs-comment"># Returns a float inside [0, 1).</span> -<num> = randint/uniform(a, b) <span class="hljs-comment"># Returns an int/float inside [a, b].</span> -<float> = gauss(mean, stdev) <span class="hljs-comment"># Also triangular(low, high, mode).</span> -<el> = choice(<sequence>) <span class="hljs-comment"># Keeps it intact. Also sample(pop, k).</span> -shuffle(<list>) <span class="hljs-comment"># Shuffles the list in place.</span> +<pre><code class="python language-python hljs"><float> = random() <span class="hljs-comment"># Returns a float inside [0, 1).</span> +<num> = randint/uniform(a, b) <span class="hljs-comment"># Returns an int/float inside [a, b].</span> +<float> = gauss(mean, stdev) <span class="hljs-comment"># Also triangular(low, high, mode).</span> +<el> = choice(<sequence>) <span class="hljs-comment"># Keeps it intact. Also sample(pop, k).</span> +shuffle(<list>) <span class="hljs-comment"># Shuffles the list in place.</span> </code></pre> -<div><h3 id="hexadecimalnumbers">Hexadecimal Numbers</h3><pre><code class="python language-python hljs"><int> = ±<span class="hljs-number">0x</span><hex> <span class="hljs-comment"># Or: ±0b<bin></span> -<int> = int(<span class="hljs-string">'±<hex>'</span>, <span class="hljs-number">16</span>) <span class="hljs-comment"># Or: int('±<bin>', 2)</span> -<int> = int(<span class="hljs-string">'±0x<hex>'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int('±0b<bin>', 0)</span> -<str> = hex(<int>) <span class="hljs-comment"># Returns '[-]0x<hex>'. Also bin().</span> +<div><h3 id="hexadecimalnumbers">Hexadecimal Numbers</h3><pre><code class="python language-python hljs"><int> = ±<span class="hljs-number">0x</span><hex> <span class="hljs-comment"># Or: ±0b<bin></span> +<int> = int(<span class="hljs-string">'±<hex>'</span>, <span class="hljs-number">16</span>) <span class="hljs-comment"># Or: int('±<bin>', 2)</span> +<int> = int(<span class="hljs-string">'±0x<hex>'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int('±0b<bin>', 0)</span> +<str> = hex(<int>) <span class="hljs-comment"># Returns '[-]0x<hex>'. Also bin().</span> </code></pre></div> -<div><h3 id="bitwiseoperators">Bitwise Operators</h3><pre><code class="python language-python hljs"><int> = <int> & <int> <span class="hljs-comment"># And (0b1100 & 0b1010 == 0b1000).</span> -<int> = <int> | <int> <span class="hljs-comment"># Or (0b1100 | 0b1010 == 0b1110).</span> -<int> = <int> ^ <int> <span class="hljs-comment"># Xor (0b1100 ^ 0b1010 == 0b0110).</span> -<int> = <int> << n_bits <span class="hljs-comment"># Left shift. Use >> for right.</span> -<int> = ~<int> <span class="hljs-comment"># Not. Also -<int> - 1.</span> +<div><h3 id="bitwiseoperators">Bitwise Operators</h3><pre><code class="python language-python hljs"><int> = <int> & <int> <span class="hljs-comment"># And (0b1100 & 0b1010 == 0b1000).</span> +<int> = <int> | <int> <span class="hljs-comment"># Or (0b1100 | 0b1010 == 0b1110).</span> +<int> = <int> ^ <int> <span class="hljs-comment"># Xor (0b1100 ^ 0b1010 == 0b0110).</span> +<int> = <int> << n_bits <span class="hljs-comment"># Left shift. Use >> for right.</span> +<int> = ~<int> <span class="hljs-comment"># Not. Also -<int> - 1.</span> </code></pre></div> <div><h2 id="combinatorics"><a href="#combinatorics" name="combinatorics">#</a>Combinatorics</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> itertools <span class="hljs-keyword">as</span> it </code></pre></div> -<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>list(it.product([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>], repeat=<span class="hljs-number">3</span>)) -[(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>), - (<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>)] +<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>list(it.product(<span class="hljs-string">'abc'</span>, repeat=<span class="hljs-number">2</span>)) <span class="hljs-comment"># a b c</span> +[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># a x x x</span> + (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># b x x x</span> + (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'c'</span>)] <span class="hljs-comment"># c x x x</span> </code></pre> -<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>list(it.product(<span class="hljs-string">'abc'</span>, <span class="hljs-string">'abc'</span>)) <span class="hljs-comment"># a b c</span> -[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># a x x x</span> - (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># b x x x</span> - (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'c'</span>)] <span class="hljs-comment"># c x x x</span> +<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>list(it.permutations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)) <span class="hljs-comment"># a b c</span> +[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># a . x x</span> + (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># b x . x</span> + (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>)] <span class="hljs-comment"># c x x .</span> </code></pre> -<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>list(it.permutations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)) <span class="hljs-comment"># a b c</span> -[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># a . x x</span> - (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># b x . x</span> - (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>)] <span class="hljs-comment"># c x x .</span> -</code></pre> -<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>list(it.combinations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)) <span class="hljs-comment"># a b c</span> -[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># a . x x</span> - (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># b . . x</span> -] <span class="hljs-comment"># c . . .</span> +<pre><code class="python language-python hljs"><span class="hljs-meta">>>> </span>list(it.combinations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)) <span class="hljs-comment"># a b c</span> +[(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># a . x x</span> + (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>), <span class="hljs-comment"># b . . x</span> +] <span class="hljs-comment"># c . . .</span> </code></pre> <div><h2 id="datetime"><a href="#datetime" name="datetime">#</a>Datetime</h2><p><strong>Provides 'date', 'time', 'datetime' and 'timedelta' classes. All are immutable and hashable.</strong></p><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install python-dateutil</span> <span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> date, time, datetime, timedelta, timezone @@ -1012,7 +1013,7 @@ P = make_dataclass(<span class="hljs-string">'P'</span>, [(<span class="hljs-str <li><strong>File objects returned by the <a href="#open">open()</a> function, etc.</strong></li> </ul><div><h3 id="callable">Callable</h3><ul> <li><strong>All functions and classes have a call() method, hence are callable.</strong></li> -<li><strong>Use <code class="python hljs"><span class="hljs-string">'callable(<obj>)'</span></code> or <code class="python hljs"><span class="hljs-string">'isinstance(<obj>, collections.abc.Callable)'</span></code> to check if object is callable.</strong></li> +<li><strong>Use <code class="python hljs"><span class="hljs-string">'callable(<obj>)'</span></code> or <code class="python hljs"><span class="hljs-string">'isinstance(<obj>, collections.abc.Callable)'</span></code> to check if object is callable. Calling an uncallable object raises <code class="python hljs"><span class="hljs-string">'TypeError'</span></code>.</strong></li> <li><strong>When this cheatsheet uses <code class="python hljs"><span class="hljs-string">'<function>'</span></code> as an argument, it means <code class="python hljs"><span class="hljs-string">'<callable>'</span></code>.</strong></li> </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span> @@ -2004,7 +2005,7 @@ print(tabulate.tabulate(rows, headers=<span class="hljs-string">'firstrow'</span <div><h2 id="consoleapp"><a href="#consoleapp" name="consoleapp">#</a>Console App</h2><div><h4 id="runsabasicfileexplorerintheconsole">Runs a basic file explorer in the console:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install windows-curses</span> <span class="hljs-keyword">import</span> curses, os -<span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER +<span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span> ch, first, selected, paths = <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>, os.listdir() @@ -2019,7 +2020,7 @@ print(tabulate.tabulate(rows, headers=<span class="hljs-string">'firstrow'</span selected += (ch == KEY_DOWN) <span class="hljs-keyword">and</span> (selected < len(paths)-<span class="hljs-number">1</span>) first -= (first > selected) first += (first < selected-(height-<span class="hljs-number">1</span>)) - <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>)]: + <span class="hljs-keyword">if</span> ch <span class="hljs-keyword">in</span> [KEY_LEFT, KEY_RIGHT, ord(<span class="hljs-string">'\n'</span>)]: new_dir = <span class="hljs-string">'..'</span> <span class="hljs-keyword">if</span> ch == KEY_LEFT <span class="hljs-keyword">else</span> paths[selected] <span class="hljs-keyword">if</span> os.path.isdir(new_dir): os.chdir(new_dir) @@ -2033,9 +2034,9 @@ print(tabulate.tabulate(rows, headers=<span class="hljs-string">'firstrow'</span <div><h2 id="guiapp"><a href="#guiapp" name="guiapp">#</a>GUI App</h2><div><h4 id="aweightconverterguiapplication">A weight converter GUI application:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install PySimpleGUI</span> <span class="hljs-keyword">import</span> PySimpleGUI <span class="hljs-keyword">as</span> sg -text_box = sg.Input(default_text=<span class="hljs-string">'100'</span>, enable_events=<span class="hljs-keyword">True</span>, key=<span class="hljs-string">'-QUANTITY-'</span>) -dropdown = sg.InputCombo([<span class="hljs-string">'g'</span>, <span class="hljs-string">'kg'</span>, <span class="hljs-string">'t'</span>], <span class="hljs-string">'kg'</span>, readonly=<span class="hljs-keyword">True</span>, enable_events=<span class="hljs-keyword">True</span>, k=<span class="hljs-string">'-UNIT-'</span>) -label = sg.Text(<span class="hljs-string">'100 kg is 220.462 lbs.'</span>, key=<span class="hljs-string">'-OUTPUT-'</span>) +text_box = sg.Input(default_text=<span class="hljs-string">'100'</span>, enable_events=<span class="hljs-keyword">True</span>, key=<span class="hljs-string">'QUANTITY'</span>) +dropdown = sg.InputCombo([<span class="hljs-string">'g'</span>, <span class="hljs-string">'kg'</span>, <span class="hljs-string">'t'</span>], <span class="hljs-string">'kg'</span>, readonly=<span class="hljs-keyword">True</span>, enable_events=<span class="hljs-keyword">True</span>, k=<span class="hljs-string">'UNIT'</span>) +label = sg.Text(<span class="hljs-string">'100 kg is 220.462 lbs.'</span>, key=<span class="hljs-string">'OUTPUT'</span>) button = sg.Button(<span class="hljs-string">'Close'</span>) window = sg.Window(<span class="hljs-string">'Weight Converter'</span>, [[text_box, dropdown], [label], [button]]) @@ -2044,13 +2045,13 @@ window = sg.Window(<span class="hljs-string">'Weight Converter'</span>, [[text <span class="hljs-keyword">if</span> event <span class="hljs-keyword">in</span> [sg.WIN_CLOSED, <span class="hljs-string">'Close'</span>]: <span class="hljs-keyword">break</span> <span class="hljs-keyword">try</span>: - quantity = float(values[<span class="hljs-string">'-QUANTITY-'</span>]) + quantity = float(values[<span class="hljs-string">'QUANTITY'</span>]) <span class="hljs-keyword">except</span> ValueError: <span class="hljs-keyword">continue</span> - unit = values[<span class="hljs-string">'-UNIT-'</span>] + unit = values[<span class="hljs-string">'UNIT'</span>] factors = {<span class="hljs-string">'g'</span>: <span class="hljs-number">0.001</span>, <span class="hljs-string">'kg'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'t'</span>: <span class="hljs-number">1000</span>} lbs = quantity * factors[unit] / <span class="hljs-number">0.45359237</span> - window[<span class="hljs-string">'-OUTPUT-'</span>].update(value=<span class="hljs-string">f'<span class="hljs-subst">{quantity}</span> <span class="hljs-subst">{unit}</span> is <span class="hljs-subst">{lbs:g}</span> lbs.'</span>) + window[<span class="hljs-string">'OUTPUT'</span>].update(value=<span class="hljs-string">f'<span class="hljs-subst">{quantity}</span> <span class="hljs-subst">{unit}</span> is <span class="hljs-subst">{lbs:g}</span> lbs.'</span>) window.close() </code></pre></div></div> @@ -2105,12 +2106,12 @@ app.run(host=<span class="hljs-keyword">None</span>, port=<span class="hljs-keyw <li><strong>Install a WSGI server like <a href="https://flask.palletsprojects.com/en/latest/deploying/waitress/">Waitress</a> and a HTTP server such as <a href="https://flask.palletsprojects.com/en/latest/deploying/nginx/">Nginx</a> for better security.</strong></li> <li><strong>Debug mode restarts the app whenever script changes and displays errors in the browser.</strong></li> </ul> -<div><h3 id="staticrequest">Static Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.route('/img/<path:filename>')</span> +<div><h3 id="servingfiles">Serving Files</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.route('/img/<path:filename>')</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">serve_file</span><span class="hljs-params">(filename)</span>:</span> <span class="hljs-keyword">return</span> fl.send_from_directory(<span class="hljs-string">'DIRNAME'</span>, filename) </code></pre></div> -<div><h3 id="dynamicrequest">Dynamic Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.route('/<sport>')</span> +<div><h3 id="servinghtml">Serving HTML</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.route('/<sport>')</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">serve_html</span><span class="hljs-params">(sport)</span>:</span> <span class="hljs-keyword">return</span> fl.render_template_string(<span class="hljs-string">'<h1>{{title}}</h1>'</span>, title=sport) </code></pre></div> @@ -2121,7 +2122,7 @@ app.run(host=<span class="hljs-keyword">None</span>, port=<span class="hljs-keyw <li><strong><code class="python hljs"><span class="hljs-string">'fl.request.args[<str>]'</span></code> returns parameter from query string (URL part right of '?').</strong></li> <li><strong><code class="python hljs"><span class="hljs-string">'fl.session[<str>] = <obj>'</span></code> stores session data. It requires secret key to be set at the startup with <code class="python hljs"><span class="hljs-string">'app.secret_key = <str>'</span></code>.</strong></li> </ul> -<div><h3 id="restrequest">REST Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.post('/<sport>/odds')</span> +<div><h3 id="servingjson">Serving JSON</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@app.post('/<sport>/odds')</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">serve_json</span><span class="hljs-params">(sport)</span>:</span> team = fl.request.form[<span class="hljs-string">'team'</span>] <span class="hljs-keyword">return</span> {<span class="hljs-string">'team'</span>: team, <span class="hljs-string">'odds'</span>: [<span class="hljs-number">2.09</span>, <span class="hljs-number">3.74</span>, <span class="hljs-number">3.68</span>]} @@ -2943,7 +2944,7 @@ $ deactivate <span class="hljs-comment"># Deactivates the active <footer> - <aside>April 17, 2025</aside> + <aside>April 22, 2025</aside> <a href="https://gto76.github.io" rel="author">Jure Šorn</a> </footer> diff --git a/parse.js b/parse.js index 7e38b93..c1e0bd1 100755 --- a/parse.js +++ b/parse.js @@ -43,10 +43,10 @@ const TOC = '</code></pre>\n'; const BIN_HEX = - '<int> = ±<span class="hljs-number">0x</span><hex> <span class="hljs-comment"># Or: ±0b<bin></span>\n' + - '<int> = int(<span class="hljs-string">\'±<hex>\'</span>, <span class="hljs-number">16</span>) <span class="hljs-comment"># Or: int(\'±<bin>\', 2)</span>\n' + - '<int> = int(<span class="hljs-string">\'±0x<hex>\'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int(\'±0b<bin>\', 0)</span>\n' + - '<str> = hex(<int>) <span class="hljs-comment"># Returns \'[-]0x<hex>\'. Also bin().</span>\n'; + '<int> = ±<span class="hljs-number">0x</span><hex> <span class="hljs-comment"># Or: ±0b<bin></span>\n' + + '<int> = int(<span class="hljs-string">\'±<hex>\'</span>, <span class="hljs-number">16</span>) <span class="hljs-comment"># Or: int(\'±<bin>\', 2)</span>\n' + + '<int> = int(<span class="hljs-string">\'±0x<hex>\'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int(\'±0b<bin>\', 0)</span>\n' + + '<str> = hex(<int>) <span class="hljs-comment"># Returns \'[-]0x<hex>\'. Also bin().</span>\n'; const CACHE = '<span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> cache\n' + @@ -175,7 +175,7 @@ const COROUTINES = const CURSES = '<span class="hljs-comment"># $ pip3 install windows-curses</span>\n' + '<span class="hljs-keyword">import</span> curses, os\n' + - '<span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER\n' + + '<span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT\n' + '\n' + '<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span>\n' + ' 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' + @@ -190,7 +190,7 @@ const CURSES = ' selected += (ch == KEY_DOWN) <span class="hljs-keyword">and</span> (selected < len(paths)-<span class="hljs-number">1</span>)\n' + ' first -= (first > selected)\n' + ' first += (first < selected-(height-<span class="hljs-number">1</span>))\n' + - ' <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' + + ' <span class="hljs-keyword">if</span> ch <span class="hljs-keyword">in</span> [KEY_LEFT, KEY_RIGHT, ord(<span class="hljs-string">\'\\n\'</span>)]:\n' + ' 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' + ' <span class="hljs-keyword">if</span> os.path.isdir(new_dir):\n' + ' os.chdir(new_dir)\n' + diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html index a4a44cc..9cb299e 100644 --- a/pdf/index_for_pdf.html +++ b/pdf/index_for_pdf.html @@ -73,7 +73,7 @@ <strong>iterator, <a href="#enumerate">3</a>-<a href="#generator">4</a>, <a href="#comprehensions">11</a>, <a href="#iterator-1">17</a></strong><br> <strong>itertools module, <a href="#itertools">3</a>, <a href="#combinatorics">8</a></strong> </p> <h3 id="j">J</h3> -<p><strong>json, <a href="#json">25</a>, <a href="#restrequest">36</a>, <a href="#fileformats">46</a></strong> </p> +<p><strong>json, <a href="#json">25</a>, <a href="#servingjson">36</a>, <a href="#fileformats">46</a></strong> </p> <h3 id="l">L</h3> <p><strong>lambda, <a href="#lambda">11</a></strong><br> <strong>lists, <a href="#list">1</a>-<a href="#list">2</a>, <a href="#abstractbaseclasses">4</a>, <a href="#otheruses">10</a>-<a href="#comprehensions">11</a>, <a href="#sequence">18</a>-<a href="#abcsequence">19</a>, <a href="#collectionsandtheirexceptions">21</a></strong><br> @@ -135,7 +135,7 @@ <strong>sys module, <a href="#cache">13</a>, <a href="#exit">21</a>-<a href="#commandlinearguments">22</a></strong> </p> <h3 id="t">T</h3> <p><strong>table, <a href="#csv">26</a>, <a href="#example-1">27</a>, <a href="#table">34</a>, <a href="#numpy">37</a>-<a href="#indexing">38</a>, <a href="#dataframe">45</a>-<a href="#dataframeaggregatetransformmap">46</a></strong><br> -<strong>template, <a href="#format">6</a>, <a href="#dynamicrequest">36</a></strong><br> +<strong>template, <a href="#format">6</a>, <a href="#servinghtml">36</a></strong><br> <strong>threading module, <a href="#threading">32</a>, <a href="#startstheappinitsownthreadandqueriesitsrestapi">36</a></strong><br> <strong>time module, <a href="#progressbar">34</a>, <a href="#profiling">36</a></strong><br> <strong>tuples, <a href="#tuple">3</a>, <a href="#abstractbaseclasses">4</a>, <a href="#otheruses">10</a>-<a href="#comprehensions">11</a>, <a href="#sequence">18</a>-<a href="#abcsequence">19</a></strong><br>