From 669ae147bf845ae79d688321930fc3ea0ec3fe61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:29:58 +0100 Subject: [PATCH 0001/2378] Dict --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9736f7d6a..768383e76 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,6 @@ index = .index() # Returns first index of item. Dictionary ---------- ```python -.update() = .keys() = .values() = .items() @@ -69,8 +68,9 @@ value = .setdefault(key, default) # Same, but also adds default to di ``` ```python -dict() # Initiates a dict from list of key-value pairs. -dict(zip(keys, values)) # Initiates a dict from two lists. +.update() + = dict() # Initiates a dict from list of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two lists. {k: v for k, v in .items() if k in } # Filters a dict by keys. ``` From f5e93c5a82c32d9d29f51085e79846010cf02d4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:32:56 +0100 Subject: [PATCH 0002/2378] Dict --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 768383e76..13da87c14 100644 --- a/README.md +++ b/README.md @@ -69,9 +69,9 @@ value = .setdefault(key, default) # Same, but also adds default to di ```python .update() - = dict() # Initiates a dict from list of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two lists. -{k: v for k, v in .items() if k in } # Filters a dict by keys. + = dict() # Initiates a dict from list of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two lists. +{k: v for k, v in .items() if k in keys} # Filters a dict by keys. ``` ### Counter From 3aff79ca433f370ae0cb450fffde7e1c4ff78610 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:41:08 +0100 Subject: [PATCH 0003/2378] String --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 13da87c14..3ea6fb43c 100644 --- a/README.md +++ b/README.md @@ -205,8 +205,8 @@ is_function = callable() String ------ ```python - = .strip() # Strips all whitespace characters. - = .strip('') # Strips all passed characters. + = .strip() # Strips all whitespace characters. + = .strip('') # Strips all passed characters. ``` ```python From 644d6c9d9c989896cf81c5ac532f087bdd3f422b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:47:20 +0100 Subject: [PATCH 0004/2378] Regex --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ea6fb43c..ecf16b659 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,8 @@ 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.** +* **Parameter 'flags=re.IGNORECASE' can be used with all functions.** +* **Parameter 'flags=re.DOTALL' makes dot also accept newline.** * **Use '\\\\1' or r'\1' for backreference.** * **Use ? to make operators non-greedy.** From bfbca77a8f78282e3bc8a3bea26b36982f19817e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:48:41 +0100 Subject: [PATCH 0005/2378] Regex --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ecf16b659..b143c0c44 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,7 @@ import re = re.finditer(, text) # Searches for all occurrences of pattern. ``` -* **Parameter 'flags=re.IGNORECASE' can be used with all functions.** +* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** * **Parameter 'flags=re.DOTALL' makes dot also accept newline.** * **Use '\\\\1' or r'\1' for backreference.** * **Use ? to make operators non-greedy.** From aa6a25bb0337bb3f37d2499858e1d2b7aef0ff06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:49:50 +0100 Subject: [PATCH 0006/2378] Regex --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b143c0c44..31a68ca10 100644 --- a/README.md +++ b/README.md @@ -265,10 +265,10 @@ import re = re.finditer(, text) # Searches for all occurrences of pattern. ``` +* **Use `'\\\\1'` or `r'\1'` for backreference.** +* **Use `?` to make operators non-greedy.** * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** -* **Parameter 'flags=re.DOTALL' makes dot also accept newline.** -* **Use '\\\\1' or r'\1' for backreference.** -* **Use ? to make operators non-greedy.** +* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** ### Match Object ```python From 8dbd264725697248b78a6500334101a9ba691132 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:51:46 +0100 Subject: [PATCH 0007/2378] Regex --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 31a68ca10..f50bc8ee4 100644 --- a/README.md +++ b/README.md @@ -267,8 +267,8 @@ import re * **Use `'\\\\1'` or `r'\1'` for backreference.** * **Use `?` to make operators non-greedy.** -* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** -* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** +* **Parameter `flags=re.IGNORECASE` can be used with all functions.** +* **Parameter `flags=re.DOTALL` makes dot also accept newline.** ### Match Object ```python From e6d4c6b14ca18f0fdbf25fb3e1d2c1b93b549194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:52:56 +0100 Subject: [PATCH 0008/2378] Regex --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f50bc8ee4..9e709a756 100644 --- a/README.md +++ b/README.md @@ -265,7 +265,7 @@ import re = re.finditer(, text) # Searches for all occurrences of pattern. ``` -* **Use `'\\\\1'` or `r'\1'` for backreference.** +* **Use `r'\1'` or `'\\\\1'` for backreference.** * **Use `?` to make operators non-greedy.** * **Parameter `flags=re.IGNORECASE` can be used with all functions.** * **Parameter `flags=re.DOTALL` makes dot also accept newline.** From 7561fe7d77235629c1e259b3dabca1d89b07c7dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:54:57 +0100 Subject: [PATCH 0009/2378] Regex --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9e709a756..e1cdc9a0c 100644 --- a/README.md +++ b/README.md @@ -266,9 +266,9 @@ import re ``` * **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use `?` to make operators non-greedy.** -* **Parameter `flags=re.IGNORECASE` can be used with all functions.** -* **Parameter `flags=re.DOTALL` makes dot also accept newline.** +* **Use '`?`' to make operators non-greedy.** +* **Parameter '`flags=re.IGNORECASE`' can be used with all functions.** +* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** ### Match Object ```python From c07a19a9e0d5bf437f748ec55bd6f9c01cfe7031 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:55:33 +0100 Subject: [PATCH 0010/2378] Regex --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e1cdc9a0c..1537b6696 100644 --- a/README.md +++ b/README.md @@ -266,8 +266,8 @@ import re ``` * **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use '`?`' to make operators non-greedy.** -* **Parameter '`flags=re.IGNORECASE`' can be used with all functions.** +* **Use `'?'` to make operators non-greedy.** +* **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** ### Match Object From db14a12fbb41df76951919b23c68fa3bf1cce9fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 09:57:09 +0100 Subject: [PATCH 0011/2378] Regex --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1537b6696..1ab4d8cdf 100644 --- a/README.md +++ b/README.md @@ -265,10 +265,10 @@ import re = re.finditer(, text) # Searches for all occurrences of pattern. ``` -* **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use `'?'` to make operators non-greedy.** * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** -* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** +* **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 From 8b3e1f4ecedfc23ef78df2daea0384cc91a4beed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 10:26:35 +0100 Subject: [PATCH 0012/2378] Numbers --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1ab4d8cdf..e86906f7b 100644 --- a/README.md +++ b/README.md @@ -351,9 +351,9 @@ Numbers ------- ### Basic Functions ```python -round( [, ndigits]) +pow(x, y) # Or: x ** y abs() -math.pow(x, y) # Or: x ** y +round( [, ndigits]) ``` ### Constants From 5ba16885b63b5af280e26944fa005fc4c4c3369e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 14:49:22 +0100 Subject: [PATCH 0013/2378] Claned profiling decorators --- README.md | 52 ++++++++++++++++++++++------------------------------ 1 file changed, 22 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index e86906f7b..bc7fdec7f 100644 --- a/README.md +++ b/README.md @@ -1359,61 +1359,53 @@ def get_filename(): return f'profile-{time_str}.png' ``` -#### Decorator for timing function execution: +#### Decorator for timing functions: ```python from timeit import default_timer from datetime import timedelta def stopwatch(func): - """Print runtime of decorated function.""" - def wrap(*args, **kw): + """Prints runtime of decorated function.""" + def out(*args, **kwargs): start = default_timer() - result = func(*args, **kw) + result = func(*args, **kwargs) delta = timedelta(seconds=(default_timer() - start)) - print(f"Function {func.__name__} finished in {delta}") + print(f'Function {func.__name__} finished in {delta}') return result - return wrap + return out ``` #### Decorator for profiling functions: ```python -import cProfile +from cProfile import Profile +from pstats import Stats def profiler(func): - """Decorator. - Create a run call profile of the decorated function.""" - def wrap(*args, **kwargs): - profile = cProfile.Profile() + """Saves run call profile of the decorated function to file.""" + def out(*args, **kwargs): + profile = Profile() result = profile.runcall(func, *args, **kwargs) - with open(f"profile_{func.__name__}.txt", "w") as stream: - stats = pstats.Stats(profile, stream=stream) - stats.strip_dirs().sort_stats("tottime") + with open(f'profile_{func.__name__}.txt', 'w') as stream: + stats = Stats(profile, stream=stream) + stats.strip_dirs().sort_stats('tottime') stats.print_stats(20) print(f"Profile saved as 'profile_{func.__name__}.txt'") return result - return wrap + return out ``` #### Decorator for function tracing: ```python def tracer(func): - """Print a trace of the input and output of a function in one line.""" - def traced_func(*args, **kwargs): + """Prints input and output of a decorated function.""" + def out(*args, **kwargs): result = func(*args, **kwargs) - if len(args) is not 0: - argslist = ", ".join(f"{x}" for x in args) - if len(kwargs) is not 0: - argslist = argslist + ", " if len(kwargs) is not 0 else "" - else: - argslist = "" - if len(kwargs) is not 0: - kwargslist = ", ".join([f"{k}={v}" for k, v in kwargs.items()]) - else: - kwargslist = "" - print( - f"{func.__name__}({argslist}{kwargslist}) = {result}") + arg_list = [str(x) for x in args] + arg_list += [f'{k}={v}' for k, v in kwargs.items()] + arg_str = ', '.join(arg_list) + print(f'{func.__name__}({arg_str}) = {result}') return result - return traced_func + return out ``` From 9a1000034291c7ed638f0e930576c51ee2fda1b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 14:53:26 +0100 Subject: [PATCH 0014/2378] Profile --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc7fdec7f..7532b38c7 100644 --- a/README.md +++ b/README.md @@ -1338,7 +1338,7 @@ duration = time() - start_time #### Times execution of the passed code: ```python from timeit import timeit -timeit('"-".join(str(n) for n in range(100))', +timeit('"-".join(str(a) for a in range(100))', number=10000, globals=globals()) ``` From 16ef452c888d8d9785fce197ef9cec5d88bc47b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 15:08:20 +0100 Subject: [PATCH 0015/2378] Profile --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7532b38c7..d70be9494 100644 --- a/README.md +++ b/README.md @@ -1397,7 +1397,7 @@ def profiler(func): #### Decorator for function tracing: ```python def tracer(func): - """Prints input and output of a decorated function.""" + """Prints arguments and output of a decorated function.""" def out(*args, **kwargs): result = func(*args, **kwargs) arg_list = [str(x) for x in args] From bc8e2171ccf1056ca53382824fab068e27bb8848 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 15:24:44 +0100 Subject: [PATCH 0016/2378] Profile --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d70be9494..c2ab4d47e 100644 --- a/README.md +++ b/README.md @@ -1385,11 +1385,12 @@ def profiler(func): def out(*args, **kwargs): profile = Profile() result = profile.runcall(func, *args, **kwargs) - with open(f'profile_{func.__name__}.txt', 'w') as stream: + filename = f'profile_{func.__name__}.txt' + with open(filename, 'w') as stream: stats = Stats(profile, stream=stream) stats.strip_dirs().sort_stats('tottime') stats.print_stats(20) - print(f"Profile saved as 'profile_{func.__name__}.txt'") + print(f"Profile saved as '{filename}'") return result return out ``` From 90e0e6b7b8e98caac4c52b31e3285dd709b5f10d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 15:39:04 +0100 Subject: [PATCH 0017/2378] Profile --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c2ab4d47e..c25e8b456 100644 --- a/README.md +++ b/README.md @@ -1401,7 +1401,7 @@ def tracer(func): """Prints arguments and output of a decorated function.""" def out(*args, **kwargs): result = func(*args, **kwargs) - arg_list = [str(x) for x in args] + arg_list = [repr(x) for x in args] arg_list += [f'{k}={v}' for k, v in kwargs.items()] arg_str = ', '.join(arg_list) print(f'{func.__name__}({arg_str}) = {result}') From fa21fc1a10637bd5ab37daa829c886af2ef472a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 15:47:07 +0100 Subject: [PATCH 0018/2378] Profile --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c25e8b456..90117a51f 100644 --- a/README.md +++ b/README.md @@ -1402,9 +1402,9 @@ def tracer(func): def out(*args, **kwargs): result = func(*args, **kwargs) arg_list = [repr(x) for x in args] - arg_list += [f'{k}={v}' for k, v in kwargs.items()] + arg_list += [f'{k}={v!r}' for k, v in kwargs.items()] arg_str = ', '.join(arg_list) - print(f'{func.__name__}({arg_str}) = {result}') + print(f'{func.__name__}({arg_str}) = {result!r}') return result return out ``` From 07136361a3dd69c0f0d7f215d301a4694603287a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 16:19:13 +0100 Subject: [PATCH 0019/2378] Format --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 90117a51f..3fb1cd360 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,9 @@ Format {123456:10,} # ' 123,456' {123456:10_} # ' 123_456' {123456:+10} # ' +123456' +{-123456:=10} # '- 123456' +{123456: } # ' 123456' +{-123456: } # '-123456' ``` ```python From e42f492640332fad5b403ca81dc515819feea734 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 16:26:33 +0100 Subject: [PATCH 0020/2378] Coroutine --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3fb1cd360..323fa4c9b 100644 --- a/README.md +++ b/README.md @@ -1135,8 +1135,8 @@ Coroutine * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** ### Helper Decorator -* **All coroutines must be "primed" by first calling .next()** -* **Remembering to call .next() is easy to forget.** +* **All coroutines must be "primed" by first calling next()** +* **Remembering to call next() is easy to forget.** * **Solved by wrapping coroutines with a decorator:** ```python From 92a8d268cb6c0fe38c0e8135a2a4fed56ba199f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 16:27:08 +0100 Subject: [PATCH 0021/2378] Coroutine --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 323fa4c9b..e001517d3 100644 --- a/README.md +++ b/README.md @@ -1135,7 +1135,7 @@ Coroutine * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** ### Helper Decorator -* **All coroutines must be "primed" by first calling next()** +* **All coroutines must be "primed" by first calling next().** * **Remembering to call next() is easy to forget.** * **Solved by wrapping coroutines with a decorator:** From f96cc4de305b9af03192320795fb300a83cfb469 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 16:31:17 +0100 Subject: [PATCH 0022/2378] Coroutine --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e001517d3..c36655e69 100644 --- a/README.md +++ b/README.md @@ -1141,11 +1141,11 @@ Coroutine ```python def coroutine(func): - def start(*args, **kwargs): + def out(*args, **kwargs): cr = func(*args, **kwargs) next(cr) return cr - return start + return out ``` ### Pipeline Example From 298f254a410a1d43a86336b17510fbfee6c1ce25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 17:11:58 +0100 Subject: [PATCH 0023/2378] Namedtuple --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c36655e69..eb725251a 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,7 @@ for i, in enumerate( [, i_start]): Named Tuple ----------- ```python ->>> Point = collections.namedtuple('Point', ['x', 'y']) +>>> Point = collections.namedtuple('Point', 'x y') >>> a = Point(1, y=2) Point(x=1, y=2) >>> a.x From e6b919a8cc39e3c26b9b089a129d3940bc76368c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 17:31:59 +0100 Subject: [PATCH 0024/2378] Reduce --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index eb725251a..7dcdbecad 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) list_of_chars = list() -product_of_elems = functools.reduce(lambda out, x: out * x, ) +product_of_elems = functools.reduce(lambda agr, x: agr * x, ) no_duplicates = list(dict.fromkeys()) ``` @@ -479,9 +479,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 sum, x: sum+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 agr, x: agr + x, range(10)) # 45 ``` ### Any, All From bf479ad66100f85ab267db1269c176e6e1c0c500 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 17:34:15 +0100 Subject: [PATCH 0025/2378] Reduce --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7dcdbecad..a7ab96af3 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) list_of_chars = list() -product_of_elems = functools.reduce(lambda agr, x: agr * x, ) +product_of_elems = functools.reduce(lambda out, x: out * x, ) no_duplicates = list(dict.fromkeys()) ``` @@ -481,7 +481,7 @@ for i in range(10): 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 agr, x: agr + x, range(10)) # 45 + = reduce(lambda out, x: out + x, range(10)) # 45 ``` ### Any, All From ed9ceeae5da0f94a1d8232696a96be1fc4ce270c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 17:49:09 +0100 Subject: [PATCH 0026/2378] Closure --- README.md | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a7ab96af3..c78f70472 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,14 @@ def get_multiplier(a): #### Or: ```python from functools import partial -partial(, [, , ...]) + = partial(, [, , ...]) +``` + +```python +>>> from operator import mul +>>> multiply_by_3 = partial(mul, 3) +>>> multiply_by_3(10) +30 ``` From 0eeab6d15d20564c2b50f76b0dfa93c1b4369212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 17:50:40 +0100 Subject: [PATCH 0027/2378] Closure --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index c78f70472..5de735c21 100644 --- a/README.md +++ b/README.md @@ -536,8 +536,7 @@ from functools import partial ``` ```python ->>> from operator import mul ->>> multiply_by_3 = partial(mul, 3) +>>> multiply_by_3 = partial(operator.mul, 3) >>> multiply_by_3(10) 30 ``` From bd1c178fe1dddc9bf8c00d1a7ba8b837d0776d15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 17:55:54 +0100 Subject: [PATCH 0028/2378] Closure --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5de735c21..918bc99d1 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,7 @@ def get_multiplier(a): #### Or: ```python from functools import partial - = partial(, [, , ...]) + = partial(, argument_1 [, argument_2, ...]) ``` ```python From 69b500c84554bb2f60237952bb83ba4ac4efe0cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 17:57:42 +0100 Subject: [PATCH 0029/2378] Closure --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 918bc99d1..9e0e16808 100644 --- a/README.md +++ b/README.md @@ -532,7 +532,7 @@ def get_multiplier(a): #### Or: ```python from functools import partial - = partial(, argument_1 [, argument_2, ...]) + = partial(, [, , ...]) ``` ```python From 8c981eb7dce81f5ecf10d0e3629749a237c177ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:05:43 +0100 Subject: [PATCH 0030/2378] Debugger example --- README.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 9e0e16808..ce705f838 100644 --- a/README.md +++ b/README.md @@ -557,7 +557,7 @@ from functools import wraps def debug(func): @wraps(func) # Needed for metadata copying (func name, ...). def out(*args, **kwargs): - print(func.__name__) + print(f'You called function {func.__name__!r}.') return func(*args, **kwargs) return out @@ -566,6 +566,12 @@ def add(x, y): return x + y ``` +```python +>>> add(2, 2) +You called function 'add'. +4 +``` + Class ----- From d4353b1a7f0a38d0351aaeb402179d08ef27db39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:07:05 +0100 Subject: [PATCH 0031/2378] Debugger example --- README.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/README.md b/README.md index ce705f838..9e0e16808 100644 --- a/README.md +++ b/README.md @@ -557,7 +557,7 @@ from functools import wraps def debug(func): @wraps(func) # Needed for metadata copying (func name, ...). def out(*args, **kwargs): - print(f'You called function {func.__name__!r}.') + print(func.__name__) return func(*args, **kwargs) return out @@ -566,12 +566,6 @@ def add(x, y): return x + y ``` -```python ->>> add(2, 2) -You called function 'add'. -4 -``` - Class ----- From 69f8e1a370c0372de23092286302a0975a0c2a20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:12:29 +0100 Subject: [PATCH 0032/2378] Eval --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9e0e16808..1314385cb 100644 --- a/README.md +++ b/README.md @@ -1093,8 +1093,8 @@ Eval ### Detailed ```python -from ast import parse, Num, BinOp, UnaryOp, \ - Add, Sub, Mult, Div, Pow, BitXor, USub +from ast import Add, Sub, Mult, Div, Pow, BitXor, USub, \ + parse, Num, BinOp, UnaryOp import operator as op operators = {Add: op.add, From 9f52f19641da97f29270a0474a58f7aad2e07bbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:13:56 +0100 Subject: [PATCH 0033/2378] Eval --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1314385cb..9e0e16808 100644 --- a/README.md +++ b/README.md @@ -1093,8 +1093,8 @@ Eval ### Detailed ```python -from ast import Add, Sub, Mult, Div, Pow, BitXor, USub, \ - parse, Num, BinOp, UnaryOp +from ast import parse, Num, BinOp, UnaryOp, \ + Add, Sub, Mult, Div, Pow, BitXor, USub import operator as op operators = {Add: op.add, From 8e5e388482885fdc95b85b12aecdb109a9d137ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:18:26 +0100 Subject: [PATCH 0034/2378] Eval --- README.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 9e0e16808..7a8b05a2f 100644 --- a/README.md +++ b/README.md @@ -1093,17 +1093,17 @@ Eval ### Detailed ```python -from ast import parse, Num, BinOp, UnaryOp, \ - Add, Sub, Mult, Div, Pow, BitXor, USub +import ast +from ast import parse, Num, BinOp, UnaryOp import operator as op -operators = {Add: op.add, - Sub: op.sub, - Mult: op.mul, - Div: op.truediv, - Pow: op.pow, - BitXor: op.xor, - USub: op.neg} +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 = parse(expression, mode='eval') From d62453d37b1dea2eb1179484dcf49f49f2086207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:21:43 +0100 Subject: [PATCH 0035/2378] Eval --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7a8b05a2f..a766dd35e 100644 --- a/README.md +++ b/README.md @@ -1094,7 +1094,7 @@ Eval ### Detailed ```python import ast -from ast import parse, Num, BinOp, UnaryOp +from ast import Num, BinOp, UnaryOp, parse import operator as op operators = {ast.Add: op.add, From b32043bc62382503e84cd9e4e39f0169e34d63b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:22:45 +0100 Subject: [PATCH 0036/2378] Eval --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a766dd35e..2472010c7 100644 --- a/README.md +++ b/README.md @@ -1094,7 +1094,7 @@ Eval ### Detailed ```python import ast -from ast import Num, BinOp, UnaryOp, parse +from ast import Num, BinOp, UnaryOp import operator as op operators = {ast.Add: op.add, @@ -1106,7 +1106,7 @@ operators = {ast.Add: op.add, ast.USub: op.neg} def evaluate(expression): - root = parse(expression, mode='eval') + root = ast.parse(expression, mode='eval') return eval_node(root.body) def eval_node(node): From 79a68b27ba6a382a652effb1e900e71332b7ccd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:26:39 +0100 Subject: [PATCH 0037/2378] Eval --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2472010c7..f07d3a5fd 100644 --- a/README.md +++ b/README.md @@ -1091,7 +1091,7 @@ Eval [1, 2, 3] ``` -### Detailed +### Using Abstract Syntax Trees ```python import ast from ast import Num, BinOp, UnaryOp From 2dba08f3c9d48c8b0dc878463f0c00150919063b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 18:35:15 +0100 Subject: [PATCH 0038/2378] Eval --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f07d3a5fd..91887c7cd 100644 --- a/README.md +++ b/README.md @@ -1097,13 +1097,13 @@ import ast from ast import Num, BinOp, UnaryOp import operator as op -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} +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') @@ -1115,7 +1115,7 @@ def eval_node(node): return node.n if type_ not in [BinOp, UnaryOp]: raise TypeError(node) - operator = operators[type(node.op)] + operator = legal_operators[type(node.op)] if type_ == BinOp: left, right = eval_node(node.left), eval_node(node.right) return operator(left, right) From 19d4425437e56df607a965176e6ee9954d234d53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 19:09:02 +0100 Subject: [PATCH 0039/2378] Eval --- README.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 91887c7cd..66a08addc 100644 --- a/README.md +++ b/README.md @@ -1110,16 +1110,19 @@ def evaluate(expression): return eval_node(root.body) def eval_node(node): - type_ = type(node) - if type_ == Num: + node_type = type(node) + if node_type == Num: return node.n - if type_ not in [BinOp, UnaryOp]: + if node_type not in [BinOp, UnaryOp]: raise TypeError(node) - operator = legal_operators[type(node.op)] - if type_ == BinOp: + op_type = type(node.op) + if op_type not in legal_operators: + raise TypeError(f'Illegal operator {node.op}') + operator = legal_operators[op_type] + if node_type == BinOp: left, right = eval_node(node.left), eval_node(node.right) return operator(left, right) - elif type_ == UnaryOp: + elif node_type == UnaryOp: operand = eval_node(node.operand) return operator(operand) ``` From 13ddb767a58aef3b828f57d61666ffc79ab2c9d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 19:15:11 +0100 Subject: [PATCH 0040/2378] Eval --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 66a08addc..eca3f0c5f 100644 --- a/README.md +++ b/README.md @@ -1115,10 +1115,10 @@ def eval_node(node): return node.n if node_type not in [BinOp, UnaryOp]: raise TypeError(node) - op_type = type(node.op) - if op_type not in legal_operators: + operator_type = type(node.op) + if operator_type not in legal_operators: raise TypeError(f'Illegal operator {node.op}') - operator = legal_operators[op_type] + operator = legal_operators[operator_type] if node_type == BinOp: left, right = eval_node(node.left), eval_node(node.right) return operator(left, right) From f2fe7fa2aec63d097fc2b16e104106166b12e9f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 19:56:58 +0100 Subject: [PATCH 0041/2378] Dictionary --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index eca3f0c5f..3f7b34b94 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ value = .setdefault(key, default) # Same, but also adds default to di .update() = dict() # Initiates a dict from list of key-value pairs. = dict(zip(keys, values)) # Initiates a dict from two lists. + = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. {k: v for k, v in .items() if k in keys} # Filters a dict by keys. ``` From 6715b0623af85a2ae652006c84c4e22704255039 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 22:11:00 +0100 Subject: [PATCH 0042/2378] System - path --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 3f7b34b94..b6fada1d4 100644 --- a/README.md +++ b/README.md @@ -680,6 +680,12 @@ import os = os.listdir() ``` +```python +>>> from glob import glob +>>> glob('*.gif') +['1.gif', 'card.gif'] +``` + ### Execute Command ```python import os From 4148f32b703b379acabf95806abb4c7b74cafb19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 28 Dec 2018 22:11:54 +0100 Subject: [PATCH 0043/2378] System - path --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b6fada1d4..197356d61 100644 --- a/README.md +++ b/README.md @@ -682,7 +682,7 @@ import os ```python >>> from glob import glob ->>> glob('*.gif') +>>> glob('../*.gif') ['1.gif', 'card.gif'] ``` From 28a2d8e7f26bcc79608adbb4832df0e668908f23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 00:34:43 +0100 Subject: [PATCH 0044/2378] Scraping --- README.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/README.md b/README.md index 197356d61..3e03c4277 100644 --- a/README.md +++ b/README.md @@ -1297,6 +1297,40 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus ``` +Scraping +-------- +```python +# $ pip3 install beautifulsoup4 +from http.cookiejar import CookieJar +from urllib.error import HTTPError, URLError +from urllib.request import build_opener, HTTPCookieProcessor +from bs4 import BeautifulSoup + +def scrape(url): + """Returns tree of HTML elements located at URL.""" + jar = CookieJar() + opener = build_opener(HTTPCookieProcessor(jar)) + opener.addheaders = [('User-agent', 'Mozilla/5.0')] + try: + html = opener.open(url) + except ValueError as error: + return print(f'Malformed URL: {url}.\n{error}') + except (HTTPError, URLError) as error: + return print(f"Can't find URL: {url}.\n{error}") + return BeautifulSoup(html, 'html.parser') +``` + +```python +>>> document = scrape('https://en.wikipedia.org/wiki/Python_(programming_language)') +>>> table = document.find('table', class_='infobox vevent') +>>> rows = table.find_all('tr') +>>> rows[11].find('a')['href'] +'https://www.python.org/' +>>> rows[6].find('div').text.split()[0] +'3.7.2' +``` + + Web --- ```python From 9257434c48a67dade0664d53e9b59c1754d11b52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 01:35:38 +0100 Subject: [PATCH 0045/2378] SQLite --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3e03c4277..85ebb469d 100644 --- a/README.md +++ b/README.md @@ -767,7 +767,7 @@ db = sqlite3.connect() ```python cursor = db.execute() if cursor: - cursor.fetchall() # Or cursor.fetchone() + = cursor.fetchall() # Or cursor.fetchone() db.close() ``` From ede7d8d5f66cce17191f0c468435b0afb785c20e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 01:44:52 +0100 Subject: [PATCH 0046/2378] Combinations --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 85ebb469d..e55dd6223 100644 --- a/README.md +++ b/README.md @@ -935,7 +935,8 @@ from itertools import * >>> combinations_with_replacement('abc', 2) [('a', 'a'), ('a', 'b'), ('a', 'c'), - ('b', 'b'), ('b', 'c'), ('c', 'c')] + ('b', 'b'), ('b', 'c'), + ('c', 'c')] >>> permutations('abc', 2) [('a', 'b'), ('a', 'c'), From 70e12f10be66bdd419504ae7c88124269deefe24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:08:01 +0100 Subject: [PATCH 0047/2378] Parameters --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e55dd6223..40cda4e15 100644 --- a/README.md +++ b/README.md @@ -1029,7 +1029,7 @@ False #### Getting the number of parameters of a function: ```python from inspect import signature -sig = signature() +sig = signature() no_of_params = len(sig.parameters) ``` From 2646204f65862b28804ce48df58af211e6aa719e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:25:06 +0100 Subject: [PATCH 0048/2378] Operator --- README.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/README.md b/README.md index 40cda4e15..fef5d3fc5 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,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. @@ -1077,14 +1078,10 @@ from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ ``` ```python -from enum import Enum from functools import reduce - product_of_elems = reduce(mul, ) sorted_by_second = sorted(, key=itemgetter(1)) sorted_by_both = sorted(, key=itemgetter(0, 1)) -LogicOp = Enum('LogicOp', {'AND': (and_, ), - 'OR' : (or_, )}) ``` From 2e8f9a045a1b127ac76703434fa53e439e839e15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:26:24 +0100 Subject: [PATCH 0049/2378] Logarithm --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index fef5d3fc5..3e1853301 100644 --- a/README.md +++ b/README.md @@ -373,7 +373,9 @@ from math import cos, acos, sin, asin, tan, atan, degrees, radians ### Logarithm ```python from math import log, log10, log2 +``` +```python log(x [, base]) # Base e, if not specified. log10(x) # Base 10. log2(x) # Base 2. From a530e90c1ea7d2b141d2626b5183fd523de29c85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:28:13 +0100 Subject: [PATCH 0050/2378] Random --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 3e1853301..be2d71cf2 100644 --- a/README.md +++ b/README.md @@ -394,6 +394,9 @@ float('inf'), float('nan') ### Random ```python from random import random, randint, choice, shuffle +``` + +```python = random() = randint(from_inclusive, to_inclusive) = choice() From 445a6b21f6cdc2e6f9931c230b51dcf6eba80c42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:30:31 +0100 Subject: [PATCH 0051/2378] Numbers --- README.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/README.md b/README.md index be2d71cf2..8f3db7277 100644 --- a/README.md +++ b/README.md @@ -373,9 +373,6 @@ from math import cos, acos, sin, asin, tan, atan, degrees, radians ### Logarithm ```python from math import log, log10, log2 -``` - -```python log(x [, base]) # Base e, if not specified. log10(x) # Base 10. log2(x) # Base 2. @@ -394,9 +391,6 @@ float('inf'), float('nan') ### Random ```python from random import random, randint, choice, shuffle -``` - -```python = random() = randint(from_inclusive, to_inclusive) = choice() From 1755086d5e6379f2209cdf062d77b1fba5fe8981 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:32:26 +0100 Subject: [PATCH 0052/2378] Operator --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 8f3db7277..4c9b53d5f 100644 --- a/README.md +++ b/README.md @@ -1077,8 +1077,7 @@ from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ ``` ```python -from functools import reduce -product_of_elems = reduce(mul, ) +product_of_elems = functools.reduce(mul, ) sorted_by_second = sorted(, key=itemgetter(1)) sorted_by_both = sorted(, key=itemgetter(0, 1)) ``` From 29314c2d336d49040685a1159e94d8ea18db7ca6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:38:51 +0100 Subject: [PATCH 0053/2378] Operator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4c9b53d5f..ba565ff08 100644 --- a/README.md +++ b/README.md @@ -1072,7 +1072,7 @@ Operator ```python from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ eq, ne, lt, le, gt, ge, \ - not_, and_, or_, xor, \ + not_, and_, or_, \ itemgetter ``` From 67714fda1f4c403ac790ba8f1a3eed016fd79d6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 02:48:35 +0100 Subject: [PATCH 0054/2378] Eval --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ba565ff08..edc670998 100644 --- a/README.md +++ b/README.md @@ -1088,8 +1088,8 @@ Eval ### Basic ```python >>> from ast import literal_eval ->>> literal_eval('1 + 1') -2 +>>> literal_eval('1 + 2') +3 >>> literal_eval('[1, 2, 3]') [1, 2, 3] ``` From 36493f5ba2c4bcba9d094db1bdfd4b140091d57f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 13:56:19 +0100 Subject: [PATCH 0055/2378] Dictionary --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index edc670998..57f11e154 100644 --- a/README.md +++ b/README.md @@ -61,10 +61,10 @@ Dictionary ``` ```python -value = .get(key, default) # Returns default if key does not exist. -value = .setdefault(key, default) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. +value = .get(key, default) # Returns default if key does not exist. +value = .setdefault(key, default) # Same, but also adds default to dict. + = collections.defaultdict() # Creates a dictionary with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. ``` ```python From a3903de7aa8050c3bd3d5f9cb9376226b2cf0e83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 13:57:15 +0100 Subject: [PATCH 0056/2378] Dictionary --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 57f11e154..edc670998 100644 --- a/README.md +++ b/README.md @@ -61,10 +61,10 @@ Dictionary ``` ```python -value = .get(key, default) # Returns default if key does not exist. -value = .setdefault(key, default) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. +value = .get(key, default) # Returns default if key does not exist. +value = .setdefault(key, default) # Same, but also adds default to dict. + = collections.defaultdict() # Creates a dictionary with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. ``` ```python From 02a09d4a8a4d50044852efe416078502c537ee99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:08:03 +0100 Subject: [PATCH 0057/2378] Iterator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index edc670998..bcb7a8cc1 100644 --- a/README.md +++ b/README.md @@ -167,7 +167,7 @@ for line in iter(input, ''): #### Same, but prints a message every time: ```python from functools import partial -for line in iter(partial(input, 'Please enter value'), ''): +for line in iter(partial(input, 'Please enter value: '), ''): ... ``` From 74e4ef67b0abfcbe8055fde3353a8aee71b7d52e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:16:00 +0100 Subject: [PATCH 0058/2378] Regex --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bcb7a8cc1..f34bf184c 100644 --- a/README.md +++ b/README.md @@ -258,8 +258,8 @@ Regex ----- ```python import re - = re.sub(, new, text, count=0) # Substitutes all occurrences. = re.findall(, text) + = re.sub(, new, text, count=0) # Substitutes 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. From 4f203520f5761370e163d039d4046165e92d4d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:17:36 +0100 Subject: [PATCH 0059/2378] Regex --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f34bf184c..bcb7a8cc1 100644 --- a/README.md +++ b/README.md @@ -258,8 +258,8 @@ Regex ----- ```python import re - = re.findall(, text) = 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. From 2d830c5329388bc9cf53d7c00f62950063561d39 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:23:36 +0100 Subject: [PATCH 0060/2378] String --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index bcb7a8cc1..820b4ddfc 100644 --- a/README.md +++ b/README.md @@ -314,6 +314,10 @@ Format ``` ### String Options +```python +{'abcde'!r} # "'abcde'" +``` + ```python {'abcde':.3} # 'abc' {'abcde':10.3} # 'abc ' From d5d06f36a1ff165fd9b3208831728b9c3bc630ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:27:17 +0100 Subject: [PATCH 0061/2378] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 820b4ddfc..807808bac 100644 --- a/README.md +++ b/README.md @@ -315,7 +315,7 @@ Format ### String Options ```python -{'abcde'!r} # "'abcde'" +{'abcde'!r} # "'abcde'" -> Uses objects repr() function. ``` ```python From cbefb525a95d871756ba38a5cb5dd2a850464d09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:34:06 +0100 Subject: [PATCH 0062/2378] String --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 807808bac..6a9363ce5 100644 --- a/README.md +++ b/README.md @@ -314,8 +314,9 @@ Format ``` ### String Options +**'!r' uses objects repr() function, instead of __format__() to get a string.** ```python -{'abcde'!r} # "'abcde'" -> Uses objects repr() function. +{'abcde'!r} # "'abcde'" ``` ```python From 52d5cb56d9a2295a8ad944774498f9f396be1472 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:36:04 +0100 Subject: [PATCH 0063/2378] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a9363ce5..88aef1dc0 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ Format ``` ### String Options -**'!r' uses objects repr() function, instead of __format__() to get a string.** +**'!r' uses objects `repr()` function, instead of `__format__()`, to get a string.** ```python {'abcde'!r} # "'abcde'" ``` From c8e5abae161c9ea69e4f9d76a296d49552ac9d20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:38:26 +0100 Subject: [PATCH 0064/2378] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 88aef1dc0..ada4dc3ff 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ Format ``` ### String Options -**'!r' uses objects `repr()` function, instead of `__format__()`, to get a string.** +**'!r' uses object's `repr()` function, instead of `__format__()`, to get a string:** ```python {'abcde'!r} # "'abcde'" ``` From 4e1a1cd4e83c29c8f81dc60e38944ba2c35f616b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 14:41:19 +0100 Subject: [PATCH 0065/2378] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ada4dc3ff..bc42a3c46 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ Format ``` ### String Options -**'!r' uses object's `repr()` function, instead of `__format__()`, to get a string:** +**`'!r'` uses object's `repr()` function, instead of `__format__()`, to get a string:** ```python {'abcde'!r} # "'abcde'" ``` From f68cd70e057bdeeb760c8a255e94e1fc52ac1ce4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:07:38 +0100 Subject: [PATCH 0066/2378] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bc42a3c46..0a0978549 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ Format ``` ### String Options -**`'!r'` uses object's `repr()` function, instead of `__format__()`, to get a string:** +**"!r" uses object's `repr()` function, instead of `__format__()`, to get a string:** ```python {'abcde'!r} # "'abcde'" ``` From 022e64213b47893e47cef25dfe7fe4f4c0b1fd65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:09:56 +0100 Subject: [PATCH 0067/2378] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a0978549..117f13567 100644 --- a/README.md +++ b/README.md @@ -314,7 +314,7 @@ Format ``` ### String Options -**"!r" uses object's `repr()` function, instead of `__format__()`, to get a string:** +**"!r" uses object's `repr()` method, instead of `__format__()`, to get a string:** ```python {'abcde'!r} # "'abcde'" ``` From 85c27cc75415dda68a17ae46886ca49b4162449c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:15:16 +0100 Subject: [PATCH 0068/2378] Namedtuple --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 117f13567..5839e7a3a 100644 --- a/README.md +++ b/README.md @@ -138,13 +138,15 @@ Named Tuple ----------- ```python >>> Point = collections.namedtuple('Point', 'x y') ->>> a = Point(1, y=2) +>>> p = Point(1, y=2) Point(x=1, y=2) ->>> a.x +>>> p[0] 1 ->>> getattr(a, 'y') +>>> p.x +1 +>>> getattr(p, 'y') 2 ->>> Point._fields +>>> Point._fields # Or: p._fields ('x', 'y') ``` From 9c67c4205f9fbef8dc4230deb17a68abf9b0c2b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:17:23 +0100 Subject: [PATCH 0069/2378] Namedtuple --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5839e7a3a..8ce3f869e 100644 --- a/README.md +++ b/README.md @@ -146,7 +146,7 @@ Point(x=1, y=2) 1 >>> getattr(p, 'y') 2 ->>> Point._fields # Or: p._fields +>>> p._fields # Or: Point._fields ('x', 'y') ``` From acf0f2ec21ce3418cbd517c49b8b2ed71ddad678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:24:45 +0100 Subject: [PATCH 0070/2378] Namedtuple --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8ce3f869e..f3d6d52a5 100644 --- a/README.md +++ b/README.md @@ -316,7 +316,7 @@ Format ``` ### String Options -**"!r" uses object's `repr()` method, instead of `__format__()`, to get a string:** +**"!r" uses object's `repr()` method, instead of `format()`, to get a string:** ```python {'abcde'!r} # "'abcde'" ``` From a25284af1fabfe77a7d6bedc1de08ff9f0a2c82c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:30:36 +0100 Subject: [PATCH 0071/2378] Format --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f3d6d52a5..871ce96ce 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,7 @@ Format #### Float presentation types: * `'f'` - Fixed point: `.f` +* `'%'` - Percent: `.%' * `'e'` - Exponent #### Integer presentation types: From d9c2df717772ebf4eb94df52ac2de00e1e414c26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:31:15 +0100 Subject: [PATCH 0072/2378] Format --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 871ce96ce..e9bc9de5b 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ Format #### Float presentation types: * `'f'` - Fixed point: `.f` -* `'%'` - Percent: `.%' +* `'%'` - Percent: `.%` * `'e'` - Exponent #### Integer presentation types: From 958c84856eeb6cebce0c2ddcf6fedb9b5d5b0b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:32:09 +0100 Subject: [PATCH 0073/2378] Format --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9bc9de5b..8f67ddee4 100644 --- a/README.md +++ b/README.md @@ -349,7 +349,7 @@ Format #### Float presentation types: * `'f'` - Fixed point: `.f` -* `'%'` - Percent: `.%` +* `'%'` - Percent: `.%` * `'e'` - Exponent #### Integer presentation types: From 67baced913447269a5310ca2b3681086b5f6d49c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:34:32 +0100 Subject: [PATCH 0074/2378] Format --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8f67ddee4..50aa6ea07 100644 --- a/README.md +++ b/README.md @@ -316,7 +316,7 @@ Format ``` ### String Options -**"!r" uses object's `repr()` method, instead of `format()`, to get a string:** +**"!r" uses object's repr() method, instead of format(), to get a string:** ```python {'abcde'!r} # "'abcde'" ``` From 837019f808f262083b9a2b4411448b90d4ff58fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:36:02 +0100 Subject: [PATCH 0075/2378] Finally --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 50aa6ea07..493d91638 100644 --- a/README.md +++ b/README.md @@ -820,7 +820,6 @@ raise ValueError('A very specific message!') ... raise KeyboardInterrupt ... finally: ... print('Goodbye, world!') -... Goodbye, world! Traceback (most recent call last): File "", line 2, in From 861ab4f466c4fcc54cae13545290c9a54e7e28e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:38:35 +0100 Subject: [PATCH 0076/2378] Exceptions --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 493d91638..70e04b04f 100644 --- a/README.md +++ b/README.md @@ -809,12 +809,12 @@ while True: break ``` -#### Raising exception: +### Raising Exceptions ```python raise ValueError('A very specific message!') ``` -#### Finally: +### Finally ```python >>> try: ... raise KeyboardInterrupt From 1175c3c48c5e83c5dda92307c803626d3f59ead0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:39:40 +0100 Subject: [PATCH 0077/2378] Exceptions --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 70e04b04f..98fb86545 100644 --- a/README.md +++ b/README.md @@ -809,7 +809,7 @@ while True: break ``` -### Raising Exceptions +#### Raising exception: ```python raise ValueError('A very specific message!') ``` From 13651336fb4201fc9ffdde222f52dfdcb24c7391 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:48:00 +0100 Subject: [PATCH 0078/2378] Enum --- README.md | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/README.md b/README.md index 98fb86545..114727296 100644 --- a/README.md +++ b/README.md @@ -620,10 +620,6 @@ class (Enum): @classmethod def get_names(cls): return [a.name for a in cls.__members__.values()] - - @classmethod - def get_values(cls): - return [a.value for a in cls.__members__.values()] ``` ```python @@ -637,6 +633,7 @@ class (Enum): ```python list_of_members = list() member_names = [a.name for a in ] +member_values = [a.value for a in ] random_member = random.choice(list()) ``` From 4ef2d28412b8e9f31cc6198f99f697cf7b83b075 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 15:53:26 +0100 Subject: [PATCH 0079/2378] Path --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 114727296..76f67cfd7 100644 --- a/README.md +++ b/README.md @@ -678,11 +678,11 @@ def write_to_file(filename, text): ### Path ```python -import os - = os.path.exists() - = os.path.isfile() - = os.path.isdir() - = os.listdir() +from os import path, listdir + = path.exists() + = path.isfile() + = path.isdir() + = listdir() ``` ```python From 93aefa59f65fea1c057d4966c88bacca191fbb7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:06:07 +0100 Subject: [PATCH 0080/2378] SQLite --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 76f67cfd7..0c2f9fd5b 100644 --- a/README.md +++ b/README.md @@ -772,7 +772,8 @@ db = sqlite3.connect() ```python cursor = db.execute() if cursor: - = cursor.fetchall() # Or cursor.fetchone() + = cursor.fetchone() # First row. + = cursor.fetchall() # Remaining rows. db.close() ``` From 9eb6389da46a1a1011220be186f8842e8c97cf81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:11:49 +0100 Subject: [PATCH 0081/2378] Infinity --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0c2f9fd5b..e47210aa2 100644 --- a/README.md +++ b/README.md @@ -388,7 +388,7 @@ log2(x) # Base 2. ### Infinity, nan ```python -from math import inf, nan, isfinite, isinf, isnan +from math import inf, nan, isinf, isnan ``` #### Or: From a4b9e18ae9d74210c8e061925220a2e970e29752 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:23:53 +0100 Subject: [PATCH 0082/2378] Pickle --- README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e47210aa2..520914458 100644 --- a/README.md +++ b/README.md @@ -787,10 +787,11 @@ db.commit() Pickle ------ ```python -import pickle -favorite_color = {'lion': 'yellow', 'kitty': 'red'} -pickle.dump(favorite_color, open('data.p', 'wb')) -favorite_color = pickle.load(open('data.p', 'rb')) +>>> 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'} ``` From 3aa852fe9dbbe95fc80f6b381254657e1fc3c30d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:35:22 +0100 Subject: [PATCH 0083/2378] Struct --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 520914458..1fd66aab3 100644 --- a/README.md +++ b/README.md @@ -875,10 +875,13 @@ Struct ### Example ```python >>> from struct import pack, unpack, calcsize + >>> 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 ``` From cb21e6ad110f39a34fb92d7184335bdec757248b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:37:37 +0100 Subject: [PATCH 0084/2378] Struct --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 1fd66aab3..6017ed244 100644 --- a/README.md +++ b/README.md @@ -875,13 +875,19 @@ Struct ### Example ```python >>> from struct import pack, unpack, calcsize +``` +```python >>> pack('hhl', 1, 2, 3) b'\x00\x01\x00\x02\x00\x00\x00\x03' +``` +```python >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) +``` +```python >>> calcsize('hhl') 8 ``` From 189db88cd10cb0e8f8014ec2f5da7a8ddf21af37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:41:33 +0100 Subject: [PATCH 0085/2378] Struct --- README.md | 6 ------ 1 file changed, 6 deletions(-) diff --git a/README.md b/README.md index 6017ed244..024e2b65e 100644 --- a/README.md +++ b/README.md @@ -880,14 +880,8 @@ Struct ```python >>> pack('hhl', 1, 2, 3) b'\x00\x01\x00\x02\x00\x00\x00\x03' -``` - -```python >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) -``` - -```python >>> calcsize('hhl') 8 ``` From a302202e617dc87e5cfee8a95150ceb67f714bfc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:42:48 +0100 Subject: [PATCH 0086/2378] Struct --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 024e2b65e..d196ef67c 100644 --- a/README.md +++ b/README.md @@ -868,15 +868,15 @@ Struct ------ **This module performs conversions between Python values and C struct represented as Python Bytes object.** ```python - = struct.pack('', [, , ...]) - = struct.unpack('', ) +from struct import pack, unpack, calcsize ``` -### Example ```python ->>> from struct import pack, unpack, calcsize + = pack('', [, , ...]) + = unpack('', ) ``` +### Example ```python >>> pack('hhl', 1, 2, 3) b'\x00\x01\x00\x02\x00\x00\x00\x03' From b018653a507210487787436f2342090fe5de1e4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:44:35 +0100 Subject: [PATCH 0087/2378] Struct --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index d196ef67c..e55a1dec8 100644 --- a/README.md +++ b/README.md @@ -869,9 +869,6 @@ Struct **This module performs conversions between Python values and C struct represented as Python Bytes object.** ```python from struct import pack, unpack, calcsize -``` - -```python = pack('', [, , ...]) = unpack('', ) ``` From 3199b3dc0cd1fcdd25651cb3e24554289b562417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:45:56 +0100 Subject: [PATCH 0088/2378] Struct --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e55a1dec8..d1d950a74 100644 --- a/README.md +++ b/README.md @@ -868,7 +868,7 @@ Struct ------ **This module performs conversions between Python values and C struct represented as Python Bytes object.** ```python -from struct import pack, unpack, calcsize +from struct import pack, unpack = pack('', [, , ...]) = unpack('', ) ``` From 1c48ef6061339a3fc2492e3a8caaea0f4c30c39e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 16:54:12 +0100 Subject: [PATCH 0089/2378] Scraping --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index d1d950a74..57ab0abd2 100644 --- a/README.md +++ b/README.md @@ -1326,9 +1326,9 @@ def scrape(url): >>> document = scrape('https://en.wikipedia.org/wiki/Python_(programming_language)') >>> table = document.find('table', class_='infobox vevent') >>> rows = table.find_all('tr') ->>> rows[11].find('a')['href'] +>>> website = rows[11].find('a')['href'] 'https://www.python.org/' ->>> rows[6].find('div').text.split()[0] +>>> latest_v = rows[6].find('div').text.split()[0] '3.7.2' ``` From 295f57c0d7bfdf15b661a685d8522b3e7ca055d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:01:35 +0100 Subject: [PATCH 0090/2378] Iterators --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 57ab0abd2..3da3616f5 100644 --- a/README.md +++ b/README.md @@ -934,7 +934,7 @@ Itertools from itertools import * ``` -### Combinatoric iterators +### Combinatoric Iterators ```python >>> combinations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'c')] @@ -958,7 +958,7 @@ from itertools import * (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] ``` -### Infinite iterators +### Infinite Iterators ```python >>> i = count(5, 2) >>> next(i), next(i), next(i) @@ -1382,7 +1382,7 @@ def odds_handler(sport): Profile ------- -#### Basic: +### Basic ```python from time import time start_time = time() @@ -1390,7 +1390,7 @@ start_time = time() duration = time() - start_time ``` -#### Times execution of the passed code: +### Timing a Snippet ```python from timeit import timeit timeit('"-".join(str(a) for a in range(100))', From 9efe21f32b7f51ca5e75d43c56b1c1f424a6403f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:02:57 +0100 Subject: [PATCH 0091/2378] Iterators --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3da3616f5..a30e2a758 100644 --- a/README.md +++ b/README.md @@ -934,7 +934,7 @@ Itertools from itertools import * ``` -### Combinatoric Iterators +### Combinatoric iterators ```python >>> combinations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'c')] @@ -958,7 +958,7 @@ from itertools import * (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] ``` -### Infinite Iterators +### Infinite iterators ```python >>> i = count(5, 2) >>> next(i), next(i), next(i) From 7b3c71193002c5b353ddd5c9d65455c5d10d4601 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:04:14 +0100 Subject: [PATCH 0092/2378] Web --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a30e2a758..87713742f 100644 --- a/README.md +++ b/README.md @@ -1347,14 +1347,14 @@ bottle.run(host='localhost', port=8080) bottle.run(host='0.0.0.0', port=80, server='cherrypy') ``` -### Static request +### Static Request ```python @route('/img/') def send_image(image): return static_file(image, 'images/', mimetype='image/png') ``` -### Dynamic request +### Dynamic Request ```python @route('/') def send_page(sport): @@ -1363,7 +1363,7 @@ def send_page(sport): return template(page) ``` -### REST request +### REST Request ```python @post('/odds/') def odds_handler(sport): From e4ae168c7c47141c23c9ee5d5121a7e4b177a511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:20:26 +0100 Subject: [PATCH 0093/2378] Profile --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 87713742f..fcc1d6019 100644 --- a/README.md +++ b/README.md @@ -1397,6 +1397,7 @@ timeit('"-".join(str(a) for a in range(100))', number=10000, globals=globals()) ``` +### PyCallGraph #### Generates a PNG image of call graph and highlights the bottlenecks: ```python # $ pip3 install pycallgraph From 0cb6d849456137a061f64c14f6576350c0f992b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:24:41 +0100 Subject: [PATCH 0094/2378] Profile --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fcc1d6019..c61bc3cbb 100644 --- a/README.md +++ b/README.md @@ -1398,7 +1398,7 @@ timeit('"-".join(str(a) for a in range(100))', ``` ### PyCallGraph -#### Generates a PNG image of call graph and highlights the bottlenecks: +#### Generates a PNG image of call graph and highlights the bottlenecks. ```python # $ pip3 install pycallgraph import pycallgraph From f646d1922b6d019f3cb0a1ef65e2a95c8d75d291 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:28:25 +0100 Subject: [PATCH 0095/2378] Profile --- README.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c61bc3cbb..8cb81d367 100644 --- a/README.md +++ b/README.md @@ -1415,13 +1415,13 @@ def get_filename(): return f'profile-{time_str}.png' ``` -#### Decorator for timing functions: +### Timing Decorators +#### Prints runtime of decorated function: ```python from timeit import default_timer from datetime import timedelta def stopwatch(func): - """Prints runtime of decorated function.""" def out(*args, **kwargs): start = default_timer() result = func(*args, **kwargs) @@ -1431,13 +1431,12 @@ def stopwatch(func): return out ``` -#### Decorator for profiling functions: +#### Saves run call profile of the decorated function to file: ```python from cProfile import Profile from pstats import Stats def profiler(func): - """Saves run call profile of the decorated function to file.""" def out(*args, **kwargs): profile = Profile() result = profile.runcall(func, *args, **kwargs) @@ -1451,10 +1450,9 @@ def profiler(func): return out ``` -#### Decorator for function tracing: +#### Prints arguments and output of a decorated function: ```python def tracer(func): - """Prints arguments and output of a decorated function.""" def out(*args, **kwargs): result = func(*args, **kwargs) arg_list = [repr(x) for x in args] From 373424a0f59a3297ce82b0e56abbc73abd5f405f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:31:28 +0100 Subject: [PATCH 0096/2378] Progress bar --- README.md | 45 --------------------------------------------- 1 file changed, 45 deletions(-) diff --git a/README.md b/README.md index 8cb81d367..8faddb7d3 100644 --- a/README.md +++ b/README.md @@ -1466,7 +1466,6 @@ def tracer(func): Progress Bar ------------ -### Tqdm ```python # $ pip3 install tqdm from tqdm import tqdm @@ -1477,50 +1476,6 @@ for i in tqdm([1, 2, 3]): sleep(0.2) ``` -### Basic -```python -import sys - -class Bar(): - @staticmethod - def range(*args): - bar = Bar(len(list(range(*args)))) - for i in range(*args): - yield i - bar.tick() - @staticmethod - def foreach(elements): - bar = Bar(len(elements)) - for el in elements: - yield el - bar.tick() - def __init__(s, steps, width=40): - s.st, s.wi, s.fl, s.i = steps, width, 0, 0 - s.th = s.fl * s.st / s.wi - s.p(f"[{' ' * s.wi}]") - s.p('\b' * (s.wi + 1)) - def tick(s): - s.i += 1 - while s.i > s.th: - s.fl += 1 - s.th = s.fl * s.st / s.wi - s.p('-') - if s.i == s.st: - s.p('\n') - def p(s, t): - sys.stdout.write(t) - sys.stdout.flush() -``` - -#### Usage: -```python -from time import sleep -for i in Bar.range(100): - sleep(0.02) -for el in Bar.foreach([1, 2, 3]): - sleep(0.2) -``` - Basic Script Template --------------------- From d94f71eb88e736fd4be359ec00b81837dd6f524c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:33:54 +0100 Subject: [PATCH 0097/2378] Basic script template --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8faddb7d3..fadc74fe2 100644 --- a/README.md +++ b/README.md @@ -1506,4 +1506,5 @@ def read_file(filename): if __name__ == '__main__': main() + ``` From 1738461e6c70f31ae3d86de915ce1a585bd8d4b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:40:17 +0100 Subject: [PATCH 0098/2378] Moved progress bar --- README.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index fadc74fe2..f1dcbd2c9 100644 --- a/README.md +++ b/README.md @@ -1204,6 +1204,19 @@ pyplot.savefig(, transparent=True) ``` +Progress Bar +------------ +```python +# $ 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) +``` + + Table ----- #### Prints CSV file as ASCII table: @@ -1464,19 +1477,6 @@ def tracer(func): ``` -Progress Bar ------------- -```python -# $ 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) -``` - - Basic Script Template --------------------- ```python From 5a44f3121734fde17c2410050f43059b000e5c46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 29 Dec 2018 17:42:01 +0100 Subject: [PATCH 0099/2378] Audio --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f1dcbd2c9..09980c44a 100644 --- a/README.md +++ b/README.md @@ -1276,7 +1276,7 @@ img.save('out.png') Audio ----- -#### Saves list of floats with values between 0 and 1 to a WAV file: +#### 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 ] From 5471ae89444d1068085be4ec8b546ff0567dc25d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 00:19:06 +0100 Subject: [PATCH 0100/2378] Enheritance --- README.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/README.md b/README.md index 09980c44a..9e5ebe30b 100644 --- a/README.md +++ b/README.md @@ -599,6 +599,19 @@ class : self.a = a ``` +### Inheritance +```python +class Person: + def __init__(self, name, age): + self.name = name + self.age = age + +class Employee(Person): + def __init__(self, name, age, staff_num): + super().__init__(name, age) + self.staff_num = staff_num +``` + ### Copy ```python from copy import copy, deepcopy From 44a43416b89061970b366a183274a5c05ae1f100 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 00:21:28 +0100 Subject: [PATCH 0101/2378] Enheritance --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9e5ebe30b..11df6dcd0 100644 --- a/README.md +++ b/README.md @@ -604,7 +604,7 @@ class : class Person: def __init__(self, name, age): self.name = name - self.age = age + self.age = age class Employee(Person): def __init__(self, name, age, staff_num): From 6332382b6ca6e7ac11dc8026d21332f99920de75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 02:36:59 +0100 Subject: [PATCH 0102/2378] Profile --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 11df6dcd0..0463bf711 100644 --- a/README.md +++ b/README.md @@ -1423,14 +1423,16 @@ timeit('"-".join(str(a) for a in range(100))', number=10000, globals=globals()) ``` -### PyCallGraph +### Call Graph #### Generates a PNG image of call graph and highlights the bottlenecks. ```python # $ pip3 install pycallgraph -import pycallgraph -graph = pycallgraph.output.GraphvizOutput() -graph.output_file = get_filename() -with pycallgraph.PyCallGraph(output=graph): +from pycallgraph import output, PyCallGraph +from datetime import datetime +graph = output.GraphvizOutput() +time_str = datetime.now().strftime('%Y%m%d%H%M%S') +graph.output_file = f'profile-{time_str}.png' +with PyCallGraph(output=graph): ``` From 09952af0ee7a83ed2bc691d62f445843ec785c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 02:38:26 +0100 Subject: [PATCH 0103/2378] Profile --- README.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/README.md b/README.md index 0463bf711..e71e72cb4 100644 --- a/README.md +++ b/README.md @@ -1436,13 +1436,6 @@ with PyCallGraph(output=graph): ``` -```python -def get_filename(): - from datetime import datetime - time_str = datetime.now().strftime('%Y%m%d%H%M%S') - return f'profile-{time_str}.png' -``` - ### Timing Decorators #### Prints runtime of decorated function: ```python From d3cec437b664e46327dcd3c3612cc8fa025761fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 02:38:59 +0100 Subject: [PATCH 0104/2378] Profile --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e71e72cb4..cfcba4c55 100644 --- a/README.md +++ b/README.md @@ -1424,7 +1424,7 @@ timeit('"-".join(str(a) for a in range(100))', ``` ### Call Graph -#### Generates a PNG image of call graph and highlights the bottlenecks. +#### Generates a PNG image of call graph with highlighted the bottlenecks. ```python # $ pip3 install pycallgraph from pycallgraph import output, PyCallGraph From 2db6d42521024ade8b2cb792b6e6cc1398b2297b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 02:56:42 +0100 Subject: [PATCH 0105/2378] Profiling --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cfcba4c55..72278623a 100644 --- a/README.md +++ b/README.md @@ -1436,7 +1436,7 @@ with PyCallGraph(output=graph): ``` -### Timing Decorators +### Profiling Decorators #### Prints runtime of decorated function: ```python from timeit import default_timer From 5a6e4928fa11bb63dc122e913e618353a09c235d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 03:00:04 +0100 Subject: [PATCH 0106/2378] Libraries --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 72278623a..e198ea11b 100644 --- a/README.md +++ b/README.md @@ -1211,6 +1211,7 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot + pyplot.plot( [, , ...]) pyplot.show() pyplot.savefig(, transparent=True) @@ -1223,6 +1224,7 @@ 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]): @@ -1237,6 +1239,7 @@ Table # $ pip3 install tabulate import csv from tabulate import tabulate + with open(, newline='') as csv_file: reader = csv.reader(csv_file, delimiter=';') headers = [a.title() for a in next(reader)] @@ -1273,6 +1276,7 @@ Image ```python # $ pip3 install pillow 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)]) @@ -1292,6 +1296,7 @@ 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) @@ -1429,6 +1434,7 @@ timeit('"-".join(str(a) for a in range(100))', # $ pip3 install pycallgraph from pycallgraph import output, PyCallGraph from datetime import datetime + graph = output.GraphvizOutput() time_str = datetime.now().strftime('%Y%m%d%H%M%S') graph.output_file = f'profile-{time_str}.png' From 274754209121cb850e23d92ecfd1cb6ed27eb4dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 03:04:44 +0100 Subject: [PATCH 0107/2378] Libraries --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e198ea11b..3ed6f5cb7 100644 --- a/README.md +++ b/README.md @@ -1211,7 +1211,6 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot - pyplot.plot( [, , ...]) pyplot.show() pyplot.savefig(, transparent=True) @@ -1237,11 +1236,11 @@ Table #### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate -import csv +from csv import reader from tabulate import tabulate with open(, newline='') as csv_file: - reader = csv.reader(csv_file, delimiter=';') + reader = reader(csv_file, delimiter=';') headers = [a.title() for a in next(reader)] print(tabulate(reader, headers)) ``` From 8f525161f3b3a74df3d3ae6d7d29c607480c00de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 03:05:57 +0100 Subject: [PATCH 0108/2378] Libraries --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index 3ed6f5cb7..40fd6fe47 100644 --- a/README.md +++ b/README.md @@ -1211,6 +1211,9 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot +``` + +```python pyplot.plot( [, , ...]) pyplot.show() pyplot.savefig(, transparent=True) @@ -1223,7 +1226,9 @@ Progress Bar # $ pip3 install tqdm from tqdm import tqdm from time import sleep +``` +```python for i in tqdm(range(100)): sleep(0.02) for i in tqdm([1, 2, 3]): @@ -1238,7 +1243,9 @@ Table # $ pip3 install tabulate from csv import reader from tabulate import tabulate +``` +```python with open(, newline='') as csv_file: reader = reader(csv_file, delimiter=';') headers = [a.title() for a in next(reader)] From 510fc4f2cfc0385dbc9d2be748a1d14b02059c8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 03:08:46 +0100 Subject: [PATCH 0109/2378] Libraries --- README.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 40fd6fe47..277685647 100644 --- a/README.md +++ b/README.md @@ -1211,9 +1211,6 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot -``` - -```python pyplot.plot( [, , ...]) pyplot.show() pyplot.savefig(, transparent=True) @@ -1226,9 +1223,6 @@ Progress Bar # $ pip3 install tqdm from tqdm import tqdm from time import sleep -``` - -```python for i in tqdm(range(100)): sleep(0.02) for i in tqdm([1, 2, 3]): @@ -1238,13 +1232,13 @@ for i in tqdm([1, 2, 3]): Table ----- -#### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate from csv import reader from tabulate import tabulate ``` +#### Prints CSV file as ASCII table: ```python with open(, newline='') as csv_file: reader = reader(csv_file, delimiter=';') @@ -1435,7 +1429,7 @@ timeit('"-".join(str(a) for a in range(100))', ``` ### Call Graph -#### Generates a PNG image of call graph with highlighted the bottlenecks. +#### Generates a PNG image of call graph with highlighted bottlenecks. ```python # $ pip3 install pycallgraph from pycallgraph import output, PyCallGraph From a31cc71e978e5c907c084122392013ff2a38fd79 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 03:11:35 +0100 Subject: [PATCH 0110/2378] Libraries --- README.md | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/README.md b/README.md index 277685647..ad4cab8db 100644 --- a/README.md +++ b/README.md @@ -1232,14 +1232,11 @@ for i in tqdm([1, 2, 3]): Table ----- +#### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate from csv import reader from tabulate import tabulate -``` - -#### Prints CSV file as ASCII table: -```python with open(, newline='') as csv_file: reader = reader(csv_file, delimiter=';') headers = [a.title() for a in next(reader)] @@ -1276,7 +1273,6 @@ Image ```python # $ pip3 install pillow 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)]) @@ -1296,7 +1292,6 @@ 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) @@ -1434,7 +1429,6 @@ timeit('"-".join(str(a) for a in range(100))', # $ pip3 install pycallgraph from pycallgraph import output, PyCallGraph from datetime import datetime - graph = output.GraphvizOutput() time_str = datetime.now().strftime('%Y%m%d%H%M%S') graph.output_file = f'profile-{time_str}.png' From 3d1516dde983b4a0a07207dcc791720b236a1c74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 12:38:22 +0100 Subject: [PATCH 0111/2378] Scraping --- README.md | 27 +++++---------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index ad4cab8db..53b1e5596 100644 --- a/README.md +++ b/README.md @@ -1328,28 +1328,11 @@ from urllib.parse import quote, quote_plus, unquote, unquote_plus Scraping -------- ```python -# $ pip3 install beautifulsoup4 -from http.cookiejar import CookieJar -from urllib.error import HTTPError, URLError -from urllib.request import build_opener, HTTPCookieProcessor -from bs4 import BeautifulSoup - -def scrape(url): - """Returns tree of HTML elements located at URL.""" - jar = CookieJar() - opener = build_opener(HTTPCookieProcessor(jar)) - opener.addheaders = [('User-agent', 'Mozilla/5.0')] - try: - html = opener.open(url) - except ValueError as error: - return print(f'Malformed URL: {url}.\n{error}') - except (HTTPError, URLError) as error: - return print(f"Can't find URL: {url}.\n{error}") - return BeautifulSoup(html, 'html.parser') -``` - -```python ->>> document = scrape('https://en.wikipedia.org/wiki/Python_(programming_language)') +# $ pip3 install requests beautifulsoup4 +>>> import requests +>>> from bs4 import BeautifulSoup +>>> page = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)') +>>> document = BeautifulSoup(page.text, 'html.parser') >>> table = document.find('table', class_='infobox vevent') >>> rows = table.find_all('tr') >>> website = rows[11].find('a')['href'] From 4e6ef3dde340350de96f0435de22fb0582165af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 12:43:13 +0100 Subject: [PATCH 0112/2378] Profiling decorators --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 53b1e5596..b8b1a8410 100644 --- a/README.md +++ b/README.md @@ -1425,7 +1425,7 @@ with PyCallGraph(output=graph): from timeit import default_timer from datetime import timedelta -def stopwatch(func): +def time_me(func): def out(*args, **kwargs): start = default_timer() result = func(*args, **kwargs) @@ -1440,7 +1440,7 @@ def stopwatch(func): from cProfile import Profile from pstats import Stats -def profiler(func): +def profile_me(func): def out(*args, **kwargs): profile = Profile() result = profile.runcall(func, *args, **kwargs) @@ -1456,7 +1456,7 @@ def profiler(func): #### Prints arguments and output of a decorated function: ```python -def tracer(func): +def trace_me(func): def out(*args, **kwargs): result = func(*args, **kwargs) arg_list = [repr(x) for x in args] From 2568023e84d5b17b2f9da9a9d32075e93017b8b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 12:48:52 +0100 Subject: [PATCH 0113/2378] Profile --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b8b1a8410..76cbefe2b 100644 --- a/README.md +++ b/README.md @@ -1407,7 +1407,7 @@ timeit('"-".join(str(a) for a in range(100))', ``` ### 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 From 81ad53ff4eb49e0f14acae9ddc4e8468d979f087 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 30 Dec 2018 13:06:44 +0100 Subject: [PATCH 0114/2378] Profile --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 76cbefe2b..2091e8608 100644 --- a/README.md +++ b/README.md @@ -1420,7 +1420,7 @@ with PyCallGraph(output=graph): ``` ### Profiling Decorators -#### Prints runtime of decorated function: +#### Prints runtime of a decorated function: ```python from timeit import default_timer from datetime import timedelta @@ -1435,7 +1435,7 @@ def time_me(func): return out ``` -#### Saves run call profile of the decorated function to file: +#### Saves run call profile of a decorated function to file: ```python from cProfile import Profile from pstats import Stats From dbb235a855db422072246e3cb8c873c8295a8ee1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 2 Jan 2019 01:40:21 +0100 Subject: [PATCH 0115/2378] Line Profiler --- README.md | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 2091e8608..ee02cbf33 100644 --- a/README.md +++ b/README.md @@ -1063,13 +1063,14 @@ type(, , ) >>> z = Z() ``` -### MetaClass -#### Class that creates class: +### Meta Class +#### Class that creates class. ```python def my_meta_class(name, parents, attrs): ... return type(name, parents, attrs) ``` + #### Or: ```python class MyMetaClass(type): @@ -1406,6 +1407,26 @@ timeit('"-".join(str(a) for a in range(100))', number=10000, globals=globals()) ``` +### Line Profiler +```python +# $ pip3 install line_profiler +@profile +def main(): + a = [(i%3 + 1) * 3 for i in range(10000)] + b = [i ** (i/10000) for i in range(10000)] +main() +``` + +```bash +$ kernprof -lv test.py +Line # Hits Time Per Hit % Time Line Contents +============================================================== + 2 @profile + 3 def main(): + 4 1 2901.0 2901.0 45.2 a = [(i%3 + 1) * 3 for i in range(10000)] + 5 1 3518.0 3518.0 54.8 b = [i ** (i/10000) for i in range(10000)] +``` + ### Call Graph #### Generates a PNG image of call graph with highlighted bottlenecks: ```python From d2bd76a429a24552f00977623b9ab4bad4e3e78c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 2 Jan 2019 01:42:49 +0100 Subject: [PATCH 0116/2378] Line Profiler --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ee02cbf33..df2ea611f 100644 --- a/README.md +++ b/README.md @@ -1417,7 +1417,7 @@ def main(): main() ``` -```bash +``` $ kernprof -lv test.py Line # Hits Time Per Hit % Time Line Contents ============================================================== From 9c55599cd4b216780bb564fc729d04670cce68ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 2 Jan 2019 01:44:04 +0100 Subject: [PATCH 0117/2378] Line Profiler --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index df2ea611f..32128c450 100644 --- a/README.md +++ b/README.md @@ -1421,10 +1421,10 @@ main() $ kernprof -lv test.py Line # Hits Time Per Hit % Time Line Contents ============================================================== - 2 @profile - 3 def main(): - 4 1 2901.0 2901.0 45.2 a = [(i%3 + 1) * 3 for i in range(10000)] - 5 1 3518.0 3518.0 54.8 b = [i ** (i/10000) for i in range(10000)] + 1 @profile + 2 def main(): + 3 1 6196.0 6196.0 53.2 a = [(i%3 + 1) * 3 for i in range(10000)] + 4 1 5455.0 5455.0 46.8 b = [i ** (i/10000) for i in range(10000)] ``` ### Call Graph From 5c51331007b815f5b4963fb5421312e45077370e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 2 Jan 2019 01:49:43 +0100 Subject: [PATCH 0118/2378] Removed profiling decorators --- README.md | 50 +------------------------------------------------- 1 file changed, 1 insertion(+), 49 deletions(-) diff --git a/README.md b/README.md index 32128c450..ce02c5004 100644 --- a/README.md +++ b/README.md @@ -1428,7 +1428,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 from pycallgraph import output, PyCallGraph @@ -1440,54 +1440,6 @@ with PyCallGraph(output=graph): ``` -### Profiling Decorators -#### Prints runtime of a decorated function: -```python -from timeit import default_timer -from datetime import timedelta - -def time_me(func): - def out(*args, **kwargs): - start = default_timer() - result = func(*args, **kwargs) - delta = timedelta(seconds=(default_timer() - start)) - print(f'Function {func.__name__} finished in {delta}') - return result - return out -``` - -#### Saves run call profile of a decorated function to file: -```python -from cProfile import Profile -from pstats import Stats - -def profile_me(func): - def out(*args, **kwargs): - profile = Profile() - result = profile.runcall(func, *args, **kwargs) - filename = f'profile_{func.__name__}.txt' - with open(filename, 'w') as stream: - stats = Stats(profile, stream=stream) - stats.strip_dirs().sort_stats('tottime') - stats.print_stats(20) - print(f"Profile saved as '{filename}'") - return result - return out -``` - -#### Prints arguments and output of a decorated function: -```python -def trace_me(func): - def out(*args, **kwargs): - result = func(*args, **kwargs) - arg_list = [repr(x) for x in args] - arg_list += [f'{k}={v!r}' for k, v in kwargs.items()] - arg_str = ', '.join(arg_list) - print(f'{func.__name__}({arg_str}) = {result!r}') - return result - return out -``` - Basic Script Template --------------------- From 218ef0edbc02260fd428dbccdbfdb1417e88c8de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 2 Jan 2019 19:11:19 +0100 Subject: [PATCH 0119/2378] Github button test --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ce02c5004..6798a4dff 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Comprehensive Python Cheatsheet =============================== [Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md) -or [Fork me on GitHub](https://github.com/gto76/python-cheatsheet). +or Star ![Monty Python](web/image_888.jpeg) From 0134c6afe63febbc80d30715d4d4f09c73e57f9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 2 Jan 2019 19:19:22 +0100 Subject: [PATCH 0120/2378] Github button test --- index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/index.html b/index.html index 048423ec1..2ac9a50b6 100644 --- a/index.html +++ b/index.html @@ -10,6 +10,7 @@ + + + +
+ + +
+ +
+ + + +
+
+
+ + 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 0710/2378] 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 0711/2378] 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 0712/2378] 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 0713/2378] 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 0714/2378] 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 0715/2378] 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 0716/2378] 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 0717/2378] 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 0718/2378] 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 0719/2378] 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 0720/2378] 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 0721/2378] 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 0722/2378] 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 0723/2378] 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 0724/2378] 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 0725/2378] 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 0726/2378] 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 0727/2378] 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 0728/2378] 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 0729/2378] 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 0730/2378] 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 0731/2378] 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 0732/2378] 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 0733/2378] 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 0734/2378] 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 0735/2378] 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 0736/2378] 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 0737/2378] 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 0738/2378] 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 0739/2378] 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 0740/2378] 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 0741/2378] 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 0742/2378] 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 0743/2378] 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 0744/2378] 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 0745/2378] 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 0746/2378] 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 0747/2378] 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 0748/2378] 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 0749/2378] 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 0750/2378] 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 0751/2378] 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 0752/2378] 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 0753/2378] 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 0754/2378] 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 0755/2378] 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 0756/2378] 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 0757/2378] 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 0758/2378] 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 0759/2378] 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() -

    +
    +