From ddfd08a10c651449a66484f4cc3dc7ba641cdef7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 08:47:06 +0100 Subject: [PATCH 0001/2188] Argparse and corrections --- README.md | 258 +++++++++++++++++++++++++++++++++--------------------- 1 file changed, 160 insertions(+), 98 deletions(-) diff --git a/README.md b/README.md index 90631bac9..5a0879503 100644 --- a/README.md +++ b/README.md @@ -101,12 +101,12 @@ Set ``` ```python - = .union() # Or: | - = .intersection() # Or: & - = .difference() # Or: - - = .symmetric_difference() # Or: ^ - = .issubset() # Or: < - = .issuperset() # Or: > + = .union() # Or: | + = .intersection() # Or: & + = .difference() # Or: - + = .symmetric_difference() # Or: ^ + = .issubset() # Or: <= + = .issuperset() # Or: >= ``` ### Frozenset @@ -158,6 +158,11 @@ Point(x=1, y=2) Iterator -------- +```python + = iter() + = iter(, to_exclusive) +``` + #### Skips first element: ```python next() @@ -184,10 +189,10 @@ Generator **Convenient way to implement the iterator protocol.** ```python -def step(start, step): +def step(start, step_size): while True: yield start - start += step + start += step_size ``` ```python @@ -205,8 +210,11 @@ Type ```python from numbers import Number, Integral, Real, Rational, Complex -is_number = isinstance(, Number) -is_function = callable() + = isinstance(, Number) +``` + +```python + = callable() ``` @@ -219,7 +227,7 @@ String ```python = .split() # Splits on any whitespace character. - = .split(sep=None, maxsplit=-1) # Splits on 'sep' at most 'maxsplit' times. + = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. = .join() # Joins elements using string as separator. ``` @@ -265,12 +273,12 @@ Regex ----- ```python import re - = re.sub(, new, text, count=0) # Substitutes all occurrences. - = re.findall(, text) - = re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches. - = re.search(, text) # Searches for first occurrence of pattern. - = re.match(, text) # Searches only at the beginning of the text. - = re.finditer(, text) # Searches for all occurrences of pattern. + = re.sub(, new, text, count=0) # Substitutes all occurrences. + = re.findall(, text) # Returns all occurrences. + = re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches. + = re.search(, text) # Searches for first occurrence of pattern. + = re.match(, text) # Searches only at the beginning of the text. + = re.finditer(, text) # Searches for all occurrences of pattern. ``` * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** @@ -323,7 +331,7 @@ Format ### String Options **"!r" uses object's repr() method, instead of format(), to get a string:** ```python -{'abcde'!r} # "'abcde'" +{'abcde'!r:<10} # "'abcde' " ``` ```python @@ -338,11 +346,11 @@ Format ``` ```python -{123456:10,} # ' 123,456' -{123456:10_} # ' 123_456' -{123456:+10} # ' +123456' +{ 123456:10,} # ' 123,456' +{ 123456:10_} # ' 123_456' +{ 123456:+10} # ' +123456' {-123456:=10} # '- 123456' -{123456: } # ' 123456' +{ 123456: } # ' 123456' {-123456: } # '-123456' ``` @@ -368,9 +376,9 @@ Numbers ------- ### Basic Functions ```python -pow(x, y) # Or: x ** y -abs() -round( [, ndigits]) + = pow(, ) # Or: ** + = abs() + = round( [, ndigits]) ``` ### Constants @@ -386,9 +394,7 @@ from math import cos, acos, sin, asin, tan, atan, degrees, radians ### Logarithm ```python from math import log, log10, log2 -log(x [, base]) # Base e, if not specified. -log10(x) # Base 10. -log2(x) # Base 2. + = log( [, base]) # Base e, if not specified. ``` ### Infinity, nan @@ -426,6 +432,7 @@ now.strftime('%Y%m%d%H%M%S') # '20180315002834' Arguments --------- **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.** + ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} @@ -473,7 +480,7 @@ lambda , : ### Comprehension ```python = [i+1 for i in range(10)] # [1, 2, ..., 10] - = {i for i in range(10) if i > 5} # {6, 7, ..., 9} + = {i for i in range(10) if i > 5} # {6, 7, 8, 9} = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} = (i+5 for i in range(10)) # (5, 6, ..., 14) ``` @@ -500,7 +507,8 @@ from functools import reduce ### Any, All ```python - = any(el[1] for el in ) + = any() # False if empty. + = all(el[1] for el in ) # True if empty. ``` ### If - Else @@ -587,10 +595,11 @@ Class class : def __init__(self, a): self.a = a + def __repr__(self): + class_name = type(self).__name__ + return f'{class_name}({self.a:!r})' def __str__(self): return str(self.a) - def __repr__(self): - return str({'a': self.a}) # Or: return f'{self.__dict__}' @classmethod def get_class_name(cls): @@ -640,11 +649,11 @@ class (Enum): ``` ```python - = . - = [''] - = () - = .name - = .value + = . + = [''] + = () +name = .name +value = .value ``` ```python @@ -725,6 +734,8 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ``` ### Input +**Reads a line from user input or pipe if present. The trailing newline gets stripped.** + ```python filename = input('Enter a file name: ') ``` @@ -740,9 +751,10 @@ while True: ### Recursion Limit ```python +>>> import sys >>> sys.getrecursionlimit() 1000 ->>> sys.setrecursionlimit(10000) +>>> sys.setrecursionlimit(5000) ``` JSON @@ -783,6 +795,8 @@ SQLite ```python import sqlite3 db = sqlite3.connect() +... +db.close() ``` ### Read @@ -791,7 +805,6 @@ cursor = db.execute() if cursor: = cursor.fetchone() # First row. = cursor.fetchall() # Remaining rows. -db.close() ``` ### Write @@ -845,21 +858,27 @@ KeyboardInterrupt Bytes ----- -**Bytes objects are immutable sequences of single bytes.** +**Bytes object is immutable sequence of single bytes. Mutable version is called bytearray. ** + +```python + = [] + = [] + = b''.join() +``` ### Encode ```python - = b'' - = .encode(encoding='utf-8') - = .to_bytes(, byteorder='big|little', signed=False) - = bytes.fromhex() + = b'' + = .encode(encoding='utf-8') + = .to_bytes(, byteorder='big|little', signed=False) + = bytes.fromhex() ``` ### Decode ```python - = .decode('utf-8') - = int.from_bytes(, byteorder='big|little', signed=False) - = .hex() + = .decode('utf-8') + = int.from_bytes(, byteorder='big|little', signed=False) + = .hex() ``` ### Read Bytes from File @@ -871,50 +890,53 @@ def read_bytes(filename): ### Write Bytes to File ```python -def write_bytes(filename, bytes): +def write_bytes(filename, bytes_obj): with open(filename, 'wb') as file: - file.write(bytes) -``` - -```python - = b''.join() + file.write(bytes_obj) ``` Struct ------ -**This module performs conversions between Python values and C struct represented as Python Bytes object.** +**This module performs conversions between Python values and C struct represented as Python bytes object. By default machine’s native sizes and byte order are used.** + ```python -from struct import pack, unpack - = pack('', [, , ...]) - = unpack('', ) +from struct import pack, unpack, calcsize + = pack('', [, , ...]) + = unpack('', ) ``` ### Example ```python ->>> pack('hhl', 1, 2, 3) +>>> pack('>hhl', 1, 2, 3) b'\x00\x01\x00\x02\x00\x00\x00\x03' ->>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') +>>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) ->>> calcsize('hhl') +>>> calcsize('>hhl') 8 ``` ### Format -**Use capital leters for unsigned type.** +**For standard sizes start format string with:** +* `'='` - native byte order +* `'<'` - little-endian +* `'>'` - big-endian + +**Use capital leter for unsigned type. Standard size in brackets.** * `'x'` - pad byte -* `'c'` - char -* `'h'` - short -* `'i'` - int -* `'l'` - long -* `'q'` - long long -* `'f'` - float -* `'d'` - double +* `'c'` - char (1) +* `'h'` - short (2) +* `'i'` - int (4) +* `'l'` - long (4) +* `'q'` - long long (8) +* `'f'` - float (4) +* `'d'` - double (8) Hashlib ------- ```python +>>> import hashlib >>> hashlib.md5(.encode()).hexdigest() '33d0eba106da4d3ebca17fcd3f4c3d77' ``` @@ -936,7 +958,7 @@ thread.join() ### Lock ```python -lock = Rlock() +lock = RLock() lock.acquire() ... lock.release() @@ -945,7 +967,7 @@ lock.release() Itertools --------- -**Every function returns an iterator and can accept any collection and/or iterator. If you want to print the iterator, you need to pass it to the list() function.** +**Every function returns an iterator and can accept any collection and/or iterator. If you want to print the iterator, you need to pass it to the list() function!** ```python from itertools import * @@ -1022,9 +1044,9 @@ Introspection and Metaprograming ### Variables ```python - = dir() # In-scope variables. - = locals() # Local variables. - = globals() # Global variables. + = dir() # Names of in-scope variables. + = locals() # Dict of local variables, same as vars(). + = globals() # Dict of global variables. ``` ### Attributes @@ -1050,11 +1072,11 @@ False ``` ### Parameters -#### Getting the number of parameters of a function: ```python from inspect import signature sig = signature() no_of_params = len(sig.parameters) +param_names = list(sig.parameters.keys()) ``` ### Type @@ -1072,7 +1094,7 @@ type(, , ) #### Class that creates class. ```python def my_meta_class(name, parents, attrs): - attrs['a'] = 1 + attrs['a'] = 'abcde' return type(name, parents, attrs) ``` @@ -1080,7 +1102,7 @@ def my_meta_class(name, parents, attrs): ```python class MyMetaClass(type): def __new__(klass, name, parents, attrs): - attrs['a'] = 1 + attrs['a'] = 'abcde' return type.__new__(klass, name, parents, attrs) ``` @@ -1089,7 +1111,7 @@ class MyMetaClass(type): ```python class MyClass(metaclass=MyMetaClass): def __init__(self): - self.b = 2 + self.b = 12345 ``` @@ -1121,7 +1143,7 @@ Eval 3 >>> literal_eval('[1, 2, 3]') [1, 2, 3] ->>> ast.literal_eval('abs(-1)') +>>> ast.literal_eval('abs(1)') ValueError: malformed node or string ``` @@ -1218,6 +1240,45 @@ reader(adder(printer())) # 100, 101, ..., 109 Libraries ========= +Argparse +-------- +```python +import argparse +parser = argparse.ArgumentParser(description='calculate X to the power of Y') +group = parser.add_mutually_exclusive_group() +group.add_argument('-v', '--verbose', action='store_true') +group.add_argument('-q', '--quiet', action='store_true') +parser.add_argument('x', type=int, help='the base') +parser.add_argument('y', type=int, help='the exponent') +args = parser.parse_args() +answer = args.x ** args.y + +if args.quiet: + print(answer) +elif args.verbose: + print('{args.x} to the power {args.y} equals {answer}') +else: + print('{args.x}^{args.y} == {answer}') +``` + +#### Usage: +```bash +$ python3 prog.py --help +usage: test2.py [-h] [-v | -q] x y + +calculate X to the power of Y + +positional arguments: + x the base + y the exponent + +optional arguments: + -h, --help show this help message and exit + -v, --verbose + -q, --quiet +``` + + Plot ---- ```python @@ -1235,10 +1296,10 @@ Progress Bar # $ pip3 install tqdm from tqdm import tqdm from time import sleep -for i in tqdm(range(100)): - sleep(0.02) for i in tqdm([1, 2, 3]): sleep(0.2) +for i in tqdm(range(100)): + sleep(0.02) ``` @@ -1348,7 +1409,7 @@ Scraping >>> document = BeautifulSoup(page.text, 'html.parser') >>> table = document.find('table', class_='infobox vevent') >>> rows = table.find_all('tr') ->>> website = rows[11].find('a')['href'] +>>> link = rows[11].find('a')['href'] 'https://www.python.org/' >>> latest_v = rows[6].find('div').text.split()[0] '3.7.2' @@ -1396,7 +1457,7 @@ def odds_handler(sport): home_odds, away_odds = get_odds(db, sport, team) db.close() - response.headers['Content-Type'] = 'application/json' + response.headers['Content-Type'] = 'application/json' response.headers['Cache-Control'] = 'no-cache' return json.dumps([home_odds, away_odds]) ``` @@ -1456,6 +1517,7 @@ with PyCallGraph(output=graph): NumPy ----- **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.** + ```python # $ pip3 install numpy import numpy as np @@ -1463,7 +1525,7 @@ import numpy as np ```python = np.array() - = np.arange(from_inclusive, to_exclusive, step) + = np.arange(from_inclusive, to_exclusive, step_size) = np.ones() = np.random.randint(from_inclusive, to_exclusive, ) ``` @@ -1501,27 +1563,27 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- **For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1]`.** ```python >>> points = np.array([0.1, 0.6, 0.8]) -array([ 0.1, 0.6, 0.8]) +[ 0.1, 0.6, 0.8] >>> wrapped_points = points.reshape(3, 1) -array([[ 0.1], - [ 0.6], - [ 0.8]]) +[[ 0.1], + [ 0.6], + [ 0.8]] >>> distances = wrapped_points - points -array([[ 0. , -0.5, -0.7], - [ 0.5, 0. , -0.2], - [ 0.7, 0.2, 0. ]]) +[[ 0. , -0.5, -0.7], + [ 0.5, 0. , -0.2], + [ 0.7, 0.2, 0. ]] >>> distances = np.abs(distances) -array([[ 0. , 0.5, 0.7], - [ 0.5, 0. , 0.2], - [ 0.7, 0.2, 0. ]]) +[[ 0. , 0.5, 0.7], + [ 0.5, 0. , 0.2], + [ 0.7, 0.2, 0. ]] >>> i = np.arange(3) -array([0, 1, 2]) +[0, 1, 2] >>> distances[i, i] = np.inf -array([[ inf, 0.5, 0.7], - [ 0.5, inf, 0.2], - [ 0.7, 0.2, inf]]) +[[ inf, 0.5, 0.7], + [ 0.5, inf, 0.2], + [ 0.7, 0.2, inf]] >>> distances.argmin(1) -array([1, 2, 1]) +[1, 2, 1] ``` From 7d91e7ca07bff3aa32126eff2961f5df92017d91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:02:23 +0100 Subject: [PATCH 0002/2188] Map --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5a0879503..10d4f0284 100644 --- a/README.md +++ b/README.md @@ -500,9 +500,9 @@ for i in range(10): ### Map, Filter, Reduce ```python from functools import reduce - = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) - = filter(lambda x: x > 5, range(10)) # (6, 7, ..., 9) - = reduce(lambda out, x: out + x, range(10)) # 45 + = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) + = filter(lambda x: x > 5, range(10)) # (6, 7, ..., 9) + = reduce(lambda out, x: out + x, range(10)) # 45 ``` ### Any, All From 137c23053e8f9412c520a4e6a1117ca4f4b24ac2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:03:36 +0100 Subject: [PATCH 0003/2188] Map --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 10d4f0284..cf8cad52b 100644 --- a/README.md +++ b/README.md @@ -501,7 +501,7 @@ for i in range(10): ```python from functools import reduce = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) - = filter(lambda x: x > 5, range(10)) # (6, 7, ..., 9) + = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) = reduce(lambda out, x: out + x, range(10)) # 45 ``` From 101405be065a818a2418588da19e7d18490bec5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:08:41 +0100 Subject: [PATCH 0004/2188] Print --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cf8cad52b..38b252e6b 100644 --- a/README.md +++ b/README.md @@ -255,7 +255,9 @@ String (97, 122) ``` -### Print + +Print +----- ```python print( [, , end='', sep='', file=]) # Use 'file=sys.stderr' for errors. ``` From fb6c9b38a8bd832274a0ac51eaad66900d7211b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:11:37 +0100 Subject: [PATCH 0005/2188] Print --- README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 38b252e6b..7d63008a8 100644 --- a/README.md +++ b/README.md @@ -218,6 +218,21 @@ from numbers import Number, Integral, Real, Rational, Complex ``` +Print +----- +```python +print( [, , end='', sep='', file=]) # Use 'file=sys.stderr' for errors. +``` + +```python +>>> from pprint import pprint +>>> pprint(locals()) +{'__doc__': None, + '__name__': '__main__', + '__package__': None, ...} +``` + + String ------ ```python @@ -256,21 +271,6 @@ String ``` -Print ------ -```python -print( [, , end='', sep='', file=]) # Use 'file=sys.stderr' for errors. -``` - -```python ->>> from pprint import pprint ->>> pprint(locals()) -{'__doc__': None, - '__name__': '__main__', - '__package__': None, ...} -``` - - Regex ----- ```python From e8ce55ed8c9bf5edefdbbbd93217984770dd8320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:14:22 +0100 Subject: [PATCH 0006/2188] Print --- README.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 7d63008a8..a6c8f29a9 100644 --- a/README.md +++ b/README.md @@ -218,21 +218,6 @@ from numbers import Number, Integral, Real, Rational, Complex ``` -Print ------ -```python -print( [, , end='', sep='', file=]) # Use 'file=sys.stderr' for errors. -``` - -```python ->>> from pprint import pprint ->>> pprint(locals()) -{'__doc__': None, - '__name__': '__main__', - '__package__': None, ...} -``` - - String ------ ```python @@ -305,6 +290,21 @@ import re ``` +Print +----- +```python +print( [, , end='', sep='', file=]) # Use 'file=sys.stderr' for errors. +``` + +```python +>>> from pprint import pprint +>>> pprint(locals()) +{'__doc__': None, + '__name__': '__main__', + '__package__': None, ...} +``` + + Format ------ ```python From ebb750f9fd016a50cf2f04892c6f851c48134c32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:17:52 +0100 Subject: [PATCH 0007/2188] Print --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a6c8f29a9..235fdcbf4 100644 --- a/README.md +++ b/README.md @@ -292,8 +292,10 @@ import re Print ----- +**Use `file=sys.stderr` for errors.** + ```python -print( [, , end='', sep='', file=]) # Use 'file=sys.stderr' for errors. +print( [, , end='', sep='', file=]) ``` ```python From a3600d23a9849133e08236af3cff88a9e51a13a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:22:32 +0100 Subject: [PATCH 0008/2188] Numbers --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 235fdcbf4..8e6988e9b 100644 --- a/README.md +++ b/README.md @@ -380,7 +380,7 @@ Numbers ------- ### Basic Functions ```python - = pow(, ) # Or: ** + = pow(, ) # Or: ** = abs() = round( [, ndigits]) ``` From d0d69f02cd9180862c0723bec0a0009a3ff9d837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:30:01 +0100 Subject: [PATCH 0009/2188] Bytes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e6988e9b..0516fd3dc 100644 --- a/README.md +++ b/README.md @@ -862,7 +862,7 @@ KeyboardInterrupt Bytes ----- -**Bytes object is immutable sequence of single bytes. Mutable version is called bytearray. ** +**Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.** ```python = [] From c296d6ae7ca37fe848d8678febc10c636eb32947 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:35:25 +0100 Subject: [PATCH 0010/2188] Argparse --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0516fd3dc..52d51baca 100644 --- a/README.md +++ b/README.md @@ -874,7 +874,7 @@ Bytes ```python = b'' = .encode(encoding='utf-8') - = .to_bytes(, byteorder='big|little', signed=False) + = .to_bytes(length, byteorder='big|little', signed=False) = bytes.fromhex() ``` @@ -1260,9 +1260,9 @@ answer = args.x ** args.y if args.quiet: print(answer) elif args.verbose: - print('{args.x} to the power {args.y} equals {answer}') + print(f'{args.x} to the power {args.y} equals {answer}') else: - print('{args.x}^{args.y} == {answer}') + print(f'{args.x}^{args.y} == {answer}') ``` #### Usage: From 7449d9d1b2bb49d23aa1c7159548ae88b57b76e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 09:40:34 +0100 Subject: [PATCH 0011/2188] Argparse --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 52d51baca..6caf78135 100644 --- a/README.md +++ b/README.md @@ -1266,7 +1266,7 @@ else: ``` #### Usage: -```bash +``` $ python3 prog.py --help usage: test2.py [-h] [-v | -q] x y From d16bc314b67c78104929894abc0642a54f9960f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:10:34 +0100 Subject: [PATCH 0012/2188] Dict --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6caf78135..008f9c73f 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ value = .setdefault(key, default) # Same, but also adds default to di ``` ```python -value = .pop(key) # Removes item from dictionary. +value = .pop(key) # Removes item from dictionary. {k: v for k, v in .items() if k in keys} # Filters dictionary by keys. ``` @@ -221,8 +221,8 @@ from numbers import Number, Integral, Real, Rational, Complex String ------ ```python - = .strip() # Strips all whitespace characters. - = .strip('') # Strips all passed characters. + = .strip() # Strips all whitespace characters. + = .strip('') # Strips all passed characters. ``` ```python From 2ba3d626a1906a289b939a441af1917c2fa90520 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:13:36 +0100 Subject: [PATCH 0013/2188] Format --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 008f9c73f..877a18c99 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ value = .setdefault(key, default) # Same, but also adds default to di ``` ```python -value = .pop(key) # Removes item from dictionary. +value = .pop(key) # Removes item from dictionary. {k: v for k, v in .items() if k in keys} # Filters dictionary by keys. ``` @@ -325,11 +325,11 @@ Format ### General Options ```python -{:<10} # ' ' -{:>10} # ' ' -{:^10} # ' ' -{:->10} # '------' -{:>0} # '' +{:<10} # ' ' +{:>10} # ' ' +{:^10} # ' ' +{:->10} # '------' +{:>0} # '' ``` ### String Options From e452f0f8087f6759c8a7de7b4319b2e9fd53db0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:15:58 +0100 Subject: [PATCH 0014/2188] Inline --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 877a18c99..c0e9187a3 100644 --- a/README.md +++ b/README.md @@ -528,15 +528,15 @@ from functools import reduce ### Namedtuple, Enum, Class ```python from collections import namedtuple -Point = namedtuple('Point', 'x y') +Point = namedtuple('Point', 'x y') from enum import Enum Direction = Enum('Direction', 'n e s w') Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) # Warning: Objects will share the objects that are initialized in the dictionary! -Creature = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n}) -creature = Creature() +Creature = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n}) +creature = Creature() ``` From c9677f13aebfec3a9aceb320bfec101788e47f78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:19:00 +0100 Subject: [PATCH 0015/2188] Inline --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c0e9187a3..0298b5a57 100644 --- a/README.md +++ b/README.md @@ -529,6 +529,7 @@ from functools import reduce ```python from collections import namedtuple Point = namedtuple('Point', 'x y') +point = Point(0, 0) from enum import Enum Direction = Enum('Direction', 'n e s w') From 33450d983526419a68ceb005f081bda1a454b8b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:20:47 +0100 Subject: [PATCH 0016/2188] Inline --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 0298b5a57..8507bef4a 100644 --- a/README.md +++ b/README.md @@ -530,11 +530,15 @@ from functools import reduce from collections import namedtuple Point = namedtuple('Point', 'x y') point = Point(0, 0) +``` +```python from enum import Enum Direction = Enum('Direction', 'n e s w') Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) +``` +```python # Warning: Objects will share the objects that are initialized in the dictionary! Creature = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n}) creature = Creature() From eebcad8e6853dea36e23ff27f7740ccb7c51634f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:33:16 +0100 Subject: [PATCH 0017/2188] Class --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8507bef4a..0433867e6 100644 --- a/README.md +++ b/README.md @@ -606,7 +606,7 @@ class : self.a = a def __repr__(self): class_name = type(self).__name__ - return f'{class_name}({self.a:!r})' + return f'{class_name}({self.a!r})' def __str__(self): return str(self.a) From a524c022c056198fb8245a658397f83b9c334005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:52:31 +0100 Subject: [PATCH 0018/2188] Enum --- README.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0433867e6..e398f96b2 100644 --- a/README.md +++ b/README.md @@ -677,14 +677,13 @@ random_member = random.choice(list()) Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon']) Cutlery = Enum('Cutlery', 'knife fork spoon') Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) +``` -# Functions can not be values, so they must be enclosed in tuple: -LogicOp = Enum('LogicOp', {'AND': (lambda l, r: l and r, ), - 'OR' : (lambda l, r: l or r, )}) - -# But 'list()' will only work if there is another value in the tuple: -LogicOp = Enum('LogicOp', {'AND': (auto(), lambda l, r: l and r), - 'OR' : (auto(), lambda l, r: l or r)}) +```python +# Functions can not be values, unless they are wrapped: +from functools import partial +LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), + 'OR' : partial(lambda l, r: l or r)}) ``` From 778e408a83635bed3626c3fabd2aec46c809e7db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 10:58:25 +0100 Subject: [PATCH 0019/2188] Enum --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e398f96b2..33cf522cf 100644 --- a/README.md +++ b/README.md @@ -679,11 +679,11 @@ Cutlery = Enum('Cutlery', 'knife fork spoon') Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) ``` +**Functions can not be values, unless they are wrapped.** ```python -# Functions can not be values, unless they are wrapped: from functools import partial -LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), - 'OR' : partial(lambda l, r: l or r)}) +LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r), + 'or' : partial(lambda l, r: l or r)}) ``` @@ -1137,8 +1137,7 @@ import operator as op product_of_elems = functools.reduce(op.mul, ) sorted_by_second = sorted(, key=op.itemgetter(1)) sorted_by_both = sorted(, key=op.itemgetter(1, 0)) -LogicOp = enum.Enum('LogicOp', {'AND': op.and_, - 'OR' : op.or_}) +LogicOp = enum.Enum('LogicOp', {'and': op.and_, 'or' : op.or_}) ``` From 668fdbd9a42d7574f3cca731abed86a6f5137587 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 11:01:45 +0100 Subject: [PATCH 0020/2188] Bytes --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 33cf522cf..c4e626b1b 100644 --- a/README.md +++ b/README.md @@ -884,9 +884,9 @@ Bytes ### Decode ```python - = .decode('utf-8') - = int.from_bytes(, byteorder='big|little', signed=False) - = .hex() + = .decode('utf-8') + = int.from_bytes(, byteorder='big|little', signed=False) + = .hex() ``` ### Read Bytes from File From 72edaacbac931828264b14e1579122c05e34c2a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 11:03:26 +0100 Subject: [PATCH 0021/2188] Bytes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c4e626b1b..56052c51c 100644 --- a/README.md +++ b/README.md @@ -869,6 +869,7 @@ Bytes **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.** ```python + = b'' = [] = [] = b''.join() @@ -876,7 +877,6 @@ Bytes ### Encode ```python - = b'' = .encode(encoding='utf-8') = .to_bytes(length, byteorder='big|little', signed=False) = bytes.fromhex() From 077aeb186427bb807e31851e382e97f4b1a7c280 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 11:07:50 +0100 Subject: [PATCH 0022/2188] Struct --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 56052c51c..405c51f07 100644 --- a/README.md +++ b/README.md @@ -906,7 +906,7 @@ def write_bytes(filename, bytes_obj): Struct ------ -**This module performs conversions between Python values and C struct represented as Python bytes object. By default machine’s native sizes and byte order are used.** +**This module performs conversions between Python values and C struct represented as Python bytes object. Machine’s native type sizes and byte order are used by default.** ```python from struct import pack, unpack, calcsize From 00f41cb474afbf7663d48886e96c9b9a2d00982a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 11:16:07 +0100 Subject: [PATCH 0023/2188] Introspection --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 405c51f07..4458c6cec 100644 --- a/README.md +++ b/README.md @@ -1053,7 +1053,7 @@ Introspection and Metaprograming ### Variables ```python = dir() # Names of in-scope variables. - = locals() # Dict of local variables, same as vars(). + = locals() # Dict of local variables. Also vars(). = globals() # Dict of global variables. ``` From 33683bdbdbfdaa7654ed15bab019d51c00a8e8f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 16:29:22 +0100 Subject: [PATCH 0024/2188] Counter --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4458c6cec..22df7de19 100644 --- a/README.md +++ b/README.md @@ -83,9 +83,9 @@ value = .pop(key) # Removes item from dictionary. ```python >>> from collections import Counter >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] ->>> Counter(colors) +>>> counter = Counter(colors) Counter({'blue': 3, 'red': 2, 'yellow': 1}) ->>> .most_common()[0][0] +>>> counter.most_common()[0][0] 'blue' ``` @@ -134,7 +134,7 @@ to_exclusive = .stop Enumerate --------- ```python -for i, in enumerate( [, i_start]): +for i, element in enumerate( [, i_start]): ... ``` From e435597d806b7e791b0aef82bb6b11b14d8d877a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 16:34:56 +0100 Subject: [PATCH 0025/2188] Enumerate --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 22df7de19..5ec7c8e6d 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ to_exclusive = .stop Enumerate --------- ```python -for i, element in enumerate( [, i_start]): +for i, el in enumerate( [, i_start]): ... ``` From 3422cb51f9698919b90a97ab6436cce3fbedac81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 16:59:08 +0100 Subject: [PATCH 0026/2188] Small titles --- README.md | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 5ec7c8e6d..e05fb4aca 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Set ``` ### Frozenset -#### Is hashable and can be used as a key in dictionary. +**Is hashable and can be used as a key in dictionary.** ```python = frozenset() ``` @@ -333,7 +333,7 @@ Format ``` ### String Options -**"!r" uses object's repr() method, instead of format(), to get a string:** +**"!r" calls object's repr() method, instead of format(), to get a string.** ```python {'abcde'!r:<10} # "'abcde' " ``` @@ -679,7 +679,7 @@ Cutlery = Enum('Cutlery', 'knife fork spoon') Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) ``` -**Functions can not be values, unless they are wrapped.** +#### Functions can not be values, so they must be wrapped: ```python from functools import partial LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r), @@ -925,7 +925,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' ``` ### Format -**For standard sizes start format string with:** +#### For standard sizes start format string with: * `'='` - native byte order * `'<'` - little-endian * `'>'` - big-endian @@ -1088,7 +1088,8 @@ param_names = list(sig.parameters.keys()) ``` ### Type -**Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!):** +**Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!).** + ```python type(, , ) ``` @@ -1099,7 +1100,8 @@ type(, , ) ``` ### Meta Class -#### Class that creates class. +**Class that creates class.** + ```python def my_meta_class(name, parents, attrs): attrs['a'] = 'abcde' @@ -1116,6 +1118,7 @@ class MyMetaClass(type): ### Metaclass Attribute **When class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type.** + ```python class MyClass(metaclass=MyMetaClass): def __init__(self): @@ -1508,7 +1511,8 @@ Line # Hits Time Per Hit % Time Line Contents ``` ### Call Graph -#### Generates a PNG image of call graph with highlighted bottlenecks. +**Generates a PNG image of call graph with highlighted bottlenecks.** + ```python # $ pip3 install pycallgraph from pycallgraph import output, PyCallGraph @@ -1554,20 +1558,24 @@ index = .argmin([axis]) left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3) ``` + **1. If array shapes differ, left-pad the smaller shape with ones.** ```python left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- ! ``` + **2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements.** ```python left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- ! right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- ! ``` + **3. If neither non-matching dimension has size 1, rise an error.** ### Example **For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1]`.** + ```python >>> points = np.array([0.1, 0.6, 0.8]) [ 0.1, 0.6, 0.8] From b45ec000e97e0330ba74c80a0bc61136f5ff67f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Jan 2019 17:03:33 +0100 Subject: [PATCH 0027/2188] Small titles --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e05fb4aca..c7f177492 100644 --- a/README.md +++ b/README.md @@ -1511,7 +1511,7 @@ Line # Hits Time Per Hit % Time Line Contents ``` ### Call Graph -**Generates a PNG image of call graph with highlighted bottlenecks.** +#### Generates a PNG image of call graph with highlighted bottlenecks: ```python # $ pip3 install pycallgraph @@ -1553,28 +1553,28 @@ index = .argmin([axis]) ``` ### Broadcasting -**Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions:** +**Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.** ```python left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3) ``` -**1. If array shapes differ, left-pad the smaller shape with ones.** +#### 1. If array shapes differ, left-pad the smaller shape with ones: ```python left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- ! ``` -**2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements.** +#### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements: ```python left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- ! right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- ! ``` -**3. If neither non-matching dimension has size 1, rise an error.** +#### 3. If neither non-matching dimension has size 1, rise an error. ### Example -**For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1]`.** +#### For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1]` ```python >>> points = np.array([0.1, 0.6, 0.8]) From ac95fff0e53452385541b139905fc2f41879d05e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 03:00:33 +0100 Subject: [PATCH 0028/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c7f177492..b2cc2a186 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Set ``` ### Frozenset -**Is hashable and can be used as a key in dictionary.** +####Is hashable and can be used as a key in dictionary. ```python = frozenset() ``` From be3fcdf4496d0487d71ddeddf7ac331ef257a4e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 03:02:05 +0100 Subject: [PATCH 0029/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b2cc2a186..96c797685 100644 --- a/README.md +++ b/README.md @@ -292,7 +292,7 @@ import re Print ----- -**Use `file=sys.stderr` for errors.** +####Use `file=sys.stderr` for errors. ```python print( [, , end='', sep='', file=]) From 9fa6e2e9d78e003d55585f0a8b2e0ad0dfc51359 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 03:05:25 +0100 Subject: [PATCH 0030/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 96c797685..c38a551ee 100644 --- a/README.md +++ b/README.md @@ -292,7 +292,7 @@ import re Print ----- -####Use `file=sys.stderr` for errors. +**Use `'file=sys.stderr'` for errors.** ```python print( [, , end='', sep='', file=]) From e7bb3fbf89283e93b8c5c30a81ec270560744318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 03:33:10 +0100 Subject: [PATCH 0031/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c38a551ee..0c91de668 100644 --- a/README.md +++ b/README.md @@ -333,7 +333,7 @@ Format ``` ### String Options -**"!r" calls object's repr() method, instead of format(), to get a string.** +**`'!r'` calls object's repr() method, instead of format(), to get a string.** ```python {'abcde'!r:<10} # "'abcde' " ``` From 916bf00e2dbd90a03c03a7c10aed105ce6592c60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 03:37:36 +0100 Subject: [PATCH 0032/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0c91de668..a52ebb9a9 100644 --- a/README.md +++ b/README.md @@ -435,7 +435,7 @@ now.strftime('%Y%m%d%H%M%S') # '20180315002834' Arguments --------- -**"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.** +**`'*'` is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.** ```python args = (1, 2) From ad6ed9f618b21502e79ab6d94bf9fe6c6efdafa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 03:38:14 +0100 Subject: [PATCH 0033/2188] Small titles --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a52ebb9a9..8bac4a5b5 100644 --- a/README.md +++ b/README.md @@ -426,9 +426,9 @@ Datetime ```python from datetime import datetime, strptime now = datetime.now() -now.month # 3 -now.strftime('%Y%m%d') # '20180315' -now.strftime('%Y%m%d%H%M%S') # '20180315002834' +now.month # 3 +now.strftime('%Y%m%d') # '20180315' +now.strftime('%Y%m%d%H%M%S') # '20180315002834' = strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M') ``` From 94c1df091c96bcd67136f2bc87b5e4b7280e073d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:07:13 +0100 Subject: [PATCH 0034/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8bac4a5b5..4d6469b74 100644 --- a/README.md +++ b/README.md @@ -683,7 +683,7 @@ Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) ```python from functools import partial LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r), - 'or' : partial(lambda l, r: l or r)}) + 'or' : partial(lambda l, r: l or r )}) ``` From c7a0decd5fd066e6313205249d0152d79e36d54c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:08:37 +0100 Subject: [PATCH 0035/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4d6469b74..8bac4a5b5 100644 --- a/README.md +++ b/README.md @@ -683,7 +683,7 @@ Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) ```python from functools import partial LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r), - 'or' : partial(lambda l, r: l or r )}) + 'or' : partial(lambda l, r: l or r)}) ``` From ab931f5034e48b3f6bbcf20d5e831e0efcfe4092 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:09:44 +0100 Subject: [PATCH 0036/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8bac4a5b5..bb99e80bb 100644 --- a/README.md +++ b/README.md @@ -742,7 +742,7 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ``` ### Input -**Reads a line from user input or pipe if present. The trailing newline gets stripped.** +#### Reads a line from user input or pipe if present. The trailing newline gets stripped: ```python filename = input('Enter a file name: ') From 919fb63745bd29cf172a753cf2277d051dd53fda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:10:53 +0100 Subject: [PATCH 0037/2188] Small titles --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bb99e80bb..3a3ad44b5 100644 --- a/README.md +++ b/README.md @@ -930,7 +930,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * `'<'` - little-endian * `'>'` - big-endian -**Use capital leter for unsigned type. Standard size in brackets.** +#### Use capital leter for unsigned type. Standard size in brackets: * `'x'` - pad byte * `'c'` - char (1) * `'h'` - short (2) From b1ece6c3321ed5df3c2a4535e8c340c86adcd60d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:15:46 +0100 Subject: [PATCH 0038/2188] Islice --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3a3ad44b5..10775547c 100644 --- a/README.md +++ b/README.md @@ -1027,7 +1027,8 @@ from itertools import * >>> compress('abc', [True, 0, 1]) ['a', 'c'] ->>> islice([1, 2, 3], 1, None) # islice(, from_inclusive, to_exclusive) +>>> # islice(, from_inclusive, to_exclusive) +>>> islice([1, 2, 3], 1, None) [2, 3] >>> people = [{'id': 1, 'name': 'Bob'}, From f9b1d3a5c7f11b0c8276e84e19909282ad5e966c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:17:50 +0100 Subject: [PATCH 0039/2188] Islice --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 10775547c..981f0ffc6 100644 --- a/README.md +++ b/README.md @@ -1027,7 +1027,7 @@ from itertools import * >>> compress('abc', [True, 0, 1]) ['a', 'c'] ->>> # islice(, from_inclusive, to_exclusive) +>>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3], 1, None) [2, 3] From a51bf3cd0eb4c57c7d0ae17a9487604b4b5ca9a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:23:44 +0100 Subject: [PATCH 0040/2188] Url --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 981f0ffc6..d8f8fc941 100644 --- a/README.md +++ b/README.md @@ -742,7 +742,7 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ``` ### Input -#### Reads a line from user input or pipe if present. The trailing newline gets stripped: +**Reads a line from user input or pipe if present. The trailing newline gets stripped.** ```python filename = input('Enter a file name: ') @@ -1393,7 +1393,7 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ``` ### Encode -```python +``` >>> quote("Can't be in URL!") 'Can%27t%20be%20in%20URL%21' >>> quote_plus("Can't be in URL!") @@ -1401,7 +1401,7 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ``` ### Decode -```python +``` >>> unquote('Can%27t+be+in+URL%21') "Can't+be+in+URL!"' >>> unquote_plus('Can%27t+be+in+URL%21') From 50f259a00928dcb99bafcfa4c0af622b7cad0784 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:25:11 +0100 Subject: [PATCH 0041/2188] Url --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d8f8fc941..ce673f09e 100644 --- a/README.md +++ b/README.md @@ -1393,7 +1393,7 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ``` ### Encode -``` +```text >>> quote("Can't be in URL!") 'Can%27t%20be%20in%20URL%21' >>> quote_plus("Can't be in URL!") @@ -1401,7 +1401,7 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ``` ### Decode -``` +```text >>> unquote('Can%27t+be+in+URL%21') "Can't+be+in+URL!"' >>> unquote_plus('Can%27t+be+in+URL%21') From a6e04a859d910c5eba3a6d53ecefb38254404fdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:26:10 +0100 Subject: [PATCH 0042/2188] Url --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ce673f09e..611772289 100644 --- a/README.md +++ b/README.md @@ -1403,7 +1403,7 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ### Decode ```text >>> unquote('Can%27t+be+in+URL%21') -"Can't+be+in+URL!"' +"Can't+be+in+URL!" >>> unquote_plus('Can%27t+be+in+URL%21') "Can't be in URL!" ``` From 573bd26ae530227023b6a4600f2bfa20227da63a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:29:04 +0100 Subject: [PATCH 0043/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 611772289..86836f8bb 100644 --- a/README.md +++ b/README.md @@ -1575,7 +1575,7 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- #### 3. If neither non-matching dimension has size 1, rise an error. ### Example -#### For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1]` +#### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`): ```python >>> points = np.array([0.1, 0.6, 0.8]) From 658e088ac00f5963ab37e6a83c3496fd049f7c66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:29:53 +0100 Subject: [PATCH 0044/2188] Argparse --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 86836f8bb..f6b07b296 100644 --- a/README.md +++ b/README.md @@ -1273,7 +1273,7 @@ else: ``` #### Usage: -``` +```text $ python3 prog.py --help usage: test2.py [-h] [-v | -q] x y @@ -1393,7 +1393,7 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ``` ### Encode -```text +```python >>> quote("Can't be in URL!") 'Can%27t%20be%20in%20URL%21' >>> quote_plus("Can't be in URL!") @@ -1401,7 +1401,7 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ``` ### Decode -```text +```python >>> unquote('Can%27t+be+in+URL%21') "Can't+be+in+URL!" >>> unquote_plus('Can%27t+be+in+URL%21') From 61df912dd9bc3d258acea3989ce0bb51e8874300 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:32:23 +0100 Subject: [PATCH 0045/2188] Line profiler --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f6b07b296..4f577e550 100644 --- a/README.md +++ b/README.md @@ -1501,7 +1501,7 @@ def main(): main() ``` -``` +```text $ kernprof -lv test.py Line # Hits Time Per Hit % Time Line Contents ============================================================== From 44735ffc6e649402d25d6340941c2910b00349fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:35:30 +0100 Subject: [PATCH 0046/2188] Line profiler --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4f577e550..18ee2b1da 100644 --- a/README.md +++ b/README.md @@ -1501,6 +1501,7 @@ def main(): main() ``` +#### Usage: ```text $ kernprof -lv test.py Line # Hits Time Per Hit % Time Line Contents From d672e2f787685384e8ccb72da4db2bdf9015a316 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:37:35 +0100 Subject: [PATCH 0047/2188] Argparse --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 18ee2b1da..06c8552fc 100644 --- a/README.md +++ b/README.md @@ -1574,6 +1574,7 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- ``` #### 3. If neither non-matching dimension has size 1, rise an error. +
### Example #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`): From e0781c82ded0a5dcf482db5d33ee5e7359dfb523 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:38:30 +0100 Subject: [PATCH 0048/2188] Argparse --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 06c8552fc..bf4ec5f18 100644 --- a/README.md +++ b/README.md @@ -1272,7 +1272,7 @@ else: print(f'{args.x}^{args.y} == {answer}') ``` -#### Usage: +### Usage ```text $ python3 prog.py --help usage: test2.py [-h] [-v | -q] x y From 94e780e05fa5c17ae84ba823f1b0cfa3e61e01f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 04:50:26 +0100 Subject: [PATCH 0049/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf4ec5f18..25c663bb7 100644 --- a/README.md +++ b/README.md @@ -1574,7 +1574,7 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- ``` #### 3. If neither non-matching dimension has size 1, rise an error. -
+ ### Example #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`): From 2c1b57e4974d5ece91dedc143fff6a038daf02b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 08:56:23 +0100 Subject: [PATCH 0050/2188] Sequence and numpy --- README.md | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 25c663bb7..b1d96e64a 100644 --- a/README.md +++ b/README.md @@ -635,6 +635,20 @@ class Employee(Person): self.staff_num = staff_num ``` +### Sequence +```python +class : + def __init__(self, seq): + self.seq = seq + def __len__(self): + return len(self.seq) + def __getitem__(self, i): + return self.seq[i] + def __iter__(self): + for el in self.seq: + yield el +``` + ### Copy ```python from copy import copy, deepcopy @@ -1321,7 +1335,7 @@ Table # $ pip3 install tabulate from csv import reader from tabulate import tabulate -with open(, newline='') as csv_file: +with open(, encoding='utf-8', newline='') as csv_file: reader = reader(csv_file, delimiter=';') headers = [a.title() for a in next(reader)] print(tabulate(reader, headers)) @@ -1544,14 +1558,16 @@ import numpy as np ``` ```python -value = .min([axis]) -index = .argmin([axis]) +first_column = [:, 0] # Or: [..., 0] +value = .min([axis]) +index = .argmin([axis]) ``` ```python - = .reshape() - = np.broadcast_to(, ) - = [filter_expression] +.shape = + = .reshape() + = np.broadcast_to(, ) + = [filter_expression] ``` ### Broadcasting From 3ac3f19323039f1fe1b97bedc6f8b6405e676834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 10:00:29 +0100 Subject: [PATCH 0051/2188] Array and deque --- README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/README.md b/README.md index b1d96e64a..368f284f0 100644 --- a/README.md +++ b/README.md @@ -955,6 +955,30 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * `'d'` - double (8) +Array +----- +**List that can only hold elements of predefined type. Available types are listed above.** + +```python +from array import array + = array( [, ]) +``` + + +Deque +----- +**Short for “double-ended queue” and pronounced “deck”. They are thread-safe lists with efficient appends and pops from either side.** + +```python +from collections import deque + = deque(, maxlen=None) +.appendleft() +.extendleft() # Collection gets reversed. + = .popleft() +.rotate(n=1) # Rotates elements to the right. +``` + + Hashlib ------- ```python From bb72b01c044cf522383a3e6bcc1fba92d7157057 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 10:03:54 +0100 Subject: [PATCH 0052/2188] Deque --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 368f284f0..0a7d5fa93 100644 --- a/README.md +++ b/README.md @@ -971,6 +971,9 @@ Deque ```python from collections import deque +``` + +```python = deque(, maxlen=None) .appendleft() .extendleft() # Collection gets reversed. From 6c9828a50088f8d338463b21926114df8078f974 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 10:04:28 +0100 Subject: [PATCH 0053/2188] Deque --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a7d5fa93..c496494a7 100644 --- a/README.md +++ b/README.md @@ -971,10 +971,10 @@ Deque ```python from collections import deque + = deque(, maxlen=None) ``` ```python - = deque(, maxlen=None) .appendleft() .extendleft() # Collection gets reversed. = .popleft() From 7faf16db85e50997de5df8e4590bdf9674c96a00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 10:27:26 +0100 Subject: [PATCH 0054/2188] Profile --- README.md | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index c496494a7..29e1abbf2 100644 --- a/README.md +++ b/README.md @@ -982,15 +982,6 @@ from collections import deque ``` -Hashlib -------- -```python ->>> import hashlib ->>> hashlib.md5(.encode()).hexdigest() -'33d0eba106da4d3ebca17fcd3f4c3d77' -``` - - Threading --------- ```python @@ -1014,6 +1005,15 @@ lock.release() ``` +Hashlib +------- +```python +>>> import hashlib +>>> hashlib.md5(.encode()).hexdigest() +'33d0eba106da4d3ebca17fcd3f4c3d77' +``` + + Itertools --------- **Every function returns an iterator and can accept any collection and/or iterator. If you want to print the iterator, you need to pass it to the list() function!** @@ -1520,11 +1520,19 @@ Profile ### Basic ```python from time import time -start_time = time() +start_time = time() # Seconds since Epoch. ... duration = time() - start_time ``` +### High Performance +```python +from time import perf_counter as pc +start_time = pc() # Seconds since restart. +... +duration = pc() - start_time +``` + ### Timing a Snippet ```python from timeit import timeit From a6dac8da6bb8f75f9767e6809129deb0a2a019ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 10:31:11 +0100 Subject: [PATCH 0055/2188] Frozenset --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 29e1abbf2..d2f30c67a 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Set ``` ### Frozenset -####Is hashable and can be used as a key in dictionary. +#### Is hashable and can be used as a key in dictionary. ```python = frozenset() ``` From 4ca2751f55de3144d420596cfefdebc61d2f7e6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 10:52:28 +0100 Subject: [PATCH 0056/2188] Comparable --- README.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index d2f30c67a..7652150d9 100644 --- a/README.md +++ b/README.md @@ -635,9 +635,23 @@ class Employee(Person): self.staff_num = staff_num ``` +### Comparable +```python +class MyComparable: + def __init__(self, a): + self.a = a + def __eq__(self, other): + # If not defined it returns id(self) == id(other). + if isinstance(other, MyComparable): + return self.a == other.a + return False + def __hash__(self): + return hash(self.a) +``` + ### Sequence ```python -class : +class MySequence: def __init__(self, seq): self.seq = seq def __len__(self): From b6999702b4001b036df7741cb5fd043c66fe6612 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 10:56:27 +0100 Subject: [PATCH 0057/2188] Sequence --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7652150d9..7762f9f7b 100644 --- a/README.md +++ b/README.md @@ -652,14 +652,14 @@ class MyComparable: ### Sequence ```python class MySequence: - def __init__(self, seq): - self.seq = seq + def __init__(self, a): + self.a = a def __len__(self): - return len(self.seq) + return len(self.a) def __getitem__(self, i): - return self.seq[i] + return self.a[i] def __iter__(self): - for el in self.seq: + for el in self.a: yield el ``` From 45bc384702074bd8fbfba2a41d46d60e018ed00f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 11:52:36 +0100 Subject: [PATCH 0058/2188] Hashable --- README.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7762f9f7b..5eede28c4 100644 --- a/README.md +++ b/README.md @@ -636,13 +636,30 @@ class Employee(Person): ``` ### Comparable +**If eq() method is not overriden, it returns `id(self) == id(other)`, which is the same as `self is other`, meaning all objects compare not equal by default.** + ```python class MyComparable: def __init__(self, a): self.a = a def __eq__(self, other): - # If not defined it returns id(self) == id(other). - if isinstance(other, MyComparable): + if isinstance(other, type(self)): + return self.a == other.a + return False +``` + +### Hashable +**Hashable object needs both hash() and eq() methods and it's hash value should not change. Objects that compare equal must have the same hash value, meaning default hash() that returns `id(self)` will not do. That is why Python automatically makes classes unhashable if you only implement eq().** + +```python +class MyHashable: + def __init__(self, a): + self.__a = a + @property + def a(self): + return self.__a + def __eq__(self, other): + if isinstance(other, type(self)): return self.a == other.a return False def __hash__(self): From 7b02b5bbf6efcc2f681b1a3669748abab95ee17e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 12:03:34 +0100 Subject: [PATCH 0059/2188] Hashable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5eede28c4..54eaa019b 100644 --- a/README.md +++ b/README.md @@ -649,7 +649,7 @@ class MyComparable: ``` ### Hashable -**Hashable object needs both hash() and eq() methods and it's hash value should not change. Objects that compare equal must have the same hash value, meaning default hash() that returns `id(self)` will not do. That is why Python automatically makes classes unhashable if you only implement eq().** +**Hashable object needs both hash() and eq() methods and it's hash value should never change. Objects that compare equal must have the same hash value, meaning default hash() that returns `id(self)` will not do. That is why Python automatically makes classes unhashable if you only implement eq().** ```python class MyHashable: From 5727449615091c2afbe9d078bccf56249f132019 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 12:07:02 +0100 Subject: [PATCH 0060/2188] Hashable --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 54eaa019b..e9a07acd1 100644 --- a/README.md +++ b/README.md @@ -636,7 +636,7 @@ class Employee(Person): ``` ### Comparable -**If eq() method is not overriden, it returns `id(self) == id(other)`, which is the same as `self is other`, meaning all objects compare not equal by default.** +**If eq() method is not overriden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`, meaning all objects compare not equal by default.** ```python class MyComparable: @@ -649,7 +649,7 @@ class MyComparable: ``` ### Hashable -**Hashable object needs both hash() and eq() methods and it's hash value should never change. Objects that compare equal must have the same hash value, meaning default hash() that returns `id(self)` will not do. That is why Python automatically makes classes unhashable if you only implement eq().** +**Hashable object needs both hash() and eq() methods and it's hash value should never change. Objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do. That is why Python automatically makes classes unhashable if you only implement eq().** ```python class MyHashable: From 2b9488d75b728cff9dd9e387cf334d4e49d81b05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 12:15:00 +0100 Subject: [PATCH 0061/2188] Hashable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9a07acd1..a78872965 100644 --- a/README.md +++ b/README.md @@ -636,7 +636,7 @@ class Employee(Person): ``` ### Comparable -**If eq() method is not overriden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`, meaning all objects compare not equal by default.** +**If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`, meaning all objects compare not equal by default.** ```python class MyComparable: From 490a763af78d5f413bc99ade75a4c8034c8c2abb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 12:20:50 +0100 Subject: [PATCH 0062/2188] Deque --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a78872965..125884768 100644 --- a/README.md +++ b/README.md @@ -998,7 +998,7 @@ from array import array Deque ----- -**Short for “double-ended queue” and pronounced “deck”. They are thread-safe lists with efficient appends and pops from either side.** +**Short for “double-ended queue” and pronounced “deck”. It is a thread-safe list with efficient appends and pops from either side.** ```python from collections import deque From b021c1213f09a82f7b80ffef33ed61a6b14a4712 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 12:44:51 +0100 Subject: [PATCH 0063/2188] Hashable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 125884768..a7eb5ae22 100644 --- a/README.md +++ b/README.md @@ -654,7 +654,7 @@ class MyComparable: ```python class MyHashable: def __init__(self, a): - self.__a = a + self.__a = copy.deepcopy(a) @property def a(self): return self.__a From 43f252bb6537dad505cb06126bf07f9462360d44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 13:41:10 +0100 Subject: [PATCH 0064/2188] Web --- README.md | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index a7eb5ae22..aed2873c8 100644 --- a/README.md +++ b/README.md @@ -1503,14 +1503,14 @@ Web --- ```python # $ pip3 install bottle -import bottle -from urllib.parse import unquote +from bottle import run, route, post, template, request, response +import json ``` ### Run ```python -bottle.run(host='localhost', port=8080) -bottle.run(host='0.0.0.0', port=80, server='cherrypy') +run(host='localhost', port=8080) +run(host='0.0.0.0', port=80, server='cherrypy') ``` ### Static Request @@ -1524,27 +1524,29 @@ def send_image(image): ```python @route('/') def send_page(sport): - sport = unquote(sport).lower() - page = read_file(sport) - return template(page) + return template('

{{title}}

', title=sport) ``` ### REST Request ```python @post('/odds/') def odds_handler(sport): - team = bottle.request.forms.get('team') - team = unquote(team).lower() - - db = sqlite3.connect() - home_odds, away_odds = get_odds(db, sport, team) - db.close() - + team = request.forms.get('team') + home_odds, away_odds = 2.44, 3.29 response.headers['Content-Type'] = 'application/json' response.headers['Cache-Control'] = 'no-cache' return json.dumps([home_odds, away_odds]) ``` +#### Test: +```python +# $ pip3 install requests +>>> import requests +>>> r = requests.post('http://localhost:8080/odds/soccer', data={'team': 'arsenal'}) +>>> r.json() +[2.44, 3.29] +``` + Profile ------- From 79b54d83c80f863c5dca8b45c640e6d925602118 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 13:49:22 +0100 Subject: [PATCH 0065/2188] Web --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index aed2873c8..ac12927b4 100644 --- a/README.md +++ b/README.md @@ -1535,16 +1535,16 @@ def odds_handler(sport): home_odds, away_odds = 2.44, 3.29 response.headers['Content-Type'] = 'application/json' response.headers['Cache-Control'] = 'no-cache' - return json.dumps([home_odds, away_odds]) + return json.dumps([team, home_odds, away_odds]) ``` #### Test: ```python # $ pip3 install requests >>> import requests ->>> r = requests.post('http://localhost:8080/odds/soccer', data={'team': 'arsenal'}) +>>> r = requests.post('http://localhost:8080/odds/soccer', data={'team': 'arsenal f.c.'}) >>> r.json() -[2.44, 3.29] +['arsenal f.c.', 2.44, 3.29] ``` From d1ad8f5b4e3054b61a7a6ae920eed529c337ecdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 13:55:26 +0100 Subject: [PATCH 0066/2188] Web --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ac12927b4..d7c4daf0c 100644 --- a/README.md +++ b/README.md @@ -1542,7 +1542,8 @@ def odds_handler(sport): ```python # $ pip3 install requests >>> import requests ->>> r = requests.post('http://localhost:8080/odds/soccer', data={'team': 'arsenal f.c.'}) +>>> url = 'http://localhost:8080/odds/soccer' +>>> r = requests.post(url, data={'team': 'arsenal f.c.'}) >>> r.json() ['arsenal f.c.', 2.44, 3.29] ``` From 8f57a77582d6072b64ef7beccb34b2fac31e3613 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 14:02:29 +0100 Subject: [PATCH 0067/2188] Set --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index d7c4daf0c..bcb504ec6 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,11 @@ Set |= ``` +```python +.remove() # Throws error. +.discard() # Doesn't throw error. +``` + ```python = .union() # Or: | = .intersection() # Or: & From c06742340b0a175e8945fa569cc54b0c21d42629 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 14:03:33 +0100 Subject: [PATCH 0068/2188] Set --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index bcb504ec6..b22b5937f 100644 --- a/README.md +++ b/README.md @@ -100,11 +100,6 @@ Set |= ``` -```python -.remove() # Throws error. -.discard() # Doesn't throw error. -``` - ```python = .union() # Or: | = .intersection() # Or: & @@ -114,6 +109,11 @@ Set = .issuperset() # Or: >= ``` +```python +.remove() # Throws error. +.discard() # Doesn't throw error. +``` + ### Frozenset #### Is hashable and can be used as a key in dictionary. ```python From 6eec781bfa7ddc59e13dd4ecc75b3245e2d0ec44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 14:24:55 +0100 Subject: [PATCH 0069/2188] Operator --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b22b5937f..4819b43d9 100644 --- a/README.md +++ b/README.md @@ -1210,7 +1210,7 @@ Operator from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ eq, ne, lt, le, gt, ge, \ not_, and_, or_, \ - itemgetter + itemgetter, attrgetter, methodcaller ``` ```python @@ -1219,6 +1219,7 @@ product_of_elems = functools.reduce(op.mul, ) sorted_by_second = sorted(, key=op.itemgetter(1)) sorted_by_both = sorted(, key=op.itemgetter(1, 0)) LogicOp = enum.Enum('LogicOp', {'and': op.and_, 'or' : op.or_}) +last_el = op.methodcaller('pop')() ``` From a1e04821d1d2cf7c01a42f8a8037b01ad4d7ca78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 15:52:23 +0100 Subject: [PATCH 0070/2188] Nonlocal --- README.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/README.md b/README.md index 4819b43d9..121b98675 100644 --- a/README.md +++ b/README.md @@ -577,6 +577,25 @@ from functools import partial 30 ``` +### Nonlocal +**If variable is assigned to anywhere in the scope, it is regarded as local variable, unless it is declared as global or nonlocal.** + +```python +def get_counter(): + a = 0 + def out(): + nonlocal a + a += 1 + return a + return out +``` + +```python +>>> counter = get_counter() +>>> counter(), counter(), counter() +(0, 1, 2) +``` + Decorator --------- From d3753e6ccaa8f7e659bfb64c4e1f779e618a08ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 16:05:41 +0100 Subject: [PATCH 0071/2188] Callable --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 121b98675..8c46ddb8a 100644 --- a/README.md +++ b/README.md @@ -704,6 +704,15 @@ class MySequence: yield el ``` +### Callable +```python +class MyCallable: + def __init__(self, a): + self.a = a + def __call__(self): + return a +``` + ### Copy ```python from copy import copy, deepcopy From b56e70e3e7fe7cdbe824b1ecffa396569b45d779 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 16:08:06 +0100 Subject: [PATCH 0072/2188] Closure --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8c46ddb8a..19956d827 100644 --- a/README.md +++ b/README.md @@ -577,7 +577,7 @@ from functools import partial 30 ``` -### Nonlocal +### Nonlocal Variables **If variable is assigned to anywhere in the scope, it is regarded as local variable, unless it is declared as global or nonlocal.** ```python From 967c8d48cc361590d67f8124fc5d3ca63cb56452 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 16:08:51 +0100 Subject: [PATCH 0073/2188] Closure --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 19956d827..8c46ddb8a 100644 --- a/README.md +++ b/README.md @@ -577,7 +577,7 @@ from functools import partial 30 ``` -### Nonlocal Variables +### Nonlocal **If variable is assigned to anywhere in the scope, it is regarded as local variable, unless it is declared as global or nonlocal.** ```python From c8f2cde9be0909cca9b166eedaea005efd2ac3c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 16:11:02 +0100 Subject: [PATCH 0074/2188] Nonlocal --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8c46ddb8a..7b7ac2da7 100644 --- a/README.md +++ b/README.md @@ -582,7 +582,7 @@ from functools import partial ```python def get_counter(): - a = 0 + a = 1 def out(): nonlocal a a += 1 @@ -593,7 +593,7 @@ def get_counter(): ```python >>> counter = get_counter() >>> counter(), counter(), counter() -(0, 1, 2) +(1, 2, 3) ``` From c47eb5ad3f63a7d6599f8244f3aa761dadb00881 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 16:30:38 +0100 Subject: [PATCH 0075/2188] LRU cache --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.md b/README.md index 7b7ac2da7..64847ad4a 100644 --- a/README.md +++ b/README.md @@ -621,6 +621,22 @@ def add(x, y): return x + y ``` +### LRU Cache +**Decorator that caches functions return values.** +```python +@lru_cache(maxsize=None) +def fib(n): + if n < 2: + return n + return fib(n-1) + fib(n-2) +``` + +```python +>>> [fib(n) for n in range(16)] +[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] +>>> fib.cache_info() +CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) +``` Class ----- From ce2675a21b87b5d5217817bf898235fef6c10a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 16:40:42 +0100 Subject: [PATCH 0076/2188] Decorator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 64847ad4a..230b1edf3 100644 --- a/README.md +++ b/README.md @@ -622,7 +622,7 @@ def add(x, y): ``` ### LRU Cache -**Decorator that caches functions return values.** +**Decorator that caches function's return values.** ```python @lru_cache(maxsize=None) def fib(n): From 0def444901f0cbf1380b798e7a1d18db680d1839 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 16:46:03 +0100 Subject: [PATCH 0077/2188] Decorator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 230b1edf3..9501e6175 100644 --- a/README.md +++ b/README.md @@ -622,7 +622,7 @@ def add(x, y): ``` ### LRU Cache -**Decorator that caches function's return values.** +**Decorator that caches function's return values. All arguments must be hashable.** ```python @lru_cache(maxsize=None) def fib(n): From 418d6d2a3de7b6bc0ab8aae2725b4b8ec2d7abf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 17:12:02 +0100 Subject: [PATCH 0078/2188] Numpy --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9501e6175..b7c3131a3 100644 --- a/README.md +++ b/README.md @@ -1676,16 +1676,16 @@ import numpy as np = np.random.randint(from_inclusive, to_exclusive, ) ``` -```python -first_column = [:, 0] # Or: [..., 0] -value = .min([axis]) -index = .argmin([axis]) -``` - ```python .shape = = .reshape() = np.broadcast_to(, ) +``` + +```python + = [:,0] # First column. + = .sum([]) # Axis is an index of dimension that gets collapsed. + = .argmin([]) # Returns index/es of smallest elements. = [filter_expression] ``` From f20b2fc01faf54ad8a00bad19a9c3e37e806d0c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 17:16:00 +0100 Subject: [PATCH 0079/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b7c3131a3..d62b3c724 100644 --- a/README.md +++ b/README.md @@ -1684,7 +1684,7 @@ import numpy as np ```python = [:,0] # First column. - = .sum([]) # Axis is an index of dimension that gets collapsed. + = .sum([]) # Axis is an index of dimension that gets collapsed. = .argmin([]) # Returns index/es of smallest elements. = [filter_expression] ``` From a3b1516b083c7a85eaaa25dd1f83b3e2c017148a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 17:18:07 +0100 Subject: [PATCH 0080/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d62b3c724..8bf961977 100644 --- a/README.md +++ b/README.md @@ -1712,7 +1712,7 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- ### Example -#### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`): +#### For each point returns index of its nearest point (`'[0.1, 0.6, 0.8] => [1, 2, 1]'`): ```python >>> points = np.array([0.1, 0.6, 0.8]) From 3f37b83475783905b6e42a2d6208ec99486354a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 17:18:53 +0100 Subject: [PATCH 0081/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8bf961977..d62b3c724 100644 --- a/README.md +++ b/README.md @@ -1712,7 +1712,7 @@ right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- ### Example -#### For each point returns index of its nearest point (`'[0.1, 0.6, 0.8] => [1, 2, 1]'`): +#### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`): ```python >>> points = np.array([0.1, 0.6, 0.8]) From 067b665ea9cc42880197ea8eb8a7a8e7e4ea35ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 17:34:49 +0100 Subject: [PATCH 0082/2188] Class --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index d62b3c724..f77aa5e6b 100644 --- a/README.md +++ b/README.md @@ -582,7 +582,7 @@ from functools import partial ```python def get_counter(): - a = 1 + a = 0 def out(): nonlocal a a += 1 @@ -722,11 +722,12 @@ class MySequence: ### Callable ```python -class MyCallable: - def __init__(self, a): - self.a = a +class Counter: + def __init__(self): + self.a = 0 def __call__(self): - return a + self.a += 1 + return self.a ``` ### Copy From 1cbb59be337920156c9d00d4c9b56be0c4d881fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 17:45:39 +0100 Subject: [PATCH 0083/2188] Metaclass --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f77aa5e6b..6b4d8289a 100644 --- a/README.md +++ b/README.md @@ -1234,9 +1234,9 @@ def my_meta_class(name, parents, attrs): #### Or: ```python class MyMetaClass(type): - def __new__(klass, name, parents, attrs): + def __new__(cls, name, parents, attrs): attrs['a'] = 'abcde' - return type.__new__(klass, name, parents, attrs) + return type.__new__(cls, name, parents, attrs) ``` ### Metaclass Attribute From a59ca7fbd42c2a0c0746e51f917b8e50c93f1978 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 19:22:18 +0100 Subject: [PATCH 0084/2188] Lru --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 6b4d8289a..eafb872e6 100644 --- a/README.md +++ b/README.md @@ -624,6 +624,8 @@ def add(x, y): ### LRU Cache **Decorator that caches function's return values. All arguments must be hashable.** ```python +from functools import lru_cache + @lru_cache(maxsize=None) def fib(n): if n < 2: From 583c614e6bad41a188bce215aa52af302d7e4ea4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 19:28:29 +0100 Subject: [PATCH 0085/2188] Fib --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index eafb872e6..44e7c7840 100644 --- a/README.md +++ b/README.md @@ -628,9 +628,7 @@ from functools import lru_cache @lru_cache(maxsize=None) def fib(n): - if n < 2: - return n - return fib(n-1) + fib(n-2) + return n if n < 2 else fib(n-1) + fib(n-2) ``` ```python From 201f9aa8034d10eb96c2b492bb5e861d80cd8f09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 19:33:57 +0100 Subject: [PATCH 0086/2188] Introspection --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 44e7c7840..93ee1f0d9 100644 --- a/README.md +++ b/README.md @@ -1182,14 +1182,15 @@ Introspection and Metaprograming ### Attributes ```python ->>> class Z: -... def __init__(self): -... self.a = 'abcde' -... self.b = 12345 ->>> z = Z() +class Z: + def __init__(self): + self.a = 'abcde' + self.b = 12345 ``` ```python +>>> z = Z() + >>> vars(z) {'a': 'abcde', 'b': 12345} From 922f6c0d33c26ba98a40e0c75c8c74188687f9b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 20:27:51 +0100 Subject: [PATCH 0087/2188] Decorator --- README.md | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 93ee1f0d9..1182031fb 100644 --- a/README.md +++ b/README.md @@ -605,12 +605,12 @@ def function_that_gets_passed_to_closure(): ... ``` -#### Debugger example: +### Debugger Example ```python from functools import wraps def debug(func): - @wraps(func) # Needed for metadata copying (func name, ...). + @wraps(func) # Copies func's metadata like name and doc to out. def out(*args, **kwargs): print(func.__name__) return func(*args, **kwargs) @@ -638,6 +638,24 @@ def fib(n): CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ``` +### Parametrized Decorator +```python +def debug(print_result=False): + def inner_decorator(func): + @wraps(func) + def out(*args, **kwargs): + result = func(*args, **kwargs) + print(func.__name__, result if print_result else '') + return result + return out + return inner_decorator + +@debug(print_result=True) +def add(x, y): + return x + y +``` + + Class ----- ```python From bd4bcdc8d309fec9c0af62c039bc15c49d151344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 20:40:58 +0100 Subject: [PATCH 0088/2188] Decorator --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1182031fb..c093bb51b 100644 --- a/README.md +++ b/README.md @@ -599,9 +599,11 @@ def get_counter(): Decorator --------- +**A decorator takes a function, adds some functionality and returns it.** + ```python -@closure_name -def function_that_gets_passed_to_closure(): +@decorator_name +def function_that_gets_passed_to_decorator(): ... ``` @@ -638,17 +640,17 @@ def fib(n): CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ``` -### Parametrized Decorator +### Parametrized Example ```python def debug(print_result=False): - def inner_decorator(func): + def decorator(func): @wraps(func) def out(*args, **kwargs): result = func(*args, **kwargs) print(func.__name__, result if print_result else '') return result return out - return inner_decorator + return decorator @debug(print_result=True) def add(x, y): From a1787f382ebf839b6bbc966223177313e122d9bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 20:45:49 +0100 Subject: [PATCH 0089/2188] Decorator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c093bb51b..e1db848bb 100644 --- a/README.md +++ b/README.md @@ -640,7 +640,7 @@ def fib(n): CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ``` -### Parametrized Example +### Parametrized Debugger ```python def debug(print_result=False): def decorator(func): From 8c2f1c24563146e0dba6d2b0f05c2680932a5237 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 28 Jan 2019 20:50:07 +0100 Subject: [PATCH 0090/2188] Decorator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e1db848bb..8b5b90cb5 100644 --- a/README.md +++ b/README.md @@ -640,7 +640,7 @@ def fib(n): CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ``` -### Parametrized Debugger +### Parametrized Decorator ```python def debug(print_result=False): def decorator(func): From 6598945923c311223da02fdf8a81c7c540aeca88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 15:47:51 +0100 Subject: [PATCH 0091/2188] Numpy --- README.md | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 8b5b90cb5..2c4f65985 100644 --- a/README.md +++ b/README.md @@ -1705,12 +1705,36 @@ import numpy as np ``` ```python - = [:,0] # First column. - = .sum([]) # Axis is an index of dimension that gets collapsed. - = .argmin([]) # Returns index/es of smallest elements. - = [filter_expression] + = .sum([]) # Axis is an index of dimension that gets collapsed. + = .argmin([]) # Returns index/es of smallest element/s. ``` +### Indexing +#### Basic indexing +```python + = <2d_array>[0, 0] +``` + +#### Basic slicing +```python +<1d_view> = <2d_array>[0] # First row. +<1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. +<3d_view> = <2d_array>[None,:,:] # Expanded by dimension of size 1. +``` + +#### Integer array indexing +**If row and column indexes differ in shape, they are combined with broadcasting.** +```python +<1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] +<2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] +``` + +#### Boolean array indexing +```python +<2d_bool_array> = <2d_array> > 0 +<1d_array> = <2d_array>[<2d_bool_array>] +`` + ### Broadcasting **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.** ```python From 94fa9d0e286c1212f3ac07883219d1855ce4f1f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 15:53:04 +0100 Subject: [PATCH 0092/2188] Decorator --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 2c4f65985..a0c9e0471 100644 --- a/README.md +++ b/README.md @@ -642,6 +642,8 @@ CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) ### Parametrized Decorator ```python +from functools import wraps + def debug(print_result=False): def decorator(func): @wraps(func) From c4ae3c6c32b1c186e0d5ec5e687f44f0acf0c435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:07:53 +0100 Subject: [PATCH 0093/2188] Argparse --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a0c9e0471..58042bc7d 100644 --- a/README.md +++ b/README.md @@ -1400,8 +1400,8 @@ Libraries Argparse -------- ```python -import argparse -parser = argparse.ArgumentParser(description='calculate X to the power of Y') +from argparse import ArgumentParser +parser = ArgumentParser(description='calculate X to the power of Y') group = parser.add_mutually_exclusive_group() group.add_argument('-v', '--verbose', action='store_true') group.add_argument('-q', '--quiet', action='store_true') From 689a9bd7011a181c1c4b8407a7cb411535c32279 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:09:50 +0100 Subject: [PATCH 0094/2188] Plot --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 58042bc7d..c2bdcb90d 100644 --- a/README.md +++ b/README.md @@ -1436,17 +1436,6 @@ optional arguments: ``` -Plot ----- -```python -# $ pip3 install matplotlib -from matplotlib import pyplot -pyplot.plot( [, , ...]) -pyplot.savefig(, transparent=True) -pyplot.show() -``` - - Progress Bar ------------ ```python @@ -1497,6 +1486,17 @@ def get_border(screen): ``` +Plot +---- +```python +# $ pip3 install matplotlib +from matplotlib import pyplot +pyplot.plot( [, , ...]) +pyplot.savefig(, transparent=True) +pyplot.show() +``` + + Image ----- #### Creates PNG image of greyscale gradient: From f3e0dd1e7e7f4fd28fed00a5627a033d877dddb7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:12:46 +0100 Subject: [PATCH 0095/2188] Web --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c2bdcb90d..86b2264bd 100644 --- a/README.md +++ b/README.md @@ -1616,7 +1616,7 @@ def odds_handler(sport): ```python # $ pip3 install requests >>> import requests ->>> url = 'http://localhost:8080/odds/soccer' +>>> url = 'http://localhost:8080/odds/football' >>> r = requests.post(url, data={'team': 'arsenal f.c.'}) >>> r.json() ['arsenal f.c.', 2.44, 3.29] From e9feb301890fe9ac9c27aee8b94efc9e6016c543 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:17:23 +0100 Subject: [PATCH 0096/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 86b2264bd..ebe5c3301 100644 --- a/README.md +++ b/README.md @@ -1735,7 +1735,7 @@ import numpy as np ```python <2d_bool_array> = <2d_array> > 0 <1d_array> = <2d_array>[<2d_bool_array>] -`` +``` ### Broadcasting **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.** From 94ac94ccb521a4f0380ea420b137f1a928ad5100 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:21:53 +0100 Subject: [PATCH 0097/2188] Format --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index ebe5c3301..ae3bac279 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ Format ``` ### General Options -```python +```bash {:<10} # ' ' {:>10} # ' ' {:^10} # ' ' @@ -1740,14 +1740,14 @@ import numpy as np ### Broadcasting **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.** ```python -left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) -right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3) +left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) +right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3) ``` #### 1. If array shapes differ, left-pad the smaller shape with ones: ```python -left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) -right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- ! +left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) +right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- ! ``` #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements: From e80383375f49261d6581fd5f4b0925f1e41661b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:24:16 +0100 Subject: [PATCH 0098/2188] Format --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ae3bac279..6bb27394a 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ Format ``` ### General Options -```bash +```perl {:<10} # ' ' {:>10} # ' ' {:^10} # ' ' From f013a32aec685c8131b7e7870f0fa967848dc0f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:26:51 +0100 Subject: [PATCH 0099/2188] Format --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 6bb27394a..3e09df63a 100644 --- a/README.md +++ b/README.md @@ -329,12 +329,12 @@ Format ``` ### General Options -```perl -{:<10} # ' ' -{:>10} # ' ' -{:^10} # ' ' -{:->10} # '------' -{:>0} # '' +```python +'{:<10}' # ' ' +'{:>10}' # ' ' +'{:^10}' # ' ' +'{:->10}' # '------' +'{:>0}' # '' ``` ### String Options From 7af16dabe4cab8d6813aa7200ef0e44ce409d487 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:29:10 +0100 Subject: [PATCH 0100/2188] Format --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 3e09df63a..e27adc7df 100644 --- a/README.md +++ b/README.md @@ -329,32 +329,32 @@ Format ``` ### General Options -```python -'{:<10}' # ' ' -'{:>10}' # ' ' -'{:^10}' # ' ' -'{:->10}' # '------' -'{:>0}' # '' +```bash +{:<10} # ' ' +{:>10} # ' ' +{:^10} # ' ' +{:->10} # '------' +{:>0} # '' ``` ### String Options **`'!r'` calls object's repr() method, instead of format(), to get a string.** -```python +```bash {'abcde'!r:<10} # "'abcde' " ``` -```python +```bash {'abcde':.3} # 'abc' {'abcde':10.3} # 'abc ' ``` ### Number Options -```python +```bash {1.23456:.3f} # '1.235' {1.23456:10.3f} # ' 1.235' ``` -```python +```bash { 123456:10,} # ' 123,456' { 123456:10_} # ' 123_456' { 123456:+10} # ' +123456' @@ -363,7 +363,7 @@ Format {-123456: } # '-123456' ``` -```python +```bash {65:c} # 'A' {3:08b} # '00000011' -> Binary with leading zeros. {3:0<8b} # '11000000' -> Binary with trailing zeros. From db2990bf6a22f6a414e1f7f19a9195d8f614853d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:30:02 +0100 Subject: [PATCH 0101/2188] Format --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index e27adc7df..28a383616 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ Format ``` ### General Options -```bash +```python {:<10} # ' ' {:>10} # ' ' {:^10} # ' ' @@ -339,22 +339,22 @@ Format ### String Options **`'!r'` calls object's repr() method, instead of format(), to get a string.** -```bash +```python {'abcde'!r:<10} # "'abcde' " ``` -```bash +```python {'abcde':.3} # 'abc' {'abcde':10.3} # 'abc ' ``` ### Number Options -```bash +```python {1.23456:.3f} # '1.235' {1.23456:10.3f} # ' 1.235' ``` -```bash +```python { 123456:10,} # ' 123,456' { 123456:10_} # ' 123_456' { 123456:+10} # ' +123456' @@ -363,7 +363,7 @@ Format {-123456: } # '-123456' ``` -```bash +```python {65:c} # 'A' {3:08b} # '00000011' -> Binary with leading zeros. {3:0<8b} # '11000000' -> Binary with trailing zeros. From 179c62773fd249618831e8f88f065816297ceb93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:37:41 +0100 Subject: [PATCH 0102/2188] Numpy --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 28a383616..3f41a8ae7 100644 --- a/README.md +++ b/README.md @@ -1693,6 +1693,7 @@ NumPy import numpy as np ``` +**Shape is a tuple of ints, representing sizes of array's dimensions.** ```python = np.array() = np.arange(from_inclusive, to_exclusive, step_size) @@ -1713,12 +1714,12 @@ import numpy as np ### Indexing #### Basic indexing -```python +```bash = <2d_array>[0, 0] ``` #### Basic slicing -```python +```bash <1d_view> = <2d_array>[0] # First row. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. <3d_view> = <2d_array>[None,:,:] # Expanded by dimension of size 1. @@ -1726,13 +1727,13 @@ import numpy as np #### Integer array indexing **If row and column indexes differ in shape, they are combined with broadcasting.** -```python +```bash <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] ``` #### Boolean array indexing -```python +```bash <2d_bool_array> = <2d_array> > 0 <1d_array> = <2d_array>[<2d_bool_array>] ``` From 093abcc5a104a7bb354612e3aeff97198afe2ebe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:42:45 +0100 Subject: [PATCH 0103/2188] Numpy --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3f41a8ae7..5b2b55d4b 100644 --- a/README.md +++ b/README.md @@ -1713,26 +1713,26 @@ import numpy as np ``` ### Indexing -#### Basic indexing +#### Basic indexing: ```bash = <2d_array>[0, 0] ``` -#### Basic slicing +#### Basic slicing: ```bash <1d_view> = <2d_array>[0] # First row. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. <3d_view> = <2d_array>[None,:,:] # Expanded by dimension of size 1. ``` -#### Integer array indexing +#### Integer array indexing: **If row and column indexes differ in shape, they are combined with broadcasting.** ```bash <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] ``` -#### Boolean array indexing +#### Boolean array indexing: ```bash <2d_bool_array> = <2d_array> > 0 <1d_array> = <2d_array>[<2d_bool_array>] From b32d5f7789279c459ac40cea4365f116e9928fdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 16:48:51 +0100 Subject: [PATCH 0104/2188] Numpy --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5b2b55d4b..f2030bbbf 100644 --- a/README.md +++ b/README.md @@ -1720,9 +1720,9 @@ import numpy as np #### Basic slicing: ```bash -<1d_view> = <2d_array>[0] # First row. -<1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. -<3d_view> = <2d_array>[None,:,:] # Expanded by dimension of size 1. +<1d_view> = <2d_array>[0] # First row. +<1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. +<3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1. ``` #### Integer array indexing: From cef1ceae1206fdb34892e6642ae8c4b430e3dca1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 17:22:03 +0100 Subject: [PATCH 0105/2188] Decorator --- README.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f2030bbbf..b72b1e535 100644 --- a/README.md +++ b/README.md @@ -608,11 +608,13 @@ def function_that_gets_passed_to_decorator(): ``` ### Debugger Example +**"Wraps" decorator copies metadata of function func() to function out(). Without it `add.__name__` would return `'out'`.** + ```python from functools import wraps def debug(func): - @wraps(func) # Copies func's metadata like name and doc to out. + @wraps(func) def out(*args, **kwargs): print(func.__name__) return func(*args, **kwargs) @@ -625,6 +627,7 @@ def add(x, y): ### LRU Cache **Decorator that caches function's return values. All arguments must be hashable.** + ```python from functools import lru_cache @@ -634,10 +637,10 @@ def fib(n): ``` ```python ->>> [fib(n) for n in range(16)] -[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] +>>> [fib(n) for n in range(8)] +[0, 1, 1, 2, 3, 5, 8, 13] >>> fib.cache_info() -CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) +CacheInfo(hits=12, misses=8, maxsize=None, currsize=8) ``` ### Parametrized Decorator From af0464f6acf003fdd99f837dff0d01d5cd9335ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 17:33:16 +0100 Subject: [PATCH 0106/2188] Decorator --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b72b1e535..6645c2416 100644 --- a/README.md +++ b/README.md @@ -608,7 +608,7 @@ def function_that_gets_passed_to_decorator(): ``` ### Debugger Example -**"Wraps" decorator copies metadata of function func() to function out(). Without it `add.__name__` would return `'out'`.** +**Prints functions name every time it gets called. Wraps is a helper decorator that copies metadata of function func() to function out(). Without it `'add.__name__'` would return `'out'`.** ```python from functools import wraps @@ -1730,6 +1730,7 @@ import numpy as np #### Integer array indexing: **If row and column indexes differ in shape, they are combined with broadcasting.** + ```bash <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] @@ -1743,6 +1744,7 @@ import numpy as np ### Broadcasting **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.** + ```python left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3) From b216b56b332927ca3db7004f3c1c3c3274128c9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 17:36:17 +0100 Subject: [PATCH 0107/2188] Decorator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6645c2416..a41d5b7f7 100644 --- a/README.md +++ b/README.md @@ -608,7 +608,7 @@ def function_that_gets_passed_to_decorator(): ``` ### Debugger Example -**Prints functions name every time it gets called. Wraps is a helper decorator that copies metadata of function func() to function out(). Without it `'add.__name__'` would return `'out'`.** +**Decorator that prints function's name every time it gets called. Wraps is a helper decorator that copies metadata of function func() to function out(). Without it `'add.__name__'` would return `'out'`.** ```python from functools import wraps From ccbcd544ae5b7e2aa6bc96ca8b12e05104355f5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 17:37:48 +0100 Subject: [PATCH 0108/2188] Decorator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a41d5b7f7..2350e1ed9 100644 --- a/README.md +++ b/README.md @@ -608,7 +608,7 @@ def function_that_gets_passed_to_decorator(): ``` ### Debugger Example -**Decorator that prints function's name every time it gets called. Wraps is a helper decorator that copies metadata of function func() to function out(). Without it `'add.__name__'` would return `'out'`.** +**Decorator that prints function's name every time it gets called. Wraps is a helper decorator that copies metadata of function add() to function out(). Without it `'add.__name__'` would return `'out'`.** ```python from functools import wraps From d054bfeb01012fcb00bd64024e91f5bc53011fc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 18:30:33 +0100 Subject: [PATCH 0109/2188] Decorator --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2350e1ed9..91ac189e8 100644 --- a/README.md +++ b/README.md @@ -637,10 +637,10 @@ def fib(n): ``` ```python ->>> [fib(n) for n in range(8)] -[0, 1, 1, 2, 3, 5, 8, 13] +>>> [fib(n) for n in range(10)] +[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] >>> fib.cache_info() -CacheInfo(hits=12, misses=8, maxsize=None, currsize=8) +CacheInfo(hits=16, misses=10, maxsize=None, currsize=10) ``` ### Parametrized Decorator From d237d07dea2c9294134e3656ce91a9f3bcd8d098 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 18:43:04 +0100 Subject: [PATCH 0110/2188] Format, Decorator, Class --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 91ac189e8..0adb96656 100644 --- a/README.md +++ b/README.md @@ -338,10 +338,10 @@ Format ``` ### String Options -**`'!r'` calls object's repr() method, instead of format(), to get a string.** ```python {'abcde'!r:<10} # "'abcde' " ``` +* **`'!r'` calls object's repr() method, instead of format(), to get a string.** ```python {'abcde':.3} # 'abc' @@ -608,7 +608,7 @@ def function_that_gets_passed_to_decorator(): ``` ### Debugger Example -**Decorator that prints function's name every time it gets called. Wraps is a helper decorator that copies metadata of function add() to function out(). Without it `'add.__name__'` would return `'out'`.** +**Decorator that prints function's name every time it gets called.** ```python from functools import wraps @@ -624,6 +624,8 @@ def debug(func): def add(x, y): return x + y ``` +* **Wraps is a helper decorator that copies metadata of function add() to function out().** +* **Without it `'add.__name__'` would return `'out'`.** ### LRU Cache **Decorator that caches function's return values. All arguments must be hashable.** @@ -714,7 +716,9 @@ class MyComparable: ``` ### Hashable -**Hashable object needs both hash() and eq() methods and it's hash value should never change. Objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do. That is why Python automatically makes classes unhashable if you only implement eq().** +* **Hashable object needs both hash() and eq() methods and it's hash value should never change.** +* **Objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.** +* **That is why Python automatically makes classes unhashable if you only implement eq().** ```python class MyHashable: From 1faec76fe98450ecabdfac2f9880a37365e155c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 18:48:04 +0100 Subject: [PATCH 0111/2188] Format, Decorator, Class --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0adb96656..948677e63 100644 --- a/README.md +++ b/README.md @@ -338,10 +338,10 @@ Format ``` ### String Options +**`'!r'` calls object's repr() method, instead of format(), to get a string.** ```python {'abcde'!r:<10} # "'abcde' " ``` -* **`'!r'` calls object's repr() method, instead of format(), to get a string.** ```python {'abcde':.3} # 'abc' @@ -703,7 +703,8 @@ class Employee(Person): ``` ### Comparable -**If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`, meaning all objects compare not equal by default.** +* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`,** +* **meaning all objects compare not equal by default.** ```python class MyComparable: From ac7f6a0bb3b7a0069b9543ad1e4feeee4c809983 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 18:50:38 +0100 Subject: [PATCH 0112/2188] Format, Decorator, Class --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 948677e63..1a6bdbb52 100644 --- a/README.md +++ b/README.md @@ -703,8 +703,8 @@ class Employee(Person): ``` ### Comparable -* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`,** -* **meaning all objects compare not equal by default.** +* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.** +* **That means all objects compare not equal by default.** ```python class MyComparable: From 31ad40fd27c96ef3186fe83152e33fc1af91f39a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:00:17 +0100 Subject: [PATCH 0113/2188] Regex --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 1a6bdbb52..790c7c08b 100644 --- a/README.md +++ b/README.md @@ -263,6 +263,11 @@ String Regex ----- +* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** +* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** +* **Use `r'\1'` or `'\\\\1'` for backreference.** +* **Use `'?'` to make operators non-greedy.** + ```python import re = re.sub(, new, text, count=0) # Substitutes all occurrences. @@ -273,11 +278,6 @@ import re = re.finditer(, text) # Searches for all occurrences of pattern. ``` -* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** -* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** -* **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use `'?'` to make operators non-greedy.** - ### Match Object ```python = .group() # Whole match. From 76ac9ab36d2651b739c3238eba174436254d32a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:01:35 +0100 Subject: [PATCH 0114/2188] Regex --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 790c7c08b..1a6bdbb52 100644 --- a/README.md +++ b/README.md @@ -263,11 +263,6 @@ String Regex ----- -* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** -* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** -* **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use `'?'` to make operators non-greedy.** - ```python import re = re.sub(, new, text, count=0) # Substitutes all occurrences. @@ -278,6 +273,11 @@ import re = re.finditer(, text) # Searches for all occurrences of pattern. ``` +* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** +* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** +* **Use `r'\1'` or `'\\\\1'` for backreference.** +* **Use `'?'` to make operators non-greedy.** + ### Match Object ```python = .group() # Whole match. From b3fc373f18d0120e8c47a1ff5dd21613b2e1ee54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:03:37 +0100 Subject: [PATCH 0115/2188] Nonlocal --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1a6bdbb52..efa8d4c45 100644 --- a/README.md +++ b/README.md @@ -578,7 +578,7 @@ from functools import partial ``` ### Nonlocal -**If variable is assigned to anywhere in the scope, it is regarded as local variable, unless it is declared as global or nonlocal.** +**If variable is assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as global or nonlocal.** ```python def get_counter(): From fe193933921116d78424dc7ca7106a61a5f0d415 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:09:46 +0100 Subject: [PATCH 0116/2188] Enum --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index efa8d4c45..d9976c2dd 100644 --- a/README.md +++ b/README.md @@ -772,6 +772,7 @@ Enum ---- ```python from enum import Enum, auto + class (Enum): = = , From 674d909779fd98d4f9795ad5d5f8a13ab32aab4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:11:01 +0100 Subject: [PATCH 0117/2188] Enum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d9976c2dd..5326c6828 100644 --- a/README.md +++ b/README.md @@ -776,7 +776,7 @@ from enum import Enum, auto class (Enum): = = , - = auto() # Can be used for automatic indexing. + = auto() @classmethod def get_member_names(cls): From 252cfdf241b9c41dfe31a297906c157baeeba556 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:19:12 +0100 Subject: [PATCH 0118/2188] Enum --- README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5326c6828..5620f3749 100644 --- a/README.md +++ b/README.md @@ -808,8 +808,13 @@ Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) #### Functions can not be values, so they must be wrapped: ```python from functools import partial -LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r), - 'or' : partial(lambda l, r: l or r)}) +LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), + 'OR' : partial(lambda l, r: l or r)}) +``` + +```python +>>> LogicOp.AND.value(True, False) +False ``` @@ -1295,7 +1300,7 @@ import operator as op product_of_elems = functools.reduce(op.mul, ) sorted_by_second = sorted(, key=op.itemgetter(1)) sorted_by_both = sorted(, key=op.itemgetter(1, 0)) -LogicOp = enum.Enum('LogicOp', {'and': op.and_, 'or' : op.or_}) +LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_}) last_el = op.methodcaller('pop')() ``` From a120b742645e92a03859d33f1e13d79335252541 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:24:10 +0100 Subject: [PATCH 0119/2188] Struct --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5620f3749..45c827234 100644 --- a/README.md +++ b/README.md @@ -1037,7 +1037,8 @@ def write_bytes(filename, bytes_obj): Struct ------ -**This module performs conversions between Python values and C struct represented as Python bytes object. Machine’s native type sizes and byte order are used by default.** +* **Module that performs conversions between Python values and C struct, represented as a Python bytes object.** +* **Machine’s native type sizes and byte order are used by default.** ```python from struct import pack, unpack, calcsize From e06bd6b31c477adfbeca31600a6e34052fb5cc22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:27:28 +0100 Subject: [PATCH 0120/2188] Struct --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 45c827234..ea52ec5c8 100644 --- a/README.md +++ b/README.md @@ -1037,7 +1037,7 @@ def write_bytes(filename, bytes_obj): Struct ------ -* **Module that performs conversions between Python values and C struct, represented as a Python bytes object.** +* **Module that performs conversions between Python values and a C struct, represented as a Python bytes object.** * **Machine’s native type sizes and byte order are used by default.** ```python From f34f596664380a6eae1f81c1c3dafec5f67cfffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:30:57 +0100 Subject: [PATCH 0121/2188] Deque --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ea52ec5c8..d8f812916 100644 --- a/README.md +++ b/README.md @@ -1085,7 +1085,8 @@ from array import array Deque ----- -**Short for “double-ended queue” and pronounced “deck”. It is a thread-safe list with efficient appends and pops from either side.** +* **Short for “double-ended queue” and pronounced “deck”.** +* **It is a thread-safe list with efficient appends and pops from either side.** ```python from collections import deque From ec60b00e7658d17d15c8c5f4cfb19b9a62577571 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:34:54 +0100 Subject: [PATCH 0122/2188] Deque --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d8f812916..c08e7f83a 100644 --- a/README.md +++ b/README.md @@ -1085,8 +1085,8 @@ from array import array Deque ----- +* **A thread-safe list with efficient appends and pops from either side.** * **Short for “double-ended queue” and pronounced “deck”.** -* **It is a thread-safe list with efficient appends and pops from either side.** ```python from collections import deque From eaa47b201b263a767ccc1ce9030fc6a8193d93e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:37:51 +0100 Subject: [PATCH 0123/2188] Deque --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index c08e7f83a..839bd6989 100644 --- a/README.md +++ b/README.md @@ -1085,8 +1085,7 @@ from array import array Deque ----- -* **A thread-safe list with efficient appends and pops from either side.** -* **Short for “double-ended queue” and pronounced “deck”.** +**A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** ```python from collections import deque From 153f79e1da45e5dcfe75cc5dcc16ced9811a84a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:47:56 +0100 Subject: [PATCH 0124/2188] Itertools, Numpy --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 839bd6989..8ecdb6437 100644 --- a/README.md +++ b/README.md @@ -1134,7 +1134,8 @@ Hashlib Itertools --------- -**Every function returns an iterator and can accept any collection and/or iterator. If you want to print the iterator, you need to pass it to the list() function!** +* **Every function returns an iterator and can accept any collection and/or iterator.** +* **If you want to print the iterator, you need to pass it to the list() function!** ```python from itertools import * @@ -1708,11 +1709,10 @@ NumPy import numpy as np ``` -**Shape is a tuple of ints, representing sizes of array's dimensions.** ```python = np.array() = np.arange(from_inclusive, to_exclusive, step_size) - = np.ones() + = np.ones() # Shape is a tuple of dimension sizes. = np.random.randint(from_inclusive, to_exclusive, ) ``` From 994a62c25d9adccb8e07f0d50d5b42e3256e7cdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:51:18 +0100 Subject: [PATCH 0125/2188] Eval --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ecdb6437..eb922dff9 100644 --- a/README.md +++ b/README.md @@ -1325,7 +1325,9 @@ ValueError: malformed node or string import ast from ast import Num, BinOp, UnaryOp import operator as op +``` +```python legal_operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, @@ -1712,7 +1714,7 @@ import numpy as np ```python = np.array() = np.arange(from_inclusive, to_exclusive, step_size) - = np.ones() # Shape is a tuple of dimension sizes. + = np.ones() # Shape is a tuple of dimension sizes. = np.random.randint(from_inclusive, to_exclusive, ) ``` From 59a2e9d75f352be96ce9196d8c0d5baeb1e8b640 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 19:53:43 +0100 Subject: [PATCH 0126/2188] Numpy --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index eb922dff9..5a163be6b 100644 --- a/README.md +++ b/README.md @@ -1714,12 +1714,12 @@ import numpy as np ```python = np.array() = np.arange(from_inclusive, to_exclusive, step_size) - = np.ones() # Shape is a tuple of dimension sizes. + = np.ones() = np.random.randint(from_inclusive, to_exclusive, ) ``` ```python -.shape = +.shape = # Shape is a tuple of dimension sizes. = .reshape() = np.broadcast_to(, ) ``` From 5ab7bfbdfa8bcc258ab7fed4675d2a4c2a641df5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:00:57 +0100 Subject: [PATCH 0127/2188] Numpy --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 5a163be6b..947d65eda 100644 --- a/README.md +++ b/README.md @@ -1325,9 +1325,7 @@ ValueError: malformed node or string import ast from ast import Num, BinOp, UnaryOp import operator as op -``` -```python legal_operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, @@ -1718,15 +1716,17 @@ import numpy as np = np.random.randint(from_inclusive, to_exclusive, ) ``` +#### Shape is a tuple of dimension sizes: ```python -.shape = # Shape is a tuple of dimension sizes. - = .reshape() - = np.broadcast_to(, ) +.shape = + = .reshape() + = np.broadcast_to(, ) ``` +#### Axis is an index of dimension that gets collapsed: ```python - = .sum([]) # Axis is an index of dimension that gets collapsed. - = .argmin([]) # Returns index/es of smallest element/s. + = .sum() + = .argmin() ``` ### Indexing From 319cf489f1ac23de1187e01c80f8ea464055b281 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:02:28 +0100 Subject: [PATCH 0128/2188] Numpy --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 947d65eda..e9dd1c6b7 100644 --- a/README.md +++ b/README.md @@ -1716,14 +1716,14 @@ import numpy as np = np.random.randint(from_inclusive, to_exclusive, ) ``` -#### Shape is a tuple of dimension sizes: +#### Shape is a tuple of dimension sizes. ```python .shape = = .reshape() = np.broadcast_to(, ) ``` -#### Axis is an index of dimension that gets collapsed: +#### Axis is an index of dimension that gets collapsed. ```python = .sum() = .argmin() From 68292d1bb2458366bd4e48696b7a3a28c392588c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:03:25 +0100 Subject: [PATCH 0129/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9dd1c6b7..f0d45c849 100644 --- a/README.md +++ b/README.md @@ -1723,7 +1723,7 @@ import numpy as np = np.broadcast_to(, ) ``` -#### Axis is an index of dimension that gets collapsed. +#### Axis is an index of dimension, that gets collapsed. ```python = .sum() = .argmin() From 4862dd6e29b45f6c2071569fbeb84720a7742eaa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:07:33 +0100 Subject: [PATCH 0130/2188] Numpy --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f0d45c849..8f44cf4e7 100644 --- a/README.md +++ b/README.md @@ -1716,19 +1716,20 @@ import numpy as np = np.random.randint(from_inclusive, to_exclusive, ) ``` -#### Shape is a tuple of dimension sizes. ```python .shape = = .reshape() = np.broadcast_to(, ) ``` -#### Axis is an index of dimension, that gets collapsed. ```python = .sum() = .argmin() ``` +* **Shape is a tuple of dimension sizes.** +* **Axis is an index of dimension, that gets collapsed.** + ### Indexing #### Basic indexing: ```bash From c94d88618d840d4e7ea8f1138bb2863450395b00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:10:27 +0100 Subject: [PATCH 0131/2188] Numpy --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8f44cf4e7..f8f42de7c 100644 --- a/README.md +++ b/README.md @@ -1744,13 +1744,13 @@ import numpy as np ``` #### Integer array indexing: -**If row and column indexes differ in shape, they are combined with broadcasting.** - ```bash <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] ``` +* **If row and column indexes differ in shape, they are combined with broadcasting.** + #### Boolean array indexing: ```bash <2d_bool_array> = <2d_array> > 0 From 1660c249145e9c7f5a70a0dd60fca7e7bb03bb50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:13:13 +0100 Subject: [PATCH 0132/2188] Numpy --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f8f42de7c..dd12d3ee0 100644 --- a/README.md +++ b/README.md @@ -1733,14 +1733,14 @@ import numpy as np ### Indexing #### Basic indexing: ```bash - = <2d_array>[0, 0] + = <2d_array>[0, 0] ``` #### Basic slicing: ```bash -<1d_view> = <2d_array>[0] # First row. -<1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. -<3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1. +<1d_view> = <2d_array>[0] # First row. +<1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. +<3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1. ``` #### Integer array indexing: @@ -1753,8 +1753,8 @@ import numpy as np #### Boolean array indexing: ```bash -<2d_bool_array> = <2d_array> > 0 -<1d_array> = <2d_array>[<2d_bool_array>] +<2d_bools> = <2d_array> > 0 +<1d_array> = <2d_array>[<2d_bools>] ``` ### Broadcasting From f30aadda92021badebbf57b32c144d49dcdc2a13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:15:01 +0100 Subject: [PATCH 0133/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dd12d3ee0..6882460b8 100644 --- a/README.md +++ b/README.md @@ -1724,7 +1724,7 @@ import numpy as np ```python = .sum() - = .argmin() +indexes = .argmin() ``` * **Shape is a tuple of dimension sizes.** From 2c432c725cd9cc86d8daf952b1f83d63219ed343 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:21:30 +0100 Subject: [PATCH 0134/2188] Numpy --- README.md | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 6882460b8..a998593d7 100644 --- a/README.md +++ b/README.md @@ -1731,32 +1731,27 @@ indexes = .argmin() * **Axis is an index of dimension, that gets collapsed.** ### Indexing -#### Basic indexing: -```bash - = <2d_array>[0, 0] -``` - -#### Basic slicing: +#### Basic: ```bash + = <2d_array>[0, 0] # First element. <1d_view> = <2d_array>[0] # First row. <1d_view> = <2d_array>[:, 0] # First column. Also [..., 0]. <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1. ``` -#### Integer array indexing: +#### Advanced: ```bash <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] ``` -* **If row and column indexes differ in shape, they are combined with broadcasting.** - -#### Boolean array indexing: ```bash <2d_bools> = <2d_array> > 0 <1d_array> = <2d_array>[<2d_bools>] ``` +* **If row and column indexes differ in shape, they are combined with broadcasting.** + ### Broadcasting **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.** From a58abf8593b9ffd0cbc6c4b6faa02721df96ee4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:25:18 +0100 Subject: [PATCH 0135/2188] Numpy --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index a998593d7..84804b73c 100644 --- a/README.md +++ b/README.md @@ -1731,7 +1731,6 @@ indexes = .argmin() * **Axis is an index of dimension, that gets collapsed.** ### Indexing -#### Basic: ```bash = <2d_array>[0, 0] # First element. <1d_view> = <2d_array>[0] # First row. @@ -1739,7 +1738,6 @@ indexes = .argmin() <3d_view> = <2d_array>[None, :, :] # Expanded by dimension of size 1. ``` -#### Advanced: ```bash <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>] <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>] From e79b047981a724ca5492d4bf60a8cff66ecb03b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:29:56 +0100 Subject: [PATCH 0136/2188] Enum --- README.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/README.md b/README.md index 84804b73c..9e09a3fe6 100644 --- a/README.md +++ b/README.md @@ -812,11 +812,6 @@ LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), 'OR' : partial(lambda l, r: l or r)}) ``` -```python ->>> LogicOp.AND.value(True, False) -False -``` - System ------ From 25ed221c74d0db27e2a54d46c2bbb2bb2c0f9982 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:31:24 +0100 Subject: [PATCH 0137/2188] Enum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9e09a3fe6..c52d9fd13 100644 --- a/README.md +++ b/README.md @@ -805,13 +805,13 @@ Cutlery = Enum('Cutlery', 'knife fork spoon') Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) ``` -#### Functions can not be values, so they must be wrapped: ```python from functools import partial LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), 'OR' : partial(lambda l, r: l or r)}) ``` +* **Functions can not be values, so they must be wrapped.** System ------ From e3d3f23f32c7c7f5c5105dc9f358da8714cffc26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:32:07 +0100 Subject: [PATCH 0138/2188] Enum --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c52d9fd13..9e09a3fe6 100644 --- a/README.md +++ b/README.md @@ -805,13 +805,13 @@ Cutlery = Enum('Cutlery', 'knife fork spoon') Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) ``` +#### Functions can not be values, so they must be wrapped: ```python from functools import partial LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), 'OR' : partial(lambda l, r: l or r)}) ``` -* **Functions can not be values, so they must be wrapped.** System ------ From 61b142b80b0997ffddf91a9f8ab2132422c75b7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:47:56 +0100 Subject: [PATCH 0139/2188] Image --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9e09a3fe6..31f9cf3e2 100644 --- a/README.md +++ b/README.md @@ -1516,7 +1516,7 @@ Image from PIL import Image width, height = 100, 100 img = Image.new('L', (width, height), 'white') -img.putdata([255*a/(width*height) for a in range(width*height)]) +img.putdata([255 * a/(width*height) for a in range(width*height)]) img.save('out.png') ``` From 27ea91998569f97abd801801236066c7e3bf179a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:58:17 +0100 Subject: [PATCH 0140/2188] Audio --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 31f9cf3e2..dd78beb76 100644 --- a/README.md +++ b/README.md @@ -1533,13 +1533,13 @@ Audio #### Saves a list of floats with values between 0 and 1 to a WAV file: ```python import wave, struct -frames = [struct.pack('h', int((a-0.5)*60000)) for a in ] -wf = wave.open(, 'wb') -wf.setnchannels(1) -wf.setsampwidth(4) -wf.setframerate(44100) -wf.writeframes(b''.join(frames)) -wf.close() +samples = [struct.pack('h', int((a-0.5)*60000)) for a in ] +wav = wave.open(, 'wb') +wav.setnchannels(1) +wav.setsampwidth(4) +wav.setframerate(44100) +wav.writeframes(b''.join(samples)) +wav.close() ``` From 9ac00bb6719ce432f6c233829ee1c34fe82ad5dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 29 Jan 2019 20:59:38 +0100 Subject: [PATCH 0141/2188] Audio --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index dd78beb76..6e0690480 100644 --- a/README.md +++ b/README.md @@ -1534,12 +1534,12 @@ Audio ```python import wave, struct samples = [struct.pack('h', int((a-0.5)*60000)) for a in ] -wav = wave.open(, 'wb') -wav.setnchannels(1) -wav.setsampwidth(4) -wav.setframerate(44100) -wav.writeframes(b''.join(samples)) -wav.close() +wf = wave.open(, 'wb') +wf.setnchannels(1) +wf.setsampwidth(4) +wf.setframerate(44100) +wf.writeframes(b''.join(samples)) +wf.close() ``` From 616cef56590b535355dca6641206486b45e78b17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 05:09:33 +0100 Subject: [PATCH 0142/2188] Pickle --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6e0690480..807a2e325 100644 --- a/README.md +++ b/README.md @@ -952,10 +952,11 @@ Pickle ------ ```python >>> import pickle ->>> favorite_color = {'lion': 'yellow', 'kitty': 'red'} ->>> pickle.dump(favorite_color, open('data.p', 'wb')) ->>> pickle.load(open('data.p', 'rb')) -{'lion': 'yellow', 'kitty': 'red'} +>>> P = collections.namedtuple('P', 'x y') +>>> points = [P(0, 0), P(1, 1), P(2, 2)] +>>> pickle.dump(points, open('points.p', 'wb')) +>>> pickle.load(open('points.p', 'rb')) +[P(x=0, y=0), P(x=1, y=1), P(x=2, y=2)] ``` From 4c9bee873195cd7e484aa50f1ca218f37ced5316 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 05:44:55 +0100 Subject: [PATCH 0143/2188] Pickle --- README.md | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 807a2e325..96ee8fc46 100644 --- a/README.md +++ b/README.md @@ -951,12 +951,27 @@ db.commit() Pickle ------ ```python ->>> import pickle ->>> P = collections.namedtuple('P', 'x y') ->>> points = [P(0, 0), P(1, 1), P(2, 2)] ->>> pickle.dump(points, open('points.p', 'wb')) ->>> pickle.load(open('points.p', 'rb')) -[P(x=0, y=0), P(x=1, y=1), P(x=2, y=2)] +import pickle +``` + +### Serialization +```python + = pickle.dumps() + = pickle.loads() +``` + +### Read Object from File +```python +def read_pickle_file(filename): + with open(filename, 'rb') as file: + return pickle.load(file) +``` + +### Write Object to File +```python +def write_to_pickle_file(filename, an_object): + with open(filename, 'wb') as file: + pickle.dump(an_object, file) ``` From d578c45ea0cd77751a8b51b78f247ce768c36981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 05:46:57 +0100 Subject: [PATCH 0144/2188] Json, Pickle --- README.md | 8 -------- 1 file changed, 8 deletions(-) diff --git a/README.md b/README.md index 96ee8fc46..916ae3354 100644 --- a/README.md +++ b/README.md @@ -895,10 +895,6 @@ JSON ---- ```python import json -``` - -### Serialization -```python = json.dumps(, ensure_ascii=True, indent=None) = json.loads() ``` @@ -952,10 +948,6 @@ Pickle ------ ```python import pickle -``` - -### Serialization -```python = pickle.dumps() = pickle.loads() ``` From 46ea5e58004636cc7092cbbfd33bdcbf31a9b353 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 05:53:48 +0100 Subject: [PATCH 0145/2188] Json, pickle --- README.md | 50 +++++++++++++++++++++++++------------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 916ae3354..3dde6a810 100644 --- a/README.md +++ b/README.md @@ -895,8 +895,8 @@ JSON ---- ```python import json - = json.dumps(, ensure_ascii=True, indent=None) - = json.loads() + = json.dumps(, ensure_ascii=True, indent=None) + = json.loads() ``` #### To preserve order: @@ -920,6 +920,29 @@ def write_to_json_file(filename, an_object): ``` +Pickle +------ +```python +import pickle + = pickle.dumps() + = pickle.loads() +``` + +### Read Object from File +```python +def read_pickle_file(filename): + with open(filename, 'rb') as file: + return pickle.load(file) +``` + +### Write Object to File +```python +def write_to_pickle_file(filename, an_object): + with open(filename, 'wb') as file: + pickle.dump(an_object, file) +``` + + SQLite ------ ```python @@ -944,29 +967,6 @@ db.commit() ``` -Pickle ------- -```python -import pickle - = pickle.dumps() - = pickle.loads() -``` - -### Read Object from File -```python -def read_pickle_file(filename): - with open(filename, 'rb') as file: - return pickle.load(file) -``` - -### Write Object to File -```python -def write_to_pickle_file(filename, an_object): - with open(filename, 'wb') as file: - pickle.dump(an_object, file) -``` - - Exceptions ---------- ```python From f1ed71041cfaba07a76cbe5140a484471b3ccf07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 05:56:40 +0100 Subject: [PATCH 0146/2188] Json --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3dde6a810..709ec3f8c 100644 --- a/README.md +++ b/README.md @@ -902,7 +902,7 @@ import json #### To preserve order: ```python from collections import OrderedDict - = json.loads(, object_pairs_hook=OrderedDict) + = json.loads(, object_pairs_hook=OrderedDict) ``` ### Read File From 027020b40feb8955fc8817d5b5099106c521bc8e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 06:23:13 +0100 Subject: [PATCH 0147/2188] Open --- README.md | 64 ++++++++++++++++++++++++++++++++++--------------------- 1 file changed, 40 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 709ec3f8c..0660b926d 100644 --- a/README.md +++ b/README.md @@ -370,14 +370,14 @@ Format ``` #### Float presentation types: -* `'f'` - Fixed point: `.f` -* `'%'` - Percent: `.%` -* `'e'` - Exponent +* `'f'` - fixed point: `.f` +* `'%'` - percent: `.%` +* `'e'` - exponent #### Integer presentation types: -* `'c'` - Character -* `'b'` - Binary -* `'x'` - Hex +* `'c'` - character +* `'b'` - binary +* `'x'` - hex * `'X'` - HEX @@ -822,14 +822,46 @@ script_name = sys.argv[0] arguments = sys.argv[1:] ``` -### Read File +### Input +**Reads a line from user input or pipe if present. The trailing newline gets stripped.** + +```python +filename = input('Enter a file name: ') +``` + +#### Prints lines until EOF: +```python +while True: + try: + print(input()) + except EOFError: + break +``` + +### Open +**Opens file and returns a corresponding file object.** + +```python + = open(, mode='r', encoding=None) +``` + +#### Modes: +* `'r'` - open for reading (default) +* `'w'` - open for writing, erasing the file first +* `'x'` - open for exclusive creation, failing if the file already exists +* `'a'` - open for writing, appending to the end of the file if it exists +* `'b'` - binary mode +* `'t'` - text mode (default) +* `'+'` - open a disk file for updating (reading and writing) + +#### Read Text File: ```python def read_file(filename): with open(filename, encoding='utf-8') as file: return file.readlines() ``` -### Write to File +#### Write to Text File: ```python def write_to_file(filename, text): with open(filename, 'w', encoding='utf-8') as file: @@ -867,22 +899,6 @@ b'.\n..\nfile1.txt\nfile2.txt\n' 0 ``` -### Input -**Reads a line from user input or pipe if present. The trailing newline gets stripped.** - -```python -filename = input('Enter a file name: ') -``` - -#### Prints lines until EOF: -```python -while True: - try: - print(input()) - except EOFError: - break -``` - ### Recursion Limit ```python >>> import sys From c5a1e5ce9793ecdfd5dbe75b9318c84e0ae2854b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 06:24:29 +0100 Subject: [PATCH 0148/2188] Format --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0660b926d..73066a0f9 100644 --- a/README.md +++ b/README.md @@ -370,9 +370,9 @@ Format ``` #### Float presentation types: -* `'f'` - fixed point: `.f` -* `'%'` - percent: `.%` -* `'e'` - exponent +* `'f'` - Fixed point: `.f` +* `'%'` - Percent: `.%` +* `'e'` - Exponent #### Integer presentation types: * `'c'` - character From 7ca352a8f61c73ea5c051de678b81c501f1323cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 06:28:12 +0100 Subject: [PATCH 0149/2188] Open --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 73066a0f9..d9ba69295 100644 --- a/README.md +++ b/README.md @@ -854,14 +854,14 @@ while True: * `'t'` - text mode (default) * `'+'` - open a disk file for updating (reading and writing) -#### Read Text File: +#### Read Text from File: ```python def read_file(filename): with open(filename, encoding='utf-8') as file: return file.readlines() ``` -#### Write to Text File: +#### Write Text to File: ```python def write_to_file(filename, text): with open(filename, 'w', encoding='utf-8') as file: From dd2c42eea9f3af923646757e1eeff761caf3ad14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 06:31:54 +0100 Subject: [PATCH 0150/2188] System --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d9ba69295..579e00015 100644 --- a/README.md +++ b/README.md @@ -815,14 +815,14 @@ LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), System ------ -### Arguments +### Command Line Arguments ```python import sys script_name = sys.argv[0] arguments = sys.argv[1:] ``` -### Input +### Input Function **Reads a line from user input or pipe if present. The trailing newline gets stripped.** ```python @@ -838,7 +838,7 @@ while True: break ``` -### Open +### Open Function **Opens file and returns a corresponding file object.** ```python @@ -883,7 +883,7 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` -### Execute Command +### Command Execution ```python import os = os.popen().read() From 0f3c8384988b4daecc6580ca6bda58efdb41419e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 06:57:01 +0100 Subject: [PATCH 0151/2188] File --- README.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 579e00015..868475535 100644 --- a/README.md +++ b/README.md @@ -846,13 +846,15 @@ while True: ``` #### Modes: -* `'r'` - open for reading (default) -* `'w'` - open for writing, erasing the file first -* `'x'` - open for exclusive creation, failing if the file already exists -* `'a'` - open for writing, appending to the end of the file if it exists -* `'b'` - binary mode -* `'t'` - text mode (default) -* `'+'` - open a disk file for updating (reading and writing) +* `'r'` - read (default) +* `'w'` - write (truncate) +* `'x'` - write or fail if the file already exists +* `'a'` - append +* `'w+'` - read and write (truncate) +* `'r+'` - read and write from begining +* `'a+'` - read and write from end +* `'b'` - binary mode +* `'t'` - text mode (default) #### Read Text from File: ```python From 60fcfaf681ff66c6169cd3af9f1ed60f34bcc2e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 07:01:42 +0100 Subject: [PATCH 0152/2188] System --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 868475535..a696b0dca 100644 --- a/README.md +++ b/README.md @@ -846,15 +846,15 @@ while True: ``` #### Modes: -* `'r'` - read (default) -* `'w'` - write (truncate) -* `'x'` - write or fail if the file already exists -* `'a'` - append -* `'w+'` - read and write (truncate) -* `'r+'` - read and write from begining -* `'a+'` - read and write from end -* `'b'` - binary mode -* `'t'` - text mode (default) +* `'r' ` - Read (default) +* `'w' ` - Write (truncate) +* `'x' ` - Write or fail if the file already exists +* `'a' ` - Append +* `'w+'` - Read and write (truncate) +* `'r+'` - Read and write from begining +* `'a+'` - Read and write from end +* `'b' ` - Binary mode +* `'t' ` - Text mode (default) #### Read Text from File: ```python From b7a24f1862121f6573337c62aa9232c0402c26f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 07:05:59 +0100 Subject: [PATCH 0153/2188] System --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index a696b0dca..868475535 100644 --- a/README.md +++ b/README.md @@ -846,15 +846,15 @@ while True: ``` #### Modes: -* `'r' ` - Read (default) -* `'w' ` - Write (truncate) -* `'x' ` - Write or fail if the file already exists -* `'a' ` - Append -* `'w+'` - Read and write (truncate) -* `'r+'` - Read and write from begining -* `'a+'` - Read and write from end -* `'b' ` - Binary mode -* `'t' ` - Text mode (default) +* `'r'` - read (default) +* `'w'` - write (truncate) +* `'x'` - write or fail if the file already exists +* `'a'` - append +* `'w+'` - read and write (truncate) +* `'r+'` - read and write from begining +* `'a+'` - read and write from end +* `'b'` - binary mode +* `'t'` - text mode (default) #### Read Text from File: ```python From 748827507a5261d8a60eb43fabc785b52ad84df2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 07:47:02 +0100 Subject: [PATCH 0154/2188] Cutlery --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 868475535..0bf5fc153 100644 --- a/README.md +++ b/README.md @@ -540,7 +540,7 @@ point = Point(0, 0) ```python from enum import Enum Direction = Enum('Direction', 'n e s w') -Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) +Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3}) ``` ```python @@ -800,9 +800,9 @@ random_member = random.choice(list()) ### Inline ```python -Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon']) -Cutlery = Enum('Cutlery', 'knife fork spoon') -Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3}) +Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon']) +Cutlery = Enum('Cutlery', 'fork knife spoon') +Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3}) ``` #### Functions can not be values, so they must be wrapped: From 2fd0723dc00c798f81b4dfb3fc1c729209db6664 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 07:54:38 +0100 Subject: [PATCH 0155/2188] Hashable --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0bf5fc153..ee456dec1 100644 --- a/README.md +++ b/README.md @@ -718,7 +718,7 @@ class MyComparable: ### Hashable * **Hashable object needs both hash() and eq() methods and it's hash value should never change.** -* **Objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.** +* **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.** * **That is why Python automatically makes classes unhashable if you only implement eq().** ```python From 83bd4fd328bb234ff4d49087df9aa94a119ffe16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 08:18:48 +0100 Subject: [PATCH 0156/2188] Sequence --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index ee456dec1..682a4282d 100644 --- a/README.md +++ b/README.md @@ -737,6 +737,8 @@ class MyHashable: ``` ### Sequence +* **Methods do not depend on each other, so they can be skipped if not needed.** +* **Any object with defined getitem() is considered iterable, even if it lacks iter().** ```python class MySequence: def __init__(self, a): From 52c2e67951011c81fbdd45113bb9ab8d3eccc907 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 08:25:36 +0100 Subject: [PATCH 0157/2188] Regex, enum --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 682a4282d..140e0223d 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,9 @@ Regex ----- ```python import re +``` + +```python = re.sub(, new, text, count=0) # Substitutes all occurrences. = re.findall(, text) # Returns all occurrences. = re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches. @@ -774,7 +777,9 @@ Enum ---- ```python from enum import Enum, auto +``` +```python class (Enum): = = , From 979482cb6507923cfecf09bf7a681da126716090 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 08:28:47 +0100 Subject: [PATCH 0158/2188] Regex --- README.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/README.md b/README.md index 140e0223d..1ec8eb885 100644 --- a/README.md +++ b/README.md @@ -265,9 +265,7 @@ Regex ----- ```python import re -``` -```python = re.sub(, new, text, count=0) # Substitutes all occurrences. = re.findall(, text) # Returns all occurrences. = re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches. @@ -777,9 +775,7 @@ Enum ---- ```python from enum import Enum, auto -``` -```python class (Enum): = = , From 56825dc10c923d0322fe0f7241bb63eb54be5b0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 08:29:43 +0100 Subject: [PATCH 0159/2188] Regex --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 1ec8eb885..682a4282d 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,6 @@ Regex ----- ```python import re - = re.sub(, new, text, count=0) # Substitutes all occurrences. = re.findall(, text) # Returns all occurrences. = re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches. From 64f65841d65e13c6e9086853a7155bda037b73b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 08:36:25 +0100 Subject: [PATCH 0160/2188] Input function --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 682a4282d..24146ae37 100644 --- a/README.md +++ b/README.md @@ -828,7 +828,7 @@ arguments = sys.argv[1:] **Reads a line from user input or pipe if present. The trailing newline gets stripped.** ```python -filename = input('Enter a file name: ') + = input(prompt=None) ``` #### Prints lines until EOF: From 97ac04ff6261c0849d0861b13367d5db01b55208 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 08:41:05 +0100 Subject: [PATCH 0161/2188] Input function --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 24146ae37..8e6969a25 100644 --- a/README.md +++ b/README.md @@ -825,7 +825,9 @@ arguments = sys.argv[1:] ``` ### Input Function -**Reads a line from user input or pipe if present. The trailing newline gets stripped.** +* **Reads a line from user input or pipe if present.** +* **The trailing newline gets stripped.** +* **The prompt string is printed to standard output before reading input.** ```python = input(prompt=None) From 6f4e4617543ecbae032e923052c620ae801f125e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:04:29 +0100 Subject: [PATCH 0162/2188] Regex --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 8e6969a25..70e2d7e3a 100644 --- a/README.md +++ b/README.md @@ -265,12 +265,12 @@ Regex ----- ```python import re - = re.sub(, new, text, count=0) # Substitutes all occurrences. - = re.findall(, text) # Returns all occurrences. - = re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches. - = re.search(, text) # Searches for first occurrence of pattern. - = re.match(, text) # Searches only at the beginning of the text. - = re.finditer(, text) # Searches for all occurrences of pattern. + = re.sub(, new, text, count=0) # Substitutes all occurrences. + = re.findall(, text) # Returns all occurrences. + = re.split(, text, maxsplit=0) # Use brackets in regex to keep the matches. + = re.search(, text) # Searches for first occurrence of pattern. + = re.match(, text) # Searches only at the beginning of the text. + = re.finditer(, text) # Returns iterator of all matches. ``` * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** From b0121514a0d13fe2ce77d4e22b48ff8b42ae0d85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:29:04 +0100 Subject: [PATCH 0163/2188] Print --- README.md | 32 +++++++++++++++----------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 70e2d7e3a..ebcfe97b2 100644 --- a/README.md +++ b/README.md @@ -295,23 +295,6 @@ import re ``` -Print ------ -**Use `'file=sys.stderr'` for errors.** - -```python -print( [, , end='', sep='', file=]) -``` - -```python ->>> from pprint import pprint ->>> pprint(locals()) -{'__doc__': None, - '__name__': '__main__', - '__package__': None, ...} -``` - - Format ------ ```python @@ -824,6 +807,21 @@ script_name = sys.argv[0] arguments = sys.argv[1:] ``` +### Print +**Use `'file=sys.stderr'` for errors.** + +```python +print( [, , end='', sep='', file=]) +``` + +```python +>>> from pprint import pprint +>>> pprint(locals()) +{'__doc__': None, + '__name__': '__main__', + '__package__': None, ...} +``` + ### Input Function * **Reads a line from user input or pipe if present.** * **The trailing newline gets stripped.** From c0f01bff8a5a8f25a56c14ce87ea699e46eacc54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:33:23 +0100 Subject: [PATCH 0164/2188] Print --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ebcfe97b2..93e297021 100644 --- a/README.md +++ b/README.md @@ -808,12 +808,13 @@ arguments = sys.argv[1:] ``` ### Print -**Use `'file=sys.stderr'` for errors.** - ```python print( [, , end='', sep='', file=]) ``` +* **Use `'file=sys.stderr'` for errors.** + +#### Pretty print: ```python >>> from pprint import pprint >>> pprint(locals()) From f3177d7afa08a0c55298d1719090ce286568491f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:37:09 +0100 Subject: [PATCH 0165/2188] Print --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 93e297021..ab41d754d 100644 --- a/README.md +++ b/README.md @@ -807,9 +807,9 @@ script_name = sys.argv[0] arguments = sys.argv[1:] ``` -### Print +### Print Function ```python -print( [, , end='', sep='', file=]) +print(, , ..., sep=' ', end='\n', file=sys.stdout) ``` * **Use `'file=sys.stderr'` for errors.** From 23056bc432a32b04a990ceb876b1f71541b30a75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:38:54 +0100 Subject: [PATCH 0166/2188] System --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ab41d754d..631727e40 100644 --- a/README.md +++ b/README.md @@ -824,14 +824,14 @@ print(, , ..., sep=' ', end='\n', file=sys.stdout) ``` ### Input Function -* **Reads a line from user input or pipe if present.** -* **The trailing newline gets stripped.** -* **The prompt string is printed to standard output before reading input.** - ```python = input(prompt=None) ``` +* **Reads a line from user input or pipe if present.** +* **The trailing newline gets stripped.** +* **The prompt string is printed to standard output before reading input.** + #### Prints lines until EOF: ```python while True: From 7e65e990e1bc06ae190e26df3666e66a9e579745 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:40:53 +0100 Subject: [PATCH 0167/2188] System --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 631727e40..ab41d754d 100644 --- a/README.md +++ b/README.md @@ -824,14 +824,14 @@ print(, , ..., sep=' ', end='\n', file=sys.stdout) ``` ### Input Function -```python - = input(prompt=None) -``` - * **Reads a line from user input or pipe if present.** * **The trailing newline gets stripped.** * **The prompt string is printed to standard output before reading input.** +```python + = input(prompt=None) +``` + #### Prints lines until EOF: ```python while True: From 79d20c2c5187ce2dbeeb8cb47a71ba38c500ee2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:44:18 +0100 Subject: [PATCH 0168/2188] System --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index ab41d754d..2ae18fb4a 100644 --- a/README.md +++ b/README.md @@ -809,10 +809,11 @@ arguments = sys.argv[1:] ### Print Function ```python -print(, , ..., sep=' ', end='\n', file=sys.stdout) +print(, , ..., sep=' ', end='\n', file=sys.stdout, flush=False) ``` * **Use `'file=sys.stderr'` for errors.** +* **Use `'flush=Ture'` to forcibly flush the stream.** #### Pretty print: ```python From cdc141cef6370def0886caecf5c0cb9c2d5aceac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:46:14 +0100 Subject: [PATCH 0169/2188] System --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2ae18fb4a..3039872ac 100644 --- a/README.md +++ b/README.md @@ -809,7 +809,7 @@ arguments = sys.argv[1:] ### Print Function ```python -print(, , ..., sep=' ', end='\n', file=sys.stdout, flush=False) +print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) ``` * **Use `'file=sys.stderr'` for errors.** From ed7fa6a64111c64e00ea4f43435c48810c402fe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 09:54:24 +0100 Subject: [PATCH 0170/2188] System --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3039872ac..c7cac91eb 100644 --- a/README.md +++ b/README.md @@ -818,10 +818,10 @@ print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) #### Pretty print: ```python >>> from pprint import pprint ->>> pprint(locals()) -{'__doc__': None, - '__name__': '__main__', - '__package__': None, ...} +>>> pprint(dir()) +['__annotations__', + '__builtins__', + '__doc__', ...] ``` ### Input Function From a4b7f674856cf39ef52c113f886a2535468c73ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 10:11:02 +0100 Subject: [PATCH 0171/2188] System --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index c7cac91eb..0667c8576 100644 --- a/README.md +++ b/README.md @@ -813,7 +813,6 @@ print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) ``` * **Use `'file=sys.stderr'` for errors.** -* **Use `'flush=Ture'` to forcibly flush the stream.** #### Pretty print: ```python From 7bff42e0d7c0b86f54767b135134264a38cc7ad5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 11:19:12 +0100 Subject: [PATCH 0172/2188] Exceptions --- README.md | 62 +++++++++++++++++++++++++++---------------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 0667c8576..04bd6bfae 100644 --- a/README.md +++ b/README.md @@ -798,6 +798,37 @@ LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), ``` +Exceptions +---------- +```python +while True: + try: + x = int(input('Please enter a number: ')) + except ValueError: + print('Oops! That was no valid number. Try again...') + else: + print('Thank you.') + break +``` + +#### Raising exception: +```python +raise ValueError('A very specific message!') +``` + +### Finally +```python +>>> try: +... raise KeyboardInterrupt +... finally: +... print('Goodbye, world!') +Goodbye, world! +Traceback (most recent call last): + File "", line 2, in +KeyboardInterrupt +``` + + System ------ ### Command Line Arguments @@ -988,37 +1019,6 @@ db.commit() ``` -Exceptions ----------- -```python -while True: - try: - x = int(input('Please enter a number: ')) - except ValueError: - print('Oops! That was no valid number. Try again...') - else: - print('Thank you.') - break -``` - -#### Raising exception: -```python -raise ValueError('A very specific message!') -``` - -### Finally -```python ->>> try: -... raise KeyboardInterrupt -... finally: -... print('Goodbye, world!') -Goodbye, world! -Traceback (most recent call last): - File "", line 2, in -KeyboardInterrupt -``` - - Bytes ----- **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.** From 7b50df6cb497e79e585b7735a446e06bd5f83fac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 11:28:13 +0100 Subject: [PATCH 0173/2188] Numpy --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 04bd6bfae..4294355b9 100644 --- a/README.md +++ b/README.md @@ -1752,7 +1752,7 @@ indexes = .argmin() ``` * **Shape is a tuple of dimension sizes.** -* **Axis is an index of dimension, that gets collapsed.** +* **Axis is an index of dimension that gets collapsed.** ### Indexing ```bash From be2411fec15d16704a5a1392c1c7a9196c3bdfc4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 11:44:26 +0100 Subject: [PATCH 0174/2188] Typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 4294355b9..2c8b4cdd0 100644 --- a/README.md +++ b/README.md @@ -885,7 +885,7 @@ while True: * `'x'` - write or fail if the file already exists * `'a'` - append * `'w+'` - read and write (truncate) -* `'r+'` - read and write from begining +* `'r+'` - read and write from beginning * `'a+'` - read and write from end * `'b'` - binary mode * `'t'` - text mode (default) @@ -1086,7 +1086,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * `'<'` - little-endian * `'>'` - big-endian -#### Use capital leter for unsigned type. Standard size in brackets: +#### Use capital letter for unsigned type. Standard size in brackets: * `'x'` - pad byte * `'c'` - char (1) * `'h'` - short (2) From b71c02a2e7d42b390afb4acb77b47a5f1a61b9f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 30 Jan 2019 12:56:13 +0100 Subject: [PATCH 0175/2188] Added twitter card --- index.html | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/index.html b/index.html index 048423ec1..7f8fd904b 100644 --- a/index.html +++ b/index.html @@ -10,6 +10,10 @@ + + + + + + +
+ + +
+ +
+ + + +
+
+
+ + From 590aa64e8249999a9ea21915b74823c5cebdb2c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 30 Mar 2019 04:32:36 +0100 Subject: [PATCH 0552/2188] Updated empty_script.py --- web/empty_script.py | 4185 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 4185 insertions(+) diff --git a/web/empty_script.py b/web/empty_script.py index 17db87be1..562703e0b 100644 --- a/web/empty_script.py +++ b/web/empty_script.py @@ -533,3 +533,4188 @@ ### ## # +# +# +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +# +# +# +# +# +# +# +# +# +# +# +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +# +# +# +# +# +# +# +# +# +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# +## +#### +####### +########## +############# +################## +###################### +########################### +################################ +####################################### +############################################ +################################################# +###################################################### +########################################################### +############################################################### +################################################################### +###################################################################### +######################################################################### +########################################################################### +############################################################################ +############################################################################# +############################################################################# +############################################################################ +########################################################################### +######################################################################### +###################################################################### +################################################################### +############################################################### +########################################################### +###################################################### +################################################# +############################################ +####################################### +################################## +############################# +######################## +################### +############### +########### +######## +##### +### +## +# From 09357cdac3a5ab94b3b77e412d0b1bfd7380b47d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 30 Mar 2019 12:53:22 +0100 Subject: [PATCH 0553/2188] Iterator --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index b72cf43c5..7c5baba2c 100644 --- a/README.md +++ b/README.md @@ -178,8 +178,6 @@ Point(x=1, y=2) Iterator -------- -**In this cheatsheet `''` can also mean an iterator.** - ```python from itertools import count, repeat, cycle, chain, islice ``` From d3953913f1d7ea1a7efbc87b59f575ffa8ed557f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 30 Mar 2019 12:53:56 +0100 Subject: [PATCH 0554/2188] Iterator --- index.html | 1 - 1 file changed, 1 deletion(-) diff --git a/index.html b/index.html index a0eb61318..9c7234492 100644 --- a/index.html +++ b/index.html @@ -273,7 +273,6 @@

#Named Tuple

'x', 'y')

#Iterator

-

In this cheatsheet '<collection>' can also mean an iterator.

from itertools import count, repeat, cycle, chain, islice
 
<iter> = iter(<collection>)

From 147a26e2457773b4fa55b93656bf737bfc0e762a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jure=20=C5=A0orn?= 
Date: Sat, 30 Mar 2019 13:42:15 +0100
Subject: [PATCH 0555/2188] Mro

---
 index.html | 17 +++++++++--------
 parse.js   | 34 ++++++++++++++++++++++++++--------
 2 files changed, 35 insertions(+), 16 deletions(-)

diff --git a/index.html b/index.html
index 9c7234492..9eadb71b3 100644
--- a/index.html
+++ b/index.html
@@ -460,15 +460,15 @@ 

#Combin

#Datetime

    -
  • Module 'datetime' provides 'date' <D>, 'time' <T>, 'datetime' <DT> and 'timedelta' <TD> classes. All are immutable and hashable.
  • -
  • Time and datetime can be 'aware' <a>, meaning they have defined timezone, or 'naive' <n>, meaning they don't.
  • +
  • Module 'datetime' provides 'date' <D>, 'time' <T>, 'datetime' <DT> and 'timedelta' <TD> classes. All are immutable and hashable.
  • +
  • Time and datetime can be 'aware' <a>, meaning they have defined timezone, or 'naive' <n>, meaning they don't.
  • If object is naive it is presumed to be in system's timezone.
from datetime import date, time, datetime, timedelta
 from dateutil.tz import UTC, tzlocal, gettz
 

Constructors

-
<D>  = date(year, month, day)
+
<D>  = date(year, month, day)
 <T>  = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
 <DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
 <TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
@@ -488,11 +488,11 @@ 

Timezone

<tz> = tzlocal() # Local timezone. <tz> = gettz('<Cont.>/<City>') # Timezone from 'Continent/City_Name' str.
-
<DTa>    = <DT>.astimezone(<tz>)            # Datetime, converted to passed timezone.
+
<DTa>    = <DT>.astimezone(<tz>)            # Datetime, converted to passed timezone.
 <Ta/DTa> = <T/DT>.replace(tzinfo=<tz>)      # Unconverted object with new timezone.
 

Encode

-
<D/T/DT> = D/T/DT.fromisoformat('<iso>')    # Object from ISO string.
+
<D/T/DT> = D/T/DT.fromisoformat('<iso>')    # Object from ISO string.
 <DT>     = DT.strptime(<str>, '<format>')   # Datetime from str, according to format.
 <D/DTn>  = D/DT.fromordinal(<int>)          # D/DTn from days since Christ.
 <DTa>    = DT.fromtimestamp(<real>, <tz>)   # DTa from seconds since Epoch in tz time.
@@ -502,7 +502,7 @@ 

Encode

  • On Unix systems Epoch is '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …
  • Decode

    -
    <str>    = <D/T/DT>.isoformat()             # ISO string representation.
    +
    <str>    = <D/T/DT>.isoformat()             # ISO string representation.
     <str>    = <D/T/DT>.strftime('<format>')    # Custom string representation.
     <int>    = <D/DT>.toordinal()               # Days since Christ, ignoring time and tz.
     <float>  = <DT>.timestamp()                 # Seconds since Epoch in local time or tz.
    @@ -749,9 +749,10 @@ 

    Multiple Inheritance

    class C(A, B): pass

    MRO determines the order in which parent classes are traversed when searching for a method:

    +
    >>> C.mro()
    -[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
    -
    +[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
    +

    Copy

    from copy import copy, deepcopy
     <object> = copy(<object>)
    diff --git a/parse.js b/parse.js
    index 3b4a74e86..61d1e3ea7 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -30,6 +30,8 @@ const TOC =
       '}\n' +
       '
    \n'; +const MRO = + '
    >>> C.mro()\n[<class \'C\'>, <class \'A\'>, <class \'B\'>, <class \'object\'>]\n
    \n' function main() { const html = getMd(); @@ -60,10 +62,7 @@ function modifyPage() { addToc(); insertLinks(); unindentBanner(); - $('code').not('.python').not('.text').not('.bash').addClass('python'); - $('code').each(function(index) { - hljs.highlightBlock(this); - }); + highlightCode(); } function removeOrigToc() { @@ -73,6 +72,11 @@ function removeOrigToc() { contentsList.remove(); } +function addToc() { + const nodes = $.parseHTML(TOC); + $('#main').before(nodes); +} + function insertLinks() { $('h2').each(function() { const aId = $(this).attr('id'); @@ -89,10 +93,24 @@ function unindentBanner() { downloadPraragrapth.addClass('banner'); } -function addToc() { - const headerMain = $('#main'); - const nodes = $.parseHTML(TOC); - headerMain.before(nodes); +function highlightCode() { + setApache('') + setApache('') + setApache('
    ') + setApache('') + setApache('') + setApache('') + $('code').not('.python').not('.text').not('.bash').not('.apache').addClass('python'); + $('code').each(function(index) { + hljs.highlightBlock(this); + }); + $('#copy').prev().remove() + const nodes = $.parseHTML(MRO); + $('#copy').before(nodes); +} + +function setApache(codeContents) { + $(`code:contains(${codeContents})`).addClass('apache'); } function readFile(filename) { From 5dd5a4bcabf391179297ff0c37e560f256aae4be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 30 Mar 2019 13:48:45 +0100 Subject: [PATCH 0556/2188] Datetime --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7c5baba2c..54e72c992 100644 --- a/README.md +++ b/README.md @@ -480,7 +480,7 @@ from dateutil.tz import UTC, tzlocal, gettz ### Timezone ```python - = UTC # UTC timezone. + = UTC # UTC timezone. London without DST. = tzlocal() # Local timezone. = gettz('/') # Timezone from 'Continent/City_Name' str. ``` diff --git a/index.html b/index.html index 9eadb71b3..84883ecaa 100644 --- a/index.html +++ b/index.html @@ -484,7 +484,7 @@

    Now

    <DTa> = DT.now(<tz>) # Aware datetime from current tz time.

    Timezone

    -
    <tz>     = UTC                              # UTC timezone.
    +
    <tz>     = UTC                              # UTC timezone. London without DST.
     <tz>     = tzlocal()                        # Local timezone.
     <tz>     = gettz('<Cont.>/<City>')          # Timezone from 'Continent/City_Name' str.
     
    From 9581ce51fdfadf3bd12d44e9ad61fee1059c1815 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 30 Mar 2019 13:51:05 +0100 Subject: [PATCH 0557/2188] Datetime --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 54e72c992..179c318d9 100644 --- a/README.md +++ b/README.md @@ -497,7 +497,7 @@ from dateutil.tz import UTC, tzlocal, gettz = D/DT.fromordinal() # D/DTn from days since Christ. = DT.fromtimestamp(, ) # DTa from seconds since Epoch in tz time. ``` -* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`. Offset is formatted as: `'HH:MM'`.** +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[]'`, or both separated by `'T'`. Offset is formatted as: `'±HH:MM'`.** * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** ### Decode diff --git a/index.html b/index.html index 84883ecaa..0794988b6 100644 --- a/index.html +++ b/index.html @@ -498,7 +498,7 @@

    Encode

    <DTa> = DT.fromtimestamp(<real>, <tz>) # DTa from seconds since Epoch in tz time.
      -
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[±<offset>]', or both separated by 'T'. Offset is formatted as: 'HH:MM'.
    • +
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[<offset>]', or both separated by 'T'. Offset is formatted as: '±HH:MM'.
    • On Unix systems Epoch is '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …

    Decode

    From a25708bcda1f824b318485f88e27f906d695740d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 30 Mar 2019 13:54:40 +0100 Subject: [PATCH 0558/2188] Datetime --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 179c318d9..54e72c992 100644 --- a/README.md +++ b/README.md @@ -497,7 +497,7 @@ from dateutil.tz import UTC, tzlocal, gettz = D/DT.fromordinal() # D/DTn from days since Christ. = DT.fromtimestamp(, ) # DTa from seconds since Epoch in tz time. ``` -* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[]'`, or both separated by `'T'`. Offset is formatted as: `'±HH:MM'`.** +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`. Offset is formatted as: `'HH:MM'`.** * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** ### Decode diff --git a/index.html b/index.html index 0794988b6..84883ecaa 100644 --- a/index.html +++ b/index.html @@ -498,7 +498,7 @@

    Encode

    <DTa> = DT.fromtimestamp(<real>, <tz>) # DTa from seconds since Epoch in tz time.
      -
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[<offset>]', or both separated by 'T'. Offset is formatted as: '±HH:MM'.
    • +
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[±<offset>]', or both separated by 'T'. Offset is formatted as: 'HH:MM'.
    • On Unix systems Epoch is '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …

    Decode

    From 69e31bb94cc44838ddf04f6f016414a3074c3bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 4 Apr 2019 01:51:15 +0200 Subject: [PATCH 0559/2188] Type and metaclasses --- README.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- index.html | 47 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 98 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 54e72c992..892fba07f 100644 --- a/README.md +++ b/README.md @@ -226,17 +226,42 @@ def count(start, step): Type ---- +* **Everything is an object.** +* **Every object has a type.** +* **Type and class are synonymous.** + +```python + = type() # Or: = .__class__ + = isinstance(, ) # Also true if 'type' is a superclass of el's type. +``` + +```python + = .__bases__ # A tuple of type's parents. + = .mro() # Returns a list of all type's superclasses. + = issubclass(, ) # Checks if 'sub_type' is a subclass of 'type'. +``` + +* **Every class is a subclass and a superclass of itself.** + ```python - = type() # / / ... +>>> type('a'), 'a'.__class__, str +(, , ) ``` +#### Some types do not have builtin names, so they must be imported: +```python +from types import FunctionType, MethodType, LambdaType, GeneratorType +``` + +### ABC-s ```python from numbers import Integral, Rational, Real, Complex, Number = isinstance(, Number) ``` ```python - = callable() +from collections.abc import Iterable, Collection, Sequence + = isinstance(, Iterable) ``` @@ -1514,6 +1539,32 @@ class MyClass(metaclass=MyMetaClass): ('abcde', 12345) ``` +#### Type diagram ('abc' is a str, str is a type, ...): +```text +┏━━━━━━━━━┯━━━━━━━━━━━━━┓ +┃ classes │ metaclasses ┃ +┠─────────┼─────────────┨ +┃ MyClass → MyMetaClass ┃ +┃ │ ↓ ┃ +┃ object ───→ type ←╮ ┃ +┃ │ ↑ ╰───╯ ┃ +┃ str ───────╯ ┃ +┗━━━━━━━━━┷━━━━━━━━━━━━━┛ +``` + +#### Inheritance diagram (str inherits from object, ...): +```text +┏━━━━━━━━━┯━━━━━━━━━━━━━┓ +┃ classes │ metaclasses ┃ +┠─────────┼─────────────┨ +┃ MyClass │ MyMetaClass ┃ +┃ ↓ │ ↓ ┃ +┃ object ←─── type ┃ +┃ ↑ │ ┃ +┃ str │ ┃ +┗━━━━━━━━━┷━━━━━━━━━━━━━┛ +``` + Operator -------- diff --git a/index.html b/index.html index 84883ecaa..7860b8b7c 100644 --- a/index.html +++ b/index.html @@ -302,12 +302,33 @@

    #Generator

    (10, 12, 14)

    #Type

    -
    <type> = type(<el>)  # <class 'int'> / <class 'str'> / ...
    +
      +
    • Everything is an object.
    • +
    • Every object has a type.
    • +
    • Type and class are synonymous.
    • +
    +
    <type>  = type(<el>)                      # Or: <type> = <el>.__class__
    +<bool>  = isinstance(<el>, <type>)        # Also true if 'type' is a superclass of el's type.
    +
    +
    <tuple> = <type>.__bases__                # A tuple of type's parents.
    +<list>  = <type>.mro()                    # Returns a list of all type's superclasses.
    +<bool>  = issubclass(<sub_type>, <type>)  # Checks if 'sub_type' is a subclass of 'type'.
    +
    +
      +
    • Every class is a subclass and a superclass of itself.
    • +
    +
    >>> type('a'), 'a'.__class__, str
    +(<class 'str'>, <class 'str'>, <class 'str'>)
    +
    +

    Some types do not have builtin names, so they must be imported:

    +
    from types import FunctionType, MethodType, LambdaType, GeneratorType
     
    +

    ABC-s

    from numbers import Integral, Rational, Real, Complex, Number
     <bool> = isinstance(<el>, Number)
     
    -
    <bool> = callable(<el>)
    +
    from collections.abc import Iterable, Collection, Sequence
    +<bool> = isinstance(<el>, Iterable)
     

    #String

    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
    @@ -1244,6 +1265,28 @@ 

    Metaclass Attribute

    >>> MyClass.a, MyClass.b
     ('abcde', 12345)
     
    +

    Type diagram ('abc' is a str, str is a type, …):

    +
    ┏━━━━━━━━━┯━━━━━━━━━━━━━┓
    +┃ classes │ metaclasses ┃
    +┠─────────┼─────────────┨
    +┃ MyClass → MyMetaClass ┃
    +┃         │     ↓       ┃
    +┃  object ───→ type ←╮  ┃
    +┃         │    ↑ ╰───╯  ┃
    +┃   str ───────╯        ┃
    +┗━━━━━━━━━┷━━━━━━━━━━━━━┛
    +
    +

    Inheritance diagram (str inherits from object, …):

    +
    ┏━━━━━━━━━┯━━━━━━━━━━━━━┓
    +┃ classes │ metaclasses ┃
    +┠─────────┼─────────────┨
    +┃ MyClass │ MyMetaClass ┃
    +┃    ↓    │     ↓       ┃
    +┃  object ←─── type     ┃
    +┃    ↑    │             ┃
    +┃   str   │             ┃
    +┗━━━━━━━━━┷━━━━━━━━━━━━━┛
    +

    #Operator

    from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
     from operator import eq, ne, lt, le, gt, ge
    
    From b053d867547c2b658de7573c2d2eb04016891ec0 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 11 Apr 2019 06:23:41 +0200
    Subject: [PATCH 0560/2188] Updated script.js
    
    ---
     index.html |  7 +++----
     parse.js   | 24 +++++++++++-------------
     2 files changed, 14 insertions(+), 17 deletions(-)
    
    diff --git a/index.html b/index.html
    index 7860b8b7c..01328dec4 100644
    --- a/index.html
    +++ b/index.html
    @@ -318,7 +318,7 @@ 

    #Type

  • Every class is a subclass and a superclass of itself.
  • >>> type('a'), 'a'.__class__, str
    -(<class 'str'>, <class 'str'>, <class 'str'>)
    +(<class 'str'>, <class 'str'>, <class 'str'>)
     

    Some types do not have builtin names, so they must be imported:

    from types import FunctionType, MethodType, LambdaType, GeneratorType
    @@ -770,10 +770,9 @@ 

    Multiple Inheritance

    class C(A, B): pass

    MRO determines the order in which parent classes are traversed when searching for a method:

    -
    >>> C.mro()
    -[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
    -
    +[<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>] +

    Copy

    from copy import copy, deepcopy
     <object> = copy(<object>)
    diff --git a/parse.js b/parse.js
    index 61d1e3ea7..9ef0ccb4f 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -30,8 +30,6 @@ const TOC =
       '}\n' +
       '
    \n'; -const MRO = - '
    >>> C.mro()\n[<class \'C\'>, <class \'A\'>, <class \'B\'>, <class \'object\'>]\n
    \n' function main() { const html = getMd(); @@ -94,23 +92,23 @@ function unindentBanner() { } function highlightCode() { - setApache('') - setApache('') - setApache('
    ') - setApache('') - setApache('') - setApache('') + setApaches(['', '', '
    ', '', '', '']); $('code').not('.python').not('.text').not('.bash').not('.apache').addClass('python'); $('code').each(function(index) { hljs.highlightBlock(this); }); - $('#copy').prev().remove() - const nodes = $.parseHTML(MRO); - $('#copy').before(nodes); + fixClasses() } -function setApache(codeContents) { - $(`code:contains(${codeContents})`).addClass('apache'); +function setApaches(elements) { + for (el of elements) { + $(`code:contains(${el})`).addClass('apache'); + } +} + +function fixClasses() { + // Changes class="hljs-keyword" to class="hljs-title" of 'class' keyword. + $('.hljs-class').filter(':contains(class \')').find(':first-child').removeClass('hljs-keyword').addClass('hljs-title') } function readFile(filename) { From 7c98b43cce5982e05f052e5116476c90dac622ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 11 Apr 2019 06:34:37 +0200 Subject: [PATCH 0561/2188] Type --- README.md | 11 ++--------- index.html | 10 ++-------- 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 892fba07f..8dc905575 100644 --- a/README.md +++ b/README.md @@ -232,17 +232,9 @@ Type ```python = type() # Or: = .__class__ - = isinstance(, ) # Also true if 'type' is a superclass of el's type. + = isinstance(, ) # Also checks subclasses and ABCs. ``` -```python - = .__bases__ # A tuple of type's parents. - = .mro() # Returns a list of all type's superclasses. - = issubclass(, ) # Checks if 'sub_type' is a subclass of 'type'. -``` - -* **Every class is a subclass and a superclass of itself.** - ```python >>> type('a'), 'a'.__class__, str (, , ) @@ -254,6 +246,7 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType ``` ### ABC-s +**Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance().** ```python from numbers import Integral, Rational, Real, Complex, Number = isinstance(, Number) diff --git a/index.html b/index.html index 01328dec4..1de9356e5 100644 --- a/index.html +++ b/index.html @@ -308,15 +308,8 @@

    #Type

  • Type and class are synonymous.
  • <type>  = type(<el>)                      # Or: <type> = <el>.__class__
    -<bool>  = isinstance(<el>, <type>)        # Also true if 'type' is a superclass of el's type.
    +<bool>  = isinstance(<el>, <type>)        # Also checks subclasses and ABCs.
     
    -
    <tuple> = <type>.__bases__                # A tuple of type's parents.
    -<list>  = <type>.mro()                    # Returns a list of all type's superclasses.
    -<bool>  = issubclass(<sub_type>, <type>)  # Checks if 'sub_type' is a subclass of 'type'.
    -
    -
      -
    • Every class is a subclass and a superclass of itself.
    • -
    >>> type('a'), 'a'.__class__, str
     (<class 'str'>, <class 'str'>, <class 'str'>)
     
    @@ -324,6 +317,7 @@

    Some types do not ha
    from types import FunctionType, MethodType, LambdaType, GeneratorType
     

    ABC-s

    +

    Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance().

    from numbers import Integral, Rational, Real, Complex, Number
     <bool> = isinstance(<el>, Number)
     
    From 298a026949ee151aee3c12753c4d253f580dbce6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 11 Apr 2019 19:54:34 +0200 Subject: [PATCH 0562/2188] Class --- README.md | 8 ++++---- index.html | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 8dc905575..e042b67e8 100644 --- a/README.md +++ b/README.md @@ -914,10 +914,10 @@ class MyCollection: return len(self.a) def __getitem__(self, i): return self.a[i] - def __setitem__(self, i, value): - self.a[i] = value - def __contains__(self, value): - return value in self.a + def __setitem__(self, i, el): + self.a[i] = el + def __contains__(self, el): + return el in self.a def __iter__(self): for el in self.a: yield el diff --git a/index.html b/index.html index 1de9356e5..b457033b4 100644 --- a/index.html +++ b/index.html @@ -818,10 +818,10 @@

    Collection

    return len(self.a) def __getitem__(self, i): return self.a[i] - def __setitem__(self, i, value): - self.a[i] = value - def __contains__(self, value): - return value in self.a + def __setitem__(self, i, el): + self.a[i] = el + def __contains__(self, el): + return el in self.a def __iter__(self): for el in self.a: yield el From 9ef6c68882d20c31fa3e9a291e260fef50722297 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 12 Apr 2019 09:18:26 +0200 Subject: [PATCH 0563/2188] Class diagrams --- README.md | 36 ++++++++++++++++++------------------ parse.js | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 69 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index e042b67e8..2b8101286 100644 --- a/README.md +++ b/README.md @@ -1534,28 +1534,28 @@ class MyClass(metaclass=MyMetaClass): #### Type diagram ('abc' is a str, str is a type, ...): ```text -┏━━━━━━━━━┯━━━━━━━━━━━━━┓ -┃ classes │ metaclasses ┃ -┠─────────┼─────────────┨ -┃ MyClass → MyMetaClass ┃ -┃ │ ↓ ┃ -┃ object ───→ type ←╮ ┃ -┃ │ ↑ ╰───╯ ┃ -┃ str ───────╯ ┃ -┗━━━━━━━━━┷━━━━━━━━━━━━━┛ ++---------+-------------+ +| classes | metaclasses | ++---------|-------------| +| MyClass > MyMetaClass | +| | v | +| object ---> type <+ | +| | ^ +---+ | +| str -------+ | ++---------+-------------+ ``` #### Inheritance diagram (str inherits from object, ...): ```text -┏━━━━━━━━━┯━━━━━━━━━━━━━┓ -┃ classes │ metaclasses ┃ -┠─────────┼─────────────┨ -┃ MyClass │ MyMetaClass ┃ -┃ ↓ │ ↓ ┃ -┃ object ←─── type ┃ -┃ ↑ │ ┃ -┃ str │ ┃ -┗━━━━━━━━━┷━━━━━━━━━━━━━┛ ++---------+-------------+ +| classes | metaclasses | ++---------|-------------| +| MyClass | MyMetaClass | +| v | v | +| object <--- type | +| ^ | | +| str | | ++---------+-------------+ ``` diff --git a/parse.js b/parse.js index 9ef0ccb4f..e0c09e7ea 100755 --- a/parse.js +++ b/parse.js @@ -30,6 +30,50 @@ const TOC = '}\n' + '
    \n'; +const DIAGRAM_1_A = + '+---------+-------------+\n' + + '| classes | metaclasses |\n' + + '+---------|-------------|\n' + + '| MyClass > MyMetaClass |\n' + + '| | v |\n' + + '| object ---> type <+ |\n' + + '| | ^ +---+ |\n' + + '| str -------+ |\n' + + '+---------+-------------+\n'; + +const DIAGRAM_1_B = + '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' + + '┃ classes │ metaclasses ┃\n' + + '┠─────────┼─────────────┨\n' + + '┃ MyClass → MyMetaClass ┃\n' + + '┃ │ ↓ ┃\n' + + '┃ object ───→ type ←╮ ┃\n' + + '┃ │ ↑ ╰───╯ ┃\n' + + '┃ str ───────╯ ┃\n' + + '┗━━━━━━━━━┷━━━━━━━━━━━━━┛\n'; + +const DIAGRAM_2_A = + '+---------+-------------+\n' + + '| classes | metaclasses |\n' + + '+---------|-------------|\n' + + '| MyClass | MyMetaClass |\n' + + '| v | v |\n' + + '| object <--- type |\n' + + '| ^ | |\n' + + '| str | |\n' + + '+---------+-------------+\n'; + +const DIAGRAM_2_B = + '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' + + '┃ classes │ metaclasses ┃\n' + + '┠─────────┼─────────────┨\n' + + '┃ MyClass │ MyMetaClass ┃\n' + + '┃ ↓ │ ↓ ┃\n' + + '┃ object ←─── type ┃\n' + + '┃ ↑ │ ┃\n' + + '┃ str │ ┃\n' + + '┗━━━━━━━━━┷━━━━━━━━━━━━━┛\n'; + function main() { const html = getMd(); @@ -50,11 +94,17 @@ function initDom(html) { } function getMd() { - const readme = readFile('README.md'); + var readme = readFile('README.md'); + readme = switchClassDiagrams(readme); const converter = new showdown.Converter(); return converter.makeHtml(readme); } +function switchClassDiagrams(readme) { + readme = readme.replace(DIAGRAM_1_A, DIAGRAM_1_B) + return readme.replace(DIAGRAM_2_A, DIAGRAM_2_B) +} + function modifyPage() { removeOrigToc(); addToc(); From 6a532b06507d2dc1425bd0255418f9b49250871c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 12 Apr 2019 09:22:04 +0200 Subject: [PATCH 0564/2188] Type --- README.md | 6 +----- index.html | 5 +---- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 2b8101286..61d19d2fd 100644 --- a/README.md +++ b/README.md @@ -247,14 +247,10 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType ### ABC-s **Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance().** -```python -from numbers import Integral, Rational, Real, Complex, Number - = isinstance(, Number) -``` ```python +from numbers import Integral, Rational, Real, Complex, Number from collections.abc import Iterable, Collection, Sequence - = isinstance(, Iterable) ``` diff --git a/index.html b/index.html index b457033b4..4c82d1d8d 100644 --- a/index.html +++ b/index.html @@ -319,10 +319,7 @@

    Some types do not ha

    ABC-s

    Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance().

    from numbers import Integral, Rational, Real, Complex, Number
    -<bool> = isinstance(<el>, Number)
    -
    -
    from collections.abc import Iterable, Collection, Sequence
    -<bool> = isinstance(<el>, Iterable)
    +from collections.abc import Iterable, Collection, Sequence
     

    #String

    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
    
    From 311c4a7af5a1c852d04b9107bb1b943445abfe28 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 12 Apr 2019 09:46:54 +0200
    Subject: [PATCH 0565/2188] Type
    
    ---
     README.md  | 6 +++---
     index.html | 6 +++---
     2 files changed, 6 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index 61d19d2fd..2f5cebc77 100644
    --- a/README.md
    +++ b/README.md
    @@ -231,8 +231,8 @@ Type
     * **Type and class are synonymous.**
     
     ```python
    -  = type()                      # Or:  = .__class__
    -  = isinstance(, )        # Also checks subclasses and ABCs.
    + = type()                # Or: .__class__
    + = isinstance(, )  # Or: issubclass(type(), )
     ```
     
     ```python
    @@ -246,7 +246,7 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType
     ```
     
     ### ABC-s
    -**Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance().**
    +**Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance() and issubclass().**
     
     ```python
     from numbers import Integral, Rational, Real, Complex, Number
    diff --git a/index.html b/index.html
    index 4c82d1d8d..d3af7c944 100644
    --- a/index.html
    +++ b/index.html
    @@ -307,8 +307,8 @@ 

    #Type

  • Every object has a type.
  • Type and class are synonymous.
  • -
    <type>  = type(<el>)                      # Or: <type> = <el>.__class__
    -<bool>  = isinstance(<el>, <type>)        # Also checks subclasses and ABCs.
    +
    <type> = type(<el>)                # Or: <el>.__class__
    +<bool> = isinstance(<el>, <type>)  # Or: issubclass(type(<el>), <type>)
     
    >>> type('a'), 'a'.__class__, str
     (<class 'str'>, <class 'str'>, <class 'str'>)
    @@ -317,7 +317,7 @@ 

    Some types do not ha
    from types import FunctionType, MethodType, LambdaType, GeneratorType
     

    ABC-s

    -

    Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance().

    +

    Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance() and issubclass().

    from numbers import Integral, Rational, Real, Complex, Number
     from collections.abc import Iterable, Collection, Sequence
     
    From fefd403fc3d4db6047671daf1f6fb35aa8fe884f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 12 Apr 2019 10:17:42 +0200 Subject: [PATCH 0566/2188] Comparable --- README.md | 4 ++-- index.html | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2f5cebc77..f56b87b19 100644 --- a/README.md +++ b/README.md @@ -876,7 +876,7 @@ class MyComparable: def __eq__(self, other): if isinstance(other, type(self)): return self.a == other.a - return False + return NotImplemented ``` ### Hashable @@ -894,7 +894,7 @@ class MyHashable: def __eq__(self, other): if isinstance(other, type(self)): return self.a == other.a - return False + return NotImplemented def __hash__(self): return hash(self.a) ``` diff --git a/index.html b/index.html index d3af7c944..472f9740c 100644 --- a/index.html +++ b/index.html @@ -782,7 +782,7 @@

    Comparable

    def __eq__(self, other): if isinstance(other, type(self)): return self.a == other.a - return False + return NotImplemented

    Hashable

      @@ -799,7 +799,7 @@

      Hashable

      def __eq__(self, other): if isinstance(other, type(self)): return self.a == other.a - return False + return NotImplemented def __hash__(self): return hash(self.a)
    From 0a5b6ba0be66637a97838312fbf28eec4974d2ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 12 Apr 2019 10:38:57 +0200 Subject: [PATCH 0567/2188] Removed green color, comparable --- README.md | 1 + index.html | 1 + web/default.min.css | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f56b87b19..4fd94836f 100644 --- a/README.md +++ b/README.md @@ -868,6 +868,7 @@ Duck Types ### Comparable * **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.** * **That means all objects compare not equal by default.** +* **Only object on the left side of a comparison has eq() called, unless it returns 'NotImplemented', in which case the right object is consulted.** ```python class MyComparable: diff --git a/index.html b/index.html index 472f9740c..3de02068d 100644 --- a/index.html +++ b/index.html @@ -775,6 +775,7 @@

    Comparable

    • If eq() method is not overridden, it returns 'id(self) == id(other)', which is the same as 'self is other'.
    • That means all objects compare not equal by default.
    • +
    • Only object on the left side of a comparison has eq() called, unless it returns 'NotImplemented', in which case the right object is consulted.
    class MyComparable:
         def __init__(self, a):
    diff --git a/web/default.min.css b/web/default.min.css
    index 447b1d3f4..f2b2eb9c1 100644
    --- a/web/default.min.css
    +++ b/web/default.min.css
    @@ -1 +1 @@
    -.hljs{overflow-x:auto}.hljs,.hljs-subst{}.hljs-comment{color:#888888}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{font-weight:bold;color:#3182bd}.hljs-type,.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#880000}.hljs-title,.hljs-section{color:#880000;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#BC6060}.hljs-literal{color:#78A960}.hljs-built_in,.hljs-bullet,.hljs-code,.hljs-addition{color:#397300}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}
    \ No newline at end of file
    +.hljs{overflow-x:auto}.hljs,.hljs-subst{}.hljs-comment{color:#888888}.hljs-keyword,.hljs-attribute,.hljs-selector-tag,.hljs-meta-keyword,.hljs-doctag,.hljs-name{font-weight:bold;color:#3182bd}.hljs-type,.hljs-string,.hljs-number,.hljs-selector-id,.hljs-selector-class,.hljs-quote,.hljs-template-tag,.hljs-deletion{color:#880000}.hljs-title,.hljs-section{color:#880000;font-weight:bold}.hljs-regexp,.hljs-symbol,.hljs-variable,.hljs-template-variable,.hljs-link,.hljs-selector-attr,.hljs-selector-pseudo{color:#BC6060}.hljs-literal{color:#78A960}.hljs-meta{color:#1f7199}.hljs-meta-string{color:#4d99bf}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}
    \ No newline at end of file
    
    From 030e49f5e4136f3904fc47bbeea86aca4ffa001f Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 12 Apr 2019 16:31:38 +0200
    Subject: [PATCH 0568/2188] ABC
    
    ---
     README.md  | 13 ++++++++++---
     index.html | 11 ++++++++---
     2 files changed, 18 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index 4fd94836f..3afb32eb1 100644
    --- a/README.md
    +++ b/README.md
    @@ -245,12 +245,19 @@ Type
     from types import FunctionType, MethodType, LambdaType, GeneratorType
     ```
     
    -### ABC-s
    -**Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance() and issubclass().**
    +### ABC
    +**An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().**
     
     ```python
     from numbers import Integral, Rational, Real, Complex, Number
    -from collections.abc import Iterable, Collection, Sequence
    +from collections.abc import Sequence, Collection, Iterable
    +```
    +
    +```python
    +>>> isinstance(123, Number)
    +True
    +>>> isinstance([1, 2, 3], Iterable)
    +True
     ```
     
     
    diff --git a/index.html b/index.html
    index 3de02068d..be132fc23 100644
    --- a/index.html
    +++ b/index.html
    @@ -316,10 +316,15 @@ 

    #Type

    Some types do not have builtin names, so they must be imported:

    from types import FunctionType, MethodType, LambdaType, GeneratorType
     
    -

    ABC-s

    -

    Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance() and issubclass().

    +

    ABC

    +

    An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().

    from numbers import Integral, Rational, Real, Complex, Number
    -from collections.abc import Iterable, Collection, Sequence
    +from collections.abc import Sequence, Collection, Iterable
    +
    +
    >>> isinstance(123, Number)
    +True
    +>>> isinstance([1, 2, 3], Iterable)
    +True
     

    #String

    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
    
    From 756bc55dfc682d1c1c5a5e4de6f0190200650179 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 12 Apr 2019 20:11:28 +0200
    Subject: [PATCH 0569/2188] Math
    
    ---
     README.md  | 3 +--
     index.html | 3 +--
     2 files changed, 2 insertions(+), 4 deletions(-)
    
    diff --git a/README.md b/README.md
    index 3afb32eb1..3cddf94fc 100644
    --- a/README.md
    +++ b/README.md
    @@ -408,10 +408,9 @@ Numbers
     
     ### Math
     ```python
    -from math import e, pi
    +from math import e, pi, inf, nan
     from math import cos, acos, sin, asin, tan, atan, degrees, radians
     from math import log, log10, log2
    -from math import inf, nan, isinf, isnan
     ```
     
     ### Statistics
    diff --git a/index.html b/index.html
    index be132fc23..88244499b 100644
    --- a/index.html
    +++ b/index.html
    @@ -432,10 +432,9 @@ 

    Basic Functions

    <real> = round(<real>, ±ndigits)

    Math

    -
    from math import e, pi
    +
    from math import e, pi, inf, nan
     from math import cos, acos, sin, asin, tan, atan, degrees, radians
     from math import log, log10, log2
    -from math import inf, nan, isinf, isnan
     

    Statistics

    from statistics import mean, median, variance, pvariance, pstdev
    
    From 4095057831d0b54186cc42c7ade20547606e1089 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 12 Apr 2019 20:16:01 +0200
    Subject: [PATCH 0570/2188] Comparable
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 3cddf94fc..592e337f1 100644
    --- a/README.md
    +++ b/README.md
    @@ -874,7 +874,7 @@ Duck Types
     ### Comparable
     * **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.**
     * **That means all objects compare not equal by default.**
    -* **Only object on the left side of a comparison has eq() called, unless it returns 'NotImplemented', in which case the right object is consulted.**
    +* **Only left side object has eq() method called, unless it returns 'NotImplemented', in which case the right object is consulted.**
     
     ```python
     class MyComparable:
    diff --git a/index.html b/index.html
    index 88244499b..f1a8b9ab0 100644
    --- a/index.html
    +++ b/index.html
    @@ -779,7 +779,7 @@ 

    Comparable

    • If eq() method is not overridden, it returns 'id(self) == id(other)', which is the same as 'self is other'.
    • That means all objects compare not equal by default.
    • -
    • Only object on the left side of a comparison has eq() called, unless it returns 'NotImplemented', in which case the right object is consulted.
    • +
    • Only left side object has eq() method called, unless it returns 'NotImplemented', in which case the right object is consulted.
    class MyComparable:
         def __init__(self, a):
    
    From aae6fa040e785068c5f5434cba83393014e51be1 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 12 Apr 2019 21:36:56 +0200
    Subject: [PATCH 0571/2188] Added JS script that checks if Menlo font exists
    
    ---
     index.html                   |  2 ++
     web/jquery-3.4.0.slim.min.js |  2 ++
     web/script_2.js              | 55 ++++++++++++++++++++++++++++++++++++
     web/template.html            |  2 ++
     4 files changed, 61 insertions(+)
     create mode 100644 web/jquery-3.4.0.slim.min.js
     create mode 100644 web/script_2.js
    
    diff --git a/index.html b/index.html
    index f1a8b9ab0..1cf24b97d 100644
    --- a/index.html
    +++ b/index.html
    @@ -1757,5 +1757,7 @@ 

    + diff --git a/web/jquery-3.4.0.slim.min.js b/web/jquery-3.4.0.slim.min.js new file mode 100644 index 000000000..6a597fc53 --- /dev/null +++ b/web/jquery-3.4.0.slim.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.4.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(g,e){"use strict";var t=[],v=g.document,r=Object.getPrototypeOf,s=t.slice,y=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,m=n.hasOwnProperty,a=m.toString,l=a.call(Object),b={},x=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},w=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function C(e,t,n){var r,i,o=(n=n||v).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function T(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.0 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector",E=function(e,t){return new E.fn.init(e,t)},d=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function p(e){var t=!!e&&"length"in e&&e.length,n=T(e);return!x(e)&&!w(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+R+")"+R+"*"),U=new RegExp(R+"|>"),V=new RegExp(W),X=new RegExp("^"+B+"$"),Q={ID:new RegExp("^#("+B+")"),CLASS:new RegExp("^\\.("+B+")"),TAG:new RegExp("^("+B+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+R+"*(even|odd|(([+-]|)(\\d*)n|)"+R+"*(?:([+-]|)"+R+"*(\\d+)|))"+R+"*\\)|)","i"),bool:new RegExp("^(?:"+I+")$","i"),needsContext:new RegExp("^"+R+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+R+"*((?:-\\d)?\\d*)"+R+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,G=/^(?:input|select|textarea|button)$/i,K=/^h\d$/i,J=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+R+"?|("+R+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){C()},ae=xe(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{O.apply(t=P.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){O={apply:t.length?function(e,t){q.apply(e,P.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,d=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==d&&9!==d&&11!==d)return n;if(!r&&((e?e.ownerDocument||e:m)!==T&&C(e),e=e||T,E)){if(11!==d&&(u=Z.exec(t)))if(i=u[1]){if(9===d){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return O.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&p.getElementsByClassName&&e.getElementsByClassName)return O.apply(n,e.getElementsByClassName(i)),n}if(p.qsa&&!S[t+" "]&&(!v||!v.test(t))&&(1!==d||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===d&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=N),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+be(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return O.apply(n,f.querySelectorAll(c)),n}catch(e){S(t,!0)}finally{s===N&&e.removeAttribute("id")}}}return g(t.replace(F,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>x.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[N]=!0,e}function ce(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)x.attrHandle[n[r]]=t}function de(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function pe(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in p=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},C=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==T&&9===r.nodeType&&r.documentElement&&(a=(T=r).documentElement,E=!i(T),m!==T&&(n=T.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),p.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),p.getElementsByTagName=ce(function(e){return e.appendChild(T.createComment("")),!e.getElementsByTagName("*").length}),p.getElementsByClassName=J.test(T.getElementsByClassName),p.getById=ce(function(e){return a.appendChild(e).id=N,!T.getElementsByName||!T.getElementsByName(N).length}),p.getById?(x.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},x.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(x.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},x.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),x.find.TAG=p.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):p.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},x.find.CLASS=p.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(p.qsa=J.test(T.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+R+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+R+"*(?:value|"+I+")"),e.querySelectorAll("[id~="+N+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+N+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=T.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+R+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(p.matchesSelector=J.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){p.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",W)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=J.test(a.compareDocumentPosition),y=t||J.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!p.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument===m&&y(m,e)?-1:t===T||t.ownerDocument===m&&y(m,t)?1:u?H(u,e)-H(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===T?-1:t===T?1:i?-1:o?1:u?H(u,e)-H(u,t):0;if(i===o)return de(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?de(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),T},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==T&&C(e),p.matchesSelector&&E&&!S[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||p.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){S(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&V.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=d[e+" "];return t||(t=new RegExp("(^|"+R+")"+e+"("+R+"|$)"))&&d(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function L(e,n,r){return x(n)?E.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?E.grep(e,function(e){return e===n!==r}):"string"!=typeof n?E.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(E.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof E?t[0]:t,E.merge(this,E.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:v,!0)),D.test(r[1])&&E.isPlainObject(t))for(r in t)x(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=v.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):x(e)?void 0!==n.ready?n.ready(e):e(E):E.makeArray(e,this)}).prototype=E.fn,j=E(v);var O=/^(?:parents|prev(?:Until|All))/,P={children:!0,contents:!0,next:!0,prev:!0};function H(e,t){while((e=e[t])&&1!==e.nodeType);return e}E.fn.extend({has:function(e){var t=E(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,pe=/^$|^module$|\/(?:java|ecma)script/i,he={option:[1,""],thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function ge(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&S(e,t)?E.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;nx",b.noCloneChecked=!!ye.cloneNode(!0).lastChild.defaultValue;var we=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Te=/^([^.]*)(?:\.(.+)|)/;function Ee(){return!0}function Ne(){return!1}function ke(e,t){return e===function(){try{return v.activeElement}catch(e){}}()==("focus"===t)}function Ae(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ae(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Ne;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return E().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=E.guid++)),e.each(function(){E.event.add(this,t,i,r,n)})}function Se(e,i,o){o?(G.set(e,i,!1),E.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=G.get(this,i);if(1&e.isTrigger&&this[i]){if(r)(E.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),G.set(this,i,r),t=o(this,i),this[i](),r!==(n=G.get(this,i))||t?G.set(this,i,!1):n=void 0,r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n}else r&&(G.set(this,i,E.event.trigger(E.extend(r.shift(),E.Event.prototype),r,this)),e.stopImmediatePropagation())}})):E.event.add(e,i,Ee)}E.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,d,p,h,g,v=G.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&E.find.matchesSelector(ie,i),n.guid||(n.guid=E.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof E&&E.event.triggered!==e.type?E.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(I)||[""]).length;while(l--)p=g=(s=Te.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),p&&(f=E.event.special[p]||{},p=(i?f.delegateType:f.bindType)||p,f=E.event.special[p]||{},c=E.extend({type:p,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&E.expr.match.needsContext.test(i),namespace:h.join(".")},o),(d=u[p])||((d=u[p]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(p,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?d.splice(d.delegateCount++,0,c):d.push(c),E.event.global[p]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,d,p,h,g,v=G.hasData(e)&&G.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(I)||[""]).length;while(l--)if(p=g=(s=Te.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),p){f=E.event.special[p]||{},d=u[p=(r?f.delegateType:f.bindType)||p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=d.length;while(o--)c=d[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(d.splice(o,1),c.selector&&d.delegateCount--,f.remove&&f.remove.call(e,c));a&&!d.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||E.removeEvent(e,p,v.handle),delete u[p])}else for(p in u)E.event.remove(e,p+t[l],n,r,!0);E.isEmptyObject(u)&&G.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=E.event.fix(e),u=new Array(arguments.length),l=(G.get(this,"events")||{})[s.type]||[],c=E.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,Le=/\s*$/g;function Oe(e,t){return S(e,"table")&&S(11!==t.nodeType?t:t.firstChild,"tr")&&E(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Ie(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(G.hasData(e)&&(o=G.access(e),a=G.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(b.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||E.isXMLDoc(e)))for(a=ge(c),r=0,i=(o=ge(e)).length;r
    ",2===pt.childNodes.length),E.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(b.createHTMLDocument?((r=(t=v.implementation.createHTMLDocument("")).createElement("base")).href=v.location.href,t.head.appendChild(r)):t=v),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&E(o).remove(),E.merge([],i.childNodes)));var r,i,o},E.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=E.css(e,"position"),c=E(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=E.css(e,"top"),u=E.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),x(t)&&(t=t.call(e,n,E.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},E.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){E.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===E.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===E.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=E(e).offset()).top+=E.css(e,"borderTopWidth",!0),i.left+=E.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-E.css(r,"marginTop",!0),left:t.left-i.left-E.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===E.css(e,"position"))e=e.offsetParent;return e||ie})}}),E.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;E.fn[t]=function(e){return z(this,function(e,t,n){var r;if(w(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),E.each(["top","left"],function(e,n){E.cssHooks[n]=ze(b.pixelPosition,function(e,t){if(t)return t=Fe(e,n),Me.test(t)?E(e).position()[n]+"px":t})}),E.each({Height:"height",Width:"width"},function(a,s){E.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){E.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return z(this,function(e,t,n){var r;return w(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?E.css(e,t,i):E.style(e,t,n,i)},s,n?e:void 0,n)}})}),E.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){E.fn[n]=function(e,t){return 0 MyMetaClass |\n' + + '| | v |\n' + + '| object ---> type <+ |\n' + + '| | ^ +---+ |\n' + + '| str -------+ |\n' + + '+---------+-------------+\n'; + +const DIAGRAM_1_B = + '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' + + '┃ classes │ metaclasses ┃\n' + + '┠─────────┼─────────────┨\n' + + '┃ MyClass → MyMetaClass ┃\n' + + '┃ │ ↓ ┃\n' + + '┃ object ───→ type ←╮ ┃\n' + + '┃ │ ↑ ╰───╯ ┃\n' + + '┃ str ───────╯ ┃\n' + + '┗━━━━━━━━━┷━━━━━━━━━━━━━┛\n'; + +const DIAGRAM_2_A = + '+---------+-------------+\n' + + '| classes | metaclasses |\n' + + '+---------|-------------|\n' + + '| MyClass | MyMetaClass |\n' + + '| v | v |\n' + + '| object <--- type |\n' + + '| ^ | |\n' + + '| str | |\n' + + '+---------+-------------+\n'; + +const DIAGRAM_2_B = + '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' + + '┃ classes │ metaclasses ┃\n' + + '┠─────────┼─────────────┨\n' + + '┃ MyClass │ MyMetaClass ┃\n' + + '┃ ↓ │ ↓ ┃\n' + + '┃ object ←─── type ┃\n' + + '┃ ↑ │ ┃\n' + + '┃ str │ ┃\n' + + '┗━━━━━━━━━┷━━━━━━━━━━━━━┛\n'; + + +(function(d){function c(c){b.style.fontFamily=c;e.appendChild(b);f=b.clientWidth;e.removeChild(b);return f}var f,e=d.body,b=d.createElement("span");b.innerHTML=Array(100).join("wi");b.style.cssText=["position:absolute","width:auto","font-size:128px","left:-99999px"].join(" !important;");var g=c("monospace"),h=c("serif"),k=c("sans-serif");window.isFontAvailable=function(b){return g!==c(b+",monospace")||k!==c(b+",sans-serif")||h!==c(b+",serif")}})(document); + +if (!isFontAvailable('Menlo')) { + $(`code:contains(${DIAGRAM_1_B})`).html(DIAGRAM_1_A) + $(`code:contains(${DIAGRAM_2_B})`).html(DIAGRAM_2_A) +} + + + + diff --git a/web/template.html b/web/template.html index c2215d579..c63f5221e 100644 --- a/web/template.html +++ b/web/template.html @@ -159,5 +159,7 @@


    + + From 7f235e81a132f739b2d2073903faa23de5e1e15a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 12 Apr 2019 21:51:24 +0200 Subject: [PATCH 0572/2188] Diagrams --- README.md | 4 ++-- parse.js | 4 ++-- web/script_2.js | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 592e337f1..036339f8c 100644 --- a/README.md +++ b/README.md @@ -1539,7 +1539,7 @@ class MyClass(metaclass=MyMetaClass): ```text +---------+-------------+ | classes | metaclasses | -+---------|-------------| ++---------+-------------| | MyClass > MyMetaClass | | | v | | object ---> type <+ | @@ -1552,7 +1552,7 @@ class MyClass(metaclass=MyMetaClass): ```text +---------+-------------+ | classes | metaclasses | -+---------|-------------| ++---------+-------------| | MyClass | MyMetaClass | | v | v | | object <--- type | diff --git a/parse.js b/parse.js index e0c09e7ea..3b19bd78d 100755 --- a/parse.js +++ b/parse.js @@ -33,7 +33,7 @@ const TOC = const DIAGRAM_1_A = '+---------+-------------+\n' + '| classes | metaclasses |\n' + - '+---------|-------------|\n' + + '+---------+-------------|\n' + '| MyClass > MyMetaClass |\n' + '| | v |\n' + '| object ---> type <+ |\n' + @@ -55,7 +55,7 @@ const DIAGRAM_1_B = const DIAGRAM_2_A = '+---------+-------------+\n' + '| classes | metaclasses |\n' + - '+---------|-------------|\n' + + '+---------+-------------|\n' + '| MyClass | MyMetaClass |\n' + '| v | v |\n' + '| object <--- type |\n' + diff --git a/web/script_2.js b/web/script_2.js index f0b417501..b9caa2b38 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -1,7 +1,7 @@ const DIAGRAM_1_A = '+---------+-------------+\n' + '| classes | metaclasses |\n' + - '+---------|-------------|\n' + + '+---------+-------------|\n' + '| MyClass > MyMetaClass |\n' + '| | v |\n' + '| object ---> type <+ |\n' + @@ -23,7 +23,7 @@ const DIAGRAM_1_B = const DIAGRAM_2_A = '+---------+-------------+\n' + '| classes | metaclasses |\n' + - '+---------|-------------|\n' + + '+---------+-------------|\n' + '| MyClass | MyMetaClass |\n' + '| v | v |\n' + '| object <--- type |\n' + From 0690c8f56d198749a00927c3ef43853ccecae781 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 12 Apr 2019 22:03:43 +0200 Subject: [PATCH 0573/2188] Empty script --- web/empty_script.py | 73 +++------------------------------------------ 1 file changed, 4 insertions(+), 69 deletions(-) diff --git a/web/empty_script.py b/web/empty_script.py index 562703e0b..aaf5317b5 100644 --- a/web/empty_script.py +++ b/web/empty_script.py @@ -1,12 +1,13 @@ # This is an empty Python script. # It is here, so it tricks GitHub into thinking that this is a Python project. # But because GitHub counts characters, we have to fill it with something. - # How about: + from math import sin, pi + LEN = 40 -wave = ['#' * (1 + round(amp * (1+sin(i/resolution*2*pi)))) - for resolution, amp in zip(range(10, 10+LEN, 2), range(2, 2+LEN, 2)) +wave = ['#' * (1 + round(amp * (1+sin(i/resolution*2*pi)))) + for resolution, amp in zip(range(10, 10+LEN, 2), range(2, 2+LEN, 2)) for i in range(resolution)] print('\n'.join(wave)) @@ -1210,44 +1211,6 @@ # # # -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# ## #### ####### @@ -3458,34 +3421,6 @@ ### ## # -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# -# ## #### ####### From 633575ca9d78d10d0f5cf7212858952f5d22cf31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 12 Apr 2019 22:21:42 +0200 Subject: [PATCH 0574/2188] JS script removes new from TOC if Menlo font not present --- web/script_2.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/web/script_2.js b/web/script_2.js index b9caa2b38..84a858a0f 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -46,8 +46,10 @@ const DIAGRAM_2_B = (function(d){function c(c){b.style.fontFamily=c;e.appendChild(b);f=b.clientWidth;e.removeChild(b);return f}var f,e=d.body,b=d.createElement("span");b.innerHTML=Array(100).join("wi");b.style.cssText=["position:absolute","width:auto","font-size:128px","left:-99999px"].join(" !important;");var g=c("monospace"),h=c("serif"),k=c("sans-serif");window.isFontAvailable=function(b){return g!==c(b+",monospace")||k!==c(b+",sans-serif")||h!==c(b+",serif")}})(document); if (!isFontAvailable('Menlo')) { - $(`code:contains(${DIAGRAM_1_B})`).html(DIAGRAM_1_A) - $(`code:contains(${DIAGRAM_2_B})`).html(DIAGRAM_2_A) + $(`code:contains(${DIAGRAM_1_B})`).html(DIAGRAM_1_A); + $(`code:contains(${DIAGRAM_2_B})`).html(DIAGRAM_2_A); + var htmlString = $('code:contains(ᴺᴱᵂ)').html().replace(/ᴺᴱᵂ/g, ''); + $('code:contains(ᴺᴱᵂ)').html(htmlString); } From 69ee03791a0c7404d2b04eed539ca234df0f7d1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 13 Apr 2019 02:23:05 +0200 Subject: [PATCH 0575/2188] Added Selenium --- README.md | 14 ++++++++++++++ index.html | 11 +++++++++++ 2 files changed, 25 insertions(+) diff --git a/README.md b/README.md index 036339f8c..d139cfc45 100644 --- a/README.md +++ b/README.md @@ -1808,6 +1808,20 @@ Scraping ('https://www.python.org/', '3.7.2') ``` +### Selenium +**Library for scraping dynamically generated web content.** + +```python +# $ brew cask install chromedriver +# $ pip3 install selenium +>>> from selenium import webdriver +>>> driver = webdriver.Chrome() +>>> driver.get(url) +>>> xpath = '//*[@id="mw-content-text"]/div/table[1]/tbody/tr[7]/td/div' +>>> driver.find_element_by_xpath(xpath).text.split()[0] +'3.7.2' +``` + Web --- diff --git a/index.html b/index.html index 1cf24b97d..39742c24f 100644 --- a/index.html +++ b/index.html @@ -1483,6 +1483,17 @@

    #Scraping

    >>> link, ver ('https://www.python.org/', '3.7.2')

    +

    Selenium

    +

    Library for scraping dynamically generated web content.

    +
    # $ brew cask install chromedriver
    +# $ pip3 install selenium
    +>>> from selenium import webdriver
    +>>> driver = webdriver.Chrome()
    +>>> driver.get(url)
    +>>> xpath  = '//*[@id="mw-content-text"]/div/table[1]/tbody/tr[7]/td/div'
    +>>> driver.find_element_by_xpath(xpath).text.split()[0]
    +'3.7.2'
    +

    #Web

    # $ pip3 install bottle
     from bottle import run, route, post, template, request, response
    
    From d5d5febb82e2dbd2c9e6e71337ba0809277a70ad Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 13 Apr 2019 02:51:43 +0200
    Subject: [PATCH 0576/2188] Logger
    
    ---
     README.md  | 10 +++++-----
     index.html | 17 +++++++++++++----
     2 files changed, 18 insertions(+), 9 deletions(-)
    
    diff --git a/README.md b/README.md
    index 03527d5c0..e3bab89f5 100644
    --- a/README.md
    +++ b/README.md
    @@ -1456,9 +1456,9 @@ lock.acquire()
     ...
     lock.release()
     ```
    -or
    +
    +#### Or:
     ```python
    -lock = RLock()
     with lock:
         ...
     ```
    @@ -1767,15 +1767,15 @@ from loguru import logger
     ```python
     logger.add('debug_{time}.log', colorize=True)  # Connects a log file.
     logger.add('error_{time}.log', level='ERROR')  # Another file for errors or higher.
    -logger.('A logging message')
    +logger.('A logging message.')
     ```
     * **Levels: `'debug'`, `'info'`, `'success'`, `'warning'`, `'error'`, `'critical'`.**
     
     ```python
     try:
         ...
    -except Exception as e:
    -    logger.exception('An error happened', e)
    +except :
    +    logger.exception('An error happened.')
     ```
     
     ### Rotation
    diff --git a/index.html b/index.html
    index 39742c24f..59533e48f 100644
    --- a/index.html
    +++ b/index.html
    @@ -1040,8 +1040,8 @@ 

    #< <str> = os.popen(<command>).read()

    Subprocess

    -
    >>> import subprocess
    ->>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
    +
    >>> import subprocess, shlex
    +>>> a = subprocess.run(shlex.split('ls -a'), stdout=subprocess.PIPE)
     >>> a.stdout
     b'.\n..\nfile1.txt\nfile2.txt\n'
     >>> a.returncode
    @@ -1207,6 +1207,10 @@ 

    Lock

    ... lock.release()
    +

    Or:

    +
    with lock:
    +    ...
    +

    #Introspection

    Inspecting code at runtime.

    Variables

    @@ -1241,7 +1245,7 @@

    Meta Class

    attrs['a'] = 'abcde' return type(name, parents, attrs)
    -

    Or:

    +

    Or:

    class MyMetaClass(type):
         def __new__(cls, name, parents, attrs):
             attrs['a'] = 'abcde'
    @@ -1441,11 +1445,16 @@ 

    #Logging

    logger.add('debug_{time}.log', colorize=True)  # Connects a log file.
     logger.add('error_{time}.log', level='ERROR')  # Another file for errors or higher.
    -logger.<level>('A logging message')
    +logger.<level>('A logging message.')
     
    • Levels: 'debug', 'info', 'success', 'warning', 'error', 'critical'.
    +
    try:
    +    ...
    +except <Exception>:
    +    logger.exception('An error happened.')
    +

    Rotation

    Parameter that sets a condition when a new log file is created.

    rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
    
    From d78171016f61633ad928fd7640e01d12efc6c975 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 13 Apr 2019 02:52:54 +0200
    Subject: [PATCH 0577/2188] Logging
    
    ---
     README.md  | 6 ------
     index.html | 4 ----
     2 files changed, 10 deletions(-)
    
    diff --git a/README.md b/README.md
    index e3bab89f5..ea0acfe78 100644
    --- a/README.md
    +++ b/README.md
    @@ -1797,12 +1797,6 @@ retention=||
     * **`''` - Max age of a file.**
     * **`''` - Max age as a string: `'1 week, 3 days'`, `'2 months'`, ...**
     
    -### Compression
    -**Sets how inactive log files are compressed.**
    -```python
    -compression='gz'|'bz2'|'tar'|'tar.gz'|'tar.bz2'|'zip'
    -```
    -
     
     Scraping
     --------
    diff --git a/index.html b/index.html
    index 59533e48f..5100473cd 100644
    --- a/index.html
    +++ b/index.html
    @@ -1474,10 +1474,6 @@ 

    Retention

  • '<timedelta>' - Max age of a file.
  • '<str>' - Max age as a string: '1 week, 3 days', '2 months', …
  • -

    Compression

    -

    Sets how inactive log files are compressed.

    -
    compression='gz'|'bz2'|'tar'|'tar.gz'|'tar.bz2'|'zip'
    -

    #Scraping

    # $ pip3 install requests beautifulsoup4
     >>> import requests
    
    From b5b53fada3d02e504e6211e28f7b2a365f383806 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 13 Apr 2019 03:00:46 +0200
    Subject: [PATCH 0578/2188] Logging
    
    ---
     README.md  | 3 +++
     index.html | 2 ++
     2 files changed, 5 insertions(+)
    
    diff --git a/README.md b/README.md
    index ea0acfe78..68da7fe8d 100644
    --- a/README.md
    +++ b/README.md
    @@ -1771,6 +1771,9 @@ logger.('A logging message.')
     ```
     * **Levels: `'debug'`, `'info'`, `'success'`, `'warning'`, `'error'`, `'critical'`.**
     
    +### Exceptions
    +**Error description, stack trace and values of variables are appended automatically.**
    +
     ```python
     try:
         ...
    diff --git a/index.html b/index.html
    index 5100473cd..ed3489a8b 100644
    --- a/index.html
    +++ b/index.html
    @@ -1450,6 +1450,8 @@ 

    #Logging

    • Levels: 'debug', 'info', 'success', 'warning', 'error', 'critical'.
    +

    Exceptions

    +

    Error description, stack trace and values of variables are appended automatically.

    try:
         ...
     except <Exception>:
    
    From 823f7f679895c112d8441b938c62ec96226ee210 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 13 Apr 2019 03:12:21 +0200
    Subject: [PATCH 0579/2188] Metaprograming
    
    ---
     README.md  | 4 ++--
     index.html | 4 ++--
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/README.md b/README.md
    index 68da7fe8d..52d482968 100644
    --- a/README.md
    +++ b/README.md
    @@ -1541,7 +1541,7 @@ class MyClass(metaclass=MyMetaClass):
     ('abcde', 12345)
     ```
     
    -#### Type diagram ('abc' is a str, str is a type, ...):
    +#### Type diagram (str is an instance of type, ...):
     ```text
     +---------+-------------+
     | classes | metaclasses |
    @@ -1554,7 +1554,7 @@ class MyClass(metaclass=MyMetaClass):
     +---------+-------------+
     ```
     
    -#### Inheritance diagram (str inherits from object, ...):
    +#### Inheritance diagram (str is a subclass of object, ...):
     ```text
     +---------+-------------+
     | classes | metaclasses |
    diff --git a/index.html b/index.html
    index ed3489a8b..e384294c4 100644
    --- a/index.html
    +++ b/index.html
    @@ -1264,7 +1264,7 @@ 

    Metaclass Attribute

    >>> MyClass.a, MyClass.b
     ('abcde', 12345)
     
    -

    Type diagram ('abc' is a str, str is a type, …):

    +

    Type diagram (str is an instance of type, …):

    ┏━━━━━━━━━┯━━━━━━━━━━━━━┓
     ┃ classes │ metaclasses ┃
     ┠─────────┼─────────────┨
    @@ -1275,7 +1275,7 @@ 

    Type diagram ('abc' is a str, str is a t ┃ str ───────╯ ┃ ┗━━━━━━━━━┷━━━━━━━━━━━━━┛

    -

    Inheritance diagram (str inherits from object, …):

    +

    Inheritance diagram (str is a subclass of object, …):

    ┏━━━━━━━━━┯━━━━━━━━━━━━━┓
     ┃ classes │ metaclasses ┃
     ┠─────────┼─────────────┨
    
    From 6c3224f9513f7df5e8df36cc7f164ef44658b7b6 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 13 Apr 2019 17:11:09 +0200
    Subject: [PATCH 0580/2188] Dataclass
    
    ---
     README.md  | 8 ++++----
     index.html | 8 ++++----
     2 files changed, 8 insertions(+), 8 deletions(-)
    
    diff --git a/README.md b/README.md
    index 52d482968..84aed0423 100644
    --- a/README.md
    +++ b/README.md
    @@ -670,7 +670,7 @@ from functools import reduce
     ['zero', 1, 'zero', 3]
     ```
     
    -### Namedtuple, Enum, Class
    +### Namedtuple, Enum, Dataclass
     ```python
     from collections import namedtuple
     Point     = namedtuple('Point', 'x y')
    @@ -684,9 +684,9 @@ Cutlery   = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
     ```
     
     ```python
    -# Warning: Objects will share the objects that are initialized in the dictionary!
    -Creature  = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n})
    -creature  = Creature()
    +from dataclasses import make_dataclass
    +Creature  = make_dataclass('Creature', ['location', 'direction'])
    +creature  = Creature(Point(0, 0), Direction.n)
     ```
     
     
    diff --git a/index.html b/index.html
    index e384294c4..25778af0c 100644
    --- a/index.html
    +++ b/index.html
    @@ -620,7 +620,7 @@ 

    If - Else

    >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
     ['zero', 1, 'zero', 3]
     
    -

    Namedtuple, Enum, Class

    +

    Namedtuple, Enum, Dataclass

    from collections import namedtuple
     Point     = namedtuple('Point', 'x y')
     point     = Point(0, 0)
    @@ -629,9 +629,9 @@ 

    Namedtuple, Enum, Class

    Direction = Enum('Direction', 'n e s w') Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
    -
    # Warning: Objects will share the objects that are initialized in the dictionary!
    -Creature  = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n})
    -creature  = Creature()
    +
    from dataclasses import make_dataclass
    +Creature  = make_dataclass('Creature', ['location', 'direction'])
    +creature  = Creature(Point(0, 0), Direction.n)
     

    #Closure

    We have a closure in Python when:

    From 93968a9de343a8d972f0eb3a778b3290961ae5d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 14 Apr 2019 17:40:24 +0200 Subject: [PATCH 0581/2188] Format --- README.md | 8 ++++++-- index.html | 8 +++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 84aed0423..645b0baac 100644 --- a/README.md +++ b/README.md @@ -344,6 +344,7 @@ Format = '{}, {}'.format(, ) ``` +### Attributes ```python >>> from collections import namedtuple >>> Person = namedtuple('Person', 'name height') @@ -357,9 +358,12 @@ Format ### General Options ```python {:<10} # ' ' -{:>10} # ' ' {:^10} # ' ' -{:.>10} # '......' +{:>10} # ' ' +``` + +```python +{:.<10} # '......' {:>0} # '' ``` diff --git a/index.html b/index.html index 25778af0c..89fdb1682 100644 --- a/index.html +++ b/index.html @@ -385,6 +385,7 @@

    #Format

    <str> = f'{<el_1>}, {<el_2>}'
     <str> = '{}, {}'.format(<el_1>, <el_2>)
     
    +

    Attributes

    >>> from collections import namedtuple
     >>> Person = namedtuple('Person', 'name height')
     >>> person = Person('Jean-Luc', 187)
    @@ -395,9 +396,10 @@ 

    #Format

    General Options

    {<el>:<10}       # '<el>      '
    -{<el>:>10}       # '      <el>'
     {<el>:^10}       # '   <el>   '
    -{<el>:.>10}      # '......<el>'
    +{<el>:>10}       # '      <el>'
    +
    +
    {<el>:.<10}      # '<el>......'
     {<el>:>0}        # '<el>'
     

    String Options

    @@ -1218,7 +1220,7 @@

    Variables

    <dict> = locals() # Dict of local variables. Also vars(). <dict> = globals() # Dict of global variables.
    -

    Attributes

    +

    Attributes

    <dict> = vars(<object>)
     <bool> = hasattr(<object>, '<attr_name>')
     value  = getattr(<object>, '<attr_name>')
    
    From f1827a610725641c179aff72769af81942998508 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sun, 14 Apr 2019 17:49:21 +0200
    Subject: [PATCH 0582/2188] Classes diagram
    
    ---
     README.md       | 4 ++--
     index.html      | 4 ++--
     parse.js        | 8 ++++----
     web/script_2.js | 8 ++++----
     4 files changed, 12 insertions(+), 12 deletions(-)
    
    diff --git a/README.md b/README.md
    index 645b0baac..adf40a1ba 100644
    --- a/README.md
    +++ b/README.md
    @@ -1548,7 +1548,7 @@ class MyClass(metaclass=MyMetaClass):
     #### Type diagram (str is an instance of type, ...):
     ```text
     +---------+-------------+
    -| classes | metaclasses |
    +| Classes | Metaclasses |
     +---------+-------------|
     | MyClass > MyMetaClass |
     |         |     v       |
    @@ -1561,7 +1561,7 @@ class MyClass(metaclass=MyMetaClass):
     #### Inheritance diagram (str is a subclass of object, ...):
     ```text
     +---------+-------------+
    -| classes | metaclasses |
    +| Classes | Metaclasses |
     +---------+-------------|
     | MyClass | MyMetaClass |
     |    v    |     v       |
    diff --git a/index.html b/index.html
    index 89fdb1682..382752f02 100644
    --- a/index.html
    +++ b/index.html
    @@ -1268,7 +1268,7 @@ 

    Metaclass Attribute

    Type diagram (str is an instance of type, …):

    ┏━━━━━━━━━┯━━━━━━━━━━━━━┓
    -┃ classes │ metaclasses ┃
    +┃ Classes │ Metaclasses ┃
     ┠─────────┼─────────────┨
     ┃ MyClass → MyMetaClass ┃
     ┃         │     ↓       ┃
    @@ -1279,7 +1279,7 @@ 

    Type diagram (str is an instance of ty

    Inheritance diagram (str is a subclass of object, …):

    ┏━━━━━━━━━┯━━━━━━━━━━━━━┓
    -┃ classes │ metaclasses ┃
    +┃ Classes │ Metaclasses ┃
     ┠─────────┼─────────────┨
     ┃ MyClass │ MyMetaClass ┃
     ┃    ↓    │     ↓       ┃
    diff --git a/parse.js b/parse.js
    index 3b19bd78d..307a1acad 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -32,7 +32,7 @@ const TOC =
     
     const DIAGRAM_1_A = 
       '+---------+-------------+\n' +
    -  '| classes | metaclasses |\n' +
    +  '| Classes | Metaclasses |\n' +
       '+---------+-------------|\n' +
       '| MyClass > MyMetaClass |\n' +
       '|         |     v       |\n' +
    @@ -43,7 +43,7 @@ const DIAGRAM_1_A =
     
     const DIAGRAM_1_B =
       '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
    -  '┃ classes │ metaclasses ┃\n' +
    +  '┃ Classes │ Metaclasses ┃\n' +
       '┠─────────┼─────────────┨\n' +
       '┃ MyClass → MyMetaClass ┃\n' +
       '┃         │     ↓       ┃\n' +
    @@ -54,7 +54,7 @@ const DIAGRAM_1_B =
     
     const DIAGRAM_2_A =
       '+---------+-------------+\n' +
    -  '| classes | metaclasses |\n' +
    +  '| Classes | Metaclasses |\n' +
       '+---------+-------------|\n' +
       '| MyClass | MyMetaClass |\n' +
       '|    v    |     v       |\n' +
    @@ -65,7 +65,7 @@ const DIAGRAM_2_A =
     
     const DIAGRAM_2_B =
       '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
    -  '┃ classes │ metaclasses ┃\n' +
    +  '┃ Classes │ Metaclasses ┃\n' +
       '┠─────────┼─────────────┨\n' +
       '┃ MyClass │ MyMetaClass ┃\n' +
       '┃    ↓    │     ↓       ┃\n' +
    diff --git a/web/script_2.js b/web/script_2.js
    index 84a858a0f..e7f73b9d3 100644
    --- a/web/script_2.js
    +++ b/web/script_2.js
    @@ -1,6 +1,6 @@
     const DIAGRAM_1_A = 
       '+---------+-------------+\n' +
    -  '| classes | metaclasses |\n' +
    +  '| Classes | Metaclasses |\n' +
       '+---------+-------------|\n' +
       '| MyClass > MyMetaClass |\n' +
       '|         |     v       |\n' +
    @@ -11,7 +11,7 @@ const DIAGRAM_1_A =
     
     const DIAGRAM_1_B =
       '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
    -  '┃ classes │ metaclasses ┃\n' +
    +  '┃ Classes │ Metaclasses ┃\n' +
       '┠─────────┼─────────────┨\n' +
       '┃ MyClass → MyMetaClass ┃\n' +
       '┃         │     ↓       ┃\n' +
    @@ -22,7 +22,7 @@ const DIAGRAM_1_B =
     
     const DIAGRAM_2_A =
       '+---------+-------------+\n' +
    -  '| classes | metaclasses |\n' +
    +  '| Classes | Metaclasses |\n' +
       '+---------+-------------|\n' +
       '| MyClass | MyMetaClass |\n' +
       '|    v    |     v       |\n' +
    @@ -33,7 +33,7 @@ const DIAGRAM_2_A =
     
     const DIAGRAM_2_B =
       '┏━━━━━━━━━┯━━━━━━━━━━━━━┓\n' +
    -  '┃ classes │ metaclasses ┃\n' +
    +  '┃ Classes │ Metaclasses ┃\n' +
       '┠─────────┼─────────────┨\n' +
       '┃ MyClass │ MyMetaClass ┃\n' +
       '┃    ↓    │     ↓       ┃\n' +
    
    From 744c360119caa3b316017e75ffe75195bbf3c9a3 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Mon, 15 Apr 2019 06:18:16 +0200
    Subject: [PATCH 0583/2188] Arguments
    
    ---
     README.md  | 14 +++++++++++---
     index.html | 12 +++++++++---
     2 files changed, 20 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index adf40a1ba..d53df1cf7 100644
    --- a/README.md
    +++ b/README.md
    @@ -556,9 +556,9 @@ Arguments
     
     ### Inside Function Definition
     ```python
    -def f():                      # def f(x, y)
    -def f():                         # def f(x=0, y=0)
    -def f(, ):      # def f(x, y=0)
    +def f(): ...                  # def f(x, y)
    +def f(): ...                     # def f(x=0, y=0)
    +def f(, ): ...  # def f(x, y=0)
     ```
     
     
    @@ -590,6 +590,13 @@ def add(*a):
     ```
     
     #### Legal argument combinations:
    +```python
    +def f(x, y, z):                # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
    +def f(*, x, y, z):             # f(x=1, y=2, z=3)
    +def f(x, *, y, z):             # f(x=1, y=2, z=3) | f(1, y=2, z=3)
    +def f(x, y, *, z):             # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
    +```
    +
     ```python
     def f(*args):                  # f(1, 2, 3)
     def f(x, *args):               # f(1, 2, 3)
    @@ -600,6 +607,7 @@ def f(x, *args, z):            # f(1, 2, z=3)
     ```python
     def f(**kwargs):               # f(x=1, y=2, z=3)
     def f(x, **kwargs):            # f(x=1, y=2, z=3) | f(1, y=2, z=3)
    +def f(*, x, **kwargs):         # f(x=1, y=2, z=3)
     ```
     
     ```python
    diff --git a/index.html b/index.html
    index 382752f02..5ab013301 100644
    --- a/index.html
    +++ b/index.html
    @@ -543,9 +543,9 @@ 

    Inside Function Call

    <function>(<positional_args>, <keyword_args>) # f(0, y=0)

    Inside Function Definition

    -
    def f(<nondefault_args>):                      # def f(x, y)
    -def f(<default_args>):                         # def f(x=0, y=0)
    -def f(<nondefault_args>, <default_args>):      # def f(x, y=0)
    +
    def f(<nondefault_args>): ...                  # def f(x, y)
    +def f(<default_args>): ...                     # def f(x=0, y=0)
    +def f(<nondefault_args>, <default_args>): ...  # def f(x, y=0)
     

    #Splat Operator

    Inside Function Call

    @@ -566,6 +566,11 @@

    Inside Function Definition

    6

    Legal argument combinations:

    +
    def f(x, y, z):                # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
    +def f(*, x, y, z):             # f(x=1, y=2, z=3)
    +def f(x, *, y, z):             # f(x=1, y=2, z=3) | f(1, y=2, z=3)
    +def f(x, y, *, z):             # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
    +
    def f(*args):                  # f(1, 2, 3)
     def f(x, *args):               # f(1, 2, 3)
     def f(*args, z):               # f(1, 2, z=3)
    @@ -573,6 +578,7 @@ 

    Legal argument combinations:

    def f(**kwargs):               # f(x=1, y=2, z=3)
     def f(x, **kwargs):            # f(x=1, y=2, z=3) | f(1, y=2, z=3)
    +def f(*, x, **kwargs):         # f(x=1, y=2, z=3)
     
    def f(*args, **kwargs):        # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
     def f(x, *args, **kwargs):     # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
    
    From d76b3b6e5f3d5355e909c1b44e245b8ecd873aa4 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Mon, 15 Apr 2019 06:25:58 +0200
    Subject: [PATCH 0584/2188] Iterator
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index d53df1cf7..6869309f0 100644
    --- a/README.md
    +++ b/README.md
    @@ -195,7 +195,7 @@ from itertools import count, repeat, cycle, chain, islice
     ```
     
     ```python
    - = chain(, , ...)       # Empties collections in order.
    + = chain(,  [, ...])    # Empties collections in order.
      = chain.from_iterable()  # Empties collections inside a collection in order.
     ```
     
    diff --git a/index.html b/index.html
    index 5ab013301..0a87f2bd4 100644
    --- a/index.html
    +++ b/index.html
    @@ -283,7 +283,7 @@ 

    #Iterator

    <iter> = repeat(<el> [, times]) # Returns element endlessly or 'times' times. <iter> = cycle(<collection>) # Repeats the sequence indefinitely.
    -
    <iter> = chain(<coll.>, <coll.>, ...)       # Empties collections in order.
    +
    <iter> = chain(<coll.>, <coll.> [, ...])    # Empties collections in order.
     <iter> = chain.from_iterable(<collection>)  # Empties collections inside a collection in order.
     
    <iter> = islice(<collection>, to_exclusive)
    
    From c1b93d3c5dec5d563dbd77b15b08ff83794c01b7 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 16 Apr 2019 11:03:54 +0200
    Subject: [PATCH 0585/2188] Dataclass, sortable
    
    ---
     README.md  | 33 +++++++++++++++++++++++++++++++++
     index.html | 33 +++++++++++++++++++++++++++++++++
     2 files changed, 66 insertions(+)
    
    diff --git a/README.md b/README.md
    index 6869309f0..5cbe6bde8 100644
    --- a/README.md
    +++ b/README.md
    @@ -871,6 +871,20 @@ class C(A, B): pass
     [, , , ]
     ```
     
    +### Dataclass
    +**Decorator that automatically generates init(), repr() and eq() magic methods. Object can also be made sortable with `'order=True'` and/or immutable with `'frozen=True'`.**
    +```python
    +from dataclasses import dataclass, field
    +
    +@dataclass(order=False, frozen=False)
    +class :
    +    : 
    +    :  = 
    +    : list/dict/set = field(default_factory=list/dict/set)
    +```
    +* **Function field() is needed because `': list = []'` would make a list that is shared among all instances.**
    +* **Default_factory can be any callable.**
    +
     ### Copy
     ```python
     from copy import copy, deepcopy
    @@ -918,6 +932,25 @@ class MyHashable:
             return hash(self.a)
     ```
     
    +### Sortable
    +* **With 'total_ordering' decorator you only need to provide one of lt(), gt(), le(), ge() magic methods.**
    +```python
    +from functools import total_ordering
    +
    +@total_ordering
    +class MySortable:
    +    def __init__(self, a):
    +        self.a = a
    +    def __eq__(self, other):
    +        if isinstance(other, type(self)):
    +            return self.a == other.a
    +        return NotImplemented
    +    def __lt__(self, other):
    +        if isinstance(other, type(self)):
    +            return self.a < other.a
    +        return NotImplemented
    +```
    +
     ### Collection
     * **Methods do not depend on each other, so they can be skipped if not needed.**
     * **Any object with defined getitem() is considered iterable, even if it lacks iter().**
    diff --git a/index.html b/index.html
    index 0a87f2bd4..fd3f9c8a1 100644
    --- a/index.html
    +++ b/index.html
    @@ -776,6 +776,20 @@ 

    Multiple Inheritance

    >>> C.mro()
     [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
     
    +

    Dataclass

    +

    Decorator that automatically generates init(), repr() and eq() magic methods. Object can also be made sortable with 'order=True' and/or immutable with 'frozen=True'.

    +
    from dataclasses import dataclass, field
    +
    +@dataclass(order=False, frozen=False)
    +class <class_name>:
    +    <attr_name_1>: <type>
    +    <attr_name_2>: <type> = <default_value>
    +    <attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
    +
    +
      +
    • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances.
    • +
    • Default_factory can be any callable.
    • +

    Copy

    from copy import copy, deepcopy
     <object> = copy(<object>)
    @@ -816,6 +830,25 @@ 

    Hashable

    def __hash__(self): return hash(self.a)
    +

    Sortable

    +
      +
    • With 'total_ordering' decorator you only need to provide one of lt(), gt(), le(), ge() magic methods.
    • +
    +
    from functools import total_ordering
    +
    +@total_ordering
    +class MySortable:
    +    def __init__(self, a):
    +        self.a = a
    +    def __eq__(self, other):
    +        if isinstance(other, type(self)):
    +            return self.a == other.a
    +        return NotImplemented
    +    def __lt__(self, other):
    +        if isinstance(other, type(self)):
    +            return self.a < other.a
    +        return NotImplemented
    +

    Collection

    • Methods do not depend on each other, so they can be skipped if not needed.
    • From 65842dc0e48c28d1763e21c27ab8e14805fa8355 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Apr 2019 11:12:12 +0200 Subject: [PATCH 0586/2188] Dataclass --- README.md | 3 ++- index.html | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5cbe6bde8..5438d18de 100644 --- a/README.md +++ b/README.md @@ -872,7 +872,7 @@ class C(A, B): pass ``` ### Dataclass -**Decorator that automatically generates init(), repr() and eq() magic methods. Object can also be made sortable with `'order=True'` and/or immutable with `'frozen=True'`.** +**Decorator that automatically generates init(), repr() and eq() magic methods.** ```python from dataclasses import dataclass, field @@ -882,6 +882,7 @@ class : : = : list/dict/set = field(default_factory=list/dict/set) ``` +* **An object can be made sortable with `'order=True'` or immutable with `'frozen=True'`.** * **Function field() is needed because `': list = []'` would make a list that is shared among all instances.** * **Default_factory can be any callable.** diff --git a/index.html b/index.html index fd3f9c8a1..cc10afcca 100644 --- a/index.html +++ b/index.html @@ -777,7 +777,7 @@

      Multiple Inheritance

      [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]

    Dataclass

    -

    Decorator that automatically generates init(), repr() and eq() magic methods. Object can also be made sortable with 'order=True' and/or immutable with 'frozen=True'.

    +

    Decorator that automatically generates init(), repr() and eq() magic methods.

    from dataclasses import dataclass, field
     
     @dataclass(order=False, frozen=False)
    @@ -787,6 +787,7 @@ 

    Dataclass

    <attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
      +
    • An object can be made sortable with 'order=True' or immutable with 'frozen=True'.
    • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances.
    • Default_factory can be any callable.
    From 4f9226592aee15d140617de883673489e69274e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Apr 2019 11:36:59 +0200 Subject: [PATCH 0587/2188] Sortable --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5438d18de..d95b3698c 100644 --- a/README.md +++ b/README.md @@ -934,7 +934,7 @@ class MyHashable: ``` ### Sortable -* **With 'total_ordering' decorator you only need to provide one of lt(), gt(), le(), ge() magic methods.** +* **With 'total_ordering' decorator you only need to provide one of lt(), gt(), le() or ge() magic methods.** ```python from functools import total_ordering diff --git a/index.html b/index.html index cc10afcca..620688c8c 100644 --- a/index.html +++ b/index.html @@ -833,7 +833,7 @@

    Hashable

    Sortable

      -
    • With 'total_ordering' decorator you only need to provide one of lt(), gt(), le(), ge() magic methods.
    • +
    • With 'total_ordering' decorator you only need to provide one of lt(), gt(), le() or ge() magic methods.
    from functools import total_ordering
     
    
    From 3f2daf867ac12485de8ed6b6610be62db1eb287b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 16 Apr 2019 15:32:17 +0200
    Subject: [PATCH 0588/2188] Magic to special
    
    ---
     README.md  | 4 ++--
     index.html | 4 ++--
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/README.md b/README.md
    index d95b3698c..19e5d28bf 100644
    --- a/README.md
    +++ b/README.md
    @@ -872,7 +872,7 @@ class C(A, B): pass
     ```
     
     ### Dataclass
    -**Decorator that automatically generates init(), repr() and eq() magic methods.**
    +**Decorator that automatically generates init(), repr() and eq() special methods.**
     ```python
     from dataclasses import dataclass, field
     
    @@ -934,7 +934,7 @@ class MyHashable:
     ```
     
     ### Sortable
    -* **With 'total_ordering' decorator you only need to provide one of lt(), gt(), le() or ge() magic methods.**
    +* **With 'total_ordering' decorator you only need to provide one of lt(), gt(), le() or ge() special methods.**
     ```python
     from functools import total_ordering
     
    diff --git a/index.html b/index.html
    index 620688c8c..d88d1cc96 100644
    --- a/index.html
    +++ b/index.html
    @@ -777,7 +777,7 @@ 

    Multiple Inheritance

    [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]

    Dataclass

    -

    Decorator that automatically generates init(), repr() and eq() magic methods.

    +

    Decorator that automatically generates init(), repr() and eq() special methods.

    from dataclasses import dataclass, field
     
     @dataclass(order=False, frozen=False)
    @@ -833,7 +833,7 @@ 

    Hashable

    Sortable

      -
    • With 'total_ordering' decorator you only need to provide one of lt(), gt(), le() or ge() magic methods.
    • +
    • With 'total_ordering' decorator you only need to provide one of lt(), gt(), le() or ge() special methods.
    from functools import total_ordering
     
    
    From 570d951dd51d8c2a4e484bc5177a19f50e76db2a Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 16 Apr 2019 20:50:02 +0200
    Subject: [PATCH 0589/2188] Added back to top button
    
    ---
     index.html              | 47 ++++++++++++++++++++++++++++++++++++++++-
     web/jquery-3.4.0.min.js |  2 ++
     web/script_2.js         | 21 ++++++++++++++----
     web/template.html       | 47 ++++++++++++++++++++++++++++++++++++++++-
     4 files changed, 111 insertions(+), 6 deletions(-)
     create mode 100644 web/jquery-3.4.0.min.js
    
    diff --git a/index.html b/index.html
    index d88d1cc96..3ef2e5401 100644
    --- a/index.html
    +++ b/index.html
    @@ -7,6 +7,7 @@
       Comprehensive Python Cheatsheet
       
       
    +  
       
       
       
    @@ -141,6 +142,49 @@
       padding: 1em;
       white-space: pre-wrap;
     }
    +
    +#return-to-top {
    +    position: fixed;
    +    bottom: 20px;
    +    right: 20px;
    +    background: rgb(0, 0, 0);
    +    background: rgba(0, 0, 0, 0.2);
    +    width: 50px;
    +    height: 50px;
    +    display: block;
    +    text-decoration: none;
    +    -webkit-border-radius: 35px;
    +    -moz-border-radius: 35px;
    +    border-radius: 35px;
    +    display: none;
    +    -webkit-transition: all 0.3s linear;
    +    -moz-transition: all 0.3s ease;
    +    -ms-transition: all 0.3s ease;
    +    -o-transition: all 0.3s ease;
    +    transition: all 0.3s ease;
    +}
    +
    +#return-to-top i {
    +    color: #fff;
    +    margin: 0;
    +    position: relative;
    +    left: 16px;
    +    top: 13px;
    +    font-size: 19px;
    +    -webkit-transition: all 0.3s ease;
    +    -moz-transition: all 0.3s ease;
    +    -ms-transition: all 0.3s ease;
    +    -o-transition: all 0.3s ease;
    +    transition: all 0.3s ease;
    +}
    +
    +#return-to-top:hover {
    +    background: rgba(0, 0, 0, 0.85);
    +}
    +
    +#return-to-top:hover i {
    +    color: #ffffff;
    +}
     
     
     
    @@ -149,6 +193,7 @@
         
       
     
    +  
        

    Comprehensive Python Cheatsheet

    @@ -1817,7 +1862,7 @@

    + diff --git a/web/jquery-3.4.0.min.js b/web/jquery-3.4.0.min.js new file mode 100644 index 000000000..fe2fa1f11 --- /dev/null +++ b/web/jquery-3.4.0.min.js @@ -0,0 +1,2 @@ +/*! jQuery v3.4.0 | (c) JS Foundation and other contributors | jquery.org/license */ +!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],E=C.document,r=Object.getPrototypeOf,s=t.slice,g=t.concat,u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.4.0",k=function(e,t){return new k.fn.init(e,t)},p=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;function d(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp($),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+$),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),ne=function(e,t,n){var r="0x"+t-65536;return r!=r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(m.childNodes),m.childNodes),t[m.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&((e?e.ownerDocument||e:m)!==C&&T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&U.test(t)){(s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=k),o=(l=h(t)).length;while(o--)l[o]="#"+s+" "+xe(l[o]);c=l.join(","),f=ee.test(t)&&ye(e.parentNode)||e}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===k&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[k]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:m;return r!==C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),m!==C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=k,!C.getElementsByName||!C.getElementsByName(k).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+k+"-]").length||v.push("~="),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+k+"+*").length||v.push(".#.+[+~]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",$)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e===C||e.ownerDocument===m&&y(m,e)?-1:t===C||t.ownerDocument===m&&y(m,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e===C?-1:t===C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]===m?-1:s[r]===m?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if((e.ownerDocument||e)!==C&&T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=p[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&p(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?k.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?k.grep(e,function(e){return e===n!==r}):"string"!=typeof n?k.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(k.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||q,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:L.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof k?t[0]:t,k.merge(this,k.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),D.test(r[1])&&k.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(k):k.makeArray(e,this)}).prototype=k.fn,q=k(E);var H=/^(?:parents|prev(?:Until|All))/,O={children:!0,contents:!0,next:!0,prev:!0};function P(e,t){while((e=e[t])&&1!==e.nodeType);return e}k.fn.extend({has:function(e){var t=k(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ge={option:[1,""],thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&N(e,t)?k.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;nx",y.noCloneChecked=!!me.cloneNode(!0).lastChild.defaultValue;var Te=/^key/,Ce=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ee=/^([^.]*)(?:\.(.+)|)/;function ke(){return!0}function Se(){return!1}function Ae(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ne(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ne(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Se;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return k().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=k.guid++)),e.each(function(){k.event.add(this,t,i,r,n)})}function De(e,i,o){o?(Q.set(e,i,!1),k.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Q.get(this,i);if(1&e.isTrigger&&this[i]){if(r)(k.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Q.set(this,i,r),t=o(this,i),this[i](),r!==(n=Q.get(this,i))||t?Q.set(this,i,!1):n=void 0,r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n}else r&&(Q.set(this,i,k.event.trigger(k.extend(r.shift(),k.Event.prototype),r,this)),e.stopImmediatePropagation())}})):k.event.add(e,i,ke)}k.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.get(t);if(v){n.handler&&(n=(o=n).handler,i=o.selector),i&&k.find.matchesSelector(ie,i),n.guid||(n.guid=k.guid++),(u=v.events)||(u=v.events={}),(a=v.handle)||(a=v.handle=function(e){return"undefined"!=typeof k&&k.event.triggered!==e.type?k.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(R)||[""]).length;while(l--)d=g=(s=Ee.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=k.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=k.event.special[d]||{},c=k.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&k.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),k.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,v=Q.hasData(e)&&Q.get(e);if(v&&(u=v.events)){l=(t=(t||"").match(R)||[""]).length;while(l--)if(d=g=(s=Ee.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=k.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,v.handle)||k.removeEvent(e,d,v.handle),delete u[d])}else for(d in u)k.event.remove(e,d+t[l],n,r,!0);k.isEmptyObject(u)&&Q.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=k.event.fix(e),u=new Array(arguments.length),l=(Q.get(this,"events")||{})[s.type]||[],c=k.event.special[s.type]||{};for(u[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,qe=/\s*$/g;function Oe(e,t){return N(e,"table")&&N(11!==t.nodeType?t:t.firstChild,"tr")&&k(e).children("tbody")[0]||e}function Pe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Re(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Me(e,t){var n,r,i,o,a,s,u,l;if(1===t.nodeType){if(Q.hasData(e)&&(o=Q.access(e),a=Q.set(t,o),l=o.events))for(i in delete a.handle,a.events={},l)for(n=0,r=l[i].length;n")},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=oe(e);if(!(y.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||k.isXMLDoc(e)))for(a=ve(c),r=0,i=(o=ve(e)).length;r").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Vt,Gt=[],Yt=/(=)\?(?=&|$)|\?\?/;k.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Gt.pop()||k.expando+"_"+kt++;return this[e]=!0,e}}),k.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Yt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Yt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Yt,"$1"+r):!1!==e.jsonp&&(e.url+=(St.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||k.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?k(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Gt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Vt=E.implementation.createHTMLDocument("").body).innerHTML="
    ",2===Vt.childNodes.length),k.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=D.exec(e))?[t.createElement(i[1])]:(i=we([e],t,o),o&&o.length&&k(o).remove(),k.merge([],i.childNodes)));var r,i,o},k.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(k.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},k.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){k.fn[t]=function(e){return this.on(t,e)}}),k.expr.pseudos.animated=function(t){return k.grep(k.timers,function(e){return t===e.elem}).length},k.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=k.css(e,"position"),c=k(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=k.css(e,"top"),u=k.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,k.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},k.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){k.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===k.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===k.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=k(e).offset()).top+=k.css(e,"borderTopWidth",!0),i.left+=k.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-k.css(r,"marginTop",!0),left:t.left-i.left-k.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===k.css(e,"position"))e=e.offsetParent;return e||ie})}}),k.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;k.fn[t]=function(e){return _(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),k.each(["top","left"],function(e,n){k.cssHooks[n]=ze(y.pixelPosition,function(e,t){if(t)return t=_e(e,n),$e.test(t)?k(e).position()[n]+"px":t})}),k.each({Height:"height",Width:"width"},function(a,s){k.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){k.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return _(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?k.css(e,t,i):k.style(e,t,n,i)},s,n?e:void 0,n)}})}),k.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){k.fn[n]=function(e,t){return 0= 50) { // If page is scrolled more than 50px + $('#return-to-top').fadeIn(200); // Fade in the arrow + } else { + $('#return-to-top').fadeOut(200); // Else fade out the arrow + } +}); +$('#return-to-top').click(function() { // When arrow is clicked + $('body,html').animate({ + scrollTop : 0 // Scroll to top of body + }, 500); +}); diff --git a/web/template.html b/web/template.html index c63f5221e..d2f2521e1 100644 --- a/web/template.html +++ b/web/template.html @@ -7,6 +7,7 @@ Comprehensive Python Cheatsheet + @@ -141,6 +142,49 @@ padding: 1em; white-space: pre-wrap; } + +#return-to-top { + position: fixed; + bottom: 20px; + right: 20px; + background: rgb(0, 0, 0); + background: rgba(0, 0, 0, 0.2); + width: 50px; + height: 50px; + display: block; + text-decoration: none; + -webkit-border-radius: 35px; + -moz-border-radius: 35px; + border-radius: 35px; + display: none; + -webkit-transition: all 0.3s linear; + -moz-transition: all 0.3s ease; + -ms-transition: all 0.3s ease; + -o-transition: all 0.3s ease; + transition: all 0.3s ease; +} + +#return-to-top i { + color: #fff; + margin: 0; + position: relative; + left: 16px; + top: 13px; + font-size: 19px; + -webkit-transition: all 0.3s ease; + -moz-transition: all 0.3s ease; + -ms-transition: all 0.3s ease; + -o-transition: all 0.3s ease; + transition: all 0.3s ease; +} + +#return-to-top:hover { + background: rgba(0, 0, 0, 0.85); +} + +#return-to-top:hover i { + color: #ffffff; +} @@ -149,6 +193,7 @@ +
    @@ -159,7 +204,7 @@


    - + From 72b5ef34ae2799f5779502c3a2fb4dfaf82d5c29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Apr 2019 21:12:39 +0200 Subject: [PATCH 0590/2188] Back to top button --- index.html | 4 ++-- web/template.html | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/index.html b/index.html index 3ef2e5401..0a837f4e2 100644 --- a/index.html +++ b/index.html @@ -179,11 +179,11 @@ } #return-to-top:hover { - background: rgba(0, 0, 0, 0.85); + background: rgba(0, 0, 0, 0.55); } #return-to-top:hover i { - color: #ffffff; + color: #f0f0f0; } diff --git a/web/template.html b/web/template.html index d2f2521e1..f13e79c63 100644 --- a/web/template.html +++ b/web/template.html @@ -179,11 +179,11 @@ } #return-to-top:hover { - background: rgba(0, 0, 0, 0.85); + background: rgba(0, 0, 0, 0.55); } #return-to-top:hover i { - color: #ffffff; + color: #f0f0f0; } From 2b9f30a4be136b3edebcd3e0192be88fd8a75c48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Apr 2019 21:19:15 +0200 Subject: [PATCH 0591/2188] Button --- index.html | 2 +- web/script_2.js | 2 +- web/template.html | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/index.html b/index.html index 0a837f4e2..5024dbd4c 100644 --- a/index.html +++ b/index.html @@ -179,7 +179,7 @@ } #return-to-top:hover { - background: rgba(0, 0, 0, 0.55); + background: rgba(0, 0, 0, 0.35); } #return-to-top:hover i { diff --git a/web/script_2.js b/web/script_2.js index a71a8a35f..56d3ba764 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -54,7 +54,7 @@ if (!isFontAvailable('Menlo')) { // ===== Scroll to Top ==== $(window).scroll(function() { - if ($(this).scrollTop() >= 50) { // If page is scrolled more than 50px + if ($(this).scrollTop() >= 590) { // If page is scrolled more than 50px $('#return-to-top').fadeIn(200); // Fade in the arrow } else { $('#return-to-top').fadeOut(200); // Else fade out the arrow diff --git a/web/template.html b/web/template.html index f13e79c63..650074a07 100644 --- a/web/template.html +++ b/web/template.html @@ -179,7 +179,7 @@ } #return-to-top:hover { - background: rgba(0, 0, 0, 0.55); + background: rgba(0, 0, 0, 0.35); } #return-to-top:hover i { From 431244d137e7663e20cf1e81c77f1788fbc898e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Apr 2019 21:33:42 +0200 Subject: [PATCH 0592/2188] Removed button from nonmobile --- web/script_2.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/web/script_2.js b/web/script_2.js index 56d3ba764..bae24a73f 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -52,9 +52,16 @@ if (!isFontAvailable('Menlo')) { $('code:contains(ᴺᴱᵂ)').html(htmlString); } +var isMobile = false; //initiate as false +// device detection +if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) + || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0,4))) { + isMobile = true; +} + // ===== Scroll to Top ==== $(window).scroll(function() { - if ($(this).scrollTop() >= 590) { // If page is scrolled more than 50px + if (isMobile && $(this).scrollTop() >= 590) { // If mobile device and page is scrolled more than 590px. $('#return-to-top').fadeIn(200); // Fade in the arrow } else { $('#return-to-top').fadeOut(200); // Else fade out the arrow @@ -66,5 +73,3 @@ $('#return-to-top').click(function() { // When arrow is clicked scrollTop : 0 // Scroll to top of body }, 500); }); - - From 7dbaaf31055d712590bc267c13a6ea767bc5027f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Apr 2019 21:34:52 +0200 Subject: [PATCH 0593/2188] Button --- web/script_2.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/script_2.js b/web/script_2.js index bae24a73f..1b4a39077 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -61,7 +61,7 @@ if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine // ===== Scroll to Top ==== $(window).scroll(function() { - if (isMobile && $(this).scrollTop() >= 590) { // If mobile device and page is scrolled more than 590px. + if (isMobile && $(this).scrollTop() >= 520) { // If mobile device and page is scrolled more than 520px. $('#return-to-top').fadeIn(200); // Fade in the arrow } else { $('#return-to-top').fadeOut(200); // Else fade out the arrow From 72383f0fb67c00a3250fce18e72e175065fd076a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 16 Apr 2019 21:37:31 +0200 Subject: [PATCH 0594/2188] Button --- web/script_2.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/script_2.js b/web/script_2.js index 1b4a39077..93eca642a 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -61,7 +61,7 @@ if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine // ===== Scroll to Top ==== $(window).scroll(function() { - if (isMobile && $(this).scrollTop() >= 520) { // If mobile device and page is scrolled more than 520px. + if (isMobile && $(this).scrollTop() >= 480) { // If mobile device and page is scrolled more than 520px. $('#return-to-top').fadeIn(200); // Fade in the arrow } else { $('#return-to-top').fadeOut(200); // Else fade out the arrow From d333be7d7afe0cf28491a1ac235f595fe83b376a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 17 Apr 2019 15:18:34 +0200 Subject: [PATCH 0595/2188] Removed Using Abstract Syntax Trees --- README.md | 46 ---------------------------------------------- index.html | 44 +------------------------------------------- 2 files changed, 1 insertion(+), 89 deletions(-) diff --git a/README.md b/README.md index 19e5d28bf..0d0bb0fcf 100644 --- a/README.md +++ b/README.md @@ -1635,7 +1635,6 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') @@ -1646,51 +1645,6 @@ Eval ValueError: malformed node or string ``` -### Using Abstract Syntax Trees -```python -import ast -from ast import Num, BinOp, UnaryOp -import operator as op - -LEGAL_OPERATORS = {ast.Add: op.add, # + - ast.Sub: op.sub, # - - ast.Mult: op.mul, # * - ast.Div: op.truediv, # / - ast.Pow: op.pow, # ** - ast.BitXor: op.xor, # ^ - ast.USub: op.neg} # - - -def evaluate(expression): - root = ast.parse(expression, mode='eval') - return eval_node(root.body) - -def eval_node(node): - node_type = type(node) - if node_type == Num: - return node.n - if node_type not in [BinOp, UnaryOp]: - raise TypeError(node) - operator_type = type(node.op) - if operator_type not in LEGAL_OPERATORS: - raise TypeError(f'Illegal operator {node.op}') - operator = LEGAL_OPERATORS[operator_type] - if node_type == BinOp: - left, right = eval_node(node.left), eval_node(node.right) - return operator(left, right) - elif node_type == UnaryOp: - operand = eval_node(node.operand) - return operator(operand) -``` - -```python ->>> evaluate('2 ^ 6') -4 ->>> evaluate('2 ** 6') -64 ->>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)') --5.0 -``` - Coroutine --------- diff --git a/index.html b/index.html index 5024dbd4c..846cd204f 100644 --- a/index.html +++ b/index.html @@ -1387,7 +1387,6 @@

    #Operator

    last_el = op.methodcaller('pop')(<list>)

    #Eval

    -

    Basic

    >>> from ast import literal_eval
     >>> literal_eval('1 + 2')
     3
    @@ -1396,47 +1395,6 @@ 

    Basic

    >>> literal_eval('abs(1)') ValueError: malformed node or string
    -

    Using Abstract Syntax Trees

    -
    import ast
    -from ast import Num, BinOp, UnaryOp
    -import operator as op
    -
    -LEGAL_OPERATORS = {ast.Add:    op.add,      # <el> + <el>
    -                   ast.Sub:    op.sub,      # <el> - <el>
    -                   ast.Mult:   op.mul,      # <el> * <el>
    -                   ast.Div:    op.truediv,  # <el> / <el>
    -                   ast.Pow:    op.pow,      # <el> ** <el>
    -                   ast.BitXor: op.xor,      # <el> ^ <el>
    -                   ast.USub:   op.neg}      # - <el>
    -
    -def evaluate(expression):
    -    root = ast.parse(expression, mode='eval')
    -    return eval_node(root.body)
    -
    -def eval_node(node):
    -    node_type = type(node)
    -    if node_type == Num:
    -        return node.n
    -    if node_type not in [BinOp, UnaryOp]:
    -        raise TypeError(node)
    -    operator_type = type(node.op)
    -    if operator_type not in LEGAL_OPERATORS:
    -        raise TypeError(f'Illegal operator {node.op}')
    -    operator = LEGAL_OPERATORS[operator_type]
    -    if node_type == BinOp:
    -        left, right = eval_node(node.left), eval_node(node.right)
    -        return operator(left, right)
    -    elif node_type == UnaryOp:
    -        operand = eval_node(node.operand)
    -        return operator(operand)
    -
    -
    >>> evaluate('2 ^ 6')
    -4
    ->>> evaluate('2 ** 6')
    -64
    ->>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
    --5.0
    -

    #Coroutine

    • Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().
    • @@ -1626,7 +1584,7 @@

      Test:

      ['arsenal f.c.', 2.44, 3.29]

    #Profile

    -

    Basic

    +

    Basic

    from time import time
     start_time = time()  # Seconds since Epoch.
     ...
    
    From 5abe6e8e286ea5facf4736eaa37d4c8edc941192 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 17 Apr 2019 15:40:24 +0200
    Subject: [PATCH 0596/2188] Inline
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 0d0bb0fcf..f26755bf3 100644
    --- a/README.md
    +++ b/README.md
    @@ -692,7 +692,7 @@ point     = Point(0, 0)
     ```python
     from enum import Enum
     Direction = Enum('Direction', 'n e s w')
    -Cutlery   = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
    +direction = Direction.n
     ```
     
     ```python
    diff --git a/index.html b/index.html
    index 846cd204f..817b4d2fe 100644
    --- a/index.html
    +++ b/index.html
    @@ -680,7 +680,7 @@ 

    Namedtuple, Enum, Dataclass

    from enum import Enum
     Direction = Enum('Direction', 'n e s w')
    -Cutlery   = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
    +direction = Direction.n
     
    from dataclasses import make_dataclass
     Creature  = make_dataclass('Creature', ['location', 'direction'])
    
    From 913817d20d51d9cbaa75e495b2134cc782c3ddbb Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 17 Apr 2019 15:53:36 +0200
    Subject: [PATCH 0597/2188] Arguments
    
    ---
     README.md  | 6 +++---
     index.html | 6 +++---
     2 files changed, 6 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index f26755bf3..da02f0f27 100644
    --- a/README.md
    +++ b/README.md
    @@ -556,9 +556,9 @@ Arguments
     
     ### Inside Function Definition
     ```python
    -def f(): ...                  # def f(x, y)
    -def f(): ...                     # def f(x=0, y=0)
    -def f(, ): ...  # def f(x, y=0)
    +def f():                      # def f(x, y):
    +def f():                         # def f(x=0, y=0):
    +def f(, ):      # def f(x, y=0):
     ```
     
     
    diff --git a/index.html b/index.html
    index 817b4d2fe..eea9e1771 100644
    --- a/index.html
    +++ b/index.html
    @@ -588,9 +588,9 @@ 

    Inside Function Call

    <function>(<positional_args>, <keyword_args>) # f(0, y=0)

    Inside Function Definition

    -
    def f(<nondefault_args>): ...                  # def f(x, y)
    -def f(<default_args>): ...                     # def f(x=0, y=0)
    -def f(<nondefault_args>, <default_args>): ...  # def f(x, y=0)
    +
    def f(<nondefault_args>):                      # def f(x, y):
    +def f(<default_args>):                         # def f(x=0, y=0):
    +def f(<nondefault_args>, <default_args>):      # def f(x, y=0):
     

    #Splat Operator

    Inside Function Call

    From 8e006496e42d5cdb011364efca056a172045e5cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 17 Apr 2019 16:13:32 +0200 Subject: [PATCH 0598/2188] Dict --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index da02f0f27..77cc5b461 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ value = .setdefault(key, default=None) # Same, but also adds default to ``` ```python -.update() # Or: dict_a = {**dict_a, **dict_b}. +.update() = dict() # Creates a dict from coll. of key-value pairs. = dict(zip(keys, values)) # Creates a dict from two collections. = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys. diff --git a/index.html b/index.html index eea9e1771..838596c59 100644 --- a/index.html +++ b/index.html @@ -251,7 +251,7 @@

    #Dictionary

    <dict> = collections.defaultdict(<type>) # Creates a dict with default value of type. <dict> = collections.defaultdict(lambda: 1) # Creates a dict with default value 1.
    -
    <dict>.update(<dict>)                           # Or: dict_a = {**dict_a, **dict_b}.
    +
    <dict>.update(<dict>)
     <dict> = dict(<collection>)                     # Creates a dict from coll. of key-value pairs.
     <dict> = dict(zip(keys, values))                # Creates a dict from two collections.
     <dict> = dict.fromkeys(keys [, value])          # Creates a dict from collection of keys.
    
    From 0cf86939e31283e60d31dd41e73d1b85320283d5 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 17 Apr 2019 16:28:06 +0200
    Subject: [PATCH 0599/2188] Dict
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 77cc5b461..d708d4752 100644
    --- a/README.md
    +++ b/README.md
    @@ -1777,7 +1777,7 @@ logger.('A logging message.')
     ```python
     try:
         ...
    -except :
    +except :
         logger.exception('An error happened.')
     ```
     
    diff --git a/index.html b/index.html
    index 838596c59..f3b23fb25 100644
    --- a/index.html
    +++ b/index.html
    @@ -1499,7 +1499,7 @@ 

    Exceptions

    Error description, stack trace and values of variables are appended automatically.

    try:
         ...
    -except <Exception>:
    +except <exception>:
         logger.exception('An error happened.')
     

    Rotation

    From a5415219f60ea4466e8e477c5d2dc6c93d7ae46a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 17 Apr 2019 16:58:33 +0200 Subject: [PATCH 0600/2188] Synhtesizer --- README.md | 3 ++- index.html | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d708d4752..b2dd3bb03 100644 --- a/README.md +++ b/README.md @@ -2127,7 +2127,7 @@ frames_i = (add_noise(a) for a in read_wav_file('test.wav')) write_to_wav_file('test.wav', frames_i) ``` -#### Plays Popcorn: +### Synthesizer ```python # $ pip3 install simpleaudio import simpleaudio, math, struct @@ -2156,6 +2156,7 @@ Basic Script Template # from collections import namedtuple +from dataclasses import make_dataclass from enum import Enum import re import sys diff --git a/index.html b/index.html index f3b23fb25..53b13153c 100644 --- a/index.html +++ b/index.html @@ -1766,7 +1766,7 @@

    Adds noise to a mono WAV file:

    frames_i = (add_noise(a) for a in read_wav_file('test.wav')) write_to_wav_file('test.wav', frames_i)
    -

    Plays Popcorn:

    +

    Synthesizer

    # $ pip3 install simpleaudio
     import simpleaudio, math, struct
     from itertools import chain, repeat
    @@ -1790,6 +1790,7 @@ 

    # from collections import namedtuple +from dataclasses import make_dataclass from enum import Enum import re import sys From e1189d1b3809961e28a9e11f0dab797f05558da2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 17 Apr 2019 17:18:36 +0200 Subject: [PATCH 0601/2188] Google site verification --- index.html | 1 + web/template.html | 1 + 2 files changed, 2 insertions(+) diff --git a/index.html b/index.html index 53b13153c..c85417b03 100644 --- a/index.html +++ b/index.html @@ -12,6 +12,7 @@ + @@ -196,14 +205,13 @@ -

    Comprehensive Python Cheatsheet

    - - +

    Comprehensive Python Cheatsheet


    + + -

    #Contents

    -
    ToC = {
    +

    #Contents

    ToC = {
         '1. Collections': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],
         '2. Types':       [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],
         '3. Syntax':      [Args, Inline, Closure, Decorator, Class, Duck_Types, Enum, Exceptions],
    @@ -213,14 +221,15 @@ 

    Comprehensive Python Cheatsheet

    '7. Libraries': [Progress_Bar, Plot, Table, Curses, Logging, Scraping, Web, Profile, NumPy, Image, Audio] } -
    -

    #Main

    -
    if __name__ == '__main__':     # Runs main() if file wasn't imported.
    +
    + +

    #Main

    if __name__ == '__main__':     # Runs main() if file wasn't imported.
         main()
    -
    -

    #List

    -
    <list> = <list>[from_inclusive : to_exclusive : ±step_size]
    -
    +
    + +

    #List

    <list> = <list>[from_inclusive : to_exclusive : ±step_size]
    +
    +
    <list>.append(<el>)            # Or: <list> += [<el>]
     <list>.extend(<collection>)    # Or: <list> += <collection>
     
    @@ -243,11 +252,11 @@

    #List

    <list>.remove(<el>) # Removes first occurrence of item or raises ValueError. <list>.clear() # Removes all items. Also works on dict and set.
    -

    #Dictionary

    -
    <view> = <dict>.keys()                          # Coll. of keys that reflects changes.
    +

    #Dictionary

    <view> = <dict>.keys()                          # Coll. of keys that reflects changes.
     <view> = <dict>.values()                        # Coll. of values that reflects changes.
     <view> = <dict>.items()                         # Coll. of key-value tuples.
    -
    +
    +
    value  = <dict>.get(key, default=None)          # Returns default if key does not exist.
     value  = <dict>.setdefault(key, default=None)   # Same, but also adds default to dict.
     <dict> = collections.defaultdict(<type>)        # Creates a dict with default value of type.
    @@ -261,17 +270,17 @@ 

    #Dictionary

    value = <dict>.pop(key)                         # Removes item from dictionary.
     {k: v for k, v in <dict>.items() if k in keys}  # Filters dictionary by keys.
     
    -

    Counter

    -
    >>> from collections import Counter
    +

    Counter

    >>> from collections import Counter
     >>> colors = ['red', 'blue', 'yellow', 'blue', 'red', 'blue']
     >>> counter = Counter(colors)
     Counter({'blue': 3, 'red': 2, 'yellow': 1})
     >>> counter.most_common()[0]
     ('blue', 3)
    -
    -

    #Set

    -
    <set> = set()
    -
    +
    + +

    #Set

    <set> = set()
    +
    +
    <set>.add(<el>)                               # Or: <set> |= {<el>}
     <set>.update(<collection>)                    # Or: <set> |= <set>
     
    @@ -285,22 +294,20 @@

    #Set

    <set>.remove(<el>)                            # Raises KeyError.
     <set>.discard(<el>)                           # Doesn't raise an error.
     
    -

    Frozen Set

    -
      +

      Frozen Set

      • Is immutable and hashable.
      • That means it can be used as a key in a dictionary or as an element in a set.
      • -
      -
      <frozenset> = frozenset(<collection>)
      -
      -

      #Tuple

      -

      Tuple is an immutable and hashable list.

      -
      <tuple> = ()
      +
    <frozenset> = frozenset(<collection>)
    +
    + + +

    #Tuple

    Tuple is an immutable and hashable list.

    <tuple> = ()
     <tuple> = (<el>, )
     <tuple> = (<el_1>, <el_2>, ...)
    -
    -

    Named Tuple

    -

    Tuple's subclass with named elements.

    -
    >>> from collections import namedtuple
    +
    + + +

    Named Tuple

    Tuple's subclass with named elements.

    >>> from collections import namedtuple
     >>> Point = namedtuple('Point', 'x y')
     >>> p = Point(1, y=2)
     Point(x=1, y=2)
    @@ -312,27 +319,29 @@ 

    Named Tuple

    2 >>> p._fields # Or: Point._fields ('x', 'y') -
    -

    #Range

    -
    <range> = range(to_exclusive)
    +
    + + +

    #Range

    <range> = range(to_exclusive)
     <range> = range(from_inclusive, to_exclusive)
     <range> = range(from_inclusive, to_exclusive, ±step_size)
    -
    +
    +
    from_inclusive = <range>.start
     to_exclusive   = <range>.stop
     
    -

    #Enumerate

    -
    for i, el in enumerate(<collection> [, i_start]):
    +

    #Enumerate

    for i, el in enumerate(<collection> [, i_start]):
         ...
    -
    -

    #Iterator

    -
    <iter> = iter(<collection>)                 # Calling `iter(<iter>)` returns unmodified iterator.
    +
    + +

    #Iterator

    <iter> = iter(<collection>)                 # Calling `iter(<iter>)` returns unmodified iterator.
     <iter> = iter(<function>, to_exclusive)     # Sequence of return values until 'to_exclusive'.
     <el>   = next(<iter> [, default])           # Raises StopIteration or returns 'default' on end.
    -
    -

    Itertools

    -
    from itertools import count, repeat, cycle, chain, islice
    -
    +
    + +

    Itertools

    from itertools import count, repeat, cycle, chain, islice
    +
    +
    <iter> = count(start=0, step=1)             # Returns incremented value endlessly.
     <iter> = repeat(<el> [, times])             # Returns element endlessly or 'times' times.
     <iter> = cycle(<collection>)                # Repeats the sequence indefinitely.
    @@ -344,42 +353,42 @@ 

    Itertools

    <iter> = islice(<collection>, from_inclusive, to_exclusive) <iter> = islice(<collection>, from_inclusive, to_exclusive, +step_size)
    -

    #Generator

    -
      +

      #Generator

      • Convenient way to implement the iterator protocol.
      • Any function that contains a yield statement returns a generator object.
      • Generators and iterators are interchangeable.
      • -
      -
      def count(start, step):
      +
    def count(start, step):
         while True:
             yield start
             start += step
    -
    +
    + +
    >>> counter = count(10, 2)
     >>> next(counter), next(counter), next(counter)
     (10, 12, 14)
     
    -

    #Type

    -
      +

      #Type

      • Everything is an object.
      • Every object has a type.
      • Type and class are synonymous.
      • -
      -
      <type> = type(<el>)                # Or: <el>.__class__
      +
    <type> = type(<el>)                # Or: <el>.__class__
     <bool> = isinstance(<el>, <type>)  # Or: issubclass(type(<el>), <type>)
    -
    +
    + +
    >>> type('a'), 'a'.__class__, str
     (<class 'str'>, <class 'str'>, <class 'str'>)
     
    -

    Some types do not have builtin names, so they must be imported:

    -
    from types import FunctionType, MethodType, LambdaType, GeneratorType
    -
    -

    ABC

    -

    An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().

    -
    >>> from collections.abc import Sequence, Collection, Iterable
    +

    Some types do not have builtin names, so they must be imported:

    from types import FunctionType, MethodType, LambdaType, GeneratorType
    +
    + +

    ABC

    An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().

    >>> from collections.abc import Sequence, Collection, Iterable
     >>> isinstance([1, 2, 3], Iterable)
     True
    -
    +
    + +
    +------------------+----------+------------+----------+
     |                  | Sequence | Collection | Iterable |
     +------------------+----------+------------+----------+
    @@ -401,10 +410,10 @@ 

    ABC

    | complex | | | | yes | yes | +--------------------+----------+----------+------+---------+--------+
    -

    #String

    -
    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
    +

    #String

    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
     <str>  = <str>.strip('<chars>')              # Strips all passed characters from both ends.
    -
    +
    +
    <list> = <str>.split()                       # Splits on one or more whitespace characters.
     <list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
     <list> = <str>.splitlines(keepends=False)    # Splits on line breaks. Keeps them if 'keepends'.
    @@ -424,10 +433,10 @@ 

    #String

  • Also: 'lstrip()', 'rstrip()'.
  • Also: 'lower()', 'upper()', 'capitalize()' and 'title()'.
  • -

    Char

    -
    <str> = chr(<int>)  # Converts int to unicode char.
    +

    Char

    <str> = chr(<int>)  # Converts int to unicode char.
     <int> = ord(<str>)  # Converts unicode char to int.
    -
    +
    +
    >>> ord('0'), ord('9')
     (48, 57)
     >>> ord('A'), ord('Z')
    @@ -435,15 +444,15 @@ 

    Char

    >>> ord('a'), ord('z') (97, 122)
    -

    #Regex

    -
    import re
    +

    #Regex

    import re
     <str>   = re.sub(<regex>, new, text, count=0)  # Substitutes all occurrences.
     <list>  = re.findall(<regex>, text)            # Returns all occurrences.
     <list>  = re.split(<regex>, text, maxsplit=0)  # Use brackets in regex to keep the matches.
     <Match> = re.search(<regex>, text)             # Searches for first occurrence of pattern.
     <Match> = re.match(<regex>, text)              # Searches only at the beginning of the text.
     <iter>  = re.finditer(<regex>, text)           # Returns all occurrences as match objects.
    -
    +
    +
    • Argument 'flags=re.IGNORECASE' can be used with all functions.
    • Argument 'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.
    • @@ -451,65 +460,64 @@

      #Regex

    • Use r'\1' or '\\1' for backreference.
    • Use '?' to make an operator non-greedy.
    -

    Match Object

    -
    <str>   = <Match>.group()   # Whole match. Also group(0).
    +

    Match Object

    <str>   = <Match>.group()   # Whole match. Also group(0).
     <str>   = <Match>.group(1)  # Part in first bracket.
     <tuple> = <Match>.groups()  # All bracketed parts.
     <int>   = <Match>.start()   # Start index of a match.
     <int>   = <Match>.end()     # Exclusive end index of a match.
    -
    -

    Special Sequences

    -
      +
    + +

    Special Sequences

    • By default digits, whitespaces and alphanumerics from all alphabets are matched, unless 'flags=re.ASCII' argument is used.
    • Use capital letters for negation.
    • -
    -
    '\d' == '[0-9]'             # Digit
    +
    '\d' == '[0-9]'             # Digit
     '\s' == '[ \t\n\r\f\v]'     # Whitespace
     '\w' == '[a-zA-Z0-9_]'      # Alphanumeric
    -
    -

    #Format

    -
    <str> = f'{<el_1>}, {<el_2>}'
    +
    + + +

    #Format

    <str> = f'{<el_1>}, {<el_2>}'
     <str> = '{}, {}'.format(<el_1>, <el_2>)
    -
    -

    Attributes

    -
    >>> from collections import namedtuple
    +
    + +

    Attributes

    >>> from collections import namedtuple
     >>> Person = namedtuple('Person', 'name height')
     >>> person = Person('Jean-Luc', 187)
     >>> f'{person.height}'
     '187'
     >>> '{p.height}'.format(p=person)
     '187'
    -
    -

    General Options

    -
    {<el>:<10}       # '<el>      '
    +
    + +

    General Options

    {<el>:<10}       # '<el>      '
     {<el>:^10}       # '   <el>   '
     {<el>:>10}       # '      <el>'
    -
    +
    +
    {<el>:.<10}      # '<el>......'
     {<el>:>0}        # '<el>'
     
    -

    Strings

    -

    '!r' calls object's repr() method, instead of str(), to get a string.

    -
    {'abcde'!r:<10}  # "'abcde'   "
    +

    Strings

    '!r' calls object's repr() method, instead of str(), to get a string.

    {'abcde'!r:<10}  # "'abcde'   "
     {'abcde':.3}     # 'abc'
     {'abcde':10.3}   # 'abc       '
    -
    -

    Numbers

    -
    { 123456:10,}    # '   123,456'
    +
    + + +

    Numbers

    { 123456:10,}    # '   123,456'
     { 123456:10_}    # '   123_456'
     { 123456:+10}    # '   +123456'
     {-123456:=10}    # '-   123456'
     { 123456: }      # ' 123456'
     {-123456: }      # '-123456'
    -
    -

    Floats

    -
    {1.23456:10.3}   # '      1.23'
    +
    + +

    Floats

    {1.23456:10.3}   # '      1.23'
     {1.23456:10.3f}  # '     1.235'
     {1.23456:10.3e}  # ' 1.235e+00'
     {1.23456:10.3%}  # '  123.456%'
    -
    -

    Comparison of float presentation types:

    -
    +----------------+----------------+---------------+----------------+-----------------+
    +
    + +

    Comparison of float presentation types:

    +----------------+----------------+---------------+----------------+-----------------+
     |                |    {<float>}   |  {<float>:f}  |   {<float>:e}  |   {<float>:%}   |
     +----------------+----------------+---------------+----------------+-----------------+
     |    0.000056789 |   '5.6789e-05' |    '0.000057' | '5.678900e-05' |     '0.005679%' |
    @@ -521,7 +529,8 @@ 

    Comparison of float presentation typ | 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' | | 567.89 | '567.89' | '567.890000' | '5.678900e+02' | '56789.000000%' | +----------------+----------------+---------------+----------------+-----------------+ -

    +
    +
    +----------------+----------------+---------------+----------------+-----------------+
     |                |  {<float>:.2}  | {<float>:.2f} |  {<float>:.2e} |  {<float>:.2%}  |
     +----------------+----------------+---------------+----------------+-----------------+
    @@ -535,62 +544,62 @@ 

    Comparison of float presentation typ | 567.89 | '5.7e+02' | '567.89' | '5.68e+02' | '56789.00%' | +----------------+----------------+---------------+----------------+-----------------+

    -

    Ints

    -
    {90:c}           # 'Z'
    +

    Ints

    {90:c}           # 'Z'
     {90:X}           # '5A'
     {90:b}           # '1011010'
    -
    -

    #Numbers

    -
    <int>      = int(<float/str/bool>)    # Or: math.floor(<float>)
    +
    + +

    #Numbers

    <int>      = int(<float/str/bool>)    # Or: math.floor(<float>)
     <float>    = float(<int/str/bool>)
     <complex>  = complex(real=0, imag=0)  # Or: <real> + <real>j
     <Fraction> = fractions.Fraction(numerator=0, denominator=1)
    -
    +
    +
    • 'int(<str>)' and 'float(<str>)' raise 'ValueError' on malformed strings.
    -

    Basic Functions

    -
    <num>  = pow(<num>, <num>)            # Or: <num> ** <num>
    +

    Basic Functions

    <num>  = pow(<num>, <num>)            # Or: <num> ** <num>
     <real> = abs(<num>)
     <int>  = round(<real>)
     <real> = round(<real>, ±ndigits)      # `round(126, -1) == 130`
    -
    -

    Math

    -
    from math import e, pi, inf, nan
    +
    + +

    Math

    from math import e, pi, inf, nan
     from math import cos, acos, sin, asin, tan, atan, degrees, radians
     from math import log, log10, log2
    -
    -

    Statistics

    -
    from statistics import mean, median, variance, pvariance, pstdev
    -
    -

    Random

    -
    from random import random, randint, choice, shuffle
    +
    + +

    Statistics

    from statistics import mean, median, variance, pvariance, pstdev
    +
    + +

    Random

    from random import random, randint, choice, shuffle
     <float> = random()
     <int>   = randint(from_inclusive, to_inclusive)
     <el>    = choice(<list>)
     shuffle(<list>)
    -
    -

    Bin, Hex

    -
    <int>     = 0b<bin>            # Or: 0x<hex>
    +
    + +

    Bin, Hex

    <int>     = 0b<bin>            # Or: 0x<hex>
     <int>     = int('0b<bin>', 0)  # Or: int('0x<hex>', 0)
     <int>     = int('<bin>', 2)    # Or: int('<hex>', 16)
     '0b<bin>' = bin(<int>)         # Or: '0x<hex>' = hex(<int>)
    -
    -

    Bitwise Operators

    -
    <int>     = <int> & <int>      # And
    +
    + +

    Bitwise Operators

    <int>     = <int> & <int>      # And
     <int>     = <int> | <int>      # Or
     <int>     = <int> ^ <int>      # Xor (0 if both bits equal)
     <int>     = <int> << n_bits    # Shift left
     <int>     = <int> >> n_bits    # Shift right
     <int>     = ~<int>             # Compliment (flips bits)
    -
    -

    #Combinatorics

    -
      +
    + +

    #Combinatorics

    • Every function returns an iterator.
    • If you want to print the iterator, you need to pass it to the list() function!
    • -
    -
    from itertools import product, combinations, combinations_with_replacement, permutations
    -
    +
    from itertools import product, combinations, combinations_with_replacement, permutations
    +
    + +
    >>> 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)]
    @@ -612,111 +621,111 @@ 

    #Combin ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]

    -

    #Datetime

    -
      +

      #Datetime

      • Module 'datetime' provides 'date' <D>, 'time' <T>, 'datetime' <DT> and 'timedelta' <TD> classes. All are immutable and hashable.
      • Time and datetime can be 'aware' <a>, meaning they have defined timezone, or 'naive' <n>, meaning they don't.
      • If object is naive it is presumed to be in system's timezone.
      • -
      -
      from datetime import date, time, datetime, timedelta
      +
    from datetime import date, time, datetime, timedelta
     from dateutil.tz import UTC, tzlocal, gettz
    -
    -

    Constructors

    -
    <D>  = date(year, month, day)
    +
    + + +

    Constructors

    <D>  = date(year, month, day)
     <T>  = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
     <DT> = datetime(year, month, day, hour=0, minute=0, second=0, ...)
     <TD> = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0,
                      minutes=0, hours=0, weeks=0)
    -
    +
    +
    • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
    • 'fold=1' means second pass in case of time jumping back for one hour.
    -

    Now

    -
    <D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
    +

    Now

    <D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
     <DTn>    = DT.utcnow()                      # Naive datetime from current UTC time.
     <DTa>    = DT.now(<tzinfo>)                 # Aware datetime from current tz time.
    -
    +
    +
    • To extract time use '<DTn>.time()', '<DTa>.time()' or '<DTa>.timetz()'.
    -

    Timezone

    -
    <tzinfo> = UTC                              # UTC timezone. London without DST.
    +

    Timezone

    <tzinfo> = UTC                              # UTC timezone. London without DST.
     <tzinfo> = tzlocal()                        # Local timezone. Also gettz().
     <tzinfo> = gettz('<Cont.>/<City>')          # Timezone from 'Continent/City_Name' str.
    -
    +
    +
    <DTa>    = <DT>.astimezone(<tzinfo>)        # Datetime, converted to passed timezone.
     <Ta/DTa> = <T/DT>.replace(tzinfo=<tzinfo>)  # Unconverted object with new timezone.
     
    -

    Encode

    -
    <D/T/DT> = D/T/DT.fromisoformat('<iso>')    # Object from ISO string.
    +

    Encode

    <D/T/DT> = D/T/DT.fromisoformat('<iso>')    # Object from ISO string.
     <DT>     = DT.strptime(<str>, '<format>')   # Datetime from str, according to format.
     <D/DTn>  = D/DT.fromordinal(<int>)          # D/DTn from days since Christ, at midnight.
     <DTn>    = DT.fromtimestamp(<real>)         # Local time DTn from seconds since Epoch.
     <DTa>    = DT.fromtimestamp(<real>, <tz.>)  # Aware datetime from seconds since Epoch.
    -
    +
    +
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[±<offset>]', or both separated by 'T'. Offset is formatted as: 'HH:MM'.
    • On Unix systems Epoch is '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …
    -

    Decode

    -
    <str>    = <D/T/DT>.isoformat()             # ISO string representation.
    +

    Decode

    <str>    = <D/T/DT>.isoformat()             # ISO string representation.
     <str>    = <D/T/DT>.strftime('<format>')    # Custom string representation.
     <int>    = <D/DT>.toordinal()               # Days since Christ, ignoring time and tz.
     <float>  = <DTn>.timestamp()                # Seconds since Epoch from DTn in local time.
     <float>  = <DTa>.timestamp()                # Seconds since Epoch from DTa.
    -
    -

    Format

    -
    >>> from datetime import datetime
    +
    + +

    Format

    >>> from datetime import datetime
     >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
     >>> dt.strftime("%A, %dth of %B '%y, %I:%M%p %Z")
     "Thursday, 14th of May '15, 11:39PM UTC+02:00"
    -
    +
    +
    • For abbreviated weekday and month use '%a' and '%b'.
    • When parsing, '%z' also accepts '±HH:MM'.
    -

    Arithmetics

    -
    <D/DT>   = <D/DT> ±  <TD>
    +

    Arithmetics

    <D/DT>   = <D/DT> ±  <TD>
     <TD>     = <TD>   ±  <TD>
     <TD>     = <TD>   */ <real>
     <float>  = <TD>   /  <TD>
    -
    -

    #Arguments

    -

    Inside Function Call

    -
    <function>(<positional_args>)                  # f(0, 0)
    +
    + +

    #Arguments

    Inside Function Call

    <function>(<positional_args>)                  # f(0, 0)
     <function>(<keyword_args>)                     # f(x=0, y=0)
     <function>(<positional_args>, <keyword_args>)  # f(0, y=0)
    -
    -

    Inside Function Definition

    -
    def f(<nondefault_args>):                      # def f(x, y):
    +
    + + +

    Inside Function Definition

    def f(<nondefault_args>):                      # def f(x, y):
     def f(<default_args>):                         # def f(x=0, y=0):
     def f(<nondefault_args>, <default_args>):      # def f(x, y=0):
    -
    -

    #Splat Operator

    -

    Inside Function Call

    -

    Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.

    -
    args   = (1, 2)
    +
    + +

    #Splat Operator

    Inside Function Call

    Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.

    args   = (1, 2)
     kwargs = {'x': 3, 'y': 4, 'z': 5}
     func(*args, **kwargs)
    -
    -

    Is the same as:

    -
    func(1, 2, x=3, y=4, z=5)
    -
    -

    Inside Function Definition

    -

    Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.

    -
    def add(*a):
    +
    + + + +

    Is the same as:

    func(1, 2, x=3, y=4, z=5)
    +
    + +

    Inside Function Definition

    Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.

    def add(*a):
         return sum(a)
    -
    +
    + +
    >>> add(1, 2, 3)
     6
     
    -

    Legal argument combinations:

    -
    def f(x, y, z):                # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
    +

    Legal argument combinations:

    def f(x, y, z):                # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)
     def f(*, x, y, z):             # f(x=1, y=2, z=3)
     def f(x, *, y, z):             # f(x=1, y=2, z=3) | f(1, y=2, z=3)
     def f(x, y, *, z):             # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
    -
    +
    +
    def f(*args):                  # f(1, 2, 3)
     def f(x, *args):               # f(1, 2, 3)
     def f(*args, z):               # f(1, 2, z=3)
    @@ -731,54 +740,54 @@ 

    Legal argument combinations:

    def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)
    -

    Other Uses

    -
    <list>  = [*<collection> [, ...]]
    +

    Other Uses

    <list>  = [*<collection> [, ...]]
     <set>   = {*<collection> [, ...]}
     <tuple> = (*<collection>, [...])
     <dict>  = {**<dict> [, ...]}
    -
    +
    +
    head, *body, tail = <collection>
     
    -

    #Inline

    -

    Lambda

    -
    <function> = lambda: <return_value>
    +

    #Inline

    Lambda

    <function> = lambda: <return_value>
     <function> = lambda <argument_1>, <argument_2>: <return_value>
    -
    -

    Comprehension

    -
    <list> = [i+1 for i in range(10)]                   # [1, 2, ..., 10]
    +
    + + +

    Comprehension

    <list> = [i+1 for i in range(10)]                   # [1, 2, ..., 10]
     <set>  = {i for i in range(10) if i > 5}            # {6, 7, 8, 9}
     <iter> = (i+5 for i in range(10))                   # (5, 6, ..., 14)
     <dict> = {i: i*2 for i in range(10)}                # {0: 0, 1: 2, ..., 9: 18}
    -
    +
    +
    out = [i+j for i in range(10) for j in range(10)]
     
    -

    Is the same as:

    -
    out = []
    +

    Is the same as:

    out = []
     for i in range(10):
         for j in range(10):
             out.append(i+j)
    -
    -

    Map, Filter, Reduce

    -
    from functools import reduce
    +
    + +

    Map, Filter, Reduce

    from functools import reduce
     <iter> = map(lambda x: x + 1, range(10))            # (1, 2, ..., 10)
     <iter> = filter(lambda x: x > 5, range(10))         # (6, 7, 8, 9)
     <int>  = reduce(lambda out, x: out + x, range(10))  # 45
    -
    -

    Any, All

    -
    <bool> = any(<collection>)                          # False if empty.
    +
    + +

    Any, All

    <bool> = any(<collection>)                          # False if empty.
     <bool> = all(el[1] for el in <collection>)          # True if empty.
    -
    -

    If - Else

    -
    <expression_if_true> if <condition> else <expression_if_false>
    -
    +
    + +

    If - Else

    <expression_if_true> if <condition> else <expression_if_false>
    +
    +
    >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
     ['zero', 1, 'zero', 3]
     
    -

    Namedtuple, Enum, Dataclass

    -
    from collections import namedtuple
    +

    Namedtuple, Enum, Dataclass

    from collections import namedtuple
     Point     = namedtuple('Point', 'x y')
     point     = Point(0, 0)
    -
    +
    +
    from enum import Enum
     Direction = Enum('Direction', 'n e s w')
     direction = Direction.n
    @@ -787,17 +796,17 @@ 

    Namedtuple, Enum, Dataclass

    Creature = make_dataclass('Creature', ['location', 'direction']) creature = Creature(Point(0, 0), Direction.n)
    -

    #Closure

    -

    We have a closure in Python when:

    -
      +

      #Closure

      We have a closure in Python when:

      • A nested function references a value of its enclosing function and then
      • the enclosing function returns the nested function.
      • -
      -
      def get_multiplier(a):
      +
    def get_multiplier(a):
         def out(b):
             return a * b
         return out
    -
    +
    + + +
    >>> multiply_by_3 = get_multiplier(3)
     >>> multiply_by_3(10)
     30
    @@ -806,10 +815,10 @@ 

    #Closure

  • If multiple nested functions within enclosing function reference the same value, that value gets shared.
  • To dynamically access function's first free variable use '<function>.__closure__[0].cell_contents'.
  • -

    Partial

    -
    from functools import partial
    +

    Partial

    from functools import partial
     <function> = partial(<function> [, <arg_1>, <arg_2>, ...])
    -
    +
    +
    >>> import operator as op
     >>> multiply_by_3 = partial(op.mul, 3)
     >>> multiply_by_3(10)
    @@ -819,29 +828,27 @@ 

    Partial

  • Partial is also useful in cases when a function needs to be passed as an argument, because it enables us to set its arguments beforehand.
  • A few examples being 'defaultdict(<function>)', 'iter(<function>, to_exclusive)' and dataclass's 'field(default_factory=<function>)'.
  • -

    Nonlocal

    -

    If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.

    -
    def get_counter():
    +

    Nonlocal

    If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.

    def get_counter():
         i = 0
         def out():
             nonlocal i
             i += 1
             return i
         return out
    -
    +
    + +
    >>> counter = get_counter()
     >>> counter(), counter(), counter()
     (1, 2, 3)
     
    -

    #Decorator

    -

    A decorator takes a function, adds some functionality and returns it.

    -
    @decorator_name
    +

    #Decorator

    A decorator takes a function, adds some functionality and returns it.

    @decorator_name
     def function_that_gets_passed_to_decorator():
         ...
    -
    -

    Debugger Example

    -

    Decorator that prints function's name every time it gets called.

    -
    from functools import wraps
    +
    + + +

    Debugger Example

    Decorator that prints function's name every time it gets called.

    from functools import wraps
     
     def debug(func):
         @wraps(func)
    @@ -853,25 +860,25 @@ 

    Debugger Example

    @debug def add(x, y): return x + y -
    +
    + +
    • Wraps is a helper decorator that copies metadata of function add() to function out().
    • Without it 'add.__name__' would return 'out'.
    -

    LRU Cache

    -

    Decorator that caches function's return values. All function's arguments must be hashable.

    -
    from functools import lru_cache
    +

    LRU Cache

    Decorator that caches function's return values. All function's arguments must be hashable.

    from functools import lru_cache
     
     @lru_cache(maxsize=None)
     def fib(n):
         return n if n < 2 else fib(n-2) + fib(n-1)
    -
    +
    + +
    • Recursion depth is limited to 1000 by default. To increase it use 'sys.setrecursionlimit(<depth>)'.
    -

    Parametrized Decorator

    -

    A decorator that accepts arguments and returns a normal decorator that accepts a function.

    -
    from functools import wraps
    +

    Parametrized Decorator

    A decorator that accepts arguments and returns a normal decorator that accepts a function.

    from functools import wraps
     
     def debug(print_result=False):
         def decorator(func):
    @@ -886,9 +893,10 @@ 

    Parametrized Decorator

    @debug(print_result=True) def add(x, y): return x + y -
    -

    #Class

    -
    class <name>:
    +
    + + +

    #Class

    class <name>:
         def __init__(self, a):
             self.a = a
         def __repr__(self):
    @@ -900,32 +908,32 @@ 

    #Class

    @classmethod def get_class_name(cls): return cls.__name__ -
    +
    +
    • Return value of repr() should be unambiguous and of str() readable.
    • If only repr() is defined, it will be also used for str().
    -

    Str() use cases:

    -
    print(<el>)
    +

    Str() use cases:

    print(<el>)
     print(f'{<el>}')
     raise Exception(<el>)
     logging.debug(<el>)
     csv.writer(<file>).writerow([<el>])
    -
    -

    Repr() use cases:

    -
    print([<el>])
    +
    + +

    Repr() use cases:

    print([<el>])
     print(f'{<el>!r}')
     >>> <el>
     loguru.logger.exception()
     Z = dataclasses.make_dataclass('Z', ['a']); print(Z(<el>))
    -
    -

    Constructor Overloading

    -
    class <name>:
    +
    + +

    Constructor Overloading

    class <name>:
         def __init__(self, a=None):
             self.a = a
    -
    -

    Inheritance

    -
    class Person:
    +
    + +

    Inheritance

    class Person:
         def __init__(self, name, age):
             self.name = name
             self.age  = age
    @@ -934,18 +942,18 @@ 

    Inheritance

    def __init__(self, name, age, staff_num): super().__init__(name, age) self.staff_num = staff_num -
    -

    Multiple Inheritance

    -
    class A: pass
    +
    + +

    Multiple Inheritance

    class A: pass
     class B: pass
     class C(A, B): pass
    -
    +
    +

    MRO determines the order in which parent classes are traversed when searching for a method:

    >>> C.mro()
     [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
     
    -

    Property

    -
    class MyClass:
    +

    Property

    class MyClass:
         @property
         def a(self):
             return self._a
    @@ -953,62 +961,61 @@ 

    Property

    @a.setter def a(self, value): self._a = value -
    +
    +
    >>> el = MyClass()
     >>> el.a = 123
     >>> el.a
     123
     
    -

    Dataclass

    -

    Decorator that automatically generates init(), repr() and eq() special methods.

    -
    from dataclasses import dataclass, field
    +

    Dataclass

    Decorator that automatically generates init(), repr() and eq() special methods.

    from dataclasses import dataclass, field
     
     @dataclass(order=False, frozen=False)
     class <class_name>:
         <attr_name_1>: <type>
         <attr_name_2>: <type> = <default_value>
         <attr_name_3>: list/dict/set = field(default_factory=list/dict/set)
    -
    +
    + +
    • An object can be made sortable with 'order=True' or immutable with 'frozen=True'.
    • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances.
    • Default_factory can be any callable.
    -

    Slots

    -

    Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.

    -
    class MyClassWithSlots:
    +

    Slots

    Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.

    class MyClassWithSlots:
         __slots__ = ['a']
         def __init__(self):
             self.a = 1
    -
    -

    Copy

    -
    from copy import copy, deepcopy
    +
    + + +

    Copy

    from copy import copy, deepcopy
     <object> = copy(<object>)
     <object> = deepcopy(<object>)
    -
    -

    #Duck Types

    -

    A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.

    -

    Comparable

    -
      +
    + +

    #Duck Types

    A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.

    Comparable

    • If eq() method is not overridden, it returns 'id(self) == id(other)', which is the same as 'self is other'.
    • That means all objects compare not equal by default.
    • Only left side object has eq() method called, unless it returns 'NotImplemented', in which case the right object is consulted.
    • -
    -
    class MyComparable:
    +
    class MyComparable:
         def __init__(self, a):
             self.a = a
         def __eq__(self, other):
             if isinstance(other, type(self)):
                 return self.a == other.a
             return NotImplemented
    -
    -

    Hashable

    -
      +
    + + + + +

    Hashable

    • Hashable object needs both hash() and eq() methods and its hash value should never change.
    • Hashable objects that compare equal must have the same hash value, meaning default hash() that returns 'id(self)' will not do.
    • That is why Python automatically makes classes unhashable if you only implement eq().
    • -
    -
    class MyHashable:
    +
    class MyHashable:
         def __init__(self, a):
             self._a = copy.deepcopy(a)
         @property
    @@ -1020,12 +1027,12 @@ 

    Hashable

    return NotImplemented def __hash__(self): return hash(self.a) -
    -

    Sortable

    -
      +
    + + +

    Sortable

    • With 'total_ordering' decorator you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.
    • -
    -
    from functools import total_ordering
    +
    from functools import total_ordering
     
     @total_ordering
     class MySortable:
    @@ -1039,13 +1046,13 @@ 

    Sortable

    if isinstance(other, type(self)): return self.a < other.a return NotImplemented -
    -

    Iterator

    -
      +
    + + +

    Iterator

    • Next() should return next item or raise 'StopIteration'.
    • Iter() should return 'self'.
    • -
    -
    class Counter:
    +
    class Counter:
         def __init__(self):
             self.i = 0
         def __next__(self):
    @@ -1053,25 +1060,26 @@ 

    Iterator

    return self.i def __iter__(self): return self -
    +
    + +
    >>> counter = Counter()
     >>> next(counter), next(counter), next(counter)
     (1, 2, 3)
     
    -

    Callable

    -
    class Counter:
    +

    Callable

    class Counter:
         def __init__(self):
             self.i = 0
         def __call__(self):
             self.i += 1
             return self.i
    -
    +
    +
    >>> counter = Counter()
     >>> counter(), counter(), counter()
     (1, 2, 3)
     
    -

    Context Manager

    -
    class MyOpen():
    +

    Context Manager

    class MyOpen():
         def __init__(self, filename):
             self.filename = filename
         def __enter__(self):
    @@ -1079,46 +1087,45 @@ 

    Context Manager

    return self.file def __exit__(self, *args): self.file.close() -
    +
    +
    >>> with open('test.txt', 'w') as file:
     ...     file.write('Hello World!')
     >>> with MyOpen('test.txt') as file:
     ...     print(file.read())
     Hello World!
     
    -

    List of existing context managers:

    -
    with open('<path>', ...) as file: ...
    +

    List of existing context managers:

    with open('<path>', ...) as file: ...
     with wave.open('<path>', ...) as wave_file: ...
     with memoryview(<bytes/bytearray/array>) as view: ...
     db = sqlite3.connect('<path>'); with db: db.execute('<insert_query>')
     lock = threading.RLock(); with lock: ...
    -
    -

    #Iterable Duck Types

    -

    Iterable

    -
      +
    + +

    #Iterable Duck Types

    Iterable

    • Only required method is iter(). It should return an iterator of object's items.
    • Contains() automatically works on any object that has iter() defined.
    • -
    -
    class MyIterable:
    +
    class MyIterable:
         def __init__(self, a):
             self.a = a
         def __iter__(self):
             for el in self.a:
                 yield el
    -
    +
    + + +
    >>> a = MyIterable([1, 2, 3])
     >>> iter(a)
     <generator object MyIterable.__iter__ at 0x1026c18b8>
     >>> 1 in a
     True
     
    -

    Collection

    -
      +

      Collection

      • Only required methods are iter() and len().
      • This cheatsheet actually means '<iterable>' when it uses '<collection>'.
      • I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.
      • -
      -
      class MyCollection:
      +
    class MyCollection:
         def __init__(self, a):
             self.a = a
         def __iter__(self):
    @@ -1127,15 +1134,15 @@ 

    Collection

    return el in self.a def __len__(self): return len(self.a) -
    -

    Sequence

    -
      +
    + + +

    Sequence

    • Only required methods are len() and getitem().
    • Getitem() should return an item at index or raise 'IndexError'.
    • Iter() and contains() automatically work on any object that has getitem() defined.
    • Reversed() automatically works on any object that has getitem() and len() defined.
    • -
    -
    class MySequence:
    +
    class MySequence:
         def __init__(self, a):
             self.a = a
         def __iter__(self):
    @@ -1148,23 +1155,24 @@ 

    Sequence

    return self.a[i] def __reversed__(self): return reversed(self.a) -
    -

    Collections.abc.Sequence

    -
      +
    + + +

    Collections.abc.Sequence

    • It's a richer interface than the basic sequence.
    • Extending it generates iter(), contains(), reversed(), index(), and count().
    • Unlike 'abc.Iterable' and 'abc.Collection', it is not a duck type. That is why 'issubclass(MySequence, collections.abc.Sequence)' would return 'False' even if 'MySequence' had all the methods defined.
    • -
    -
    class MyAbcSequence(collections.abc.Sequence):
    +
    class MyAbcSequence(collections.abc.Sequence):
         def __init__(self, a):
             self.a = a
         def __len__(self):
             return len(self.a)
         def __getitem__(self, i):
             return self.a[i]
    -
    -

    Table of required and available special methods:

    -
    +------------+----------+------------+----------+--------------+
    +
    + + +

    Table of required and available special methods:

    +------------+----------+------------+----------+--------------+
     |            | Iterable | Collection | Sequence | abc.Sequence |
     +------------+----------+------------+----------+--------------+
     | iter()     |   REQ    |    REQ     |   yes    |     yes      |
    @@ -1175,12 +1183,12 @@ 

    Table of required and availab | index() | | | | yes | | count() | | | | yes | +------------+----------+------------+----------+--------------+ -

    +
    +
    • Other useful ABCs that automatically generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.
    -

    #Enum

    -
    from enum import Enum, auto
    +

    #Enum

    from enum import Enum, auto
     
     class <enum_name>(Enum):
         <member_name_1> = <value_1>
    @@ -1190,7 +1198,8 @@ 

    #Enum

    @classmethod def get_member_names(cls): return [a.name for a in cls.__members__.values()] -
    +
    +
    • If there are no numeric values before auto(), it returns 1.
    • Otherwise it returns an increment of last numeric value.
    • @@ -1206,29 +1215,28 @@

      #Enum

      member_values = [a.value for a in <enum>] random_member = random.choice(list(<enum>))
    -

    Inline

    -
    Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
    +

    Inline

    Cutlery = Enum('Cutlery', ['fork', 'knife', 'spoon'])
     Cutlery = Enum('Cutlery', 'fork knife spoon')
     Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3})
    -
    -

    Functions can not be values, so they must be wrapped:

    -
    from functools import partial
    +
    + +

    Functions can not be values, so they must be wrapped:

    from functools import partial
     LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
                                'OR' : partial(lambda l, r: l or r)})
    -
    +
    +
    • Another solution in this particular case, is to use 'and_' and 'or_' functions from module Operator.
    -

    #Exceptions

    -

    Basic Example

    -
    try:
    +

    #Exceptions

    Basic Example

    try:
         <code>
     except <exception>:
         <code>
    -
    -

    Complex Example

    -
    try:
    -    <code_1>
    +
    + + +

    Complex Example

    try:
    +    <code_1>
     except <exception_a>:
         <code_2_a>
     except <exception_b>:
    @@ -1237,34 +1245,34 @@ 

    Complex Example

    <code_2_c> finally: <code_3> -
    -

    Catching Exceptions

    -
    except <exception>:
    +
    + +

    Catching Exceptions

    except <exception>:
     except <exception> as <name>:
     except (<exception_1>, <exception_2>, ...):
     except (<exception_1>, <exception_2>, ...) as <name>:
    -
    +
    +
    • Also catches subclasses of the exception.
    -

    Raising Exceptions

    -
    raise <exception>
    +

    Raising Exceptions

    raise <exception>
     raise <exception>()
     raise <exception>(<el>)
     raise <exception>(<el_1>, <el_2>, ...)
    -
    -

    Useful built-in exceptions:

    -
    raise ValueError('Argument is of right type but inappropriate value!')
    +
    + +

    Useful built-in exceptions:

    raise ValueError('Argument is of right type but inappropriate value!')
     raise TypeError('Argument is of wrong type!')
     raise RuntimeError('None of above!')
    -
    -

    Re-raising caught exception:

    -
    except <exception>:
    +
    + +

    Re-raising caught exception:

    except <exception>:
         <code>
         raise
    -
    -

    Common Built-in Exceptions

    -
    BaseException
    +
    + +

    Common Built-in Exceptions

    BaseException
      +-- SystemExit                   # Raised by the sys.exit() function.
      +-- KeyboardInterrupt            # Raised when the user hits the interrupt key.
      +-- Exception                    # User-defined exceptions should be derived from this class.
    @@ -1284,50 +1292,50 @@ 

    Common Built-in Exceptions

    +-- TypeError # Raised when an argument is of wrong type. +-- ValueError # When an argument is of right type but inappropriate value. +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails. -
    -

    User-defined Exceptions

    -
    class MyError(Exception):
    +
    + +

    User-defined Exceptions

    class MyError(Exception):
         pass
     
     class MyInputError(MyError):
         pass
    -
    -

    #Print

    -
    print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    -
    +
    + +

    #Print

    print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    +
    +
    • Use 'file=sys.stderr' for errors.
    • Use 'flush=True' to forcibly flush the stream.
    -

    Pretty Print

    -
    >>> from pprint import pprint
    +

    Pretty Print

    >>> from pprint import pprint
     >>> pprint(dir())
     ['__annotations__',
      '__builtins__',
      '__doc__', ...]
    -
    -

    #Input

    -
      +
    + +

    #Input

    • Reads a line from user input or pipe if present.
    • Trailing newline gets stripped.
    • Prompt string is printed to the standard output before reading input.
    • -
    -
    <str> = input(prompt=None)
    -
    -

    Prints lines until EOF:

    -
    while True:
    +
    <str> = input(prompt=None)
    +
    + + +

    Prints lines until EOF:

    while True:
         try:
             print(input())
         except EOFError:
             break
    -
    -

    #Command Line Arguments

    -
    import sys
    +
    + +

    #Command Line Arguments

    import sys
     script_name = sys.argv[0]
     arguments   = sys.argv[1:]
    -
    -

    Argparse

    -
    from argparse import ArgumentParser, FileType
    +
    + +

    Argparse

    from argparse import ArgumentParser, FileType
     p = ArgumentParser(description=<str>)
     p.add_argument('-<short_name>', '--<name>', action='store_true')  # Flag
     p.add_argument('-<short_name>', '--<name>', type=<type>)          # Option
    @@ -1335,22 +1343,22 @@ 

    Argparse

    p.add_argument('<name>', type=<type>, nargs='+') # Arguments args = p.parse_args() value = args.<name> -
    +
    +
    • Use 'help=<str>' for argument description.
    • Use 'type=FileType(<mode>)' for files.
    -

    #Open

    -

    Opens a file and returns a corresponding file object.

    -
    <file> = open('<path>', mode='r', encoding=None, newline=None)
    -
    +

    #Open

    Opens a file and returns a corresponding file object.

    <file> = open('<path>', mode='r', encoding=None, newline=None)
    +
    + +
    • 'encoding=None' means default encoding is used, which is platform dependent. Best practice is to use 'encoding="utf-8"' whenever possible.
    • 'newline=None' means all different end of line combinations are converted to '\n' on read, while on write all '\n' characters are converted to system's default line separator.
    • 'newline=""' means no conversions take place, but lines are still broken by readline() on either '\n', '\r' or '\r\n'.
    -

    Modes

    -
      +

      Modes

      • 'r' - Read (default).
      • 'w' - Write (truncate).
      • 'x' - Write or fail if the file already exists.
      • @@ -1360,20 +1368,21 @@

        Modes

      • 'a+' - Read and write from the end.
      • 't' - Text mode (default).
      • 'b' - Binary mode.
      • -
      -

      Exceptions

      -
        +

      Exceptions

      • 'FileNotFoundError' can be risen when reading with 'r' or 'r+'.
      • 'FileExistsError' can be risen when writing with 'x'.
      • 'IsADirectoryError' and 'PermissionError' can be risen by any.
      • 'OSError' is the parent class of all listed exceptions.
      • -
      -

      File

      -
      <file>.seek(0)                      # Moves to the start of the file.
      +

    File

    <file>.seek(0)                      # Moves to the start of the file.
     <file>.seek(offset)                 # Moves 'offset' chars/bytes from the start.
     <file>.seek(0, 2)                   # Moves to the end of the file.
     <bin_file>.seek(±offset, <anchor>)  # Anchor: 0 start, 1 current pos., 2 end.
    -
    +
    + + + + +
    <str/bytes> = <file>.read(size=-1)  # Reads 'size' chars/bytes or until EOF.
     <str/bytes> = <file>.readline()     # Returns a line or empty string on EOF.
     <list>      = <file>.readlines()    # Returns a list of lines or empty list.
    @@ -1386,20 +1395,20 @@ 

    File

    • Methods do not add or strip trailing newlines, even writelines().
    -

    Read Text from File

    -
    def read_file(filename):
    +

    Read Text from File

    def read_file(filename):
         with open(filename, encoding='utf-8') as file:
             return file.readlines()
    -
    -

    Write Text to File

    -
    def write_to_file(filename, text):
    +
    + +

    Write Text to File

    def write_to_file(filename, text):
         with open(filename, 'w', encoding='utf-8') as file:
             file.write(text)
    -
    -

    #Path

    -
    from os import path, listdir
    +
    + +

    #Path

    from os import path, listdir
     from glob import glob
    -
    +
    +
    <bool> = path.exists('<path>')
     <bool> = path.isfile('<path>')
     <bool> = path.isdir('<path>')
    @@ -1407,9 +1416,9 @@ 

    #Path

    <list> = listdir('<path>')         # List of filenames located at 'path'.
     <list> = glob('<pattern>')         # Filenames matching the wildcard pattern.
     
    -

    Pathlib

    -
    from pathlib import Path
    -
    +

    Pathlib

    from pathlib import Path
    +
    +
    cwd    = Path()
     <Path> = Path('<path>' [, '<path>', <Path>, ...])
     <Path> = <Path> / '<dir>' / '<file>'
    @@ -1430,16 +1439,16 @@ 

    Pathlib

    <str> = <Path>.suffix # Final component's extension. <Path> = <Path>.parent # Path without final component.
    -

    #Command Execution

    -

    Files and Directories

    -
      +

      #Command Execution

      Files and Directories

      • Paths can be either strings or Path objects.
      • All exceptions are either 'OSError' or its subclasses.
      • -
      -
      import os
      +
    import os
     <str> = os.getcwd()                # Returns the current working directory.
     os.chdir(<path>)                   # Changes the current working directory.
    -
    +
    + + +
    os.remove(<path>)                  # Deletes the file.
     os.rmdir(<path>)                   # Deletes empty directory.
     shutil.rmtree(<path>)              # Deletes the entire directory tree.
    @@ -1450,32 +1459,32 @@ 

    Files and Directories

    os.mkdir(<path>, mode=0o777)       # Creates a directory.
     <iter> = os.scandir(path='.')      # Returns os.DirEntry objects located at path.
     
    -

    DirEntry:

    -
    <str>  = <DirEntry>.name           # Final component of the path.
    +

    DirEntry:

    <str>  = <DirEntry>.name           # Final component of the path.
     <str>  = <DirEntry>.path           # Path with final component.
     <Path> = Path(<DirEntry>)          # Path object.
    -
    +
    +
    <bool> = <DirEntry>.is_file()
     <bool> = <DirEntry>.is_dir()
     <bool> = <DirEntry>.is_symlink()
     
    -

    Shell Commands

    -
    import os
    +

    Shell Commands

    import os
     <str> = os.popen('<shell_command>').read()
    -
    -

    Using subprocess:

    -
    >>> import subprocess, shlex
    +
    + +

    Using subprocess:

    >>> import subprocess, shlex
     >>> a = subprocess.run(shlex.split('ls -a'), stdout=subprocess.PIPE)
     >>> a.stdout
     b'.\n..\nfile1.txt\nfile2.txt\n'
     >>> a.returncode
     0
    -
    -

    #CSV

    -
    import csv
    +
    + +

    #CSV

    import csv
     <reader> = csv.reader(<file>, dialect='excel', delimiter=',')
     <list>   = next(<reader>)        # Returns a row as list of strings.
    -
    +
    +
    <writer> = csv.writer(<file>, dialect='excel', delimiter=',')
     <writer>.writerow(<collection>)  # Encodes objects using `str(<el>)`.
     <writer>.writerows(<coll_of_coll>)
    @@ -1483,8 +1492,7 @@ 

    #CSV

    • File must be opened with 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!
    -

    Parameters

    -
      +

      Parameters

      • 'dialect' - Master parameter that sets the default values.
      • 'delimiter' - A one-character string used to separate fields.
      • 'quotechar' - Character for quoting fields that contain special characters.
      • @@ -1493,9 +1501,7 @@

        Parameters

      • 'lineterminator' - How does writer terminate lines.
      • 'quoting' - Controls the amount of quoting: 0 - as necessary, 1 - all.
      • 'escapechar' - Character for escaping quotechar if doublequote is false.
      • -
      -

      Dialects

      -
      +------------------+-----------+-----------+--------------+
      +

    Dialects

    +------------------+-----------+-----------+--------------+
     |                  |   excel   | excel_tab | unix_dialect |
     +------------------+-----------+-----------+--------------+
     | delimiter        |      ','  |     '\t'  |       ','    |
    @@ -1506,172 +1512,175 @@ 

    Dialects

    | quoting | 0 | 0 | 1 | | escapechar | None | None | None | +------------------+-----------+-----------+--------------+ -
    -

    Read Rows from CSV File

    -
    def read_csv_file(filename):
    +
    + + + +

    Read Rows from CSV File

    def read_csv_file(filename):
         with open(filename, encoding='utf-8', newline='') as file:
             return csv.reader(file)
    -
    -

    Write Rows to CSV File

    -
    def write_to_csv_file(filename, rows):
    +
    + +

    Write Rows to CSV File

    def write_to_csv_file(filename, rows):
         with open(filename, 'w', encoding='utf-8', newline='') as file:
             writer = csv.writer(file)
             writer.writerows(rows)
    -
    -

    #JSON

    -
    import json
    +
    + +

    #JSON

    import json
     <str>    = json.dumps(<object>, ensure_ascii=True, indent=None)
     <object> = json.loads(<str>)
    -
    -

    Read Object from JSON File

    -
    def read_json_file(filename):
    +
    + +

    Read Object from JSON File

    def read_json_file(filename):
         with open(filename, encoding='utf-8') as file:
             return json.load(file)
    -
    -

    Write Object to JSON File

    -
    def write_to_json_file(filename, an_object):
    +
    + +

    Write Object to JSON File

    def write_to_json_file(filename, an_object):
         with open(filename, 'w', encoding='utf-8') as file:
             json.dump(an_object, file, ensure_ascii=False, indent=2)
    -
    -

    #Pickle

    -
    import pickle
    +
    + +

    #Pickle

    import pickle
     <bytes>  = pickle.dumps(<object>)
     <object> = pickle.loads(<bytes>)
    -
    -

    Read Object from File

    -
    def read_pickle_file(filename):
    +
    + +

    Read Object from File

    def read_pickle_file(filename):
         with open(filename, 'rb') as file:
             return pickle.load(file)
    -
    -

    Write Object to File

    -
    def write_to_pickle_file(filename, an_object):
    +
    + +

    Write Object to File

    def write_to_pickle_file(filename, an_object):
         with open(filename, 'wb') as file:
             pickle.dump(an_object, file)
    -
    -

    #SQLite

    -

    Server-less database engine that stores each database into separate file.

    -
    import sqlite3
    +
    + +

    #SQLite

    Server-less database engine that stores each database into separate file.

    import sqlite3
     db = sqlite3.connect('<path>')                # Also ':memory:'.
     ...
     db.close()
    -
    +
    + +
    • New database will be created if path doesn't exist.
    -

    Read

    -
    cursor = db.execute('<query>')
    +

    Read

    cursor = db.execute('<query>')
     if cursor:
         <tuple> = cursor.fetchone()               # First row.
         <list>  = cursor.fetchall()               # Remaining rows.
    -
    +
    +
    • Returned values can be of type str, int, float, bytes or None.
    -

    Write

    -
    db.execute('<query>')
    +

    Write

    db.execute('<query>')
     db.commit()
    -
    -

    Placeholders

    -
    db.execute('<query>', <list/tuple>)           # Replaces '?'s in query with values.
    +
    + +

    Placeholders

    db.execute('<query>', <list/tuple>)           # Replaces '?'s in query with values.
     db.execute('<query>', <dict/namedtuple>)      # Replaces ':<key>'s with values.
     db.executemany('<query>', <coll_of_above>)    # Runs execute() many times.
    -
    +
    +
    • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.
    -

    MySQL

    -

    Has a very similar interface, with differences listed below.

    -
    # $ pip3 install mysql-connector
    +

    MySQL

    Has a very similar interface, with differences listed below.

    # $ pip3 install mysql-connector
     from mysql import connector
     db = connector.connect(host=<str>, user=<str>, password=<str>, database=<str>)
     cursor = db.cursor()
     cursor.execute('<query>')                     # Connector doesn't have execute method.
     cursor.execute('<query>', <list/tuple>)       # Replaces '%s's in query with values.
     cursor.execute('<query>', <dict/namedtuple>)  # Replaces '%(<key>)s's with values.
    -
    -

    #Bytes

    -

    Bytes object is an immutable sequence of single bytes. Mutable version is called 'bytearray'.

    -
    <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00 - \xff.
    +
    + + +

    #Bytes

    Bytes object is an immutable sequence of single bytes. Mutable version is called 'bytearray'.

    <bytes> = b'<str>'                       # Only accepts ASCII characters and \x00 - \xff.
     <int>   = <bytes>[<index>]               # Returns int in range from 0 to 255.
     <bytes> = <bytes>[<slice>]               # Returns bytes even if it has only one element.
     <bytes> = <bytes>.join(<coll_of_bytes>)  # Joins elements using bytes object as separator.
    -
    -

    Encode

    -
    <bytes> = <str>.encode('utf-8')          # Or: bytes(<str>, 'utf-8')
    +
    + + +

    Encode

    <bytes> = <str>.encode('utf-8')          # Or: bytes(<str>, 'utf-8')
     <bytes> = bytes(<coll_of_ints>)          # Ints must be in range from 0 to 255.
     <bytes> = <int>.to_bytes(<length>, byteorder='big|little', signed=False)
     <bytes> = bytes.fromhex('<hex>')
    -
    -

    Decode

    -
    <str>   = <bytes>.decode('utf-8')        # Or: str(<bytes>, 'utf-8')
    +
    + +

    Decode

    <str>   = <bytes>.decode('utf-8')        # Or: str(<bytes>, 'utf-8')
     <list>  = list(<bytes>)                  # Returns ints in range from 0 to 255.
     <int>   = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
     '<hex>' = <bytes>.hex()
    -
    -

    Read Bytes from File

    -
    def read_bytes(filename):
    +
    + +

    Read Bytes from File

    def read_bytes(filename):
         with open(filename, 'rb') as file:
             return file.read()
    -
    -

    Write Bytes to File

    -
    def write_bytes(filename, bytes_obj):
    +
    + +

    Write Bytes to File

    def write_bytes(filename, bytes_obj):
         with open(filename, 'wb') as file:
             file.write(bytes_obj)
    -
    -

    #Struct

    -
      +
    + +

    #Struct

    • Module that performs conversions between a sequence of numbers and a C struct, represented as a Python bytes object.
    • Machine’s native type sizes and byte order are used by default.
    • -
    -
    from struct import pack, unpack, iter_unpack, calcsize
    +
    from struct import pack, unpack, iter_unpack, calcsize
     <bytes>  = pack('<format>', <num_1> [, <num_2>, ...])
     <tuple>  = unpack('<format>', <bytes>)
     <tuples> = iter_unpack('<format>', <bytes>)
    -
    -

    Example

    -
    >>> pack('>hhl', 1, 2, 3)
    +
    + + +

    Example

    >>> pack('>hhl', 1, 2, 3)
     b'\x00\x01\x00\x02\x00\x00\x00\x03'
     >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
     (1, 2, 3)
     >>> calcsize('>hhl')
     8
    -
    -

    Format

    -

    For standard sizes start format string with:

    -
      +
    + +

    Format

    For standard sizes start format string with:

    • '=' - native byte order
    • '<' - little-endian
    • '>' - big-endian
    • -
    -

    Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:

    -
      +

    Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:

    • 'x' - pad byte
    • 'b' - char (1)
    • 'h' - short (2)
    • 'i' - int (4)
    • 'l' - long (4)
    • 'q' - long long (8)
    • -
    -

    Floating point types:

    -
      +

    Floating point types:

    • 'f' - float (4)
    • 'd' - double (8)
    • -
    -

    #Array

    -

    List that can only hold numbers of predefined type. Available types and their sizes in bytes are listed above.

    -
    from array import array
    +
    + + + + + + +

    #Array

    List that can only hold numbers of predefined type. Available types and their sizes in bytes are listed above.

    from array import array
     <array> = array('<typecode>' [, <collection>])
    -
    -

    #Memory View

    -

    Used for accessing the internal data of an object that supports the buffer protocol.

    -
    <memoryview> = memoryview(<bytes> / <bytearray> / <array>)
    +
    + + +

    #Memory View

    Used for accessing the internal data of an object that supports the buffer protocol.

    <memoryview> = memoryview(<bytes> / <bytearray> / <array>)
     <memoryview>.release()
    -
    -

    #Deque

    -

    A thread-safe list with efficient appends and pops from either side. Pronounced "deck".

    -
    from collections import deque
    +
    + + +

    #Deque

    A thread-safe list with efficient appends and pops from either side. Pronounced "deck".

    from collections import deque
     <deque> = deque(<collection>, maxlen=None)
    -
    +
    + +
    <deque>.appendleft(<el>)
     <el> = <deque>.popleft()
     <deque>.extendleft(<collection>)            # Collection gets reversed.
    @@ -1685,83 +1694,83 @@ 

    #Deque

    >>> a.insert(1, 6) IndexError: deque already at its maximum size
    -

    #Threading

    -
    from threading import Thread, RLock
    -
    -

    Thread

    -
    thread = Thread(target=<function>, args=(<first_arg>, ))
    +

    #Threading

    from threading import Thread, RLock
    +
    + +

    Thread

    thread = Thread(target=<function>, args=(<first_arg>, ))
     thread.start()
     ...
     thread.join()
    -
    -

    Lock

    -
    lock = RLock()
    +
    + +

    Lock

    lock = RLock()
     lock.acquire()
     ...
     lock.release()
    -
    -

    Or:

    -
    lock = RLock()
    +
    + +

    Or:

    lock = RLock()
     with lock:
         ...
    -
    -

    #Introspection

    -

    Inspecting code at runtime.

    -

    Variables

    -
    <list> = dir()      # Names of variables in current scope.
    +
    + +

    #Introspection

    Inspecting code at runtime.

    Variables

    <list> = dir()      # Names of variables in current scope.
     <dict> = locals()   # Dict of local variables. Also vars().
     <dict> = globals()  # Dict of global variables.
    -
    -

    Attributes

    -
    <dict> = vars(<object>)
    +
    + + + +

    Attributes

    <dict> = vars(<object>)
     <bool> = hasattr(<object>, '<attr_name>')
     value  = getattr(<object>, '<attr_name>')
     setattr(<object>, '<attr_name>', value)
    -
    -

    Parameters

    -
    from inspect import signature
    +
    + +

    Parameters

    from inspect import signature
     <sig>        = signature(<function>)
     no_of_params = len(<sig>.parameters)
     param_names  = list(<sig>.parameters.keys())
    -
    -

    #Metaprograming

    -

    Code that generates code.

    -

    Type

    -

    Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.

    -
    <class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
    -
    +
    + +

    #Metaprograming

    Code that generates code.

    Type

    Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.

    <class> = type(<class_name>, <parents_tuple>, <attributes_dict>)
    +
    + + + +
    >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
     >>> z = Z()
     
    -

    Meta Class

    -

    Class that creates class.

    -
    def my_meta_class(name, parents, attrs):
    +

    Meta Class

    Class that creates class.

    def my_meta_class(name, parents, attrs):
         attrs['a'] = 'abcde'
         return type(name, parents, attrs)
    -
    -

    Or:

    -
    class MyMetaClass(type):
    +
    + + +

    Or:

    class MyMetaClass(type):
         def __new__(cls, name, parents, attrs):
             attrs['a'] = 'abcde'
             return type.__new__(cls, name, parents, attrs)
    -
    +
    +
    • New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.
    • It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance ('MyMetaClass' in our case).
    • New() can also be called directly, usually from a new() method of a child class (def __new__(cls): return super().__new__(cls)), in which case init() is not called.
    -

    Metaclass Attribute

    -

    Right before a class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().

    -
    class MyClass(metaclass=MyMetaClass):
    +

    Metaclass Attribute

    Right before a class is created it checks if it has metaclass defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().

    class MyClass(metaclass=MyMetaClass):
         b = 12345
    -
    +
    + +
    >>> MyClass.a, MyClass.b
     ('abcde', 12345)
     
    -

    Type Diagram

    -
    type(MyClass)     == MyMetaClass  # MyClass is an instance of MyMetaClass.
    +

    Type Diagram

    type(MyClass)     == MyMetaClass  # MyClass is an instance of MyMetaClass.
     type(MyMetaClass) == type         # MyMetaClass is an instance of type.
    -
    +
    +
    +---------+-------------+
     | Classes | Metaclasses |
     +---------+-------------|
    @@ -1772,10 +1781,10 @@ 

    Type Diagram

    | str -------+ | +---------+-------------+
    -

    Inheritance Diagram

    -
    MyClass.__base__     == object    # MyClass is a subclass of object.
    +

    Inheritance Diagram

    MyClass.__base__     == object    # MyClass is a subclass of object.
     MyMetaClass.__base__ == type      # MyMetaClass is a subclass of type.
    -
    +
    +
    +---------+-------------+
     | Classes | Metaclasses |
     +---------+-------------|
    @@ -1786,12 +1795,12 @@ 

    Inheritance Diagram

    | str | | +---------+-------------+
    -

    #Operator

    -
    from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
    +

    #Operator

    from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs
     from operator import eq, ne, lt, le, gt, ge
     from operator import and_, or_, not_
     from operator import itemgetter, attrgetter, methodcaller
    -
    +
    +
    import operator as op
     sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
     sorted_by_both   = sorted(<collection>, key=op.itemgetter(1, 0))
    @@ -1799,36 +1808,35 @@ 

    #Operator

    LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_}) last_el = op.methodcaller('pop')(<list>)
    -

    #Eval

    -
    >>> from ast import literal_eval
    +

    #Eval

    >>> from ast import literal_eval
     >>> literal_eval('1 + 2')
     3
     >>> literal_eval('[1, 2, 3]')
     [1, 2, 3]
     >>> literal_eval('abs(1)')
     ValueError: malformed node or string
    -
    -

    #Coroutine

    -
      +
    + +

    #Coroutine

    • Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().
    • Coroutines provide more powerful data routing possibilities than iterators.
    • If you build a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.
    • -
    -

    Helper Decorator

    -
      +

    Helper Decorator

    • All coroutines must be "primed" by first calling next().
    • Remembering to call next() is easy to forget.
    • Solved by wrapping coroutines with a decorator:
    • -
    -
    def coroutine(func):
    +
    def coroutine(func):
         def out(*args, **kwargs):
             cr = func(*args, **kwargs)
             next(cr)
             return cr
         return out
    -
    -

    Pipeline Example

    -
    def reader(target):
    +
    + + + + +

    Pipeline Example

    def reader(target):
         for i in range(10):
             target.send(i)
         target.close()
    @@ -1846,29 +1854,28 @@ 

    Pipeline Example

    print(value) reader(adder(printer())) # 100, 101, ..., 109 -
    +
    +



    -

    Libraries

    -

    #Progress Bar

    -
    # $ pip3 install tqdm
    +

    Libraries

    +

    #Progress Bar

    # $ pip3 install tqdm
     from tqdm import tqdm
     from time import sleep
     for i in tqdm([1, 2, 3]):
         sleep(0.2)
     for i in tqdm(range(100)):
         sleep(0.02)
    -
    -

    #Plot

    -
    # $ pip3 install matplotlib
    +
    + +

    #Plot

    # $ pip3 install matplotlib
     from matplotlib import pyplot
     pyplot.plot(<data_1> [, <data_2>, ...])  # Or: hist(<data>).
     pyplot.savefig(<filename>)
     pyplot.show()
     pyplot.clf()                             # Clears figure.
    -
    -

    #Table

    -

    Prints a CSV file as an ASCII table:

    -
    # $ pip3 install tabulate
    +
    + +

    #Table

    Prints a CSV file as an ASCII table:

    # $ pip3 install tabulate
     from tabulate import tabulate
     import csv
     with open(<filename>, encoding='utf-8', newline='') as file:
    @@ -1876,9 +1883,10 @@ 

    Prints a CSV file as an ASCII table:

    headers = [header.title() for header in next(lines)] table = tabulate(lines, headers) print(table) -
    -

    #Curses

    -
    from curses import wrapper, ascii
    +
    + + +

    #Curses

    from curses import wrapper, ascii
     
     def main():
         wrapper(draw)
    @@ -1897,11 +1905,12 @@ 

    #Curses

    if __name__ == '__main__': main() -
    -

    #Logging

    -
    # $ pip3 install loguru
    +
    + +

    #Logging

    # $ pip3 install loguru
     from loguru import logger
    -
    +
    +
    logger.add('debug_{time}.log', colorize=True)  # Connects a log file.
     logger.add('error_{time}.log', level='ERROR')  # Another file for errors or higher.
     logger.<level>('A logging message.')
    @@ -1909,35 +1918,33 @@ 

    #Logging

    • Levels: 'debug', 'info', 'success', 'warning', 'error', 'critical'.
    -

    Exceptions

    -

    Error description, stack trace and values of variables are appended automatically.

    -
    try:
    +

    Exceptions

    Error description, stack trace and values of variables are appended automatically.

    try:
         ...
     except <exception>:
         logger.exception('An error happened.')
    -
    -

    Rotation

    -

    Argument that sets a condition when a new log file is created.

    -
    rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
    -
    +
    + + +

    Rotation

    Argument that sets a condition when a new log file is created.

    rotation=<int>|<datetime.timedelta>|<datetime.time>|<str>
    +
    + +
    • '<int>' - Max file size in bytes.
    • '<timedelta>' - Max age of a file.
    • '<time>' - Time of day.
    • '<str>' - Any of above as a string: '100 MB', '1 month', 'monday at 12:00', …
    -

    Retention

    -

    Sets a condition which old log files are deleted.

    -
    retention=<int>|<datetime.timedelta>|<str>
    -
    +

    Retention

    Sets a condition which old log files are deleted.

    retention=<int>|<datetime.timedelta>|<str>
    +
    + +
    • '<int>' - Max number of files.
    • '<timedelta>' - Max age of a file.
    • '<str>' - Max age as a string: '1 week, 3 days', '2 months', …
    -

    #Scraping

    -

    Scrapes and prints Python's URL and version number from Wikipedia:

    -
    # $ pip3 install requests beautifulsoup4
    +

    #Scraping

    Scrapes and prints Python's URL and version number from Wikipedia:

    # $ pip3 install requests beautifulsoup4
     import requests
     from bs4 import BeautifulSoup
     url   = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
    @@ -1948,83 +1955,83 @@ 

    Scrapes and pri link = rows[11].find('a')['href'] ver = rows[6].find('div').text.split()[0] print(link, ver) -

    -

    #Web

    -
    # $ pip3 install bottle
    +
    + + +

    #Web

    # $ pip3 install bottle
     from bottle import run, route, post, template, request, response
     import json
    -
    -

    Run

    -
    run(host='localhost', port=8080)
    +
    + +

    Run

    run(host='localhost', port=8080)
     run(host='0.0.0.0', port=80, server='cherrypy')
    -
    -

    Static Request

    -
    @route('/img/<image>')
    +
    + +

    Static Request

    @route('/img/<image>')
     def send_image(image):
         return static_file(image, 'images/', mimetype='image/png')
    -
    -

    Dynamic Request

    -
    @route('/<sport>')
    +
    + +

    Dynamic Request

    @route('/<sport>')
     def send_page(sport):
         return template('<h1>{{title}}</h1>', title=sport)
    -
    -

    REST Request

    -
    @post('/odds/<sport>')
    +
    + +

    REST Request

    @post('/odds/<sport>')
     def odds_handler(sport):
         team = request.forms.get('team')
         home_odds, away_odds = 2.44, 3.29
         response.headers['Content-Type'] = 'application/json'
         response.headers['Cache-Control'] = 'no-cache'
         return json.dumps([team, home_odds, away_odds])
    -
    -

    Test:

    -
    # $ pip3 install requests
    +
    + +

    Test:

    # $ pip3 install requests
     >>> import requests
     >>> url  = 'http://localhost:8080/odds/football'
     >>> data = {'team': 'arsenal f.c.'}
     >>> response = requests.post(url, data=data)
     >>> response.json()
     ['arsenal f.c.', 2.44, 3.29]
    -
    -

    #Profile

    -

    Basic

    -
    from time import time
    +
    + +

    #Profile

    Basic

    from time import time
     start_time = time()                  # Seconds since Epoch.
     ...
     duration = time() - start_time
    -
    -

    High Performance

    -
    from time import perf_counter as pc
    +
    + + +

    High Performance

    from time import perf_counter as pc
     start_time = pc()                    # Seconds since restart.
     ...
     duration = pc() - start_time
    -
    -

    Timing a Snippet

    -
    >>> from timeit import timeit
    +
    + +

    Timing a Snippet

    >>> from timeit import timeit
     >>> timeit('"-".join(str(a) for a in range(100))',
     ...        number=10000, globals=globals(), setup='pass')
     0.34986
    -
    -

    Line Profiler

    -
    # $ pip3 install line_profiler
    +
    + +

    Line Profiler

    # $ pip3 install line_profiler
     @profile
     def main():
         a = [*range(10000)]
         b = {*range(10000)}
     main()
    -
    -

    Usage:

    -
    $ kernprof -lv test.py
    +
    + +

    Usage:

    $ kernprof -lv test.py
     Line #      Hits         Time  Per Hit   % Time  Line Contents
     ==============================================================
          1                                           @profile
          2                                           def main():
          3         1       1128.0   1128.0     27.4      a = [*range(10000)]
          4         1       2994.0   2994.0     72.6      b = {*range(10000)}
    -
    -

    Call Graph

    -

    Generates a PNG image of a call graph with highlighted bottlenecks:

    -
    # $ pip3 install pycallgraph
    +
    + +

    Call Graph

    Generates a PNG image of a call graph with highlighted bottlenecks:

    # $ pip3 install pycallgraph
     from pycallgraph import output, PyCallGraph
     from datetime import datetime
     time_str = datetime.now().strftime('%Y%m%d%H%M%S')
    @@ -2032,12 +2039,14 @@ 

    Generates a PN drawer = output.GraphvizOutput(output_file=filename) with PyCallGraph(drawer): <code_to_be_profiled> -

    -

    #NumPy

    -

    Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.

    -
    # $ pip3 install numpy
    +
    + + +

    #NumPy

    Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.

    # $ pip3 install numpy
     import numpy as np
    -
    +
    + +
    <array> = np.array(<list>)
     <array> = np.arange(from_inclusive, to_exclusive, ±step_size)
     <array> = np.ones(<shape>)
    @@ -2054,12 +2063,12 @@ 

    #NumPy

  • Shape is a tuple of dimension sizes.
  • Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.
  • -

    Indexing

    -
    <el>       = <2d_array>[0, 0]        # First element.
    +

    Indexing

    <el>       = <2d_array>[0, 0]        # First element.
     <1d_view>  = <2d_array>[0]           # First row.
     <1d_view>  = <2d_array>[:, 0]        # First column. Also [..., 0].
     <3d_view>  = <2d_array>[None, :, :]  # Expanded by dimension of size 1.
    -
    +
    +
    <1d_array> = <2d_array>[<1d_row_indexes>, <1d_column_indexes>]
     <2d_array> = <2d_array>[<2d_row_indexes>, <2d_column_indexes>]
     
    @@ -2069,23 +2078,20 @@

    Indexing

    • If row and column indexes differ in shape, they are combined with broadcasting.
    -

    Broadcasting

    -

    Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.

    -
    left  = [[0.1], [0.6], [0.8]]  # Shape: (3, 1)
    +

    Broadcasting

    Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.

    left  = [[0.1], [0.6], [0.8]]  # Shape: (3, 1)
     right = [ 0.1 ,  0.6 ,  0.8 ]  # Shape: (3)
    -
    -

    1. If array shapes differ in length, left-pad the shorter shape with ones:

    -
    left  = [[0.1], [0.6], [0.8]]  # Shape: (3, 1)
    +
    + + +

    1. If array shapes differ in length, left-pad the shorter shape with ones:

    left  = [[0.1], [0.6], [0.8]]  # Shape: (3, 1)
     right = [[0.1 ,  0.6 ,  0.8]]  # Shape: (1, 3) <- !
    -
    -

    2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:

    -
    left  = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]]  # Shape: (3, 3) <- !
    +
    + +

    2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:

    left  = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]]  # Shape: (3, 3) <- !
     right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]]  # Shape: (3, 3) <- !
    -
    -

    3. If neither non-matching dimension has size 1, rise an error.

    -

    Example

    -

    For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

    -
    >>> points = np.array([0.1, 0.6, 0.8])
    +
    + +

    3. If neither non-matching dimension has size 1, rise an error.

    Example

    For each point returns index of its nearest point ([0.1, 0.6, 0.8] => [1, 2, 1]):

    >>> points = np.array([0.1, 0.6, 0.8])
     [ 0.1,  0.6,  0.8]
     >>> wrapped_points = points.reshape(3, 1)
     [[ 0.1],
    @@ -2107,13 +2113,15 @@ 

    For each point retur [ 0.7, 0.2, inf]] >>> distances.argmin(1) [1, 2, 1] -

    -

    #Image

    -
    # $ pip3 install pillow
    +
    + + + +

    #Image

    # $ pip3 install pillow
     from PIL import Image
    -
    -

    Creates a PNG image of a rainbow gradient:

    -
    width  = 100
    +
    + +

    Creates a PNG image of a rainbow gradient:

    width  = 100
     height = 100
     size   = width * height
     pixels = [255 * i/size for i in range(size)]
    @@ -2121,56 +2129,56 @@ 

    Creates a PNG image of a rainbow gra img = Image.new('HSV', (width, height)) img.putdata([(int(a), 255, 255) for a in pixels]) img.convert(mode='RGB').save('test.png') -

    -

    Adds noise to a PNG image:

    -
    from random import randint
    +
    + +

    Adds noise to a PNG image:

    from random import randint
     add_noise = lambda value: max(0, min(255, value + randint(-20, 20)))
     img = Image.open('test.png').convert(mode='HSV')
     img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()])
     img.convert(mode='RGB').save('test.png')
    -
    -

    Modes

    -
      +
    + +

    Modes

    • '1' - 1-bit pixels, black and white, stored with one pixel per byte.
    • 'L' - 8-bit pixels, greyscale.
    • 'RGB' - 3x8-bit pixels, true color.
    • 'RGBA' - 4x8-bit pixels, true color with transparency mask.
    • 'HSV' - 3x8-bit pixels, Hue, Saturation, Value color space.
    • -
    -

    #Audio

    -
    import wave
    +
    + +

    #Audio

    import wave
     from struct import pack, iter_unpack
    -
    -

    Read Frames from WAV File

    -
    def read_wav_file(filename):
    +
    + +

    Read Frames from WAV File

    def read_wav_file(filename):
         with wave.open(filename, 'rb') as wf:
             frames = wf.readframes(wf.getnframes())
             return [a[0] for a in iter_unpack('<h', frames)]
    -
    -

    Write Frames to WAV File

    -
    def write_to_wav_file(filename, frames_int, mono=True):
    +
    + +

    Write Frames to WAV File

    def write_to_wav_file(filename, frames_int, mono=True):
         frames_short = (pack('<h', a) for a in frames_int)
         with wave.open(filename, 'wb') as wf:
             wf.setnchannels(1 if mono else 2)
             wf.setsampwidth(2)
             wf.setframerate(44100)
             wf.writeframes(b''.join(frames_short))
    -
    -

    Examples

    -

    Saves a sine wave to a mono WAV file:

    -
    from math import pi, sin
    +
    + +

    Examples

    Saves a sine wave to a mono WAV file:

    from math import pi, sin
     frames_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000))
     frames_i = (int(a * 30000) for a in frames_f)
     write_to_wav_file('test.wav', frames_i)
    -
    -

    Adds noise to a mono WAV file:

    -
    from random import randint
    +
    + + +

    Adds noise to a mono WAV file:

    from random import randint
     add_noise = lambda value: max(-32768, min(32767, value + randint(-500, 500)))
     frames_i  = (add_noise(a) for a in read_wav_file('test.wav'))
     write_to_wav_file('test.wav', frames_i)
    -
    -

    Synthesizer

    -
    # $ pip3 install simpleaudio
    +
    + +

    Synthesizer

    # $ pip3 install simpleaudio
     import simpleaudio, math, struct
     from itertools import chain, repeat
     F  = 44100
    @@ -2185,9 +2193,9 @@ 

    Synthesizer

    frames_f = chain.from_iterable(get_frames(n) for n in f'{P1}{P1}{P2}'.split(',')) frames_b = b''.join(struct.pack('<h', int(f * 30000)) for f in frames_f) simpleaudio.play_buffer(frames_b, 1, 2, F) -
    -

    #Basic Script Template

    -
    #!/usr/bin/env python3
    +
    + +

    #Basic Script Template

    #!/usr/bin/env python3
     #
     # Usage: .py
     #
    @@ -2214,7 +2222,8 @@ 

    if __name__ == '__main__': main() -

    +
    +