From d4c8e004d9632e0f6b00b9021ed8b6c4b3a43d1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 30 Dec 2021 23:23:41 +0100 Subject: [PATCH 001/638] Datetime, Splat operator --- README.md | 7 +++---- index.html | 15 ++++++++------- pdf/remove_links.py | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index fea2ede09..c732d6881 100644 --- a/README.md +++ b/README.md @@ -602,7 +602,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary ``` * **Use `'.weekday()'` to get the day of the week (Mon == 0).** * **`'fold=1'` means the second pass in case of time jumping back for one hour.** -* **TD converts and normalizes args to ±days, seconds (< 86 400) and microseconds (< 1M).** +* **Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).** ### Now ```python @@ -675,6 +675,8 @@ def f(): # def f(x, y): def f(): # def f(x=0, y=0): def f(, ): # def f(x, y=0): ``` +* **A function has it's default values evaluated when it's first encountered in the scope.** +* **Any changes to mutable objects will persist between invocations.** Splat Operator @@ -706,7 +708,6 @@ 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) @@ -716,13 +717,11 @@ 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) -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 c1f260f15..ea13ff09e 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -535,7 +535,7 @@
  • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
  • 'fold=1' means the second pass in case of time jumping back for one hour.
  • -
  • TD converts and normalizes args to ±days, seconds (< 86 400) and microseconds (< 1M).
  • +
  • Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).

Now

<D/DTn>  = D/DT.today()                     # Current local date or naive datetime.
 <DTn>    = DT.utcnow()                      # Naive datetime from current UTC time.
@@ -597,6 +597,10 @@
 def f(<nondefault_args>, <default_args>):      # def f(x, y=0):
 
+
    +
  • A function has it's default values evaluated when it's first encountered in the scope.
  • +
  • Any changes to mutable objects will persist between invocations.
  • +

#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)
@@ -615,8 +619,7 @@
 
>>> 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)
-def f(*, x, y, z):             # f(x=1, y=2, z=3)
+

Legal argument combinations:

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)
 
@@ -624,11 +627,9 @@
def f(*args):                  # f(1, 2, 3)
 def f(x, *args):               # f(1, 2, 3)
 def f(*args, z):               # f(1, 2, z=3)
-def f(x, *args, z):            # f(1, 2, z=3)
 
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)
@@ -2875,7 +2876,7 @@
  
 
   
- +
diff --git a/pdf/remove_links.py b/pdf/remove_links.py index 86f333539..5480a8fbf 100755 --- a/pdf/remove_links.py +++ b/pdf/remove_links.py @@ -7,7 +7,7 @@ MATCHES = { - 'For details about built-in functions sorted(), min() and max() see sortable.': 'For details about built-in functions sorted(), min() and max() see sortable (p. 16).', + 'For details about sorted(), min() and max() see sortable.': 'For details about sorted(), min() and max() see sortable (p. 16).', 'Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.': 'Module \'operator\' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.', 'Adding \'!r\' before the colon converts object to string by calling its repr() method.': 'Adding \'!r\' before the colon converts object to string by calling its repr() method (p. 14).', 'It can be any callable, but is usually implemented as a function that returns a closure.': 'It can be any callable (p. 17), but is usually implemented as a function that returns a closure (p. 12).', From bd53edb6d03ce4e811c8f319cff49ae6b5615114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 1 Jan 2022 20:03:02 +0100 Subject: [PATCH 002/638] Type annotations --- README.md | 12 +++++++++--- index.html | 14 +++++++++----- pdf/index_for_pdf.html | 4 ++-- pdf/index_for_pdf_print.html | 4 ++-- pdf/remove_links.py | 1 + 5 files changed, 23 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index c732d6881..74ed73171 100644 --- a/README.md +++ b/README.md @@ -675,7 +675,7 @@ def f(): # def f(x, y): def f(): # def f(x=0, y=0): def f(, ): # def f(x, y=0): ``` -* **A function has it's default values evaluated when it's first encountered in the scope.** +* **A function has its default values evaluated when it's first encountered in the scope.** * **Any changes to mutable objects will persist between invocations.** @@ -1043,7 +1043,7 @@ class : : list/dict/set = field(default_factory=list/dict/set) ``` * **Objects can be made [sortable](#sortable) with `'order=True'` and immutable with `'frozen=True'`.** -* **For object to be hashable, all attributes must be hashable and frozen must be True.** +* **For object to be [hashable](#hashable), all attributes must be hashable and frozen must be True.** * **Function field() is needed because `': list = []'` would make a list that is shared among all instances. Its 'default_factory' argument can be any [callable](#callable).** * **For attributes of arbitrary type use `'typing.Any'`.** @@ -1055,6 +1055,13 @@ from dataclasses import make_dataclass = ('', [, ]) ``` +#### Rest of type annotations (CPython interpreter ignores them all): +```python +def func(: [= ]) -> : +: typing.List/Set/Iterable/Sequence/Optional[] +: typing.Dict/Tuple/Union[, ...] +``` + ### Slots **Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.** @@ -1068,7 +1075,6 @@ class MyClassWithSlots: ### Copy ```python from copy import copy, deepcopy - = copy() = deepcopy() ``` diff --git a/index.html b/index.html index ea13ff09e..25dcf98c1 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -598,7 +598,7 @@
    -
  • A function has it's default values evaluated when it's first encountered in the scope.
  • +
  • A function has its default values evaluated when it's first encountered in the scope.
  • Any changes to mutable objects will persist between invocations.

#Splat Operator

Inside Function Call

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

args   = (1, 2)
@@ -886,7 +886,7 @@
 
 
  • Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
  • -
  • For object to be hashable, all attributes must be hashable and frozen must be True.
  • +
  • For object to be hashable, all attributes must be hashable and frozen must be True.
  • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances. Its 'default_factory' argument can be any callable.
  • For attributes of arbitrary type use 'typing.Any'.
@@ -895,6 +895,11 @@ <class> = make_dataclass('<class_name>', <coll_of_tuples>) <tuple> = ('<attr_name>', <type> [, <default_value>])
+

Rest of type annotations (CPython interpreter ignores them all):

def func(<arg_name>: <type> [= <obj>]) -> <type>:
+<var_name>: typing.List/Set/Iterable/Sequence/Optional[<type>]
+<var_name>: typing.Dict/Tuple/Union[<type>, ...]
+
+

Slots

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

class MyClassWithSlots:
     __slots__ = ['a']
     def __init__(self):
@@ -903,7 +908,6 @@
 
 
 

Copy

from copy import copy, deepcopy
-
 <object> = copy(<object>)
 <object> = deepcopy(<object>)
 
@@ -2876,7 +2880,7 @@
- +
diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html index 2610191ec..365b8c112 100644 --- a/pdf/index_for_pdf.html +++ b/pdf/index_for_pdf.html @@ -132,7 +132,6 @@

S

struct module, 28-29
subprocess module, 25
super function, 14
-synthesizer, 41
sys module, 13, 21-22

T

table, 26, 27, 34, 37-38, 45-46
@@ -140,7 +139,8 @@

T

threading module, 30
time module, 34, 36
tuples, 3, 4, 11
-type, 4, 31-32

+type, 4, 31-32
+type annotations, 15

W

wave module, 40-41
web, 36

diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 1b93c3fa6..3aa2bfe29 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -132,7 +132,6 @@

S

struct module, 28-29
subprocess module, 25
super function, 14
-synthesizer, 41
sys module, 13, 21-22

T

table, 26, 27, 34, 37-38, 45-46
@@ -140,7 +139,8 @@

T

threading module, 30
time module, 34, 36
tuples, 3, 4, 11
-type, 4, 31-32

+type, 4, 31-32
+type annotations, 15

W

wave module, 40-41
web, 36

diff --git a/pdf/remove_links.py b/pdf/remove_links.py index 5480a8fbf..9ca06f5b9 100755 --- a/pdf/remove_links.py +++ b/pdf/remove_links.py @@ -12,6 +12,7 @@ 'Adding \'!r\' before the colon converts object to string by calling its repr() method.': 'Adding \'!r\' before the colon converts object to string by calling its repr() method (p. 14).', 'It can be any callable, but is usually implemented as a function that returns a closure.': 'It can be any callable (p. 17), but is usually implemented as a function that returns a closure (p. 12).', 'Objects can be made sortable with \'order=True\' and immutable with \'frozen=True\'.': 'Objects can be made sortable with \'order=True\' and immutable with \'frozen=True\'.', + 'For object to be hashable, all attributes must be hashable and frozen must be True.': 'For object to be hashable, all attributes must be hashable and frozen must be True.', 'Function field() is needed because \'<attr_name>: list = []\' would make a list that is shared among all instances. Its \'default_factory\' argument can be any callable.': 'Function field() is needed because \'<attr_name>: list = []\' would make a list that is shared among all instances. Its \'default_factory\' argument can be any callable (p. 17).', 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator.': 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).', 'Objects returned by the itertools module, such as count, repeat and cycle.': 'Objects returned by the itertools module, such as count, repeat and cycle (p. 3).', From d8354f9608bf1c4a9690e9d2183aef05767684cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 5 Jan 2022 14:13:09 +0100 Subject: [PATCH 003/638] Arguments, Threading, Operator, Web --- README.md | 30 +++++++++++++++--------------- index.html | 37 +++++++++++++++++++------------------ pdf/remove_links.py | 2 +- 3 files changed, 35 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 74ed73171..dd9bdc07b 100644 --- a/README.md +++ b/README.md @@ -676,7 +676,7 @@ def f(): # def f(x=0, y=0): def f(, ): # def f(x, y=0): ``` * **A function has its default values evaluated when it's first encountered in the scope.** -* **Any changes to mutable objects will persist between invocations.** +* **Any changes to default values that are mutable will persist between invocations.** Splat Operator @@ -722,13 +722,13 @@ def f(*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 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) 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 @@ -2107,7 +2107,9 @@ with : # Enters the block by calling acq ``` ### Thread Pool Executor -**Object that manages thread execution.** +* **Object that manages thread execution.** +* **An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be [pickable](#pickle).** + ```python = ThreadPoolExecutor(max_workers=None) # Or: `with ThreadPoolExecutor() as : …` .shutdown(wait=True) # Blocks until all threads finish executing. @@ -2139,24 +2141,23 @@ Operator -------- **Module of functions that provide the functionality of operators.** ```python -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_, xor, inv -from operator import itemgetter, attrgetter, methodcaller +import operator as op + = op.add/sub/mul/truediv/floordiv/mod(, ) # +, -, *, /, //, % + = op.and_/or_/xor(, ) # &, |, ^ + = op.eq/ne/lt/le/gt/ge(, ) # ==, !=, <, <=, >, >= + = op.itemgetter/attrgetter/methodcaller() # [], ., .() ``` ```python -import operator as op elementwise_sum = map(op.add, list_a, list_b) sorted_by_second = sorted(, key=op.itemgetter(1)) sorted_by_both = sorted(, key=op.itemgetter(1, 0)) product_of_elems = functools.reduce(op.mul, ) union_of_sets = functools.reduce(op.or_, ) -last_element = op.methodcaller('pop')() +first_element = op.methodcaller('pop', 0)() ``` -* **Functions and\_(), or\_(), xor() and inv() correspond to operators '&', '|', '^' and '~'.** -* **They only work on objects with and(), or(), xor() and invert() special methods.** -* **Also: `' = &|^ '` and `' = &|^ '`.** +* **Binary operators require objects to have and(), or(), xor() and invert() special methods, unlike logical operators that work on all types of objects.** +* **Also: `' = &|^ '` and `' = &|^ '`.** Introspection @@ -2526,10 +2527,9 @@ def send_html(sport): @post('//odds') def send_json(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]) + return json.dumps({'team': team, 'odds': [2.09, 3.74, 3.68]}) ``` #### Test: @@ -2541,7 +2541,7 @@ def send_json(sport): >>> data = {'team': 'arsenal f.c.'} >>> response = requests.post(url, data=data) >>> response.json() -['arsenal f.c.', 2.44, 3.29] +{'team': 'arsenal f.c.', 'odds': [2.09, 3.74, 3.68]} ``` diff --git a/index.html b/index.html index 25dcf98c1..d81b1f287 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -599,7 +599,7 @@
  • A function has its default values evaluated when it's first encountered in the scope.
  • -
  • Any changes to mutable objects will persist between invocations.
  • +
  • Any changes to default values that are mutable will persist between invocations.

#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}
@@ -630,11 +630,11 @@
 
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)
 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> [, ...]]
 <set>   = {*<collection> [, ...]}
@@ -1737,7 +1737,10 @@
 <Barrier>   = Barrier(n_times)                 # Wait() blocks until it's called n_times.
 
-

Thread Pool Executor

Object that manages thread execution.

<Exec> = ThreadPoolExecutor(max_workers=None)  # Or: `with ThreadPoolExecutor() as <name>: …`
+

Thread Pool Executor

    +
  • Object that manages thread execution.
  • +
  • An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable.
  • +
<Exec> = ThreadPoolExecutor(max_workers=None)  # Or: `with ThreadPoolExecutor() as <name>: …`
 <Exec>.shutdown(wait=True)                     # Blocks until all threads finish executing.
 
@@ -1757,25 +1760,24 @@ <el> = <Queue>.get() # Blocks until queue stops being empty. <el> = <Queue>.get_nowait() # Raises queue.Empty exception if empty.
-

#Operator

Module of functions that provide the functionality of operators.

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_, xor, inv
-from operator import itemgetter, attrgetter, methodcaller
+

#Operator

Module of functions that provide the functionality of operators.

import operator as op
+<el>      = op.add/sub/mul/truediv/floordiv/mod(<el>, <el>)   # +, -, *, /, //, %
+<int/set> = op.and_/or_/xor(<int/set>, <int/set>)             # &, |, ^
+<bool>    = op.eq/ne/lt/le/gt/ge(<sortable>, <sortable>)      # ==, !=, <, <=, >, >=
+<func>    = op.itemgetter/attrgetter/methodcaller(<int/str>)  # [<int/str>], .<str>, .<str>()
 
-
import operator as op
-elementwise_sum  = map(op.add, list_a, list_b)
+
elementwise_sum  = map(op.add, list_a, list_b)
 sorted_by_second = sorted(<collection>, key=op.itemgetter(1))
 sorted_by_both   = sorted(<collection>, key=op.itemgetter(1, 0))
 product_of_elems = functools.reduce(op.mul, <collection>)
 union_of_sets    = functools.reduce(op.or_, <coll_of_sets>)
-last_element     = op.methodcaller('pop')(<list>)
+first_element    = op.methodcaller('pop', 0)(<list>)
 
    -
  • Functions and_(), or_(), xor() and inv() correspond to operators '&', '|', '^' and '~'.
  • -
  • They only work on objects with and(), or(), xor() and invert() special methods.
  • -
  • Also: '<int> = <int> &|^ <bool>' and '<bool> = <bool> &|^ <bool>'.
  • +
  • Binary operators require objects to have and(), or(), xor() and invert() special methods, unlike logical operators that work on all types of objects.
  • +
  • Also: '<bool> = <bool> &|^ <bool>' and '<int> = <bool> &|^ <int>'.

#Introspection

Inspecting code at runtime.

Variables

<list> = dir()                             # Names of local variables (incl. functions).
 <dict> = vars()                            # Dict of local variables. Also locals().
@@ -2062,10 +2064,9 @@
 

REST Request

@post('/<sport>/odds')
 def send_json(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])
+    return json.dumps({'team': team, 'odds': [2.09, 3.74, 3.68]})
 

Test:

# $ pip3 install requests
@@ -2075,7 +2076,7 @@
 >>> data = {'team': 'arsenal f.c.'}
 >>> response = requests.post(url, data=data)
 >>> response.json()
-['arsenal f.c.', 2.44, 3.29]
+{'team': 'arsenal f.c.', 'odds': [2.09, 3.74, 3.68]}
 

#Profiling

Stopwatch

from time import time
@@ -2880,7 +2881,7 @@
  
 
   
 
diff --git a/pdf/remove_links.py b/pdf/remove_links.py
index 9ca06f5b9..1a98ae53e 100755
--- a/pdf/remove_links.py
+++ b/pdf/remove_links.py
@@ -18,9 +18,9 @@
     'Objects returned by the itertools module, such as count, repeat and cycle.': 'Objects returned by the itertools module, such as count, repeat and cycle (p. 3).',
     'Generators returned by the generator functions and generator expressions.': 'Generators returned by the generator functions (p. 4) and generator expressions (p. 11).',
     'File objects returned by the open() function, etc.': 'File objects returned by the open() function (p. 22), etc.',
-    'Another solution in this particular case is to use functions and_() and or_() from the module operator.': 'Another solution in this particular case is to use functions and_() and or_() from the module \'operator\' (p. 31).',
     'Functions report OS related errors by raising either OSError or one of its subclasses.': 'Functions report OS related errors by raising OSError or one of its subclasses (p. 23).',
     'Bools will be stored and returned as ints and dates as ISO formatted strings.': 'Bools will be stored and returned as ints and dates as ISO formatted strings (p. 9).',
+    'An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable.': 'An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable (p. 25).',
     'Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.': 'Asyncio module also provides its own Queue, Event, Lock and Semaphore classes (p. 30).',
 }
 

From 1b04c2c8d26acfbd1893f7477278003d3b4cfecb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jure=20=C5=A0orn?= 
Date: Thu, 6 Jan 2022 15:59:43 +0100
Subject: [PATCH 004/638] Class, Tabulate

---
 README.md           | 30 +++++++++++++++---------------
 index.html          | 34 +++++++++++++++++-----------------
 pdf/README.md       |  4 ++++
 pdf/remove_links.py |  3 +--
 4 files changed, 37 insertions(+), 34 deletions(-)

diff --git a/README.md b/README.md
index dd9bdc07b..265584bb9 100644
--- a/README.md
+++ b/README.md
@@ -708,27 +708,27 @@ def add(*a):
 
 #### Legal argument combinations:
 ```python
-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(*, 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)
-def f(*args, z):               # 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)
 ```
 
 ```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)
+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
-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)
-def f(*args, y, **kwargs):     # f(x=1, y=2, z=3) | f(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)
+def f(*args, y, **kwargs):  # f(x=1, y=2, z=3) | f(1, y=2, z=3)
 ```
 
 ### Other Uses
@@ -1042,8 +1042,8 @@ class :
     :  = 
     : list/dict/set = field(default_factory=list/dict/set)
 ```
-* **Objects can be made [sortable](#sortable) with `'order=True'` and immutable with `'frozen=True'`.**
-* **For object to be [hashable](#hashable), all attributes must be hashable and frozen must be True.**
+* **Objects can be made sortable with `'order=True'` and immutable with `'frozen=True'`.**
+* **For object to be hashable, all attributes must be [hashable](#hashable) and frozen must be True.**
 * **Function field() is needed because `': list = []'` would make a list that is shared among all instances. Its 'default_factory' argument can be any [callable](#callable).**
 * **For attributes of arbitrary type use `'typing.Any'`.**
 
@@ -2393,7 +2393,7 @@ with open('test.csv', encoding='utf-8', newline='') as file:
     rows   = csv.reader(file)
     header = [a.title() for a in next(rows)]
     table  = tabulate.tabulate(rows, header)
-    print(table)
+print(table)
 ```
 
 
diff --git a/index.html b/index.html
index d81b1f287..b719efcb5 100644
--- a/index.html
+++ b/index.html
@@ -54,7 +54,7 @@
 
 
   
- +
@@ -619,22 +619,22 @@
>>> add(1, 2, 3)
 6
 
-

Legal argument combinations:

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)
+

Legal argument combinations:

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)
+
def f(*args):               # f(1, 2, 3)
+def f(x, *args):            # f(1, 2, 3)
+def f(*args, z):            # f(1, 2, z=3)
 
-
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(**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)
-def f(*args, y, **kwargs):     # f(x=1, y=2, z=3) | f(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)
+def f(*args, y, **kwargs):  # f(x=1, y=2, z=3) | f(1, y=2, z=3)
 

Other Uses

<list>  = [*<collection> [, ...]]
 <set>   = {*<collection> [, ...]}
@@ -885,8 +885,8 @@
 
 
 
    -
  • Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
  • -
  • For object to be hashable, all attributes must be hashable and frozen must be True.
  • +
  • Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
  • +
  • For object to be hashable, all attributes must be hashable and frozen must be True.
  • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances. Its 'default_factory' argument can be any callable.
  • For attributes of arbitrary type use 'typing.Any'.
@@ -1956,7 +1956,7 @@ rows = csv.reader(file) header = [a.title() for a in next(rows)] table = tabulate.tabulate(rows, header) - print(table) +print(table)
@@ -2881,7 +2881,7 @@ diff --git a/pdf/README.md b/pdf/README.md index b299c81be..82f00bf04 100644 --- a/pdf/README.md +++ b/pdf/README.md @@ -2,6 +2,7 @@ How To Create PDF (on macOS) ============================ PDF file can also be purchased here: https://transactions.sendowl.com/products/78175486/4422834F/view + Setup ----- * Install Adobe Acrobat Pro DC. @@ -9,6 +10,7 @@ Setup * Change date in header and footer element of `web/template.html`. * Run `./parse.js` and commit changes. + Printing to PDF --------------- ### Normal PDF @@ -39,6 +41,7 @@ Printing to PDF * Select 'Print...' with destination 'Save as PDF', paper size 'A4', 'Default' margins (top 10mm, right 9.5mm, bottom 8mm and left 10mm), 'Default' scale and no headers and footers and save (the document should be 51 pages long with last page empty). * Check if plots were rendered correctly. + Adding headers and footers to PDF (the same for both files) ----------------------------------------------------------- * Open the PDF file in Adobe Acrobat Pro DC. @@ -52,6 +55,7 @@ Adding headers and footers to PDF (the same for both files) * Save the progress by running 'Save as' in Format: 'Adobe PDF Files'. * Run 'Save as' again, this time in 'Adobe PDF Files, Optimized', so that Menlo font error gets fixed. + Printing the PDF ---------------- * Open the PDF that was optimized for printing in Chrome and print on A4 on both sides with default margins, scale 98% and no headers and footers. diff --git a/pdf/remove_links.py b/pdf/remove_links.py index 1a98ae53e..e46c0b897 100755 --- a/pdf/remove_links.py +++ b/pdf/remove_links.py @@ -11,8 +11,7 @@ 'Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.': 'Module \'operator\' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.', 'Adding \'!r\' before the colon converts object to string by calling its repr() method.': 'Adding \'!r\' before the colon converts object to string by calling its repr() method (p. 14).', 'It can be any callable, but is usually implemented as a function that returns a closure.': 'It can be any callable (p. 17), but is usually implemented as a function that returns a closure (p. 12).', - 'Objects can be made sortable with \'order=True\' and immutable with \'frozen=True\'.': 'Objects can be made sortable with \'order=True\' and immutable with \'frozen=True\'.', - 'For object to be hashable, all attributes must be hashable and frozen must be True.': 'For object to be hashable, all attributes must be hashable and frozen must be True.', + 'For object to be hashable, all attributes must be hashable and frozen must be True.': 'For object to be hashable, all attributes must be hashable (p. 16) and frozen must be True.', 'Function field() is needed because \'<attr_name>: list = []\' would make a list that is shared among all instances. Its \'default_factory\' argument can be any callable.': 'Function field() is needed because \'<attr_name>: list = []\' would make a list that is shared among all instances. Its \'default_factory\' argument can be any callable (p. 17).', 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator.': 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).', 'Objects returned by the itertools module, such as count, repeat and cycle.': 'Objects returned by the itertools module, such as count, repeat and cycle (p. 3).', From bf4c926bea80c09d035f455367cea30d0294d33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 19 Jan 2022 08:54:55 +0100 Subject: [PATCH 005/638] Operator, Coroutines example --- README.md | 38 +++++++++++++++++++------------------- index.html | 42 +++++++++++++++++++++--------------------- 2 files changed, 40 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 265584bb9..31be97047 100644 --- a/README.md +++ b/README.md @@ -2142,10 +2142,10 @@ Operator **Module of functions that provide the functionality of operators.** ```python import operator as op - = op.add/sub/mul/truediv/floordiv/mod(, ) # +, -, *, /, //, % - = op.and_/or_/xor(, ) # &, |, ^ - = op.eq/ne/lt/le/gt/ge(, ) # ==, !=, <, <=, >, >= - = op.itemgetter/attrgetter/methodcaller() # [], ., .() + = op.add/sub/mul/truediv/floordiv/mod(, ) # +, -, *, /, //, % + = op.and_/or_/xor(, ) # &, |, ^ + = op.eq/ne/lt/le/gt/ge(, ) # ==, !=, <, <=, >, >= + = op.itemgetter/attrgetter/methodcaller() # [index/key], ., .() ``` ```python @@ -2300,10 +2300,11 @@ Coroutines #### Runs a terminal game where you control an asterisk that must avoid numbers: ```python -import asyncio, collections, curses, enum, random +import asyncio, collections, curses, curses.textpad, enum, random P = collections.namedtuple('P', 'x y') # Position D = enum.Enum('D', 'n e s w') # Direction +W, H = 15, 7 # Width, Height def main(screen): curses.curs_set(0) # Makes cursor invisible. @@ -2311,19 +2312,17 @@ def main(screen): asyncio.run(main_coroutine(screen)) # Starts running asyncio code. async def main_coroutine(screen): - state = {'*': P(0, 0), **{id_: P(30, 10) for id_ in range(10)}} + state = {'*': P(0, 0), **{id_: P(W//2, H//2) for id_ in range(10)}} moves = asyncio.Queue() coros = (*(random_controller(id_, moves) for id_ in range(10)), - human_controller(screen, moves), - model(moves, state, *screen.getmaxyx()), - view(state, screen)) + human_controller(screen, moves), model(moves, state), view(state, screen)) await asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED) async def random_controller(id_, moves): while True: d = random.choice(list(D)) moves.put_nowait((id_, d)) - await asyncio.sleep(random.random() / 2) + await asyncio.sleep(random.triangular(0.01, 0.65)) async def human_controller(screen, moves): while True: @@ -2331,23 +2330,24 @@ async def human_controller(screen, moves): key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w} if ch in key_mappings: moves.put_nowait(('*', key_mappings[ch])) - await asyncio.sleep(0.01) + await asyncio.sleep(0.005) -async def model(moves, state, height, width): +async def model(moves, state): while state['*'] not in {p for id_, p in state.items() if id_ != '*'}: id_, d = await moves.get() - p = state[id_] + x, y = state[id_] deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)} - new_p = P(p.x + deltas[d].x, p.y + deltas[d].y) - if 0 <= new_p.x < width-1 and 0 <= new_p.y < height: - state[id_] = new_p + state[id_] = P((x + deltas[d].x) % W, (y + deltas[d].y) % H) async def view(state, screen): + offset = P(x=curses.COLS//2 - W//2, y=curses.LINES//2 - H//2) while True: - screen.clear() + screen.erase() + curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W) for id_, p in state.items(): - screen.addstr(p.y, p.x, str(id_)) - await asyncio.sleep(0.01) + screen.addstr(offset.y + (p.y - state['*'].y + H//2) % H, + offset.x + (p.x - state['*'].x + W//2) % W, str(id_)) + await asyncio.sleep(0.005) if __name__ == '__main__': curses.wrapper(main) diff --git a/index.html b/index.html index b719efcb5..311fdb20c 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -1761,10 +1761,10 @@ <el> = <Queue>.get_nowait() # Raises queue.Empty exception if empty.

#Operator

Module of functions that provide the functionality of operators.

import operator as op
-<el>      = op.add/sub/mul/truediv/floordiv/mod(<el>, <el>)   # +, -, *, /, //, %
-<int/set> = op.and_/or_/xor(<int/set>, <int/set>)             # &, |, ^
-<bool>    = op.eq/ne/lt/le/gt/ge(<sortable>, <sortable>)      # ==, !=, <, <=, >, >=
-<func>    = op.itemgetter/attrgetter/methodcaller(<int/str>)  # [<int/str>], .<str>, .<str>()
+<el>      = op.add/sub/mul/truediv/floordiv/mod(<el>, <el>)  # +, -, *, /, //, %
+<int/set> = op.and_/or_/xor(<int/set>, <int/set>)            # &, |, ^
+<bool>    = op.eq/ne/lt/le/gt/ge(<sortable>, <sortable>)     # ==, !=, <, <=, >, >=
+<func>    = op.itemgetter/attrgetter/methodcaller(<el>)      # [index/key], .<str>, .<str>()
 
@@ -1876,10 +1876,11 @@
  • 'asyncio.run(<coroutine>)' is the main entry point for asynchronous programs.
  • Functions wait(), gather() and as_completed() can be used when multiple coroutines need to be started at the same time.
  • Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.
  • -

    Runs a terminal game where you control an asterisk that must avoid numbers:

    import asyncio, collections, curses, enum, random
    +

    Runs a terminal game where you control an asterisk that must avoid numbers:

    import asyncio, collections, curses, curses.textpad, enum, random
     
     P = collections.namedtuple('P', 'x y')         # Position
     D = enum.Enum('D', 'n e s w')                  # Direction
    +W, H = 15, 7                                   # Width, Height
     
     def main(screen):
         curses.curs_set(0)                         # Makes cursor invisible.
    @@ -1887,19 +1888,17 @@
         asyncio.run(main_coroutine(screen))        # Starts running asyncio code.
     
     async def main_coroutine(screen):
    -    state = {'*': P(0, 0), **{id_: P(30, 10) for id_ in range(10)}}
    +    state = {'*': P(0, 0), **{id_: P(W//2, H//2) for id_ in range(10)}}
         moves = asyncio.Queue()
         coros = (*(random_controller(id_, moves) for id_ in range(10)),
    -             human_controller(screen, moves),
    -             model(moves, state, *screen.getmaxyx()),
    -             view(state, screen))
    +             human_controller(screen, moves), model(moves, state), view(state, screen))
         await asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED)
     
     async def random_controller(id_, moves):
         while True:
             d = random.choice(list(D))
             moves.put_nowait((id_, d))
    -        await asyncio.sleep(random.random() / 2)
    +        await asyncio.sleep(random.triangular(0.01, 0.65))
     
     async def human_controller(screen, moves):
         while True:
    @@ -1907,23 +1906,24 @@
             key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w}
             if ch in key_mappings:
                 moves.put_nowait(('*', key_mappings[ch]))
    -        await asyncio.sleep(0.01)  
    +        await asyncio.sleep(0.005)
     
    -async def model(moves, state, height, width):
    +async def model(moves, state):
         while state['*'] not in {p for id_, p in state.items() if id_ != '*'}:
             id_, d = await moves.get()
    -        p      = state[id_]
    +        x, y   = state[id_]
             deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
    -        new_p  = P(p.x + deltas[d].x, p.y + deltas[d].y)
    -        if 0 <= new_p.x < width-1 and 0 <= new_p.y < height:
    -            state[id_] = new_p
    +        state[id_] = P((x + deltas[d].x) % W, (y + deltas[d].y) % H)
     
     async def view(state, screen):
    +    offset = P(x=curses.COLS//2 - W//2, y=curses.LINES//2 - H//2)
         while True:
    -        screen.clear()
    +        screen.erase()
    +        curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W)
             for id_, p in state.items():
    -            screen.addstr(p.y, p.x, str(id_))
    -        await asyncio.sleep(0.01)  
    +            screen.addstr(offset.y + (p.y - state['*'].y + H//2) % H,
    +                          offset.x + (p.x - state['*'].x + W//2) % W, str(id_))
    +        await asyncio.sleep(0.005)
     
     if __name__ == '__main__':
         curses.wrapper(main)
    @@ -2881,7 +2881,7 @@
      
     
       
     
    
    From c1da0dac148835ff8dd443179ebac89050326d4d Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 22 Jan 2022 04:53:00 +0100
    Subject: [PATCH 006/638] Numbers, datetime
    
    ---
     README.md  | 4 ++--
     index.html | 8 ++++----
     2 files changed, 6 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index 31be97047..52c306164 100644
    --- a/README.md
    +++ b/README.md
    @@ -519,7 +519,7 @@ from random import random, randint, choice, shuffle, gauss, seed
     
      = random()                       # A float inside [0, 1).
        = randint(from_inc, to_inc)      # An int inside [from_inc, to_inc].
    -    = choice()                 # Keeps the list intact.
    +    = choice()             # Keeps the sequence intact.
     ```
     
     ### Bin, Hex
    @@ -630,7 +630,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary
         = DT.fromtimestamp(, )  # Aware datetime from seconds since the Epoch.
     ```
     * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by an arbitrary character. Offset is formatted as: `'HH:MM'`.**
    -* **Epoch on Unix systems is: `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...**
    +* **Python uses the Unix Epoch: `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...**
     
     ### Decode
     ```python
    diff --git a/index.html b/index.html
    index 311fdb20c..db2699ee0 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -472,7 +472,7 @@ <float> = random() # A float inside [0, 1). <int> = randint(from_inc, to_inc) # An int inside [from_inc, to_inc]. -<el> = choice(<list>) # Keeps the list intact. +<el> = choice(<sequence>) # Keeps the sequence intact.

    Bin, Hex

    <int> = ±0b<bin>                         # Or: ±0x<hex>
    @@ -561,7 +561,7 @@
     
     
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[±<offset>]', or both separated by an arbitrary character. Offset is formatted as: 'HH:MM'.
    • -
    • Epoch on Unix systems is: '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …
    • +
    • Python uses the Unix Epoch: '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …

    Decode

    <str>    = <D/T/DT>.isoformat(sep='T')      # Also timespec='auto/hours/minutes/seconds'.
     <str>    = <D/T/DT>.strftime('<format>')    # Custom string representation.
    @@ -2881,7 +2881,7 @@
      
     
       
    - +
    From b29867ac9d266438e9fc48a7c3295fe65a48e854 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 25 Jan 2022 13:56:36 +0100 Subject: [PATCH 007/638] Format, Class, NumPy --- README.md | 26 +++++++++++++------------- index.html | 30 +++++++++++++++--------------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 52c306164..5f96c80f3 100644 --- a/README.md +++ b/README.md @@ -390,8 +390,8 @@ import re Format ------ ```python - = f'{}, {}' - = '{}, {}'.format(, ) + = f'{}, {}' # Or: '%s, %s' % (, ) + = '{}, {}'.format(, ) # Or: '{0}, {1}'.format(, ) ``` ### Attributes @@ -1014,21 +1014,21 @@ class C(A, B): pass ### Property **Pythonic way of implementing getters and setters.** ```python -class MyClass: +class Person: @property - def a(self): - return self._a + def name(self): + return ' '.join(a if a == 'van' else a.title() for a in self._name) - @a.setter - def a(self, value): - self._a = value + @name.setter + def name(self, value): + self._name = value.lower().split() ``` ```python ->>> obj = MyClass() ->>> obj.a = 123 ->>> obj.a -123 +>>> person = Person() +>>> person.name = ' gUiDo VaN rOsSuM ' +>>> person.name +'Guido van Rossum' ``` ### Dataclass @@ -2624,7 +2624,7 @@ import numpy as np ``` ```python - = np.array() + = np.array() = np.arange(from_inclusive, to_exclusive, ±step_size) = np.ones() = np.random.randint(from_inclusive, to_exclusive, ) diff --git a/index.html b/index.html index db2699ee0..c08e59edf 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -364,8 +364,8 @@
    -

    #Format

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

    #Format

    <str> = f'{<el_1>}, {<el_2>}'                  # Or: '%s, %s' % (<el_1>, <el_2>)
    +<str> = '{}, {}'.format(<el_1>, <el_2>)        # Or: '{0}, {1}'.format(<el_1>, <el_2>)
     

    Attributes

    >>> from collections import namedtuple
    @@ -858,21 +858,21 @@
     
    >>> C.mro()
     [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
     
    -

    Property

    Pythonic way of implementing getters and setters.

    class MyClass:
    +

    Property

    Pythonic way of implementing getters and setters.

    class Person:
         @property
    -    def a(self):
    -        return self._a
    +    def name(self):
    +        return ' '.join(a if a == 'van' else a.title() for a in self._name)
     
    -    @a.setter
    -    def a(self, value):
    -        self._a = value
    +    @name.setter
    +    def name(self, value):
    +        self._name = value.lower().split()
     
    -
    >>> obj = MyClass()
    ->>> obj.a = 123
    ->>> obj.a
    -123
    +
    >>> person = Person()
    +>>> person.name = ' gUiDo  VaN  rOsSuM '
    +>>> person.name
    +'Guido van Rossum'
     

    Dataclass

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

    from dataclasses import dataclass, field
     
    @@ -2137,7 +2137,7 @@
     
    -
    <array> = np.array(<list>)
    +
    <array> = np.array(<list/list_of_lists>)
     <array> = np.arange(from_inclusive, to_exclusive, ±step_size)
     <array> = np.ones(<shape>)
     <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
    @@ -2881,7 +2881,7 @@
      
     
       
    - +
    From 48a4bb5b4096bec48d69ca562f801879858c8168 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 25 Jan 2022 14:09:09 +0100 Subject: [PATCH 008/638] Class --- README.md | 6 +++--- index.html | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 5f96c80f3..cec86db32 100644 --- a/README.md +++ b/README.md @@ -1017,7 +1017,7 @@ class C(A, B): pass class Person: @property def name(self): - return ' '.join(a if a == 'van' else a.title() for a in self._name) + return ' '.join(a.title() for a in self._name) @name.setter def name(self, value): @@ -1026,9 +1026,9 @@ class Person: ```python >>> person = Person() ->>> person.name = ' gUiDo VaN rOsSuM ' +>>> person.name = ' jEaN-lUc gOdArD ' >>> person.name -'Guido van Rossum' +'Jean-Luc Godard' ``` ### Dataclass diff --git a/index.html b/index.html index c08e59edf..2ecdbd497 100644 --- a/index.html +++ b/index.html @@ -861,7 +861,7 @@

    Property

    Pythonic way of implementing getters and setters.

    class Person:
         @property
         def name(self):
    -        return ' '.join(a if a == 'van' else a.title() for a in self._name)
    +        return ' '.join(a.title() for a in self._name)
     
         @name.setter
         def name(self, value):
    @@ -870,9 +870,9 @@
     
     
     
    >>> person = Person()
    ->>> person.name = ' gUiDo  VaN  rOsSuM '
    +>>> person.name = ' jEaN-lUc gOdArD '
     >>> person.name
    -'Guido van Rossum'
    +'Jean-Luc Godard'
     

    Dataclass

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

    from dataclasses import dataclass, field
     
    
    From 37ed7cf07d853a886ad6a9c59789a24abf4acf78 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 26 Jan 2022 08:14:45 +0100
    Subject: [PATCH 009/638] Format
    
    ---
     README.md  | 4 ++--
     index.html | 8 ++++----
     2 files changed, 6 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index cec86db32..78443f2ad 100644
    --- a/README.md
    +++ b/README.md
    @@ -390,8 +390,8 @@ import re
     Format
     ------
     ```python
    - = f'{}, {}'                  # Or: '%s, %s' % (, )
    - = '{}, {}'.format(, )        # Or: '{0}, {1}'.format(, )
    + = f'{}, {}'
    + = '{}, {}'.format(, )
     ```
     
     ### Attributes
    diff --git a/index.html b/index.html
    index 2ecdbd497..3aee3cc09 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -364,8 +364,8 @@
    -

    #Format

    <str> = f'{<el_1>}, {<el_2>}'                  # Or: '%s, %s' % (<el_1>, <el_2>)
    -<str> = '{}, {}'.format(<el_1>, <el_2>)        # Or: '{0}, {1}'.format(<el_1>, <el_2>)
    +

    #Format

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

    Attributes

    >>> from collections import namedtuple
    @@ -2881,7 +2881,7 @@
      
     
       
    - +
    From dc87ae23ea0e01676be02e29ff1d45c8c77884d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 26 Jan 2022 09:38:16 +0100 Subject: [PATCH 010/638] Class --- README.md | 8 ++++---- index.html | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 78443f2ad..c56cfbe54 100644 --- a/README.md +++ b/README.md @@ -1017,18 +1017,18 @@ class C(A, B): pass class Person: @property def name(self): - return ' '.join(a.title() for a in self._name) + return ' '.join(self._name) @name.setter def name(self, value): - self._name = value.lower().split() + self._name = value.split() ``` ```python >>> person = Person() ->>> person.name = ' jEaN-lUc gOdArD ' +>>> person.name = '\t Guido van Rossum \n' >>> person.name -'Jean-Luc Godard' +'Guido van Rossum' ``` ### Dataclass diff --git a/index.html b/index.html index 3aee3cc09..7ee2c5bdf 100644 --- a/index.html +++ b/index.html @@ -861,18 +861,18 @@

    Property

    Pythonic way of implementing getters and setters.

    class Person:
         @property
         def name(self):
    -        return ' '.join(a.title() for a in self._name)
    +        return ' '.join(self._name)
     
         @name.setter
         def name(self, value):
    -        self._name = value.lower().split()
    +        self._name = value.split()
     
    >>> person = Person()
    ->>> person.name = ' jEaN-lUc gOdArD '
    +>>> person.name = '\t Guido  van Rossum \n'
     >>> person.name
    -'Jean-Luc Godard'
    +'Guido van Rossum'
     

    Dataclass

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

    from dataclasses import dataclass, field
     
    
    From e65b8715e2e4895efc0c152bff28977d7fb4c76f Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 27 Jan 2022 11:30:00 +0100
    Subject: [PATCH 011/638] Datetime, Class, Coroutines
    
    ---
     README.md  | 16 ++++++++--------
     index.html | 20 ++++++++++----------
     2 files changed, 18 insertions(+), 18 deletions(-)
    
    diff --git a/README.md b/README.md
    index c56cfbe54..869fd1ce4 100644
    --- a/README.md
    +++ b/README.md
    @@ -643,11 +643,11 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary
     
     ### Format
     ```python
    ->>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
    +>>> dt = datetime.strptime('2015-05-14 23:39:00.00 +02:00', '%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"
     ```
    -* **`'%Z'` only accepts `'UTC/GMT'` and local timezone's code. `'%z'` also accepts `'±HH:MM'`.**
    +* **`'%Z'` only accepts `'UTC/GMT'` and local timezone's code. `'%z'` also accepts `'±HHMM'`.**
     * **For abbreviated weekday and month use `'%a'` and `'%b'`.**
     
     ### Arithmetics
    @@ -964,18 +964,18 @@ class :
     #### Str() use cases:
     ```python
     print()
    -print(f'{}')
    -raise Exception()
    -csv.writer().writerow([])
    +f'{}'
     logging.warning()
    +csv.writer().writerow([])
    +raise Exception()
     ```
     
     #### Repr() use cases:
     ```python
     print([])
    -print(f'{!r}')
    ->>> 
    +f'{!r}'
     Z = dataclasses.make_dataclass('Z', ['a']); print(Z())
    +>>> 
     ```
     
     ### Constructor Overloading
    @@ -2327,7 +2327,7 @@ async def random_controller(id_, moves):
     async def human_controller(screen, moves):
         while True:
             ch = screen.getch()
    -        key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w}
    +        key_mappings = {258: D.s, 259: D.n, 260: D.w, 261: D.e}
             if ch in key_mappings:
                 moves.put_nowait(('*', key_mappings[ch]))
             await asyncio.sleep(0.005)
    diff --git a/index.html b/index.html
    index 7ee2c5bdf..7beb5b03b 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -570,13 +570,13 @@ <float> = <DTa>.timestamp() # Seconds since the Epoch, from DTa.
    -

    Format

    >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z')
    +

    Format

    >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +02:00', '%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"
     
      -
    • '%Z' only accepts 'UTC/GMT' and local timezone's code. '%z' also accepts '±HH:MM'.
    • +
    • '%Z' only accepts 'UTC/GMT' and local timezone's code. '%z' also accepts '±HHMM'.
    • For abbreviated weekday and month use '%a' and '%b'.

    Arithmetics

    <D/DT>   = <D/DT>  ± <TD>                   # Returned datetime can fall into missing hour.
    @@ -821,16 +821,16 @@
     
  • If only repr() is defined, it will also be used for str().
  • Str() use cases:

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

    Repr() use cases:

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

    Constructor Overloading

    class <name>:
    @@ -1903,7 +1903,7 @@
     async def human_controller(screen, moves):
         while True:
             ch = screen.getch()
    -        key_mappings = {259: D.n, 261: D.e, 258: D.s, 260: D.w}
    +        key_mappings = {258: D.s, 259: D.n, 260: D.w, 261: D.e}
             if ch in key_mappings:
                 moves.put_nowait(('*', key_mappings[ch]))
             await asyncio.sleep(0.005)
    @@ -2881,7 +2881,7 @@
      
     
       
    - +
    From e989e71488ec233ed07701971aa24d04618a6b3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 27 Jan 2022 14:37:54 +0100 Subject: [PATCH 012/638] Pygame, removed spaces before EOL --- README.md | 26 +++++++++++++------------- index.html | 40 ++++++++++++++++++++-------------------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 869fd1ce4..bbdb6a07a 100644 --- a/README.md +++ b/README.md @@ -1906,7 +1906,7 @@ with : # Exits the block with commit() 1 >>> conn.execute('SELECT * FROM person').fetchall() [(1, 'Jean-Luc', 187)] -``` +``` ### MySQL **Has a very similar interface, with differences listed below.** @@ -2401,14 +2401,14 @@ Curses ------ #### Runs a basic file explorer in the terminal: ```python -from curses import wrapper, ascii, A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER +from curses import wrapper, ascii, A_REVERSE, KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_ENTER from os import listdir, path, chdir def main(screen): ch, first, selected, paths = 0, 0, 0, listdir() while ch != ascii.ESC: height, _ = screen.getmaxyx() - screen.clear() + screen.erase() for y, filename in enumerate(paths[first : first+height]): screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y)) ch = screen.getch() @@ -2872,7 +2872,7 @@ def write_to_wav_file(filename, float_samples, nchannels=1, sampwidth=2, framera a_float = max(-1, min(1 - 2e-16, a_float)) a_float += sampwidth == 1 a_float *= pow(2, sampwidth * 8 - 1) - return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1) + return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1) with wave.open(filename, 'wb') as file: file.setnchannels(nchannels) file.setsampwidth(sampwidth) @@ -2949,8 +2949,8 @@ screen = pg.display.set_mode((500, 500)) rect = pg.Rect(240, 240, 20, 20) while all(event.type != pg.QUIT for event in pg.event.get()): deltas = {pg.K_UP: (0, -1), pg.K_RIGHT: (1, 0), pg.K_DOWN: (0, 1), pg.K_LEFT: (-1, 0)} - for key_code, is_pressed in enumerate(pg.key.get_pressed()): - rect = rect.move(deltas[key_code]) if key_code in deltas and is_pressed else rect + for ch, is_pressed in enumerate(pg.key.get_pressed()): + rect = rect.move(deltas[ch]) if ch in deltas and is_pressed else rect screen.fill((0, 0, 0)) pg.draw.rect(screen, (255, 255, 255), rect) pg.display.flip() @@ -3046,7 +3046,7 @@ def run(screen, images, mario, tiles): clock = pg.time.Clock() while all(event.type != pg.QUIT for event in pg.event.get()): keys = {pg.K_UP: D.n, pg.K_RIGHT: D.e, pg.K_DOWN: D.s, pg.K_LEFT: D.w} - pressed = {keys.get(i) for i, on in enumerate(pg.key.get_pressed()) if on} + pressed = {keys.get(ch) for ch, is_prsd in enumerate(pg.key.get_pressed()) if is_prsd} update_speed(mario, tiles, pressed) update_position(mario, tiles) draw(screen, images, mario, tiles, pressed) @@ -3216,9 +3216,9 @@ b 3 4 #### Merge, Join, Concat: ```python >>> l = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y']) - x y -a 1 2 -b 3 4 + x y +a 1 2 +b 3 4 >>> r = DataFrame([[4, 5], [6, 7]], index=['b', 'c'], columns=['y', 'z']) y z b 4 5 @@ -3263,7 +3263,7 @@ c 6 7 = .rank/diff/cumsum/ffill/interpl() # Or: .apply/agg/transform() = .fillna() # Or: .applymap() ``` -* **All operations operate on columns by default. Use `'axis=1'` parameter to process the rows instead.** +* **All operations operate on columns by default. Use `'axis=1'` parameter to process the rows instead.** ```python >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y']) @@ -3331,7 +3331,7 @@ c 7 8 #### Aggregate, Transform, Map: ```python = .sum/max/mean/idxmax/all() # Or: .apply/agg() - = .rank/diff/cumsum/ffill() # Or: .aggregate() + = .rank/diff/cumsum/ffill() # Or: .aggregate() = .fillna() # Or: .transform() ``` @@ -3386,7 +3386,7 @@ from plotly.express import line
    ```python -covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv', +covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv', usecols=['iso_code', 'date', 'total_deaths', 'population']) continents = pd.read_csv('https://gist.githubusercontent.com/stevewithington/20a69c0b6d2ff' '846ea5d35e5fc47f26c/raw/country-and-continent-codes-list-csv.csv', diff --git a/index.html b/index.html index 7beb5b03b..12607bd55 100644 --- a/index.html +++ b/index.html @@ -1960,14 +1960,14 @@
    -

    #Curses

    Runs a basic file explorer in the terminal:

    from curses import wrapper, ascii, A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER
    +

    #Curses

    Runs a basic file explorer in the terminal:

    from curses import wrapper, ascii, A_REVERSE, KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_ENTER
     from os import listdir, path, chdir
     
     def main(screen):
         ch, first, selected, paths = 0, 0, 0, listdir()
         while ch != ascii.ESC:
             height, _ = screen.getmaxyx()
    -        screen.clear()
    +        screen.erase()
             for y, filename in enumerate(paths[first : first+height]):
                 screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y))
             ch = screen.getch()
    @@ -2034,7 +2034,7 @@
         version    = table.find('th', text='Stable release').next_sibling.strings.__next__()
         logo_url   = table.find('img')['src']
         logo       = requests.get(f'https:{logo_url}').content
    -    with open('test.png', 'wb') as file:
    +    with open(os.path.basename(logo_url), 'wb') as file:
             file.write(logo)
         print(python_url, version)
     except requests.exceptions.ConnectionError:
    @@ -2101,8 +2101,8 @@
     

    Profiling by Line

    # $ pip3 install line_profiler memory_profiler
     @profile
     def main():
    -    a = [*range(10000)]
    -    b = {*range(10000)}
    +    l = list(range(10000))
    +    s = set(range(10000))
     main()
     
    @@ -2111,16 +2111,16 @@ ======================================================= 1 @profile 2 def main(): - 3 1 955.0 955.0 43.7 a = [*range(10000)] - 4 1 1231.0 1231.0 56.3 b = {*range(10000)} + 3 1 955.0 955.0 43.7 l = list(range(10000)) + 4 1 1231.0 1231.0 56.3 s = set(range(10000))
    $ python3 -m memory_profiler test.py
     Line #         Mem usage      Increment   Line Contents
     =======================================================
          1        37.668 MiB     37.668 MiB   @profile
          2                                    def main():
    -     3        38.012 MiB      0.344 MiB       a = [*range(10000)]
    -     4        38.477 MiB      0.465 MiB       b = {*range(10000)}
    +     3        38.012 MiB      0.344 MiB       l = list(range(10000))
    +     4        38.477 MiB      0.465 MiB       s = set(range(10000))
     

    Call Graph

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

    # $ pip3 install pycallgraph2
     from pycallgraph2 import output, PyCallGraph
    @@ -2274,7 +2274,7 @@
         y = sum(range(velocity))
         frame = Image.new('L', (WIDTH, WIDTH))
         draw  = ImageDraw.Draw(frame)
    -    draw.ellipse((WIDTH/2-R, y, WIDTH/2+R, y+R*2), fill='white')
    +    draw.ellipse(((WIDTH / 2) - R, y, (WIDTH / 2) + R, y + (R * 2)), fill='white')
         frames.append(frame)
     frames += reversed(frames[1:-1])
     imageio.mimsave('test.gif', frames, duration=0.03)
    @@ -2332,7 +2332,7 @@
             a_float = max(-1, min(1 - 2e-16, a_float))
             a_float += sampwidth == 1
             a_float *= pow(2, sampwidth * 8 - 1)
    -        return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1) 
    +        return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1)
         with wave.open(filename, 'wb') as file:
             file.setnchannels(nchannels)
             file.setsampwidth(sampwidth)
    @@ -2392,8 +2392,8 @@
     rect = pg.Rect(240, 240, 20, 20)
     while all(event.type != pg.QUIT for event in pg.event.get()):
         deltas = {pg.K_UP: (0, -1), pg.K_RIGHT: (1, 0), pg.K_DOWN: (0, 1), pg.K_LEFT: (-1, 0)}
    -    for key_code, is_pressed in enumerate(pg.key.get_pressed()):
    -        rect = rect.move(deltas[key_code]) if key_code in deltas and is_pressed else rect
    +    for ch, is_pressed in enumerate(pg.key.get_pressed()):
    +        rect = rect.move(deltas[ch]) if ch in deltas and is_pressed else rect
         screen.fill((0, 0, 0))
         pg.draw.rect(screen, (255, 255, 255), rect)
         pg.display.flip()
    @@ -2472,7 +2472,7 @@
         clock = pg.time.Clock()
         while all(event.type != pg.QUIT for event in pg.event.get()):
             keys = {pg.K_UP: D.n, pg.K_RIGHT: D.e, pg.K_DOWN: D.s, pg.K_LEFT: D.w}
    -        pressed = {keys.get(i) for i, on in enumerate(pg.key.get_pressed()) if on}
    +        pressed = {keys.get(ch) for ch, is_prsd in enumerate(pg.key.get_pressed()) if is_prsd}
             update_speed(mario, tiles, pressed)
             update_position(mario, tiles)
             draw(screen, images, mario, tiles, pressed)
    @@ -2606,9 +2606,9 @@
     <DF>    = <DF>.sort_values(column_key/s)      # Sorts rows by the passed column/s.
     

    Merge, Join, Concat:

    >>> l = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
    -   x  y 
    -a  1  2 
    -b  3  4 
    +   x  y
    +a  1  2
    +b  3  4
     >>> r = DataFrame([[4, 5], [6, 7]], index=['b', 'c'], columns=['y', 'z'])
        y  z
     b  4  5
    @@ -2651,7 +2651,7 @@
     
      -
    • All operations operate on columns by default. Use 'axis=1' parameter to process the rows instead.
    • +
    • All operations operate on columns by default. Use 'axis=1' parameter to process the rows instead.
    >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
    @@ -2704,7 +2704,7 @@
     <DF> = <GB>.get_group(group_key/s)            # Selects a group by value of grouping column.
     

    Aggregate, Transform, Map:

    <DF> = <GB>.sum/max/mean/idxmax/all()         # Or: <GB>.apply/agg(<agg_func>)
    -<DF> = <GB>.rank/diff/cumsum/ffill()          # Or: <GB>.aggregate(<trans_func>)  
    +<DF> = <GB>.rank/diff/cumsum/ffill()          # Or: <GB>.aggregate(<trans_func>)
     <DF> = <GB>.fillna(<el>)                      # Or: <GB>.transform(<map_func>)
     
    @@ -2742,7 +2742,7 @@ <Figure>.write_html/json/image('<path>') # Also: <Figure>.show()
    -

    Covid deaths by continent:

    covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv', 
    +

    Covid deaths by continent:

    covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv',
                         usecols=['iso_code', 'date', 'total_deaths', 'population'])
     continents = pd.read_csv('https://gist.githubusercontent.com/stevewithington/20a69c0b6d2ff'
                              '846ea5d35e5fc47f26c/raw/country-and-continent-codes-list-csv.csv',
    
    From 726ddca3b18490f66d15863d80827b27a82698c2 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 27 Jan 2022 14:41:28 +0100
    Subject: [PATCH 013/638] Pygame, removed spaces before EOL
    
    ---
     index.html | 16 ++++++++--------
     1 file changed, 8 insertions(+), 8 deletions(-)
    
    diff --git a/index.html b/index.html
    index 12607bd55..c8be88668 100644
    --- a/index.html
    +++ b/index.html
    @@ -2034,7 +2034,7 @@
         version    = table.find('th', text='Stable release').next_sibling.strings.__next__()
         logo_url   = table.find('img')['src']
         logo       = requests.get(f'https:{logo_url}').content
    -    with open(os.path.basename(logo_url), 'wb') as file:
    +    with open('test.png', 'wb') as file:
             file.write(logo)
         print(python_url, version)
     except requests.exceptions.ConnectionError:
    @@ -2101,8 +2101,8 @@
     

    Profiling by Line

    # $ pip3 install line_profiler memory_profiler
     @profile
     def main():
    -    l = list(range(10000))
    -    s = set(range(10000))
    +    a = [*range(10000)]
    +    b = {*range(10000)}
     main()
     
    @@ -2111,16 +2111,16 @@ ======================================================= 1 @profile 2 def main(): - 3 1 955.0 955.0 43.7 l = list(range(10000)) - 4 1 1231.0 1231.0 56.3 s = set(range(10000)) + 3 1 955.0 955.0 43.7 a = [*range(10000)] + 4 1 1231.0 1231.0 56.3 b = {*range(10000)}
    $ python3 -m memory_profiler test.py
     Line #         Mem usage      Increment   Line Contents
     =======================================================
          1        37.668 MiB     37.668 MiB   @profile
          2                                    def main():
    -     3        38.012 MiB      0.344 MiB       l = list(range(10000))
    -     4        38.477 MiB      0.465 MiB       s = set(range(10000))
    +     3        38.012 MiB      0.344 MiB       a = [*range(10000)]
    +     4        38.477 MiB      0.465 MiB       b = {*range(10000)}
     

    Call Graph

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

    # $ pip3 install pycallgraph2
     from pycallgraph2 import output, PyCallGraph
    @@ -2274,7 +2274,7 @@
         y = sum(range(velocity))
         frame = Image.new('L', (WIDTH, WIDTH))
         draw  = ImageDraw.Draw(frame)
    -    draw.ellipse(((WIDTH / 2) - R, y, (WIDTH / 2) + R, y + (R * 2)), fill='white')
    +    draw.ellipse((WIDTH/2-R, y, WIDTH/2+R, y+R*2), fill='white')
         frames.append(frame)
     frames += reversed(frames[1:-1])
     imageio.mimsave('test.gif', frames, duration=0.03)
    
    From 82c90eaf594bbeb3d5b1f5d606f89a6df0e4e2e7 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 27 Jan 2022 20:30:43 +0100
    Subject: [PATCH 014/638] Coroutine, Audio, Pygame
    
    ---
     README.md  | 8 ++++----
     index.html | 8 ++++----
     2 files changed, 8 insertions(+), 8 deletions(-)
    
    diff --git a/README.md b/README.md
    index bbdb6a07a..11823d058 100644
    --- a/README.md
    +++ b/README.md
    @@ -2340,7 +2340,7 @@ async def model(moves, state):
             state[id_] = P((x + deltas[d].x) % W, (y + deltas[d].y) % H)
     
     async def view(state, screen):
    -    offset = P(x=curses.COLS//2 - W//2, y=curses.LINES//2 - H//2)
    +    offset = P(curses.COLS//2 - W//2, curses.LINES//2 - H//2)
         while True:
             screen.erase()
             curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W)
    @@ -2856,7 +2856,7 @@ nframes      = .getnframes()         # Number of frames.
     ```python
     def read_wav_file(filename):
         def get_int(bytes_obj):
    -        an_int = int.from_bytes(bytes_obj, 'little', signed=sampwidth!=1)
    +        an_int = int.from_bytes(bytes_obj, 'little', signed=(sampwidth != 1))
             return an_int - 128 * (sampwidth == 1)
         with wave.open(filename, 'rb') as file:
             sampwidth = file.getsampwidth()
    @@ -2872,7 +2872,7 @@ def write_to_wav_file(filename, float_samples, nchannels=1, sampwidth=2, framera
             a_float = max(-1, min(1 - 2e-16, a_float))
             a_float += sampwidth == 1
             a_float *= pow(2, sampwidth * 8 - 1)
    -        return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1)
    +        return int(a_float).to_bytes(sampwidth, 'little', signed=(sampwidth != 1))
         with wave.open(filename, 'wb') as file:
             file.setnchannels(nchannels)
             file.setsampwidth(sampwidth)
    @@ -3064,7 +3064,7 @@ def update_position(mario, tiles):
         n_steps = max(abs(s) for s in mario.spd)
         for _ in range(n_steps):
             mario.spd = stop_on_collision(mario.spd, get_boundaries(mario.rect, tiles))
    -        x, y = x + mario.spd.x/n_steps, y + mario.spd.y/n_steps
    +        x, y = x + mario.spd.x / n_steps, y + mario.spd.y / n_steps
             mario.rect.topleft = x, y
     
     def get_boundaries(rect, tiles):
    diff --git a/index.html b/index.html
    index c8be88668..e0906bacc 100644
    --- a/index.html
    +++ b/index.html
    @@ -1916,7 +1916,7 @@
             state[id_] = P((x + deltas[d].x) % W, (y + deltas[d].y) % H)
     
     async def view(state, screen):
    -    offset = P(x=curses.COLS//2 - W//2, y=curses.LINES//2 - H//2)
    +    offset = P(curses.COLS//2 - W//2, curses.LINES//2 - H//2)
         while True:
             screen.erase()
             curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W)
    @@ -2318,7 +2318,7 @@
     
     

    Read Float Samples from WAV File

    def read_wav_file(filename):
         def get_int(bytes_obj):
    -        an_int = int.from_bytes(bytes_obj, 'little', signed=sampwidth!=1)
    +        an_int = int.from_bytes(bytes_obj, 'little', signed=(sampwidth != 1))
             return an_int - 128 * (sampwidth == 1)
         with wave.open(filename, 'rb') as file:
             sampwidth = file.getsampwidth()
    @@ -2332,7 +2332,7 @@
             a_float = max(-1, min(1 - 2e-16, a_float))
             a_float += sampwidth == 1
             a_float *= pow(2, sampwidth * 8 - 1)
    -        return int(a_float).to_bytes(sampwidth, 'little', signed=sampwidth!=1)
    +        return int(a_float).to_bytes(sampwidth, 'little', signed=(sampwidth != 1))
         with wave.open(filename, 'wb') as file:
             file.setnchannels(nchannels)
             file.setsampwidth(sampwidth)
    @@ -2490,7 +2490,7 @@
         n_steps = max(abs(s) for s in mario.spd)
         for _ in range(n_steps):
             mario.spd = stop_on_collision(mario.spd, get_boundaries(mario.rect, tiles))
    -        x, y = x + mario.spd.x/n_steps, y + mario.spd.y/n_steps
    +        x, y = x + mario.spd.x / n_steps, y + mario.spd.y / n_steps
             mario.rect.topleft = x, y
     
     def get_boundaries(rect, tiles):
    
    From ed0b0b30948b3408fb050aed7a921e37a74079c6 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 29 Jan 2022 16:41:24 +0100
    Subject: [PATCH 015/638] Class, Scraping
    
    ---
     README.md           |  9 +++++----
     index.html          | 13 +++++++------
     pdf/remove_links.py |  1 -
     3 files changed, 12 insertions(+), 11 deletions(-)
    
    diff --git a/README.md b/README.md
    index 11823d058..a822351f7 100644
    --- a/README.md
    +++ b/README.md
    @@ -1043,7 +1043,7 @@ class :
         : list/dict/set = field(default_factory=list/dict/set)
     ```
     * **Objects can be made sortable with `'order=True'` and immutable with `'frozen=True'`.**
    -* **For object to be hashable, all attributes must be [hashable](#hashable) and frozen must be True.**
    +* **For object to be hashable, all attributes must be hashable and 'frozen' must be True.**
     * **Function field() is needed because `': list = []'` would make a list that is shared among all instances. Its 'default_factory' argument can be any [callable](#callable).**
     * **For attributes of arbitrary type use `'typing.Any'`.**
     
    @@ -2475,7 +2475,7 @@ Scraping
     #### Scrapes Python's URL, version number and logo from its Wikipedia page:
     ```python
     # $ pip3 install requests beautifulsoup4
    -import requests, bs4, sys
    +import requests, bs4, os, sys
     
     WIKI_URL = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
     try:
    @@ -2486,9 +2486,10 @@ try:
         version    = table.find('th', text='Stable release').next_sibling.strings.__next__()
         logo_url   = table.find('img')['src']
         logo       = requests.get(f'https:{logo_url}').content
    -    with open('test.png', 'wb') as file:
    +    filename   = os.path.basename(logo_url)
    +    with open(filename, 'wb') as file:
             file.write(logo)
    -    print(python_url, version)
    +    print(f'{python_url}, {version}, file://{os.path.abspath(filename)}')
     except requests.exceptions.ConnectionError:
         print("You've got problems with connection.", file=sys.stderr)
     ```
    diff --git a/index.html b/index.html
    index e0906bacc..278a4f5eb 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -886,7 +886,7 @@
    • Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
    • -
    • For object to be hashable, all attributes must be hashable and frozen must be True.
    • +
    • For object to be hashable, all attributes must be hashable and 'frozen' must be True.
    • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances. Its 'default_factory' argument can be any callable.
    • For attributes of arbitrary type use 'typing.Any'.
    @@ -2023,7 +2023,7 @@
  • '<str>' - Max age as a string: '1 week, 3 days', '2 months', …
  • #Scraping

    Scrapes Python's URL, version number and logo from its Wikipedia page:

    # $ pip3 install requests beautifulsoup4
    -import requests, bs4, sys
    +import requests, bs4, os, sys
     
     WIKI_URL = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
     try:
    @@ -2034,9 +2034,10 @@
         version    = table.find('th', text='Stable release').next_sibling.strings.__next__()
         logo_url   = table.find('img')['src']
         logo       = requests.get(f'https:{logo_url}').content
    -    with open('test.png', 'wb') as file:
    +    filename   = os.path.basename(logo_url)
    +    with open(filename, 'wb') as file:
             file.write(logo)
    -    print(python_url, version)
    +    print(f'{python_url}, {version}, file://{os.path.abspath(filename)}')
     except requests.exceptions.ConnectionError:
         print("You've got problems with connection.", file=sys.stderr)
     
    @@ -2881,7 +2882,7 @@
    - +
    diff --git a/pdf/remove_links.py b/pdf/remove_links.py index e46c0b897..8a35856ac 100755 --- a/pdf/remove_links.py +++ b/pdf/remove_links.py @@ -11,7 +11,6 @@ 'Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.': 'Module \'operator\' (p. 31) provides functions itemgetter() and mul() that offer the same functionality as lambda expressions (p. 11) above.', 'Adding \'!r\' before the colon converts object to string by calling its repr() method.': 'Adding \'!r\' before the colon converts object to string by calling its repr() method (p. 14).', 'It can be any callable, but is usually implemented as a function that returns a closure.': 'It can be any callable (p. 17), but is usually implemented as a function that returns a closure (p. 12).', - 'For object to be hashable, all attributes must be hashable and frozen must be True.': 'For object to be hashable, all attributes must be hashable (p. 16) and frozen must be True.', 'Function field() is needed because \'<attr_name>: list = []\' would make a list that is shared among all instances. Its \'default_factory\' argument can be any callable.': 'Function field() is needed because \'<attr_name>: list = []\' would make a list that is shared among all instances. Its \'default_factory\' argument can be any callable (p. 17).', 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator.': 'Sequence iterators returned by the iter() function, such as list_iterator and set_iterator (p. 3).', 'Objects returned by the itertools module, such as count, repeat and cycle.': 'Objects returned by the itertools module, such as count, repeat and cycle (p. 3).', From 8bf7bece10be9b70b752d2d2798751337d7612bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 4 Feb 2022 15:03:29 +0100 Subject: [PATCH 016/638] Pandas --- README.md | 111 +++++++++++++++++++++++++------------------------ index.html | 119 ++++++++++++++++++++++++++--------------------------- parse.js | 94 +++++++++++++++++++++--------------------- 3 files changed, 161 insertions(+), 163 deletions(-) diff --git a/README.md b/README.md index a822351f7..34e688f08 100644 --- a/README.md +++ b/README.md @@ -3142,11 +3142,11 @@ Name: a, dtype: int64 #### Aggregate, Transform, Map: ```python - = .sum/max/mean/idxmax/all() # Or: .aggregate() - = .rank/diff/cumsum/ffill/interpl() # Or: .agg/transform() - = .fillna() # Or: .apply/agg/transform/map() + = .sum/max/mean/idxmax/all() # Or: .agg(lambda : ) + = .rank/diff/cumsum/ffill/interpl() # Or: .agg/transform(lambda : ) + = .fillna() # Or: .agg/transform/map(lambda : ) ``` -* **The way `'aggregate()'` and `'transform()'` find out whether the passed function accepts an element or the whole Series is by passing it a single value at first and if it raises an error, then they pass it the whole Series.** +* **The way `'agg()'` and `'transform()'` find out whether the passed function accepts an element or the whole Series is by passing it a single value at first and if it raises an error, then they pass it the whole Series. `'agg()'` only accepts Attribute/Type/ValueError.** ```python >>> sr = Series([1, 2], index=['x', 'y']) @@ -3155,22 +3155,22 @@ y 2 ``` ```text -+-------------+-------------+-------------+---------------+ -| | 'sum' | ['sum'] | {'s': 'sum'} | -+-------------+-------------+-------------+---------------+ -| sr.apply(…) | 3 | sum 3 | s 3 | -| sr.agg(…) | | | | -+-------------+-------------+-------------+---------------+ ++-----------------+-------------+-------------+---------------+ +| | 'sum' | ['sum'] | {'s': 'sum'} | ++-----------------+-------------+-------------+---------------+ +| sr.apply(…) | 3 | sum 3 | s 3 | +| sr.agg(…) | | | | ++-----------------+-------------+-------------+---------------+ ``` ```text -+-------------+-------------+-------------+---------------+ -| | 'rank' | ['rank'] | {'r': 'rank'} | -+-------------+-------------+-------------+---------------+ -| sr.apply(…) | | rank | | -| sr.agg(…) | x 1 | x 1 | r x 1 | -| sr.trans(…) | y 2 | y 2 | y 2 | -+-------------+-------------+-------------+---------------+ ++-----------------+-------------+-------------+---------------+ +| | 'rank' | ['rank'] | {'r': 'rank'} | ++-----------------+-------------+-------------+---------------+ +| sr.apply(…) | | rank | | +| sr.agg(…) | x 1 | x 1 | r x 1 | +| sr.transform(…) | y 2 | y 2 | y 2 | ++-----------------+-------------+-------------+---------------+ ``` * **Last result has a hierarchical index. Use `'[key_1, key_2]'` to get its values.** @@ -3260,11 +3260,11 @@ c 6 7 #### Aggregate, Transform, Map: ```python - = .sum/max/mean/idxmax/all() # Or: .apply/agg/transform() - = .rank/diff/cumsum/ffill/interpl() # Or: .apply/agg/transform() - = .fillna() # Or: .applymap() + = .sum/max/mean/idxmax/all() # Or: .apply/agg(lambda : ) + = .rank/diff/cumsum/ffill/interpl() # Or: .apply/agg/transform(lambda : ) + = .fillna() # Or: .applymap(lambda : ) ``` -* **All operations operate on columns by default. Use `'axis=1'` parameter to process the rows instead.** +* **All operations operate on columns by default. Use `'axis=1'` parameter to process the rows instead. Transform passes DF to a function if it rases an error after receiving a Sr.** ```python >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y']) @@ -3274,24 +3274,24 @@ b 3 4 ``` ```text -+-------------+-------------+-------------+---------------+ -| | 'sum' | ['sum'] | {'x': 'sum'} | -+-------------+-------------+-------------+---------------+ -| df.apply(…) | | x y | | -| df.agg(…) | x 4 | sum 4 6 | x 4 | -| | y 6 | | | -+-------------+-------------+-------------+---------------+ ++-----------------+-------------+-------------+---------------+ +| | 'sum' | ['sum'] | {'x': 'sum'} | ++-----------------+-------------+-------------+---------------+ +| df.apply(…) | | x y | | +| df.agg(…) | x 4 | sum 4 6 | x 4 | +| | y 6 | | | ++-----------------+-------------+-------------+---------------+ ``` ```text -+-------------+-------------+-------------+---------------+ -| | 'rank' | ['rank'] | {'x': 'rank'} | -+-------------+-------------+-------------+---------------+ -| df.apply(…) | x y | x y | x | -| df.agg(…) | a 1 1 | rank rank | a 1 | -| df.trans(…) | b 2 2 | a 1 1 | b 2 | -| | | b 2 2 | | -+-------------+-------------+-------------+---------------+ ++-----------------+-------------+-------------+---------------+ +| | 'rank' | ['rank'] | {'x': 'rank'} | ++-----------------+-------------+-------------+---------------+ +| df.apply(…) | x y | x y | x | +| df.agg(…) | a 1 1 | rank rank | a 1 | +| df.transform(…) | b 2 2 | a 1 1 | b 2 | +| | | b 2 2 | | ++-----------------+-------------+-------------+---------------+ ``` * **Use `'[col_key_1, col_key_2][row_key]'` to get the fifth result's values.** @@ -3315,9 +3315,6 @@ b 3 4 ```python >>> df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 6]], index=list('abc'), columns=list('xyz')) ->>> df.groupby('z').get_group(3) - x y -a 1 2 >>> df.groupby('z').get_group(6) x y b 4 5 @@ -3327,13 +3324,15 @@ c 7 8 ```python = .groupby(column_key/s) # DF is split into groups based on passed column. = .get_group(group_key/s) # Selects a group by value of grouping column. + = .apply() # Maps each group. Func can return DF, Sr or el. + = [column_key] # A single column GB. All operations return a Sr. ``` #### Aggregate, Transform, Map: ```python - = .sum/max/mean/idxmax/all() # Or: .apply/agg() - = .rank/diff/cumsum/ffill() # Or: .aggregate() - = .fillna() # Or: .transform() + = .sum/max/mean/idxmax/all() # Or: .agg(lambda : ) + = .rank/diff/cumsum/ffill() # Or: .transform(lambda : ) + = .fillna() # Or: .transform(lambda : ) ``` ```python @@ -3345,20 +3344,20 @@ c 7 8 ``` ```text -+-------------+-------------+-------------+-------------+---------------+ -| | 'sum' | 'rank' | ['rank'] | {'x': 'rank'} | -+-------------+-------------+-------------+-------------+---------------+ -| gb.agg(…) | x y | x y | x y | x | -| | z | a 1 1 | rank rank | a 1 | -| | 3 1 2 | b 1 1 | a 1 1 | b 1 | -| | 6 11 13 | c 2 2 | b 1 1 | c 2 | -| | | | c 2 2 | | -+-------------+-------------+-------------+-------------+---------------+ -| gb.trans(…) | x y | x y | | | -| | a 1 2 | a 1 1 | | | -| | b 11 13 | b 1 1 | | | -| | c 11 13 | c 1 1 | | | -+-------------+-------------+-------------+-------------+---------------+ ++-----------------+-------------+-------------+-------------+---------------+ +| | 'sum' | 'rank' | ['rank'] | {'x': 'rank'} | ++-----------------+-------------+-------------+-------------+---------------+ +| gb.agg(…) | x y | x y | x y | x | +| | z | a 1 1 | rank rank | a 1 | +| | 3 1 2 | b 1 1 | a 1 1 | b 1 | +| | 6 11 13 | c 2 2 | b 1 1 | c 2 | +| | | | c 2 2 | | ++-----------------+-------------+-------------+-------------+---------------+ +| gb.transform(…) | x y | x y | | | +| | a 1 2 | a 1 1 | | | +| | b 11 13 | b 1 1 | | | +| | c 11 13 | c 2 2 | | | ++-----------------+-------------+-------------+-------------+---------------+ ``` ### Rolling diff --git a/index.html b/index.html index 278a4f5eb..90ad9fd4c 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -2549,32 +2549,32 @@ <Sr> = <Sr>.combine_first(<Sr>) # Adds items that are not yet present. <Sr>.update(<Sr>) # Updates items that are already present.
    -

    Aggregate, Transform, Map:

    <el> = <Sr>.sum/max/mean/idxmax/all()         # Or: <Sr>.aggregate(<agg_func>)
    -<Sr> = <Sr>.rank/diff/cumsum/ffill/interpl()  # Or: <Sr>.agg/transform(<trans_func>)
    -<Sr> = <Sr>.fillna(<el>)                      # Or: <Sr>.apply/agg/transform/map(<map_func>)
    +

    Aggregate, Transform, Map:

    <el> = <Sr>.sum/max/mean/idxmax/all()         # Or: <Sr>.agg(lambda <Sr>: <el>)
    +<Sr> = <Sr>.rank/diff/cumsum/ffill/interpl()  # Or: <Sr>.agg/transform(lambda <Sr>: <Sr>)
    +<Sr> = <Sr>.fillna(<el>)                      # Or: <Sr>.agg/transform/map(lambda <el>: <el>)
     
      -
    • The way 'aggregate()' and 'transform()' find out whether the passed function accepts an element or the whole Series is by passing it a single value at first and if it raises an error, then they pass it the whole Series.
    • +
    • The way 'agg()' and 'transform()' find out whether the passed function accepts an element or the whole Series is by passing it a single value at first and if it raises an error, then they pass it the whole Series. 'agg()' only accepts Attribute/Type/ValueError.
    >>> sr = Series([1, 2], index=['x', 'y'])
     x    1
     y    2
     
    -
    ┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    -┃             │    'sum'    │   ['sum']   │ {'s': 'sum'}  ┃
    -┠─────────────┼─────────────┼─────────────┼───────────────┨
    -┃ sr.apply(…) │      3      │    sum  3   │     s  3      ┃
    -┃ sr.agg(…)   │             │             │               ┃
    -┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    -
    -
    ┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    -┃             │    'rank'   │   ['rank']  │ {'r': 'rank'} ┃
    -┠─────────────┼─────────────┼─────────────┼───────────────┨
    -┃ sr.apply(…) │             │      rank   │               ┃
    -┃ sr.agg(…)   │     x  1    │   x     1   │    r  x  1    ┃
    -┃ sr.trans(…) │     y  2    │   y     2   │       y  2    ┃
    -┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    +
    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    +┃                 │    'sum'    │   ['sum']   │ {'s': 'sum'}  ┃
    +┠─────────────────┼─────────────┼─────────────┼───────────────┨
    +┃ sr.apply(…)     │      3      │    sum  3   │     s  3      ┃
    +┃ sr.agg(…)       │             │             │               ┃
    +┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    +
    +
    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    +┃                 │    'rank'   │   ['rank']  │ {'r': 'rank'} ┃
    +┠─────────────────┼─────────────┼─────────────┼───────────────┨
    +┃ sr.apply(…)     │             │      rank   │               ┃
    +┃ sr.agg(…)       │     x  1    │   x     1   │    r  x  1    ┃
    +┃ sr.transform(…) │     y  2    │   y     2   │       y  2    ┃
    +┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
     
    • Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
    • @@ -2646,35 +2646,35 @@ ┃ │ c . 6 7 │ │ │ R must be a DataFrame. ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━┛
    -

    Aggregate, Transform, Map:

    <Sr> = <DF>.sum/max/mean/idxmax/all()         # Or: <DF>.apply/agg/transform(<agg_func>)
    -<DF> = <DF>.rank/diff/cumsum/ffill/interpl()  # Or: <DF>.apply/agg/transform(<trans_func>)
    -<DF> = <DF>.fillna(<el>)                      # Or: <DF>.applymap(<map_func>)
    +

    Aggregate, Transform, Map:

    <Sr> = <DF>.sum/max/mean/idxmax/all()         # Or: <DF>.apply/agg(lambda <Sr>: <el>)
    +<DF> = <DF>.rank/diff/cumsum/ffill/interpl()  # Or: <DF>.apply/agg/transform(lambda <Sr>: <Sr>)
    +<DF> = <DF>.fillna(<el>)                      # Or: <DF>.applymap(lambda <el>: <el>)
     
      -
    • All operations operate on columns by default. Use 'axis=1' parameter to process the rows instead.
    • +
    • All operations operate on columns by default. Use 'axis=1' parameter to process the rows instead. Transform passes DF to a function if it rases an error after receiving a Sr.
    >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
     a  1  2
     b  3  4
     
    -
    ┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    -┃             │    'sum'    │   ['sum']   │ {'x': 'sum'}  ┃
    -┠─────────────┼─────────────┼─────────────┼───────────────┨
    -┃ df.apply(…) │             │       x  y  │               ┃
    -┃ df.agg(…)   │     x  4    │  sum  4  6  │     x  4      ┃
    -┃             │     y  6    │             │               ┃
    -┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    -
    -
    ┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    -┃             │    'rank'   │   ['rank']  │ {'x': 'rank'} ┃
    -┠─────────────┼─────────────┼─────────────┼───────────────┨
    -┃ df.apply(…) │      x  y   │      x    y │        x      ┃
    -┃ df.agg(…)   │   a  1  1   │   rank rank │     a  1      ┃
    -┃ df.trans(…) │   b  2  2   │ a    1    1 │     b  2      ┃
    -┃             │             │ b    2    2 │               ┃
    -┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    +
    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    +┃                 │    'sum'    │   ['sum']   │ {'x': 'sum'}  ┃
    +┠─────────────────┼─────────────┼─────────────┼───────────────┨
    +┃ df.apply(…)     │             │       x  y  │               ┃
    +┃ df.agg(…)       │     x  4    │  sum  4  6  │     x  4      ┃
    +┃                 │     y  6    │             │               ┃
    +┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    +
    +
    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    +┃                 │    'rank'   │   ['rank']  │ {'x': 'rank'} ┃
    +┠─────────────────┼─────────────┼─────────────┼───────────────┨
    +┃ df.apply(…)     │      x  y   │      x    y │        x      ┃
    +┃ df.agg(…)       │   a  1  1   │   rank rank │     a  1      ┃
    +┃ df.transform(…) │   b  2  2   │ a    1    1 │     b  2      ┃
    +┃                 │             │ b    2    2 │               ┃
    +┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
     
    • Use '<DF>[col_key_1, col_key_2][row_key]' to get the fifth result's values.
    • @@ -2691,9 +2691,6 @@ <DF>.to_sql('<table_name>', <connection>)

    GroupBy

    Object that groups together rows of a dataframe based on the value of the passed column.

    >>> df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 6]], index=list('abc'), columns=list('xyz'))
    ->>> df.groupby('z').get_group(3)
    -   x  y
    -a  1  2
     >>> df.groupby('z').get_group(6)
        x  y
     b  4  5
    @@ -2703,10 +2700,12 @@
     
     
    <GB> = <DF>.groupby(column_key/s)             # DF is split into groups based on passed column.
     <DF> = <GB>.get_group(group_key/s)            # Selects a group by value of grouping column.
    +<DF> = <GB>.apply(<func>)                     # Maps each group. Func can return DF, Sr or el.
    +<GB> = <GB>[column_key]                       # A single column GB. All operations return a Sr.
     
    -

    Aggregate, Transform, Map:

    <DF> = <GB>.sum/max/mean/idxmax/all()         # Or: <GB>.apply/agg(<agg_func>)
    -<DF> = <GB>.rank/diff/cumsum/ffill()          # Or: <GB>.aggregate(<trans_func>)
    -<DF> = <GB>.fillna(<el>)                      # Or: <GB>.transform(<map_func>)
    +

    Aggregate, Transform, Map:

    <DF> = <GB>.sum/max/mean/idxmax/all()         # Or: <GB>.agg(lambda <Sr>: <el>)
    +<DF> = <GB>.rank/diff/cumsum/ffill()          # Or: <GB>.transform(lambda <Sr>: <Sr>)
    +<DF> = <GB>.fillna(<el>)                      # Or: <GB>.transform(lambda <Sr>: <Sr>)
     
    >>> gb = df.groupby('z')
    @@ -2715,20 +2714,20 @@
     6: b  4  5  6
        c  7  8  6
     
    -
    ┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    -┃             │    'sum''rank'   │   ['rank']  │ {'x': 'rank'} ┃
    -┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
    -┃ gb.agg(…)   │      x   y  │      x  y   │      x    y │        x      ┃
    -┃             │  z          │   a  1  1   │   rank rank │     a  1      ┃
    -┃             │  3   1   2  │   b  1  1   │ a    1    1 │     b  1      ┃
    -┃             │  6  11  13  │   c  2  2   │ b    1    1 │     c  2      ┃
    -┃             │             │             │ c    2    2 │               ┃
    -┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
    -┃ gb.trans(…) │      x   y  │      x  y   │             │               ┃
    -┃             │  a   1   2  │   a  1  1   │             │               ┃
    -┃             │  b  11  13  │   b  1  1   │             │               ┃
    -┃             │  c  11  13  │   c  1  1   │             │               ┃
    -┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    +
    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    +┃                 │    'sum''rank'   │   ['rank']  │ {'x': 'rank'} ┃
    +┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
    +┃ gb.agg(…)       │      x   y  │      x  y   │      x    y │        x      ┃
    +┃                 │  z          │   a  1  1   │   rank rank │     a  1      ┃
    +┃                 │  3   1   2  │   b  1  1   │ a    1    1 │     b  1      ┃
    +┃                 │  6  11  13  │   c  2  2   │ b    1    1 │     c  2      ┃
    +┃                 │             │             │ c    2    2 │               ┃
    +┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨
    +┃ gb.transform(…) │      x   y  │      x  y   │             │               ┃
    +┃                 │  a   1   2  │   a  1  1   │             │               ┃
    +┃                 │  b  11  13  │   b  1  1   │             │               ┃
    +┃                 │  c  11  13  │   c  2  2   │             │               ┃
    +┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
     

    Rolling

    Object for rolling window calculations.

    <R_Sr/R_DF/R_GB> = <Sr/DF/GB>.rolling(window_size)  # Also: `min_periods=None, center=False`.
     <R_Sr/R_DF>      = <R_DF/R_GB>[column_key/s]        # Or: <R>.column_key
    @@ -2882,7 +2881,7 @@
      
     
       
    - +
    diff --git a/parse.js b/parse.js index 2a8e96f96..acce34927 100755 --- a/parse.js +++ b/parse.js @@ -308,27 +308,27 @@ const DIAGRAM_12_B = '┗━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━┷━━━━━━━━━━━━━┛\n'; const DIAGRAM_13_A = - '| sr.apply(…) | 3 | sum 3 | s 3 |'; + '| sr.apply(…) | 3 | sum 3 | s 3 |'; const DIAGRAM_13_B = - "┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + - "┃ │ 'sum' │ ['sum'] │ {'s': 'sum'} ┃\n" + - "┠─────────────┼─────────────┼─────────────┼───────────────┨\n" + - "┃ sr.apply(…) │ 3 │ sum 3 │ s 3 ┃\n" + - "┃ sr.agg(…) │ │ │ ┃\n" + - "┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; + "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + + "┃ │ 'sum' │ ['sum'] │ {'s': 'sum'} ┃\n" + + "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" + + "┃ sr.apply(…) │ 3 │ sum 3 │ s 3 ┃\n" + + "┃ sr.agg(…) │ │ │ ┃\n" + + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; const DIAGRAM_14_A = - '| sr.apply(…) | | rank | |'; + '| sr.apply(…) | | rank | |'; const DIAGRAM_14_B = - "┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + - "┃ │ 'rank' │ ['rank'] │ {'r': 'rank'} ┃\n" + - "┠─────────────┼─────────────┼─────────────┼───────────────┨\n" + - "┃ sr.apply(…) │ │ rank │ ┃\n" + - "┃ sr.agg(…) │ x 1 │ x 1 │ r x 1 ┃\n" + - "┃ sr.trans(…) │ y 2 │ y 2 │ y 2 ┃\n" + - "┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; + "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + + "┃ │ 'rank' │ ['rank'] │ {'r': 'rank'} ┃\n" + + "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" + + "┃ sr.apply(…) │ │ rank │ ┃\n" + + "┃ sr.agg(…) │ x 1 │ x 1 │ r x 1 ┃\n" + + "┃ sr.transform(…) │ y 2 │ y 2 │ y 2 ┃\n" + + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; const DIAGRAM_15_A = '+------------------------+---------------+------------+------------+--------------------------+'; @@ -365,48 +365,48 @@ const DIAGRAM_15_B = "┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n"; const DIAGRAM_16_A = - '| df.apply(…) | | x y | |'; + '| df.apply(…) | | x y | |'; const DIAGRAM_16_B = - "┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + - "┃ │ 'sum' │ ['sum'] │ {'x': 'sum'} ┃\n" + - "┠─────────────┼─────────────┼─────────────┼───────────────┨\n" + - "┃ df.apply(…) │ │ x y │ ┃\n" + - "┃ df.agg(…) │ x 4 │ sum 4 6 │ x 4 ┃\n" + - "┃ │ y 6 │ │ ┃\n" + - "┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; + "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + + "┃ │ 'sum' │ ['sum'] │ {'x': 'sum'} ┃\n" + + "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" + + "┃ df.apply(…) │ │ x y │ ┃\n" + + "┃ df.agg(…) │ x 4 │ sum 4 6 │ x 4 ┃\n" + + "┃ │ y 6 │ │ ┃\n" + + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; const DIAGRAM_17_A = - '| df.apply(…) | x y | x y | x |'; + '| df.apply(…) | x y | x y | x |'; const DIAGRAM_17_B = - "┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + - "┃ │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" + - "┠─────────────┼─────────────┼─────────────┼───────────────┨\n" + - "┃ df.apply(…) │ x y │ x y │ x ┃\n" + - "┃ df.agg(…) │ a 1 1 │ rank rank │ a 1 ┃\n" + - "┃ df.trans(…) │ b 2 2 │ a 1 1 │ b 2 ┃\n" + - "┃ │ │ b 2 2 │ ┃\n" + - "┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; + "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + + "┃ │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" + + "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" + + "┃ df.apply(…) │ x y │ x y │ x ┃\n" + + "┃ df.agg(…) │ a 1 1 │ rank rank │ a 1 ┃\n" + + "┃ df.transform(…) │ b 2 2 │ a 1 1 │ b 2 ┃\n" + + "┃ │ │ b 2 2 │ ┃\n" + + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; const DIAGRAM_18_A = - '| gb.agg(…) | x y | x y | x y | x |'; + '| gb.agg(…) | x y | x y | x y | x |'; const DIAGRAM_18_B = - "┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + - "┃ │ 'sum' │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" + - "┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" + - "┃ gb.agg(…) │ x y │ x y │ x y │ x ┃\n" + - "┃ │ z │ a 1 1 │ rank rank │ a 1 ┃\n" + - "┃ │ 3 1 2 │ b 1 1 │ a 1 1 │ b 1 ┃\n" + - "┃ │ 6 11 13 │ c 2 2 │ b 1 1 │ c 2 ┃\n" + - "┃ │ │ │ c 2 2 │ ┃\n" + - "┠─────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" + - "┃ gb.trans(…) │ x y │ x y │ │ ┃\n" + - "┃ │ a 1 2 │ a 1 1 │ │ ┃\n" + - "┃ │ b 11 13 │ b 1 1 │ │ ┃\n" + - "┃ │ c 11 13 │ c 1 1 │ │ ┃\n" + - "┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; + "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + + "┃ │ 'sum' │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" + + "┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" + + "┃ gb.agg(…) │ x y │ x y │ x y │ x ┃\n" + + "┃ │ z │ a 1 1 │ rank rank │ a 1 ┃\n" + + "┃ │ 3 1 2 │ b 1 1 │ a 1 1 │ b 1 ┃\n" + + "┃ │ 6 11 13 │ c 2 2 │ b 1 1 │ c 2 ┃\n" + + "┃ │ │ │ c 2 2 │ ┃\n" + + "┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨\n" + + "┃ gb.transform(…) │ x y │ x y │ │ ┃\n" + + "┃ │ a 1 2 │ a 1 1 │ │ ┃\n" + + "┃ │ b 11 13 │ b 1 1 │ │ ┃\n" + + "┃ │ c 11 13 │ c 2 2 │ │ ┃\n" + + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; const MENU = 'Download text file, Buy PDF, Fork me on GitHub, Check out FAQ or Switch to dark theme.\n'; From 5f23075fe6cd86fb0592e8e7ddbd5c0338343537 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 4 Feb 2022 18:19:28 +0100 Subject: [PATCH 017/638] Pandas --- README.md | 2 +- index.html | 4 ++-- parse.js | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 34e688f08..19daa0a75 100644 --- a/README.md +++ b/README.md @@ -3264,7 +3264,7 @@ c 6 7 = .rank/diff/cumsum/ffill/interpl() # Or: .apply/agg/transform(lambda : ) = .fillna() # Or: .applymap(lambda : ) ``` -* **All operations operate on columns by default. Use `'axis=1'` parameter to process the rows instead. Transform passes DF to a function if it rases an error after receiving a Sr.** +* **All operations operate on columns by default. Use `'axis=1'` parameter to process the rows instead. Transform passes DF to a function if it raises an error after receiving a Sr.** ```python >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y']) diff --git a/index.html b/index.html index 90ad9fd4c..1907d86b1 100644 --- a/index.html +++ b/index.html @@ -1230,7 +1230,7 @@ ├── NameError # Raised when a variable name is not found. ├── OSError # Errors such as “file not found” or “disk full” (see Open). │ └── FileNotFoundError # When a file or directory is requested but doesn't exist. - ├── RuntimeError # Raised by errors that don't fall in other categories. + ├── RuntimeError # Raised by errors that don't fall into other categories. │ └── RecursionError # Raised when the maximum recursion depth is exceeded. ├── StopIteration # Raised by next() when run on an empty iterator. ├── TypeError # Raised when an argument is of wrong type. @@ -2652,7 +2652,7 @@
      -
    • All operations operate on columns by default. Use 'axis=1' parameter to process the rows instead. Transform passes DF to a function if it rases an error after receiving a Sr.
    • +
    • All operations operate on columns by default. Use 'axis=1' parameter to process the rows instead. Transform passes DF to a function if it raises an error after receiving a Sr.
    >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
    diff --git a/parse.js b/parse.js
    index acce34927..13b06bf7e 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -218,7 +218,7 @@ const DIAGRAM_7_B =
       "      ├── NameError               # Raised when a variable name is not found.\n" +
       "      ├── OSError                 # Errors such as “file not found” or “disk full” (see Open).\n" +
       "      │    └── FileNotFoundError  # When a file or directory is requested but doesn't exist.\n" +
    -  "      ├── RuntimeError            # Raised by errors that don't fall in other categories.\n" +
    +  "      ├── RuntimeError            # Raised by errors that don't fall into other categories.\n" +
       "      │    └── RecursionError     # Raised when the maximum recursion depth is exceeded.\n" +
       "      ├── StopIteration           # Raised by next() when run on an empty iterator.\n" +
       "      ├── TypeError               # Raised when an argument is of wrong type.\n" +
    
    From a3278d23d6e0cdcb7dd1ec4dd2e1df11329122d1 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 5 Feb 2022 20:18:50 +0100
    Subject: [PATCH 018/638] Pandas
    
    ---
     README.md                    | 22 +++++++++++-----------
     index.html                   | 28 +++++++++++++++-------------
     parse.js                     | 18 ++++--------------
     pdf/index_for_pdf.html       | 14 +++++++-------
     pdf/index_for_pdf_print.html |  2 +-
     5 files changed, 38 insertions(+), 46 deletions(-)
    
    diff --git a/README.md b/README.md
    index 19daa0a75..c056a158a 100644
    --- a/README.md
    +++ b/README.md
    @@ -3140,7 +3140,7 @@ Name: a, dtype: int64
     .update()                             # Updates items that are already present.
     ```
     
    -#### Aggregate, Transform, Map:
    +#### Series — Aggregate, Transform, Map:
     ```python
      = .sum/max/mean/idxmax/all()         # Or: .agg(lambda : )
      = .rank/diff/cumsum/ffill/interpl()  # Or: .agg/transform(lambda : )
    @@ -3161,9 +3161,7 @@ y    2
     | sr.apply(…)     |      3      |    sum  3   |     s  3      |
     | sr.agg(…)       |             |             |               |
     +-----------------+-------------+-------------+---------------+
    -```
     
    -```text
     +-----------------+-------------+-------------+---------------+
     |                 |    'rank'   |   ['rank']  | {'r': 'rank'} |
     +-----------------+-------------+-------------+---------------+
    @@ -3214,7 +3212,7 @@ b  3  4
         = .sort_values(column_key/s)      # Sorts rows by the passed column/s.
     ```
     
    -#### Merge, Join, Concat:
    +#### DataFrame — Merge, Join, Concat:
     ```python
     >>> l = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
    @@ -3258,13 +3256,13 @@ c  6  7
     +------------------------+---------------+------------+------------+--------------------------+
     ```
     
    -#### Aggregate, Transform, Map:
    +#### DataFrame — Aggregate, Transform, Map:
     ```python
      = .sum/max/mean/idxmax/all()         # Or: .apply/agg(lambda : )
      = .rank/diff/cumsum/ffill/interpl()  # Or: .apply/agg/transform(lambda : )
      = .fillna()                      # Or: .applymap(lambda : )
     ```
    -* **All operations operate on columns by default. Use `'axis=1'` parameter to process the rows instead. Transform passes DF to a function if it raises an error after receiving a Sr.**
    +* **All operations operate on columns by default. Pass `'axis=1'` to process the rows instead.**
     
     ```python
     >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
    @@ -3281,9 +3279,7 @@ b  3  4
     | df.agg(…)       |     x  4    |  sum  4  6  |     x  4      |
     |                 |     y  6    |             |               |
     +-----------------+-------------+-------------+---------------+
    -```
     
    -```text
     +-----------------+-------------+-------------+---------------+
     |                 |    'rank'   |   ['rank']  | {'x': 'rank'} |
     +-----------------+-------------+-------------+---------------+
    @@ -3295,7 +3291,7 @@ b  3  4
     ```
     * **Use `'[col_key_1, col_key_2][row_key]'` to get the fifth result's values.**
     
    -#### Encode, Decode:
    +#### DataFrame — Encode, Decode, Plot:
     ```python
      = pd.read_json/html('')
      = pd.read_csv/pickle/excel('')
    @@ -3310,6 +3306,11 @@ b  3  4
     .to_sql('', )
     ```
     
    +```python
    +import matplotlib.pyplot as plt
    +.plot.line/bar/hist/scatter([x=column_key, y=column_key/s]); plt.show()
    +```
    +
     ### GroupBy
     **Object that groups together rows of a dataframe based on the value of the passed column.**
     
    @@ -3323,12 +3324,11 @@ c  7  8
     
     ```python
      = .groupby(column_key/s)             # DF is split into groups based on passed column.
    - = .get_group(group_key/s)            # Selects a group by value of grouping column.
      = .apply()                     # Maps each group. Func can return DF, Sr or el.
      = [column_key]                       # A single column GB. All operations return a Sr.
     ```
     
    -#### Aggregate, Transform, Map:
    +#### GroupBy — Aggregate, Transform, Map:
     ```python
      = .sum/max/mean/idxmax/all()         # Or: .agg(lambda : )
      = .rank/diff/cumsum/ffill()          # Or: .transform(lambda : )
    diff --git a/index.html b/index.html
    index 1907d86b1..911cec416 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -2549,7 +2549,7 @@ <Sr> = <Sr>.combine_first(<Sr>) # Adds items that are not yet present. <Sr>.update(<Sr>) # Updates items that are already present.
    -

    Aggregate, Transform, Map:

    <el> = <Sr>.sum/max/mean/idxmax/all()         # Or: <Sr>.agg(lambda <Sr>: <el>)
    +

    Series — Aggregate, Transform, Map:

    <el> = <Sr>.sum/max/mean/idxmax/all()         # Or: <Sr>.agg(lambda <Sr>: <el>)
     <Sr> = <Sr>.rank/diff/cumsum/ffill/interpl()  # Or: <Sr>.agg/transform(lambda <Sr>: <Sr>)
     <Sr> = <Sr>.fillna(<el>)                      # Or: <Sr>.agg/transform/map(lambda <el>: <el>)
     
    @@ -2567,8 +2567,8 @@ ┃ sr.apply(…) │ 3 │ sum 3 │ s 3 ┃ ┃ sr.agg(…) │ │ │ ┃ ┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛ -
    -
    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    +
    +┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
     ┃                 │    'rank'   │   ['rank']  │ {'r': 'rank'} ┃
     ┠─────────────────┼─────────────┼─────────────┼───────────────┨
     ┃ sr.apply(…)     │             │      rank   │               ┃
    @@ -2606,7 +2606,7 @@
     <DF>    = <DF>.sort_index(ascending=True)     # Sorts rows by row keys.
     <DF>    = <DF>.sort_values(column_key/s)      # Sorts rows by the passed column/s.
     
    -

    Merge, Join, Concat:

    >>> l = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
    +

    DataFrame — Merge, Join, Concat:

    >>> l = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
     a  1  2
     b  3  4
    @@ -2646,13 +2646,13 @@
     ┃                        │ c  .   6   7  │            │            │ R must be a DataFrame.   ┃
     ┗━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━┛
     
    -

    Aggregate, Transform, Map:

    <Sr> = <DF>.sum/max/mean/idxmax/all()         # Or: <DF>.apply/agg(lambda <Sr>: <el>)
    +

    DataFrame — Aggregate, Transform, Map:

    <Sr> = <DF>.sum/max/mean/idxmax/all()         # Or: <DF>.apply/agg(lambda <Sr>: <el>)
     <DF> = <DF>.rank/diff/cumsum/ffill/interpl()  # Or: <DF>.apply/agg/transform(lambda <Sr>: <Sr>)
     <DF> = <DF>.fillna(<el>)                      # Or: <DF>.applymap(lambda <el>: <el>)
     
      -
    • All operations operate on columns by default. Use 'axis=1' parameter to process the rows instead. Transform passes DF to a function if it raises an error after receiving a Sr.
    • +
    • All operations operate on columns by default. Pass 'axis=1' to process the rows instead.
    >>> df = DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
    @@ -2666,8 +2666,8 @@
     ┃ df.agg(…)       │     x  4    │  sum  4  6  │     x  4      ┃
     ┃                 │     y  6    │             │               ┃
     ┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    -
    -
    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
    +
    +┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓
     ┃                 │    'rank'   │   ['rank']  │ {'x': 'rank'} ┃
     ┠─────────────────┼─────────────┼─────────────┼───────────────┨
     ┃ df.apply(…)     │      x  y   │      x    y │        x      ┃
    @@ -2679,7 +2679,7 @@
     
    • Use '<DF>[col_key_1, col_key_2][row_key]' to get the fifth result's values.
    -

    Encode, Decode:

    <DF> = pd.read_json/html('<str/path/url>')
    +

    DataFrame — Encode, Decode, Plot:

    <DF> = pd.read_json/html('<str/path/url>')
     <DF> = pd.read_csv/pickle/excel('<path/url>')
     <DF> = pd.read_sql('<table_name/query>', <connection>)
     <DF> = pd.read_clipboard()
    @@ -2690,6 +2690,9 @@
     <DF>.to_pickle/excel(<path>)
     <DF>.to_sql('<table_name>', <connection>)
     
    +
    import matplotlib.pyplot as plt
    +<DF>.plot.line/bar/hist/scatter([x=column_key, y=column_key/s]); plt.show()
    +

    GroupBy

    Object that groups together rows of a dataframe based on the value of the passed column.

    >>> df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 6]], index=list('abc'), columns=list('xyz'))
     >>> df.groupby('z').get_group(6)
        x  y
    @@ -2699,11 +2702,10 @@
     
     
     
    <GB> = <DF>.groupby(column_key/s)             # DF is split into groups based on passed column.
    -<DF> = <GB>.get_group(group_key/s)            # Selects a group by value of grouping column.
     <DF> = <GB>.apply(<func>)                     # Maps each group. Func can return DF, Sr or el.
     <GB> = <GB>[column_key]                       # A single column GB. All operations return a Sr.
     
    -

    Aggregate, Transform, Map:

    <DF> = <GB>.sum/max/mean/idxmax/all()         # Or: <GB>.agg(lambda <Sr>: <el>)
    +

    GroupBy — Aggregate, Transform, Map:

    <DF> = <GB>.sum/max/mean/idxmax/all()         # Or: <GB>.agg(lambda <Sr>: <el>)
     <DF> = <GB>.rank/diff/cumsum/ffill()          # Or: <GB>.transform(lambda <Sr>: <Sr>)
     <DF> = <GB>.fillna(<el>)                      # Or: <GB>.transform(lambda <Sr>: <Sr>)
     
    @@ -2881,7 +2883,7 @@
    - +
    diff --git a/parse.js b/parse.js index 13b06bf7e..7c2443a95 100755 --- a/parse.js +++ b/parse.js @@ -316,12 +316,8 @@ const DIAGRAM_13_B = "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" + "┃ sr.apply(…) │ 3 │ sum 3 │ s 3 ┃\n" + "┃ sr.agg(…) │ │ │ ┃\n" + - "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; - -const DIAGRAM_14_A = - '| sr.apply(…) | | rank | |'; - -const DIAGRAM_14_B = + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n" + + "\n" + "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + "┃ │ 'rank' │ ['rank'] │ {'r': 'rank'} ┃\n" + "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" + @@ -374,12 +370,8 @@ const DIAGRAM_16_B = "┃ df.apply(…) │ │ x y │ ┃\n" + "┃ df.agg(…) │ x 4 │ sum 4 6 │ x 4 ┃\n" + "┃ │ y 6 │ │ ┃\n" + - "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; - -const DIAGRAM_17_A = - '| df.apply(…) | x y | x y | x |'; - -const DIAGRAM_17_B = + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n" + + "\n" + "┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓\n" + "┃ │ 'rank' │ ['rank'] │ {'x': 'rank'} ┃\n" + "┠─────────────────┼─────────────┼─────────────┼───────────────┨\n" + @@ -524,10 +516,8 @@ function updateDiagrams() { $(`code:contains(${DIAGRAM_11_A})`).html(DIAGRAM_11_B); $(`code:contains(${DIAGRAM_12_A})`).html(DIAGRAM_12_B).removeClass("text").removeClass("language-text").addClass("python"); $(`code:contains(${DIAGRAM_13_A})`).html(DIAGRAM_13_B).removeClass("text").removeClass("language-text").addClass("python"); - $(`code:contains(${DIAGRAM_14_A})`).html(DIAGRAM_14_B).removeClass("text").removeClass("language-text").addClass("python"); $(`code:contains(${DIAGRAM_15_A})`).html(DIAGRAM_15_B).removeClass("text").removeClass("language-text").addClass("python"); $(`code:contains(${DIAGRAM_16_A})`).html(DIAGRAM_16_B).removeClass("text").removeClass("language-text").addClass("python"); - $(`code:contains(${DIAGRAM_17_A})`).html(DIAGRAM_17_B).removeClass("text").removeClass("language-text").addClass("python"); $(`code:contains(${DIAGRAM_18_A})`).html(DIAGRAM_18_B).removeClass("text").removeClass("language-text").addClass("python"); } diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html index 365b8c112..92976e2ac 100644 --- a/pdf/index_for_pdf.html +++ b/pdf/index_for_pdf.html @@ -32,7 +32,7 @@

    C

    copy function, 15
    coroutine, 33
    counter, 2, 4, 12, 17
    -csv, 26, 34, 46, 47
    +csv, 26, 34, 46, 47
    curses module, 33, 34
    cython, 49

    D

    @@ -48,7 +48,7 @@

    E

    eval function, 33
    exceptions, 20-21, 23, 35

    F

    -

    files, 22-29, 34, 46
    +

    files, 22-29, 34, 46
    filter function, 11
    floats, 4, 6, 7
    format, 6-7, 37
    @@ -73,7 +73,7 @@

    I

    iterator, 3-4, 11, 17
    itertools module, 3, 8

    J

    -

    json, 25, 36, 46

    +

    json, 25, 36, 46

    L

    lambda, 11
    list comprehension, 11
    @@ -102,7 +102,7 @@

    P

    paths, 23-24, 34
    pickle module, 25
    pillow library, 39-40
    -plotting, 34, 47-48
    +plotting, 34, 46, 47-48
    print function, 22
    profiling, 36-37
    progress bar, 34
    @@ -118,7 +118,7 @@

    R

    regular expressions, 5-6
    requests library, 35, 36

    S

    -

    scraping, 35, 43, 46, 47-48
    +

    scraping, 35, 43, 46, 47-48
    sequence, 4, 18-19
    sets, 2, 4, 11, 19, 21, 31
    shell commands, 25
    @@ -126,7 +126,7 @@

    S

    slots attribute, 15
    sortable, 1, 16
    splat operator, 10-11
    -sql, 27, 46
    +sql, 27, 46
    statistics, 7, 37-38, 44-48
    strings, 4-7, 14
    struct module, 28-29
    @@ -134,7 +134,7 @@

    S

    super function, 14
    sys module, 13, 21-22

    T

    -

    table, 26, 27, 34, 37-38, 45-46
    +

    table, 26, 27, 34, 37-38, 45-46
    template, 6, 36
    threading module, 30
    time module, 34, 36
    diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 3aa2bfe29..f9964fe03 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -102,7 +102,7 @@

    P

    paths, 23-24, 34
    pickle module, 25
    pillow library, 39-40
    -plotting, 34, 47-48
    +plotting, 34, 46, 47-48
    print function, 22
    profiling, 36-37
    progress bar, 34
    From 019fa61d2699c009b0ab6a37643026e3713a3178 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 6 Feb 2022 14:13:19 +0100 Subject: [PATCH 019/638] TOC --- README.md | 2 +- index.html | 6 +++--- parse.js | 2 +- web/script_2.js | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c056a158a..4fe7f2c9c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Contents -------- **   ** **1. Collections:** ** ** **[`List`](#list)**__,__ **[`Dictionary`](#dictionary)**__,__ **[`Set`](#set)**__,__ **[`Tuple`](#tuple)**__,__ **[`Range`](#range)**__,__ **[`Enumerate`](#enumerate)**__,__ **[`Iterator`](#iterator)**__,__ **[`Generator`](#generator)**__.__ **   ** **2. Types:** **          ** **[`Type`](#type)**__,__ **[`String`](#string)**__,__ **[`Regular_Exp`](#regex)**__,__ **[`Format`](#format)**__,__ **[`Numbers`](#numbers-1)**__,__ **[`Combinatorics`](#combinatorics)**__,__ **[`Datetime`](#datetime)**__.__ -**   ** **3. Syntax:** **         ** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Imports`](#imports)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Type`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exception`](#exceptions)**__.__ +**   ** **3. Syntax:** **         ** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Import`](#imports)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Types`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exception`](#exceptions)**__.__ **   ** **4. System:** **        ** **[`Exit`](#exit)**__,__ **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#paths)**__,__ **[`OS_Commands`](#os-commands)**__.__ **   ** **5. Data:** **             ** **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`Memory_View`](#memory-view)**__,__ **[`Deque`](#deque)**__.__ **   ** **6. Advanced:** **   ** **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Introspection`](#introspection)**__,__ **[`Metaprograming`](#metaprogramming)**__,__ **[`Eval`](#eval)**__,__ **[`Coroutines`](#coroutines)**__.__ diff --git a/index.html b/index.html index 911cec416..6f38a79d7 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -82,7 +82,7 @@

    #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, Imports, Decorator, Class, Duck_Type, Enum, Exception],
    +    '3. Syntax':      [Args, Inline, Import, Decorator, Class, Duck_Types, Enum, Exception],
         '4. System':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],
         '5. Data':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],
         '6. Advanced':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],
    @@ -2883,7 +2883,7 @@
      
     
       
    - +
    diff --git a/parse.js b/parse.js index 7c2443a95..0fdc92e77 100755 --- a/parse.js +++ b/parse.js @@ -35,7 +35,7 @@ const TOC = '
    ToC = {\n' +
       '    \'1. Collections\': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],\n' +
       '    \'2. Types\':       [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],\n' +
    -  '    \'3. Syntax\':      [Args, Inline, Imports, Decorator, Class, Duck_Type, Enum, Exception],\n' +
    +  '    \'3. Syntax\':      [Args, Inline, Import, Decorator, Class, Duck_Types, Enum, Exception],\n' +
       '    \'4. System\':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],\n' +
       '    \'5. Data\':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],\n' +
       '    \'6. Advanced\':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' +
    diff --git a/web/script_2.js b/web/script_2.js
    index ebb8b9147..e6b7d5bdd 100644
    --- a/web/script_2.js
    +++ b/web/script_2.js
    @@ -2,7 +2,7 @@ const TOC =
       'ToC = {\n' +
       '    \'1. Collections\': [List, Dictionary, Set, Tuple, Range, Enumerate, Iterator, Generator],\n' +
       '    \'2. Types\':       [Type, String, Regular_Exp, Format, Numbers, Combinatorics, Datetime],\n' +
    -  '    \'3. Syntax\':      [Args, Inline, Imports, Decorator, Class, Duck_Type, Enum, Exception],\n' +
    +  '    \'3. Syntax\':      [Args, Inline, Import, Decorator, Class, Duck_Types, Enum, Exception],\n' +
       '    \'4. System\':      [Exit, Print, Input, Command_Line_Arguments, Open, Path, OS_Commands],\n' +
       '    \'5. Data\':        [JSON, Pickle, CSV, SQLite, Bytes, Struct, Array, Memory_View, Deque],\n' +
       '    \'6. Advanced\':    [Threading, Operator, Introspection, Metaprograming, Eval, Coroutine],\n' +
    @@ -18,9 +18,9 @@ const TOC_MOBILE =
       '    \'2. Types\':       [Type, String, Regular_Exp,\n' +
       '                       Format, Numbers,\n' +
       '                       Combinatorics, Datetime],\n' +
    -  '    \'3. Syntax\':      [Args, Inline, Imports,\n' +
    +  '    \'3. Syntax\':      [Args, Inline, Import,\n' +
       '                       Decorator, Class,\n' +
    -  '                       Duck_Type, Enum,\n' +
    +  '                       Duck_Types, Enum,\n' +
       '                       Exception],\n' +
       '    \'4. System\':      [Exit, Print, Input,\n' +
       '                       Command_Line_Arguments,\n' +
    
    From 63a85ba7e9ecebf9663bd2eb2b2c2f19c24bc19e Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sun, 13 Feb 2022 00:19:41 +0100
    Subject: [PATCH 020/638] Type, String
    
    ---
     README.md  |  4 ++--
     index.html |  8 ++++----
     parse.js   | 44 ++++++++++++++++++++++++++++++++++++++++++++
     3 files changed, 50 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index 4fe7f2c9c..daf5ef82a 100644
    --- a/README.md
    +++ b/README.md
    @@ -262,7 +262,7 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleTyp
     ```
     
     ### Abstract Base Classes
    -**Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().**
    +**Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Collection ABC looks for methods iter(), contains() and len(), while Iterable ABC only looks for method iter().**
     
     ```python
     >>> from collections.abc import Sequence, Collection, Iterable
    @@ -318,7 +318,7 @@ String
      = .startswith()         # Pass tuple of strings for multiple options.
      = .endswith()           # Pass tuple of strings for multiple options.
       = .find()               # Returns start index of the first match or -1.
    -  = .index()              # Same but raises ValueError if missing.
    +  = .index()              # Same, but raises ValueError if missing.
     ```
     
     ```python
    diff --git a/index.html b/index.html
    index 6f38a79d7..a62a1b794 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -263,7 +263,7 @@

    Some types do not have built-in names, so they must be imported:

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

    Abstract Base Classes

    Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().

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

    Abstract Base Classes

    Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Collection ABC looks for methods iter(), contains() and len(), while Iterable ABC only looks for method iter().

    >>> from collections.abc import Sequence, Collection, Iterable
     >>> isinstance([1, 2, 3], Iterable)
     True
     
    @@ -304,7 +304,7 @@ <bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options. <bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options. <int> = <str>.find(<sub_str>) # Returns start index of the first match or -1. -<int> = <str>.index(<sub_str>) # Same but raises ValueError if missing. +<int> = <str>.index(<sub_str>) # Same, but raises ValueError if missing.
    <str>  = <str>.replace(old, new [, count])   # Replaces 'old' with 'new' at most 'count' times.
     <str>  = <str>.translate(<table>)            # Use `str.maketrans(<dict>)` to generate table.
    @@ -2883,7 +2883,7 @@
      
     
       
    - +
    diff --git a/parse.js b/parse.js index 0fdc92e77..828c4dbb1 100755 --- a/parse.js +++ b/parse.js @@ -115,6 +115,15 @@ const DIAGRAM_1_B = '┃ iter │ │ │ ✓ ┃\n' + '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; +// const DIAGRAM_1_B = + // '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + + // '┃ │ Iterable │ Collection │ Sequence ┃\n' + + // '┠──────────────────┼────────────┼────────────┼────────────┨\n' + + // '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + + // '┃ dict, set │ ✓ │ ✓ │ ┃\n' + + // '┃ iter │ ✓ │ │ ┃\n' + + // '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; + const DIAGRAM_2_A = '+--------------------+----------+----------+----------+----------+----------+\n' + '| | Integral | Rational | Real | Complex | Number |\n' + @@ -131,6 +140,17 @@ const DIAGRAM_2_B = '┃ decimal.Decimal │ │ │ │ │ ✓ ┃\n' + '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; +// const DIAGRAM_2_B = +// '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + +// '┃ │ Number │ Complex │ Real │ Rational │ Integral ┃\n' + +// '┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' + +// '┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + +// '┃ fractions.Fraction │ ✓ │ ✓ │ ✓ │ ✓ │ ┃\n' + +// '┃ float │ ✓ │ ✓ │ ✓ │ │ ┃\n' + +// '┃ complex │ ✓ │ ✓ │ │ │ ┃\n' + +// '┃ decimal.Decimal │ ✓ │ │ │ │ ┃\n' + +// '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; + const DIAGRAM_3_A = '+---------------+----------+----------+----------+----------+----------+\n'; @@ -145,6 +165,17 @@ const DIAGRAM_3_B = '┃ isdecimal() │ │ │ │ │ ✓ ┃\n' + '┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; +// const DIAGRAM_3_B = +// '┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + +// '┃ │ [0-9] │ [²³¹] │ [¼½¾] │ [a-zA-Z] │ [ !#$%…] ┃\n' + +// '┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' + +// '┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + +// '┃ isalnum() │ ✓ │ ✓ │ ✓ │ ✓ │ ┃\n' + +// '┃ isnumeric() │ ✓ │ ✓ │ ✓ │ │ ┃\n' + +// '┃ isdigit() │ ✓ │ ✓ │ │ │ ┃\n' + +// '┃ isdecimal() │ ✓ │ │ │ │ ┃\n' + +// '┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; + const DIAGRAM_4_A = "+--------------+----------------+----------------+----------------+----------------+\n" + "| | {} | {:f} | {:e} | {:%} |\n" + @@ -199,6 +230,19 @@ const DIAGRAM_6_B = '┃ count() │ │ │ │ ✓ ┃\n' + '┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n'; +// const DIAGRAM_6_B = +// '┏━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + +// '┃ │ abc.Sequence │ Sequence │ Collection │ Iterable ┃\n' + +// '┠────────────┼──────────────┼────────────┼────────────┼────────────┨\n' + +// '┃ iter() │ ✓ │ ✓ │ ! │ ! ┃\n' + +// '┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + +// '┃ len() │ ! │ ! │ ! │ ┃\n' + +// '┃ getitem() │ ! │ ! │ │ ┃\n' + +// '┃ reversed() │ ✓ │ ✓ │ │ ┃\n' + +// '┃ index() │ ✓ │ │ │ ┃\n' + +// '┃ count() │ ✓ │ │ │ ┃\n' + +// '┗━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; + const DIAGRAM_7_A = 'BaseException\n' + ' +-- SystemExit'; From daacc4c44160a110d62cd496728b7ce5d3ed5840 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 13 Feb 2022 00:22:49 +0100 Subject: [PATCH 021/638] Cleanup of parse.js --- parse.js | 38 +++++++------------------------------- 1 file changed, 7 insertions(+), 31 deletions(-) diff --git a/parse.js b/parse.js index 828c4dbb1..8e7348cd8 100755 --- a/parse.js +++ b/parse.js @@ -116,13 +116,13 @@ const DIAGRAM_1_B = '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; // const DIAGRAM_1_B = - // '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + - // '┃ │ Iterable │ Collection │ Sequence ┃\n' + - // '┠──────────────────┼────────────┼────────────┼────────────┨\n' + - // '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + - // '┃ dict, set │ ✓ │ ✓ │ ┃\n' + - // '┃ iter │ ✓ │ │ ┃\n' + - // '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; +// '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + +// '┃ │ Iterable │ Collection │ Sequence ┃\n' + +// '┠──────────────────┼────────────┼────────────┼────────────┨\n' + +// '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + +// '┃ dict, set │ ✓ │ ✓ │ ┃\n' + +// '┃ iter │ ✓ │ │ ┃\n' + +// '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; const DIAGRAM_2_A = '+--------------------+----------+----------+----------+----------+----------+\n' + @@ -165,17 +165,6 @@ const DIAGRAM_3_B = '┃ isdecimal() │ │ │ │ │ ✓ ┃\n' + '┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; -// const DIAGRAM_3_B = -// '┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + -// '┃ │ [0-9] │ [²³¹] │ [¼½¾] │ [a-zA-Z] │ [ !#$%…] ┃\n' + -// '┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' + -// '┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ isalnum() │ ✓ │ ✓ │ ✓ │ ✓ │ ┃\n' + -// '┃ isnumeric() │ ✓ │ ✓ │ ✓ │ │ ┃\n' + -// '┃ isdigit() │ ✓ │ ✓ │ │ │ ┃\n' + -// '┃ isdecimal() │ ✓ │ │ │ │ ┃\n' + -// '┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; - const DIAGRAM_4_A = "+--------------+----------------+----------------+----------------+----------------+\n" + "| | {} | {:f} | {:e} | {:%} |\n" + @@ -230,19 +219,6 @@ const DIAGRAM_6_B = '┃ count() │ │ │ │ ✓ ┃\n' + '┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛\n'; -// const DIAGRAM_6_B = -// '┏━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + -// '┃ │ abc.Sequence │ Sequence │ Collection │ Iterable ┃\n' + -// '┠────────────┼──────────────┼────────────┼────────────┼────────────┨\n' + -// '┃ iter() │ ✓ │ ✓ │ ! │ ! ┃\n' + -// '┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ len() │ ! │ ! │ ! │ ┃\n' + -// '┃ getitem() │ ! │ ! │ │ ┃\n' + -// '┃ reversed() │ ✓ │ ✓ │ │ ┃\n' + -// '┃ index() │ ✓ │ │ │ ┃\n' + -// '┃ count() │ ✓ │ │ │ ┃\n' + -// '┗━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; - const DIAGRAM_7_A = 'BaseException\n' + ' +-- SystemExit'; From 6a91771156a0c7a57e4a7d7ccc88ffc9e4a1fa16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 17 Feb 2022 00:15:06 +0100 Subject: [PATCH 022/638] Type, Regex, Numbers --- README.md | 25 ++++++++++---------- index.html | 27 +++++++++++----------- parse.js | 68 +++++++++++++++++++++++++++--------------------------- 3 files changed, 61 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index daf5ef82a..2678e96ca 100644 --- a/README.md +++ b/README.md @@ -262,39 +262,39 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleTyp ``` ### Abstract Base Classes -**Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Collection ABC looks for methods iter(), contains() and len(), while Iterable ABC only looks for method iter().** +**Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().** ```python ->>> from collections.abc import Sequence, Collection, Iterable +>>> from collections.abc import Iterable, Collection, Sequence >>> isinstance([1, 2, 3], Iterable) True ``` ```text +------------------+------------+------------+------------+ -| | Sequence | Collection | Iterable | +| | Iterable | Collection | Sequence | +------------------+------------+------------+------------+ | list, range, str | yes | yes | yes | -| dict, set | | yes | yes | -| iter | | | yes | +| dict, set | yes | yes | | +| iter | yes | | | +------------------+------------+------------+------------+ ``` ```python ->>> from numbers import Integral, Rational, Real, Complex, Number +>>> from numbers import Number, Complex, Real, Rational, Integral >>> isinstance(123, Number) True ``` ```text +--------------------+----------+----------+----------+----------+----------+ -| | Integral | Rational | Real | Complex | Number | +| | Number | Complex | Real | Rational | Integral | +--------------------+----------+----------+----------+----------+----------+ | int | yes | yes | yes | yes | yes | -| fractions.Fraction | | yes | yes | yes | yes | -| float | | | yes | yes | yes | -| complex | | | | yes | yes | -| decimal.Decimal | | | | | yes | +| fractions.Fraction | yes | yes | yes | yes | | +| float | yes | yes | yes | | | +| complex | yes | yes | | | | +| decimal.Decimal | yes | | | | | +--------------------+----------+----------+----------+----------+----------+ ``` @@ -360,6 +360,7 @@ import re = re.finditer(, text) # Returns all occurrences as match objects. ``` +* **Argument 'new' can be a function that accepts a match and returns a string.** * **Search() and match() return None if they can't find a match.** * **Argument `'flags=re.IGNORECASE'` can be used with all functions.** * **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.** @@ -510,7 +511,7 @@ from math import log, log10, log2 ### Statistics ```python -from statistics import mean, median, variance, stdev, pvariance, pstdev +from statistics import mean, median, variance, stdev, quantiles, groupby ``` ### Random diff --git a/index.html b/index.html index a62a1b794..3d7926937 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -263,32 +263,32 @@

    Some types do not have built-in names, so they must be imported:

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

    Abstract Base Classes

    Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Collection ABC looks for methods iter(), contains() and len(), while Iterable ABC only looks for method iter().

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

    Abstract Base Classes

    Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().

    >>> from collections.abc import Iterable, Collection, Sequence
     >>> isinstance([1, 2, 3], Iterable)
     True
     
    ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
    -┃                  │  Sequence  │ Collection │  Iterable  ┃
    +┃                  │  Iterable  │ Collection │  Sequence  ┃
     ┠──────────────────┼────────────┼────────────┼────────────┨
     ┃ list, range, str │     ✓      │     ✓      │     ✓      ┃
    -┃ dict, set        │            │     ✓      │     ✓      ┃
    -┃ iter             │            │            │     ✓      ┃
    +┃ dict, set        │     ✓      │     ✓      │            ┃
    +┃ iter             │     ✓      │            │            ┃
     ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
     
    -
    >>> from numbers import Integral, Rational, Real, Complex, Number
    +
    >>> from numbers import Number, Complex, Real, Rational, Integral
     >>> isinstance(123, Number)
     True
     
    ┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
    -┃                    │ Integral │ Rational │   Real   │ Complex  │  Number  ┃
    +┃                    │  Number  │  Complex │   Real   │ Rational │ Integral ┃
     ┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
     ┃ int                │    ✓     │    ✓     │    ✓     │    ✓     │    ✓     ┃
    -┃ fractions.Fraction │          │    ✓     │    ✓     │    ✓     │    ✓     ┃
    -┃ float              │          │          │    ✓     │    ✓     │    ✓     ┃
    -┃ complex            │          │          │          │    ✓     │    ✓     ┃
    -┃ decimal.Decimal    │          │          │          │          │    ✓     ┃
    +┃ fractions.Fraction │    ✓     │    ✓     │    ✓     │    ✓     │          ┃
    +┃ float              │    ✓     │    ✓     │    ✓     │          │          ┃
    +┃ complex            │    ✓     │    ✓     │          │          │          ┃
    +┃ decimal.Decimal    │    ✓     │          │          │          │          ┃
     ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
     

    #String

    <str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
    @@ -340,6 +340,7 @@
     
      +
    • Argument 'new' can be a function that accepts a match and returns a string.
    • Search() and match() return None if they can't find a match.
    • Argument 'flags=re.IGNORECASE' can be used with all functions.
    • Argument 'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.
    • @@ -465,7 +466,7 @@ from math import log, log10, log2
    -

    Statistics

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

    Statistics

    from statistics import mean, median, variance, stdev, quantiles, groupby
     

    Random

    from random import random, randint, choice, shuffle, gauss, seed
    @@ -2883,7 +2884,7 @@
      
     
       
    - +
    diff --git a/parse.js b/parse.js index 8e7348cd8..c77d68ff6 100755 --- a/parse.js +++ b/parse.js @@ -103,54 +103,54 @@ const INDEX = const DIAGRAM_1_A = '+------------------+------------+------------+------------+\n' + - '| | Sequence | Collection | Iterable |\n' + + '| | Iterable | Collection | Sequence |\n' + '+------------------+------------+------------+------------+\n'; -const DIAGRAM_1_B = - '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + - '┃ │ Sequence │ Collection │ Iterable ┃\n' + - '┠──────────────────┼────────────┼────────────┼────────────┨\n' + - '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + - '┃ dict, set │ │ ✓ │ ✓ ┃\n' + - '┃ iter │ │ │ ✓ ┃\n' + - '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; - // const DIAGRAM_1_B = -// '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + -// '┃ │ Iterable │ Collection │ Sequence ┃\n' + -// '┠──────────────────┼────────────┼────────────┼────────────┨\n' + -// '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ dict, set │ ✓ │ ✓ │ ┃\n' + -// '┃ iter │ ✓ │ │ ┃\n' + -// '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; +// '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + +// '┃ │ Sequence │ Collection │ Iterable ┃\n' + +// '┠──────────────────┼────────────┼────────────┼────────────┨\n' + +// '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + +// '┃ dict, set │ │ ✓ │ ✓ ┃\n' + +// '┃ iter │ │ │ ✓ ┃\n' + +// '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; + +const DIAGRAM_1_B = +'┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + +'┃ │ Iterable │ Collection │ Sequence ┃\n' + +'┠──────────────────┼────────────┼────────────┼────────────┨\n' + +'┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + +'┃ dict, set │ ✓ │ ✓ │ ┃\n' + +'┃ iter │ ✓ │ │ ┃\n' + +'┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; const DIAGRAM_2_A = '+--------------------+----------+----------+----------+----------+----------+\n' + - '| | Integral | Rational | Real | Complex | Number |\n' + + '| | Number | Complex | Real | Rational | Integral |\n' + '+--------------------+----------+----------+----------+----------+----------+\n'; -const DIAGRAM_2_B = - '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + - '┃ │ Integral │ Rational │ Real │ Complex │ Number ┃\n' + - '┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' + - '┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + - '┃ fractions.Fraction │ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + - '┃ float │ │ │ ✓ │ ✓ │ ✓ ┃\n' + - '┃ complex │ │ │ │ ✓ │ ✓ ┃\n' + - '┃ decimal.Decimal │ │ │ │ │ ✓ ┃\n' + - '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; - // const DIAGRAM_2_B = // '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + -// '┃ │ Number │ Complex │ Real │ Rational │ Integral ┃\n' + +// '┃ │ Integral │ Rational │ Real │ Complex │ Number ┃\n' + // '┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' + // '┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ fractions.Fraction │ ✓ │ ✓ │ ✓ │ ✓ │ ┃\n' + -// '┃ float │ ✓ │ ✓ │ ✓ │ │ ┃\n' + -// '┃ complex │ ✓ │ ✓ │ │ │ ┃\n' + -// '┃ decimal.Decimal │ ✓ │ │ │ │ ┃\n' + +// '┃ fractions.Fraction │ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + +// '┃ float │ │ │ ✓ │ ✓ │ ✓ ┃\n' + +// '┃ complex │ │ │ │ ✓ │ ✓ ┃\n' + +// '┃ decimal.Decimal │ │ │ │ │ ✓ ┃\n' + // '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; +const DIAGRAM_2_B = + '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + + '┃ │ Number │ Complex │ Real │ Rational │ Integral ┃\n' + + '┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' + + '┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + + '┃ fractions.Fraction │ ✓ │ ✓ │ ✓ │ ✓ │ ┃\n' + + '┃ float │ ✓ │ ✓ │ ✓ │ │ ┃\n' + + '┃ complex │ ✓ │ ✓ │ │ │ ┃\n' + + '┃ decimal.Decimal │ ✓ │ │ │ │ ┃\n' + + '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; + const DIAGRAM_3_A = '+---------------+----------+----------+----------+----------+----------+\n'; From c6564ccd73059c6cabc4f86d7854435741d9608d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Feb 2022 06:45:30 +0100 Subject: [PATCH 023/638] Paths --- README.md | 4 ++-- index.html | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 2678e96ca..3f4d7b2f6 100644 --- a/README.md +++ b/README.md @@ -1655,7 +1655,7 @@ from pathlib import Path ```python = Path( [, ...]) # Accepts strings, Paths and DirEntry objects. - = / [/ ...] # One of the two paths must be a Path object. + = / [/ ...] # First or second path must be a Path object. ``` ```python @@ -1674,7 +1674,7 @@ from pathlib import Path ``` ```python - = .iterdir() # Returns dir contents as Path objects. + = .iterdir() # Returns directory contents as Path objects. = .glob('') # Returns Paths matching the wildcard pattern. ``` diff --git a/index.html b/index.html index 3d7926937..1987bb77a 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -1400,7 +1400,7 @@
    <Path> = Path(<path> [, ...])       # Accepts strings, Paths and DirEntry objects.
    -<Path> = <path> / <path> [/ ...]    # One of the two paths must be a Path object.
    +<Path> = <path> / <path> [/ ...]    # First or second path must be a Path object.
     
    <Path> = Path()                     # Returns relative cwd. Also Path('.').
     <Path> = Path.cwd()                 # Returns absolute cwd. Also Path().resolve().
    @@ -1413,7 +1413,7 @@
     <str>  = <Path>.suffix              # Returns final component's extension.
     <tup.> = <Path>.parts               # Returns all components as strings.
     
    -
    <iter> = <Path>.iterdir()           # Returns dir contents as Path objects.
    +
    <iter> = <Path>.iterdir()           # Returns directory contents as Path objects.
     <iter> = <Path>.glob('<pattern>')   # Returns Paths matching the wildcard pattern.
     
    <str>  = str(<Path>)                # Returns path as a string.
    @@ -2884,7 +2884,7 @@
      
     
       
    - +
    From 9af8d0b2cba76f7c5dc427d6c0f8074aa111e0ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Feb 2022 07:29:42 +0100 Subject: [PATCH 024/638] Paths --- README.md | 4 ++-- index.html | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3f4d7b2f6..33873a20c 100644 --- a/README.md +++ b/README.md @@ -1645,7 +1645,7 @@ from os import scandir = scandir(path='.') # Returns DirEntry objects located at path. = .path # Returns whole path as a string. = .name # Returns final component as a string. - = open() # Opens the file and returns file object. + = open() # Opens the file and returns a file object. ``` ### Path Object @@ -1680,7 +1680,7 @@ from pathlib import Path ```python = str() # Returns path as a string. - = open() # Opens the file and returns file object. + = open() # Opens the file and returns a file object. ``` diff --git a/index.html b/index.html index 1987bb77a..a1fb8f998 100644 --- a/index.html +++ b/index.html @@ -1394,7 +1394,7 @@
    <iter> = scandir(path='.')          # Returns DirEntry objects located at path.
     <str>  = <DirEntry>.path            # Returns whole path as a string.
     <str>  = <DirEntry>.name            # Returns final component as a string.
    -<file> = open(<DirEntry>)           # Opens the file and returns file object.
    +<file> = open(<DirEntry>)           # Opens the file and returns a file object.
     

    Path Object

    from pathlib import Path
     
    @@ -1417,7 +1417,7 @@ <iter> = <Path>.glob('<pattern>') # Returns Paths matching the wildcard pattern.
    <str>  = str(<Path>)                # Returns path as a string.
    -<file> = open(<Path>)               # Opens the file and returns file object.
    +<file> = open(<Path>)               # Opens the file and returns a file object.
     

    #OS Commands

    Files and Directories

    • Paths can be either strings, Paths or DirEntry objects.
    • From 14233c43fc58744bc6b2b088088191cb4e53b40f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 27 Feb 2022 07:38:03 +0100 Subject: [PATCH 025/638] Grammar --- README.md | 6 +++--- index.html | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 33873a20c..60d415fda 100644 --- a/README.md +++ b/README.md @@ -1802,7 +1802,7 @@ import csv ```python = csv.reader() # Also: `dialect='excel', delimiter=','`. = next() # Returns next row as a list of strings. - = list() # Returns list of remaining rows. + = list() # Returns a list of remaining rows. ``` * **File must be opened with a `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!** @@ -1928,7 +1928,7 @@ Bytes ```python = b'' # Only accepts ASCII characters and \x00-\xff. - = [] # Returns int in range from 0 to 255. + = [] # Returns an int in range from 0 to 255. = [] # Returns bytes even if it has only one element. = .join() # Joins elements using bytes as a separator. ``` @@ -2044,7 +2044,7 @@ Memory View ``` ```python - = list() # Returns list of ints or floats. + = list() # Returns a list of ints or floats. = str(, 'utf-8') # Treats mview as a bytes object. = int.from_bytes(, …) # `byteorder='big/little', signed=False`. '' = .hex() # Treats mview as a bytes object. diff --git a/index.html b/index.html index a1fb8f998..589747ba5 100644 --- a/index.html +++ b/index.html @@ -1496,7 +1496,7 @@

      Read

      <reader> = csv.reader(<file>)       # Also: `dialect='excel', delimiter=','`.
       <list>   = next(<reader>)           # Returns next row as a list of strings.
      -<list>   = list(<reader>)           # Returns list of remaining rows.
      +<list>   = list(<reader>)           # Returns a list of remaining rows.
       
        @@ -1597,7 +1597,7 @@

        #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.
        +<int>   = <bytes>[<index>]               # Returns an 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 as a separator.
         
        @@ -1691,7 +1691,7 @@ <file>.write(<mview>) # Writes mview to the binary file.
    -
    <list>  = list(<mview>)                        # Returns list of ints or floats.
    +
    <list>  = list(<mview>)                        # Returns a list of ints or floats.
     <str>   = str(<mview>, 'utf-8')                # Treats mview as a bytes object.
     <int>   = int.from_bytes(<mview>, …)           # `byteorder='big/little', signed=False`.
     '<hex>' = <mview>.hex()                        # Treats mview as a bytes object.
    
    From 13d97443bafc06e386b2adac587b0f4dfaf89859 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 1 Mar 2022 08:50:59 +0100
    Subject: [PATCH 026/638] Coroutines, Pandas
    
    ---
     README.md  | 26 +++++++++++++-------------
     index.html | 36 ++++++++++++++++++------------------
     2 files changed, 31 insertions(+), 31 deletions(-)
    
    diff --git a/README.md b/README.md
    index 60d415fda..55f09046d 100644
    --- a/README.md
    +++ b/README.md
    @@ -1122,7 +1122,7 @@ class MyHashable:
     ```
     
     ### Sortable
    -* **With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.**
    +* **With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.**
     * **Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts.**
     * **When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.**
     
    @@ -1525,11 +1525,11 @@ arguments    = sys.argv[1:]
     ```python
     from argparse import ArgumentParser, FileType
     p = ArgumentParser(description=)
    -p.add_argument('-', '--', action='store_true')  # Flag
    -p.add_argument('-', '--', type=)          # Option
    -p.add_argument('', type=, nargs=1)                    # First argument
    -p.add_argument('', type=, nargs='+')                  # Remaining arguments
    -p.add_argument('', type=, nargs='*')                  # Optional arguments
    +p.add_argument('-', '--', action='store_true')  # Flag.
    +p.add_argument('-', '--', type=)          # Option.
    +p.add_argument('', type=, nargs=1)                    # First argument.
    +p.add_argument('', type=, nargs='+')                  # Remaining arguments.
    +p.add_argument('', type=, nargs='*')                  # Optional arguments.
     args  = p.parse_args()                                            # Exits on error.
     value = args.
     ```
    @@ -2334,7 +2334,7 @@ async def human_controller(screen, moves):
             await asyncio.sleep(0.005)
     
     async def model(moves, state):
    -    while state['*'] not in {p for id_, p in state.items() if id_ != '*'}:
    +    while state['*'] not in (state[id_] for id_ in range(10)):
             id_, d = await moves.get()
             x, y   = state[id_]
             deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)}
    @@ -3292,7 +3292,12 @@ b  3  4
     ```
     * **Use `'[col_key_1, col_key_2][row_key]'` to get the fifth result's values.**
     
    -#### DataFrame — Encode, Decode, Plot:
    +#### DataFrame — Plot, Encode, Decode:
    +```python
    +import matplotlib.pyplot as plt
    +.plot.line/bar/hist/scatter([x=column_key, y=column_key/s]); plt.show()
    +```
    +
     ```python
      = pd.read_json/html('')
      = pd.read_csv/pickle/excel('')
    @@ -3307,11 +3312,6 @@ b  3  4
     .to_sql('', )
     ```
     
    -```python
    -import matplotlib.pyplot as plt
    -.plot.line/bar/hist/scatter([x=column_key, y=column_key/s]); plt.show()
    -```
    -
     ### GroupBy
     **Object that groups together rows of a dataframe based on the value of the passed column.**
     
    diff --git a/index.html b/index.html
    index 589747ba5..7edc05340 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -950,7 +950,7 @@

    Sortable

      -
    • With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.
    • +
    • With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.
    • Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts.
    • When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.
    from functools import total_ordering
    @@ -1057,7 +1057,7 @@
     

    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'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only iterable objects that are not collections.
    • +
    • I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are not collections while being iterable.
    class MyCollection:
         def __init__(self, a):
             self.a = a
    @@ -1298,11 +1298,11 @@
     
     

    Argument Parser

    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
    -p.add_argument('<name>', type=<type>, nargs=1)                    # First argument
    -p.add_argument('<name>', type=<type>, nargs='+')                  # Remaining arguments
    -p.add_argument('<name>', type=<type>, nargs='*')                  # Optional arguments
    +p.add_argument('-<short_name>', '--<name>', action='store_true')  # Flag.
    +p.add_argument('-<short_name>', '--<name>', type=<type>)          # Option.
    +p.add_argument('<name>', type=<type>, nargs=1)                    # First argument.
    +p.add_argument('<name>', type=<type>, nargs='+')                  # Remaining arguments.
    +p.add_argument('<name>', type=<type>, nargs='*')                  # Optional arguments.
     args  = p.parse_args()                                            # Exits on error.
     value = args.<name>
     
    @@ -1319,7 +1319,7 @@
    • 'encoding=None' means that the 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 input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.
    • +
    • 'newline=""' means no conversions take place, but input is still broken into chunks by readline() and readlines() on '\n', '\r' and '\r\n'.

    Modes

    • 'r' - Read (default).
    • @@ -1330,7 +1330,7 @@
    • 'r+' - Read and write from the start.
    • 'a+' - Read and write from the end.
    • 't' - Text mode (default).
    • -
    • 'b' - Binary mode.
    • +
    • 'b' - Binary mode (must be paired with one of above).

    Exceptions

    • 'FileNotFoundError' can be raised when reading with 'r' or 'r+'.
    • 'FileExistsError' can be raised when writing with 'x'.
    • @@ -1910,7 +1910,7 @@ await asyncio.sleep(0.005) async def model(moves, state): - while state['*'] not in {p for id_, p in state.items() if id_ != '*'}: + while state['*'] not in (state[id_] for id_ in range(10)): id_, d = await moves.get() x, y = state[id_] deltas = {D.n: P(0, -1), D.e: P(1, 0), D.s: P(0, 1), D.w: P(-1, 0)} @@ -2680,20 +2680,20 @@
      • Use '<DF>[col_key_1, col_key_2][row_key]' to get the fifth result's values.
      -

      DataFrame — Encode, Decode, Plot:

      <DF> = pd.read_json/html('<str/path/url>')
      +

      DataFrame — Plot, Encode, Decode:

      import matplotlib.pyplot as plt
      +<DF>.plot.line/bar/hist/scatter([x=column_key, y=column_key/s]); plt.show()
      +
      + +
      <DF> = pd.read_json/html('<str/path/url>')
       <DF> = pd.read_csv/pickle/excel('<path/url>')
       <DF> = pd.read_sql('<table_name/query>', <connection>)
       <DF> = pd.read_clipboard()
      -
      - +
    <dict> = <DF>.to_dict(['d/l/s/sp/r/i'])
     <str>  = <DF>.to_json/html/csv/markdown/latex([<path>])
     <DF>.to_pickle/excel(<path>)
     <DF>.to_sql('<table_name>', <connection>)
     
    -
    import matplotlib.pyplot as plt
    -<DF>.plot.line/bar/hist/scatter([x=column_key, y=column_key/s]); plt.show()
    -

    GroupBy

    Object that groups together rows of a dataframe based on the value of the passed column.

    >>> df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 6]], index=list('abc'), columns=list('xyz'))
     >>> df.groupby('z').get_group(6)
        x  y
    @@ -2884,7 +2884,7 @@
      
     
       
     
    
    From 23f0b7a66fc9d8bcb3707726ccd908fcc20fbd6b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 1 Mar 2022 08:52:04 +0100
    Subject: [PATCH 027/638] Coroutines, Pandas
    
    ---
     index.html | 6 +++---
     1 file changed, 3 insertions(+), 3 deletions(-)
    
    diff --git a/index.html b/index.html
    index 7edc05340..1ffdd4eed 100644
    --- a/index.html
    +++ b/index.html
    @@ -1057,7 +1057,7 @@
     

    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'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are not collections while being iterable.
    • +
    • I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only iterable objects that are not collections.
    class MyCollection:
         def __init__(self, a):
             self.a = a
    @@ -1319,7 +1319,7 @@
     
    • 'encoding=None' means that the 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 input is still broken into chunks by readline() and readlines() on '\n', '\r' and '\r\n'.
    • +
    • 'newline=""' means no conversions take place, but input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.

    Modes

    • 'r' - Read (default).
    • @@ -1330,7 +1330,7 @@
    • 'r+' - Read and write from the start.
    • 'a+' - Read and write from the end.
    • 't' - Text mode (default).
    • -
    • 'b' - Binary mode (must be paired with one of above).
    • +
    • 'b' - Binary mode.

    Exceptions

    • 'FileNotFoundError' can be raised when reading with 'r' or 'r+'.
    • 'FileExistsError' can be raised when writing with 'x'.
    • From c13adfeadcd43aacc95a329a0b768415d74f2326 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 1 Mar 2022 12:56:07 +0100 Subject: [PATCH 028/638] Regex --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 55f09046d..c0d642df8 100644 --- a/README.md +++ b/README.md @@ -360,7 +360,7 @@ import re = re.finditer(, text) # Returns all occurrences as match objects. ``` -* **Argument 'new' can be a function that accepts a match and returns a string.** +* **Argument 'new' can be a function that accepts a match object and returns a string.** * **Search() and match() return None if they can't find a match.** * **Argument `'flags=re.IGNORECASE'` can be used with all functions.** * **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.** diff --git a/index.html b/index.html index 1ffdd4eed..32e46a1fe 100644 --- a/index.html +++ b/index.html @@ -340,7 +340,7 @@
      -
    • Argument 'new' can be a function that accepts a match and returns a string.
    • +
    • Argument 'new' can be a function that accepts a match object and returns a string.
    • Search() and match() return None if they can't find a match.
    • Argument 'flags=re.IGNORECASE' can be used with all functions.
    • Argument 'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.
    • From 4086f76a2038faab4535026f0db3cb476f864ccf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 2 Mar 2022 15:49:52 +0100 Subject: [PATCH 029/638] Collection, Open --- README.md | 6 +++--- index.html | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index c0d642df8..0e5cb6bbd 100644 --- a/README.md +++ b/README.md @@ -1239,7 +1239,7 @@ True ### Collection * **Only required methods are iter() and len().** * **This cheatsheet actually means `''` when it uses `''`.** -* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only iterable objects that are not collections.** +* **I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.** ```python class MyCollection: def __init__(self, a): @@ -1548,7 +1548,7 @@ Open ``` * **`'encoding=None'` means that the 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 input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.** +* **`'newline=""'` means no conversions take place, but input is still broken into chunks by readline() and readlines() on '\n', '\r' and '\r\n'.** ### Modes * **`'r'` - Read (default).** @@ -1585,7 +1585,7 @@ Open ```python .write() # Writes a string or bytes object. .writelines() # Writes a coll. of strings or bytes objects. -.flush() # Flushes write buffer. +.flush() # Flushes write buffer. Runs every 4096/8192 B. ``` * **Methods do not add or strip trailing newlines, even writelines().** diff --git a/index.html b/index.html index 32e46a1fe..761ccd858 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
      - +
      @@ -1057,7 +1057,7 @@

      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'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only iterable objects that are not collections.
      • +
      • I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'. The only drawback of this decision is that a reader could think a certain function doesn't accept iterators when it does, since iterators are the only built-in objects that are iterable but are not collections.
      class MyCollection:
           def __init__(self, a):
               self.a = a
      @@ -1319,7 +1319,7 @@
       
      • 'encoding=None' means that the 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 input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.
      • +
      • 'newline=""' means no conversions take place, but input is still broken into chunks by readline() and readlines() on '\n', '\r' and '\r\n'.

      Modes

      • 'r' - Read (default).
      • @@ -1353,7 +1353,7 @@
      <file>.write(<str/bytes>)           # Writes a string or bytes object.
       <file>.writelines(<collection>)     # Writes a coll. of strings or bytes objects.
      -<file>.flush()                      # Flushes write buffer.
      +<file>.flush()                      # Flushes write buffer. Runs every 4096/8192 B.
       
      • Methods do not add or strip trailing newlines, even writelines().
      • @@ -2884,7 +2884,7 @@ From 2d135d9883cd7e98fbe4ad477264e827903cd3b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 3 Mar 2022 10:25:59 +0100 Subject: [PATCH 030/638] Open --- README.md | 2 +- index.html | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0e5cb6bbd..4bbd39cfe 100644 --- a/README.md +++ b/README.md @@ -1559,7 +1559,7 @@ Open * **`'r+'` - Read and write from the start.** * **`'a+'` - Read and write from the end.** * **`'t'` - Text mode (default).** -* **`'b'` - Binary mode.** +* **`'b'` - Binary mode (`'br'`, `'bw'`, `'bx'`, …).** ### Exceptions * **`'FileNotFoundError'` can be raised when reading with `'r'` or `'r+'`.** diff --git a/index.html b/index.html index 761ccd858..1a8c61b7a 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
        - +
        @@ -1330,7 +1330,7 @@
      • 'r+' - Read and write from the start.
      • 'a+' - Read and write from the end.
      • 't' - Text mode (default).
      • -
      • 'b' - Binary mode.
      • +
      • 'b' - Binary mode ('br', 'bw', 'bx', …).

      Exceptions

      • 'FileNotFoundError' can be raised when reading with 'r' or 'r+'.
      • 'FileExistsError' can be raised when writing with 'x'.
      • @@ -2884,7 +2884,7 @@ From 4c3bfcd01c3ac16ddca53eb1f0d87195bd17487a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 3 Mar 2022 15:17:22 +0100 Subject: [PATCH 031/638] Bitwise operators --- README.md | 10 +++++----- index.html | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 4bbd39cfe..d8709b6fe 100644 --- a/README.md +++ b/README.md @@ -533,11 +533,11 @@ from random import random, randint, choice, shuffle, gauss, seed ### Bitwise Operators ```python - = & # And: `0b1100 & 0b1010 == 0b1000`. - = | # Or: `0b1100 | 0b1010 == 0b1110`. - = ^ # Xor: `0b1100 ^ 0b1010 == 0b0110`. - = << n_bits # Left shift (>> for right) - = ~ # Not (also: - - 1) + = & # And (0b1100 & 0b1010 == 0b1000). + = | # Or (0b1100 | 0b1010 == 0b1110). + = ^ # Xor (0b1100 ^ 0b1010 == 0b0110). + = << n_bits # Left shift (>> for right). + = ~ # Not (also: - - 1). ``` diff --git a/index.html b/index.html index 1a8c61b7a..08b9d0a1b 100644 --- a/index.html +++ b/index.html @@ -482,11 +482,11 @@ <str> = bin(<int>) # Returns '[-]0b<bin>'.
    -

    Bitwise Operators

    <int> = <int> & <int>                    # And: `0b1100 & 0b1010 == 0b1000`.
    -<int> = <int> | <int>                    # Or:  `0b1100 | 0b1010 == 0b1110`.
    -<int> = <int> ^ <int>                    # Xor: `0b1100 ^ 0b1010 == 0b0110`.
    -<int> = <int> << n_bits                  # Left shift (>> for right)
    -<int> = ~<int>                           # Not (also: -<int> - 1)
    +

    Bitwise Operators

    <int> = <int> & <int>                    # And (0b1100 & 0b1010 == 0b1000).
    +<int> = <int> | <int>                    # Or  (0b1100 | 0b1010 == 0b1110).
    +<int> = <int> ^ <int>                    # Xor (0b1100 ^ 0b1010 == 0b0110).
    +<int> = <int> << n_bits                  # Left shift (>> for right).
    +<int> = ~<int>                           # Not (also: -<int> - 1).
     

    #Combinatorics

      From e78169d34b2b8832a77598bfafeb99d03c9fe457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 8 Mar 2022 11:54:40 +0100 Subject: [PATCH 032/638] Open, Series --- README.md | 13 +++++++++---- index.html | 15 ++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index d8709b6fe..0fea7d33b 100644 --- a/README.md +++ b/README.md @@ -381,6 +381,7 @@ import re * **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.** * **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'` (the so-called separator characters).** * **Use a capital letter for negation.** + ```python '\d' == '[0-9]' # Matches decimal characters. '\w' == '[a-zA-Z0-9_]' # Matches alphanumerics and underscore. @@ -1548,7 +1549,7 @@ Open ``` * **`'encoding=None'` means that the 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 input is still broken into chunks by readline() and readlines() on '\n', '\r' and '\r\n'.** +* **`'newline=""'` means no conversions take place, but input is still broken into chunks by readline() and readlines() on every '\n', '\r' and '\r\n'.** ### Modes * **`'r'` - Read (default).** @@ -1898,8 +1899,7 @@ with : # Exits the block with commit() ``` ### Example -**In this example values are not actually saved because `'conn.commit()'` is omitted!** - +**Values are not actually saved in this example because `'conn.commit()'` is omitted!** ```python >>> conn = sqlite3.connect('test.db') >>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)') @@ -3147,7 +3147,6 @@ Name: a, dtype: int64 = .rank/diff/cumsum/ffill/interpl() # Or: .agg/transform(lambda : ) = .fillna() # Or: .agg/transform/map(lambda : ) ``` -* **The way `'agg()'` and `'transform()'` find out whether the passed function accepts an element or the whole Series is by passing it a single value at first and if it raises an error, then they pass it the whole Series. `'agg()'` only accepts Attribute/Type/ValueError.** ```python >>> sr = Series([1, 2], index=['x', 'y']) @@ -3173,6 +3172,12 @@ y 2 ``` * **Last result has a hierarchical index. Use `'[key_1, key_2]'` to get its values.** +#### Series — Plot: +```python +import matplotlib.pyplot as plt +.plot.line/area/bar/pie/hist(); plt.show() +``` + ### DataFrame **Table with labeled rows and columns.** diff --git a/index.html b/index.html index 08b9d0a1b..8442484a0 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
      - +
      @@ -1319,7 +1319,7 @@
      • 'encoding=None' means that the 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 input is still broken into chunks by readline() and readlines() on '\n', '\r' and '\r\n'.
      • +
      • 'newline=""' means no conversions take place, but input is still broken into chunks by readline() and readlines() on every '\n', '\r' and '\r\n'.

      Modes

      • 'r' - Read (default).
      • @@ -1577,7 +1577,7 @@
    -

    Example

    In this example values are not actually saved because 'conn.commit()' is omitted!

    >>> conn = sqlite3.connect('test.db')
    +

    Example

    Values are not actually saved in this example because 'conn.commit()' is omitted!

    >>> conn = sqlite3.connect('test.db')
     >>> conn.execute('CREATE TABLE person (person_id INTEGER PRIMARY KEY, name, height)')
     >>> conn.execute('INSERT INTO person VALUES (NULL, ?, ?)', ('Jean-Luc', 187)).lastrowid
     1
    @@ -2555,9 +2555,6 @@
     <Sr> = <Sr>.fillna(<el>)                      # Or: <Sr>.agg/transform/map(lambda <el>: <el>)
     
    -
      -
    • The way 'agg()' and 'transform()' find out whether the passed function accepts an element or the whole Series is by passing it a single value at first and if it raises an error, then they pass it the whole Series. 'agg()' only accepts Attribute/Type/ValueError.
    • -
    >>> sr = Series([1, 2], index=['x', 'y'])
     x    1
     y    2
    @@ -2580,6 +2577,10 @@
     
    • Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
    +

    Series — Plot:

    import matplotlib.pyplot as plt
    +<Sr>.plot.line/area/bar/pie/hist(); plt.show()
    +
    +

    DataFrame

    Table with labeled rows and columns.

    >>> DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
     a  1  2
    @@ -2884,7 +2885,7 @@
      
     
       
     
    
    From 271fe2a0f8ee24a64855d459ebe0f9852a378f27 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 12 Mar 2022 11:59:40 +0100
    Subject: [PATCH 033/638] Iterator, Datetime
    
    ---
     README.md  | 4 ++--
     index.html | 8 ++++----
     2 files changed, 6 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index 0fea7d33b..3539f534d 100644
    --- a/README.md
    +++ b/README.md
    @@ -211,7 +211,7 @@ from itertools import count, repeat, cycle, chain, islice
     ```
     
     ```python
    - = chain(,  [, ...])  # Empties collections in order.
    + = chain(,  [, ...])  # Empties collections in order (figuratively).
      = chain.from_iterable()  # Empties collections inside a collection in order.
     ```
     
    @@ -657,7 +657,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary
        =   ±                    # Returned datetime can fall into missing hour.
          =  -                 # Returns the difference, ignoring time jumps.
          =    -                   # Ignores time jumps if they share tzinfo object.
    -     =     *                  # Also:  = abs() and  =  ±% 
    +     =     *                  # Also:  = abs() and  =  ±% .
       =     /                    # How many weeks/years there are in TD. Also '//'.
     ```
     
    diff --git a/index.html b/index.html
    index 8442484a0..1a7795ff5 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -228,7 +228,7 @@ <iter> = repeat(<el> [, times]) # Returns element endlessly or 'times' times. <iter> = cycle(<collection>) # Repeats the sequence endlessly.
    -
    <iter> = chain(<coll_1>, <coll_2> [, ...])  # Empties collections in order.
    +
    <iter> = chain(<coll_1>, <coll_2> [, ...])  # Empties collections in order (figuratively).
     <iter> = chain.from_iterable(<collection>)  # Empties collections inside a collection in order.
     
    <iter> = islice(<coll>, to_exclusive)       # Only returns first 'to_exclusive' elements.
    @@ -583,7 +583,7 @@
     

    Arithmetics

    <D/DT>   = <D/DT>  ± <TD>                   # Returned datetime can fall into missing hour.
     <TD>     = <D/DTn> - <D/DTn>                # Returns the difference, ignoring time jumps.
     <TD>     = <DTa>   - <DTa>                  # Ignores time jumps if they share tzinfo object.
    -<TD>     = <TD>    * <real>                 # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>
    +<TD>     = <TD>    * <real>                 # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>.
     <float>  = <TD>    / <TD>                   # How many weeks/years there are in TD. Also '//'.
     
    @@ -2885,7 +2885,7 @@ From 3633f6db4278c18e3d4924032ea388424d752933 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 12 Apr 2022 06:54:45 +0200 Subject: [PATCH 034/638] List, Pandas --- README.md | 13 ++++++------- index.html | 13 ++++++------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 3539f534d..37bad5886 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ list_of_chars = list() ```python .insert(, ) # Inserts item at index and moves the rest to the right. - = .pop([]) # Returns and removes item at index or from the end. + = .pop([]) # Removes and returns item at index or from the end. = .count() # Returns number of occurrences. Also works on strings. = .index() # Returns index of the first occurrence or raises ValueError. .remove() # Removes first occurrence of the item or raises ValueError. @@ -3141,6 +3141,11 @@ Name: a, dtype: int64 .update() # Updates items that are already present. ``` +```python +.plot.line/area/bar/pie/hist() # Generates a Matplotlib plot. +matplotlib.pyplot.show() # Displays the plot. Also savefig(). +``` + #### Series — Aggregate, Transform, Map: ```python = .sum/max/mean/idxmax/all() # Or: .agg(lambda : ) @@ -3172,12 +3177,6 @@ y 2 ``` * **Last result has a hierarchical index. Use `'[key_1, key_2]'` to get its values.** -#### Series — Plot: -```python -import matplotlib.pyplot as plt -.plot.line/area/bar/pie/hist(); plt.show() -``` - ### DataFrame **Table with labeled rows and columns.** diff --git a/index.html b/index.html index 1a7795ff5..0f25dea1e 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -124,7 +124,7 @@
  • Module operator provides functions itemgetter() and mul() that offer the same functionality as lambda expressions above.
  • <list>.insert(<int>, <el>)     # Inserts item at index and moves the rest to the right.
    -<el>  = <list>.pop([<int>])    # Returns and removes item at index or from the end.
    +<el>  = <list>.pop([<int>])    # Removes and returns item at index or from the end.
     <int> = <list>.count(<el>)     # Returns number of occurrences. Also works on strings.
     <int> = <list>.index(<el>)     # Returns index of the first occurrence or raises ValueError.
     <list>.remove(<el>)            # Removes first occurrence of the item or raises ValueError.
    @@ -2550,6 +2550,9 @@
     <Sr> = <Sr>.combine_first(<Sr>)               # Adds items that are not yet present.
     <Sr>.update(<Sr>)                             # Updates items that are already present.
     
    +
    <Sr>.plot.line/area/bar/pie/hist()            # Generates a Matplotlib plot.
    +matplotlib.pyplot.show()                      # Displays the plot. Also savefig(<path>).
    +

    Series — Aggregate, Transform, Map:

    <el> = <Sr>.sum/max/mean/idxmax/all()         # Or: <Sr>.agg(lambda <Sr>: <el>)
     <Sr> = <Sr>.rank/diff/cumsum/ffill/interpl()  # Or: <Sr>.agg/transform(lambda <Sr>: <Sr>)
     <Sr> = <Sr>.fillna(<el>)                      # Or: <Sr>.agg/transform/map(lambda <el>: <el>)
    @@ -2577,10 +2580,6 @@
     
    • Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
    -

    Series — Plot:

    import matplotlib.pyplot as plt
    -<Sr>.plot.line/area/bar/pie/hist(); plt.show()
    -
    -

    DataFrame

    Table with labeled rows and columns.

    >>> DataFrame([[1, 2], [3, 4]], index=['a', 'b'], columns=['x', 'y'])
        x  y
     a  1  2
    @@ -2885,7 +2884,7 @@
      
     
       
     
    
    From fccd460292b3a92022cdd0fd369e99f34f03e5ab Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 12 Apr 2022 17:28:39 +0200
    Subject: [PATCH 035/638] Regex, Format, Numbers
    
    ---
     README.md  | 12 ++++++------
     index.html | 15 ++++++++-------
     parse.js   | 11 ++---------
     3 files changed, 16 insertions(+), 22 deletions(-)
    
    diff --git a/README.md b/README.md
    index 37bad5886..c4c0baf65 100644
    --- a/README.md
    +++ b/README.md
    @@ -365,8 +365,8 @@ import re
     * **Argument `'flags=re.IGNORECASE'` can be used with all functions.**
     * **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.**
     * **Argument `'flags=re.DOTALL'` makes dot also accept the `'\n'`.**
    -* **Use `r'\1'` or `'\\1'` for backreference.**
    -* **Add `'?'` after an operator to make it non-greedy.**
    +* **Use `r'\1'` or `'\\1'` for backreference (`'\1'` returns a character with octal code 1).**
    +* **Add `'?'` after `'*'` and `'+'` to make them non-greedy.**
     
     ### Match Object
     ```python
    @@ -380,7 +380,7 @@ import re
     ### Special Sequences
     * **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.**
     * **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'` (the so-called separator characters).**
    -* **Use a capital letter for negation.**
    +* **Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).**
     
     ```python
     '\d' == '[0-9]'                                # Matches decimal characters.
    @@ -458,8 +458,7 @@ Format
     |  5.6789      |   '5.6789'     |    '5.678900'  | '5.678900e+00' |  '567.890000%' |
     | 56.789       |  '56.789'      |   '56.789000'  | '5.678900e+01' | '5678.900000%' |
     +--------------+----------------+----------------+----------------+----------------+
    -```
    -```text
    +
     +--------------+----------------+----------------+----------------+----------------+
     |              |  {:.2}  |  {:.2f} |  {:.2e} |  {:.2%} |
     +--------------+----------------+----------------+----------------+----------------+
    @@ -473,6 +472,7 @@ Format
     +--------------+----------------+----------------+----------------+----------------+
     ```
     * **When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes `'{6.5:.0f}'` a `'6'` and `'{7.5:.0f}'` an `'8'`.**
    +* **This rule only works for numbers that can be represented exactly by a float (`.5`, `.25`, …).**
     
     ### Ints
     ```python
    @@ -493,7 +493,7 @@ Numbers
       = decimal.Decimal()  # Or: Decimal((sign, digits, exponent))
     ```
     * **`'int()'` and `'float()'` raise ValueError on malformed strings.**
    -* **Decimal numbers can be represented exactly, unlike floats where `'1.1 + 2.2 != 3.3'`.**
    +* **All decimal numbers are stored exactly, unlike floats where `'1.1 + 2.2 != 3.3'`.**
     * **Precision of decimal operations is set with: `'decimal.getcontext().prec = '`.**
     
     ### Basic Functions
    diff --git a/index.html b/index.html
    index 0f25dea1e..cb99022e6 100644
    --- a/index.html
    +++ b/index.html
    @@ -345,8 +345,8 @@
     
  • Argument 'flags=re.IGNORECASE' can be used with all functions.
  • Argument 'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.
  • Argument 'flags=re.DOTALL' makes dot also accept the '\n'.
  • -
  • Use r'\1' or '\\1' for backreference.
  • -
  • Add '?' after an operator to make it non-greedy.
  • +
  • Use r'\1' or '\\1' for backreference ('\1' returns a character with octal code 1).
  • +
  • Add '?' after '*' and '+' to make them non-greedy.
  • Match Object

    <str>   = <Match>.group()                      # Returns the whole match. Also group(0).
     <str>   = <Match>.group(1)                     # Returns part in the first bracket.
    @@ -358,7 +358,7 @@
     

    Special Sequences

    • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
    • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
    • -
    • Use a capital letter for negation.
    • +
    • Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
    '\d' == '[0-9]'                                # Matches decimal characters.
     '\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
     '\s' == '[ \t\n\r\f\v]'                        # Matches whitespaces.
    @@ -421,9 +421,8 @@
     ┃  5.6789      │   '5.6789'     │    '5.678900'  │ '5.678900e+00' │  '567.890000%' ┃
     ┃ 56.789       │  '56.789'      │   '56.789000'  │ '5.678900e+01' │ '5678.900000%' ┃
     ┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
    -
    -
    ┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
    +┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
     ┃              │  {<float>:.2}  │  {<float>:.2f} │  {<float>:.2e} │  {<float>:.2%} ┃
     ┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨
     ┃  0.000056789 │    '5.7e-05'   │      '0.00'    │   '5.68e-05'   │      '0.01%'   ┃
    @@ -434,9 +433,11 @@
     ┃  5.6789      │    '5.7'       │      '5.68'    │   '5.68e+00'   │    '567.89%'   ┃
     ┃ 56.789       │    '5.7e+01'   │     '56.79'    │   '5.68e+01'   │   '5678.90%'   ┃
     ┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
    -
    +
    +
    • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
    • +
    • This rule only works for numbers that can be represented exactly by a float (.5, .25, …).

    Ints

    {90:c}                                   # 'Z'
     {90:b}                                   # '1011010'
    @@ -453,7 +454,7 @@
     
     
    • 'int(<str>)' and 'float(<str>)' raise ValueError on malformed strings.
    • -
    • Decimal numbers can be represented exactly, unlike floats where '1.1 + 2.2 != 3.3'.
    • +
    • All decimal numbers are stored exactly, unlike floats where '1.1 + 2.2 != 3.3'.
    • Precision of decimal operations is set with: 'decimal.getcontext().prec = <int>'.

    Basic Functions

    <num> = pow(<num>, <num>)                # Or: <num> ** <num>
    diff --git a/parse.js b/parse.js
    index c77d68ff6..4bab16039 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -181,14 +181,8 @@ const DIAGRAM_4_B =
       "┃  0.56789     │   '0.56789'    │    '0.567890'  │ '5.678900e-01' │   '56.789000%' ┃\n" +
       "┃  5.6789      │   '5.6789'     │    '5.678900'  │ '5.678900e+00' │  '567.890000%' ┃\n" +
       "┃ 56.789       │  '56.789'      │   '56.789000'  │ '5.678900e+01' │ '5678.900000%' ┃\n" +
    -  "┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛\n";
    -
    -const DIAGRAM_5_A =
    -  "+--------------+----------------+----------------+----------------+----------------+\n" +
    -  "|              |  {:.2}  |  {:.2f} |  {:.2e} |  {:.2%} |\n" +
    -  "+--------------+----------------+----------------+----------------+----------------+\n";
    -
    -const DIAGRAM_5_B =
    +  "┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛\n" +
    +  "\n" +
       "┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓\n" +
       "┃              │  {<float>:.2}  │  {<float>:.2f} │  {<float>:.2e} │  {<float>:.2%} ┃\n" +
       "┠──────────────┼────────────────┼────────────────┼────────────────┼────────────────┨\n" +
    @@ -527,7 +521,6 @@ function updateDiagrams() {
       $(`code:contains(${DIAGRAM_2_A})`).html(DIAGRAM_2_B);
       $(`code:contains(${DIAGRAM_3_A})`).html(DIAGRAM_3_B);
       $(`code:contains(${DIAGRAM_4_A})`).html(DIAGRAM_4_B);
    -  $(`code:contains(${DIAGRAM_5_A})`).html(DIAGRAM_5_B);
       $(`code:contains(${DIAGRAM_6_A})`).html(DIAGRAM_6_B);
       $(`code:contains(${DIAGRAM_7_A})`).html(DIAGRAM_7_B);
       $(`code:contains(${DIAGRAM_8_A})`).html(DIAGRAM_8_B);
    
    From 4f6d5cf3acc62b666dd847aa2c5b8c3a85fd14aa Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 15 Apr 2022 11:28:56 +0200
    Subject: [PATCH 036/638] Format, Numbers, Decorator, Class
    
    ---
     README.md  | 10 ++++++----
     index.html | 16 ++++++++++------
     parse.js   |  7 +++++++
     3 files changed, 23 insertions(+), 10 deletions(-)
    
    diff --git a/README.md b/README.md
    index c4c0baf65..8a5ce7d60 100644
    --- a/README.md
    +++ b/README.md
    @@ -472,7 +472,7 @@ Format
     +--------------+----------------+----------------+----------------+----------------+
     ```
     * **When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes `'{6.5:.0f}'` a `'6'` and `'{7.5:.0f}'` an `'8'`.**
    -* **This rule only works for numbers that can be represented exactly by a float (`.5`, `.25`, …).**
    +* **This rule only effects numbers that can be represented exactly by a float (`.5`, `.25`, …).**
     
     ### Ints
     ```python
    @@ -493,7 +493,7 @@ Numbers
       = decimal.Decimal()  # Or: Decimal((sign, digits, exponent))
     ```
     * **`'int()'` and `'float()'` raise ValueError on malformed strings.**
    -* **All decimal numbers are stored exactly, unlike floats where `'1.1 + 2.2 != 3.3'`.**
    +* **Decimal numbers are stored exactly, unlike most floats where `'1.1 + 2.2 != 3.3'`.**
     * **Precision of decimal operations is set with: `'decimal.getcontext().prec = '`.**
     
     ### Basic Functions
    @@ -921,6 +921,7 @@ from functools import lru_cache
     def fib(n):
         return n if n < 2 else fib(n-2) + fib(n-1)
     ```
    +* **Default size of the cache is 128 values. Passing `'maxsize=None'` makes it unbounded.**
     * **CPython interpreter limits recursion depth to 1000 by default. To increase it use `'sys.setrecursionlimit()'`.**
     
     ### Parametrized Decorator
    @@ -942,6 +943,7 @@ def debug(print_result=False):
     def add(x, y):
         return x + y
     ```
    +* **Using only `'@debug'` to decorate the add() function would not work here, because debug would then receive the add() function as a 'print_result' argument. Decorators can however manually check if the argument they received is a function and act accordingly.**
     
     
     Class
    @@ -974,9 +976,9 @@ raise Exception()
     
     #### Repr() use cases:
     ```python
    -print([])
    +print/str/repr([])
     f'{!r}'
    -Z = dataclasses.make_dataclass('Z', ['a']); print(Z())
    +Z = dataclasses.make_dataclass('Z', ['a']); print/str/repr(Z())
     >>> 
     ```
     
    diff --git a/index.html b/index.html
    index cb99022e6..1e609fc8a 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -437,7 +437,7 @@
    • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
    • -
    • This rule only works for numbers that can be represented exactly by a float (.5, .25, …).
    • +
    • This rule only effects numbers that can be represented exactly by a float (.5, .25, …).

    Ints

    {90:c}                                   # 'Z'
     {90:b}                                   # '1011010'
    @@ -454,7 +454,7 @@
     
     
    • 'int(<str>)' and 'float(<str>)' raise ValueError on malformed strings.
    • -
    • All decimal numbers are stored exactly, unlike floats where '1.1 + 2.2 != 3.3'.
    • +
    • Decimal numbers are stored exactly, unlike most floats where '1.1 + 2.2 != 3.3'.
    • Precision of decimal operations is set with: 'decimal.getcontext().prec = <int>'.

    Basic Functions

    <num> = pow(<num>, <num>)                # Or: <num> ** <num>
    @@ -784,6 +784,7 @@
     
     
     
      +
    • Default size of the cache is 128 values. Passing 'maxsize=None' makes it unbounded.
    • CPython interpreter limits recursion depth 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
    @@ -804,6 +805,9 @@
     
    +
      +
    • Using only '@debug' to decorate the add() function would not work here, because debug would then receive the add() function as a 'print_result' argument. Decorators can however manually check if the argument they received is a function and act accordingly.
    • +

    #Class

    class <name>:
         def __init__(self, a):
             self.a = a
    @@ -829,9 +833,9 @@
     raise Exception(<el>)
     
    -

    Repr() use cases:

    print([<el>])
    +

    Repr() use cases:

    print/str/repr([<el>])
     f'{<el>!r}'
    -Z = dataclasses.make_dataclass('Z', ['a']); print(Z(<el>))
    +Z = dataclasses.make_dataclass('Z', ['a']); print/str/repr(Z(<el>))
     >>> <el>
     
    @@ -2885,7 +2889,7 @@ diff --git a/parse.js b/parse.js index 4bab16039..8eb91cbb1 100755 --- a/parse.js +++ b/parse.js @@ -51,6 +51,12 @@ const LRU_CACHE = 'def fib(n):\n' + ' return n if n < 2 else fib(n-2) + fib(n-1)\n'; +const REPR_USE_CASES = + 'print/str/repr([<el>])\n' + + 'f\'{<el>!r}\'\n' + + 'Z = dataclasses.make_dataclass(\'Z\', [\'a\']); print/str/repr(Z(<el>))\n' + + '>>> <el>\n'; + const CONSTRUCTOR_OVERLOADING = 'class <name>:\n' + ' def __init__(self, a=None):\n' + @@ -562,6 +568,7 @@ function fixClasses() { function fixHighlights() { $(`code:contains(@lru_cache(maxsize=None))`).html(LRU_CACHE); $(`code:contains((self, a=None):)`).html(CONSTRUCTOR_OVERLOADING); + $(`code:contains(print/str/repr([]))`).html(REPR_USE_CASES); $(`code:contains(make_dataclass(\'\')`).html(DATACLASS); $(`code:contains(shutil.copy)`).html(SHUTIL_COPY); $(`code:contains(os.rename)`).html(OS_RENAME); From 9c9aa99510c21e4952dd45b7ef21105c667b447d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Apr 2022 16:26:18 +0200 Subject: [PATCH 037/638] OS Commands, Operator --- README.md | 26 +++++++++++--------------- index.html | 44 +++++++++++++++++++++----------------------- 2 files changed, 32 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 8a5ce7d60..144a3385b 100644 --- a/README.md +++ b/README.md @@ -1610,7 +1610,7 @@ def write_to_file(filename, text): Paths ----- ```python -from os import getcwd, path, listdir +from os import getcwd, path, listdir, scandir from glob import glob ``` @@ -1640,10 +1640,6 @@ from glob import glob ### DirEntry **Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.** -```python -from os import scandir -``` - ```python = scandir(path='.') # Returns DirEntry objects located at path. = .path # Returns whole path as a string. @@ -1689,14 +1685,14 @@ from pathlib import Path OS Commands ----------- +```python +import os, shutil, subprocess +``` + ### Files and Directories * **Paths can be either strings, Paths or DirEntry objects.** * **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).** -```python -import os, shutil -``` - ```python os.chdir() # Changes the current working directory. os.mkdir(, mode=0o777) # Creates a directory. Mode is in octal. @@ -1721,14 +1717,14 @@ shutil.rmtree() # Deletes the directory. ### Shell Commands ```python -import os - = os.popen('').read() + = os.popen('') # Executes command in sh/cmd and returns its stdout pipe. + = .read() # Waits for EOF and returns result. Also readline/s(). + = .close() # Closes the pipe. Returns None on success, int on error. ``` #### Sends '1 + 1' to the basic calculator and captures its output: ```python ->>> from subprocess import run ->>> run('bc', input='1 + 1\n', capture_output=True, text=True) +>>> subprocess.run('bc', input='1 + 1\n', capture_output=True, text=True) CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') ``` @@ -1736,7 +1732,7 @@ CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') ```python >>> from shlex import split >>> os.popen('echo 1 + 1 > test.in') ->>> run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w')) +>>> subprocess.run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w')) CompletedProcess(args=['bc', '-s'], returncode=0) >>> open('test.out').read() '2\n' @@ -2148,7 +2144,7 @@ import operator as op = op.add/sub/mul/truediv/floordiv/mod(, ) # +, -, *, /, //, % = op.and_/or_/xor(, ) # &, |, ^ = op.eq/ne/lt/le/gt/ge(, ) # ==, !=, <, <=, >, >= - = op.itemgetter/attrgetter/methodcaller() # [index/key], ., .() + = op.itemgetter/attrgetter/methodcaller() # [index/key], .name, .name() ``` ```python diff --git a/index.html b/index.html index 1e609fc8a..9bdd5173b 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -1373,7 +1373,7 @@ file.write(text)
    -

    #Paths

    from os import getcwd, path, listdir
    +

    #Paths

    from os import getcwd, path, listdir, scandir
     from glob import glob
     
    @@ -1392,15 +1392,13 @@ <bool> = path.isfile(<path>) # Or: <DirEntry/Path>.is_file() <bool> = path.isdir(<path>) # Or: <DirEntry/Path>.is_dir()
    -

    DirEntry

    Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.

    from os import scandir
    -
    - - -
    <iter> = scandir(path='.')          # Returns DirEntry objects located at path.
    +

    DirEntry

    Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.

    <iter> = scandir(path='.')          # Returns DirEntry objects located at path.
     <str>  = <DirEntry>.path            # Returns whole path as a string.
     <str>  = <DirEntry>.name            # Returns final component as a string.
     <file> = open(<DirEntry>)           # Opens the file and returns a file object.
    -
    +
    + +

    Path Object

    from pathlib import Path
     
    @@ -1424,18 +1422,18 @@
    <str>  = str(<Path>)                # Returns path as a string.
     <file> = open(<Path>)               # Opens the file and returns a file object.
     
    -

    #OS Commands

    Files and Directories

      +

      #OS Commands

      import os, shutil, subprocess
      +
      + +

      Files and Directories

      • Paths can be either strings, Paths or DirEntry objects.
      • Functions report OS related errors by raising either OSError or one of its subclasses.
      • -
      import os, shutil
      -
    - - - -
    os.chdir(<path>)                    # Changes the current working directory.
    +
    os.chdir(<path>)                    # Changes the current working directory.
     os.mkdir(<path>, mode=0o777)        # Creates a directory. Mode is in octal.
     os.makedirs(<path>, mode=0o777)     # Creates all directories in the path.
    -
    +
    + +
    shutil.copy(from, to)               # Copies the file. 'to' can exist or be a dir.
     shutil.copytree(from, to)           # Copies the directory. 'to' must not exist.
     
    @@ -1446,18 +1444,18 @@ os.rmdir(<path>) # Deletes the empty directory. shutil.rmtree(<path>) # Deletes the directory.
    -

    Shell Commands

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

    Shell Commands

    <pipe> = os.popen('<command>')      # Executes command in sh/cmd and returns its stdout pipe.
    +<str>  = <pipe>.read()              # Waits for EOF and returns result. Also readline/s().
    +<int>  = <pipe>.close()             # Closes the pipe. Returns None on success, int on error.
     
    -

    Sends '1 + 1' to the basic calculator and captures its output:

    >>> from subprocess import run
    ->>> run('bc', input='1 + 1\n', capture_output=True, text=True)
    +

    Sends '1 + 1' to the basic calculator and captures its output:

    >>> subprocess.run('bc', input='1 + 1\n', capture_output=True, text=True)
     CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')
     

    Sends test.in to the basic calculator running in standard mode and saves its output to test.out:

    >>> from shlex import split
     >>> os.popen('echo 1 + 1 > test.in')
    ->>> run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w'))
    +>>> subprocess.run(split('bc -s'), stdin=open('test.in'), stdout=open('test.out', 'w'))
     CompletedProcess(args=['bc', '-s'], returncode=0)
     >>> open('test.out').read()
     '2\n'
    @@ -1770,7 +1768,7 @@
     <el>      = op.add/sub/mul/truediv/floordiv/mod(<el>, <el>)  # +, -, *, /, //, %
     <int/set> = op.and_/or_/xor(<int/set>, <int/set>)            # &, |, ^
     <bool>    = op.eq/ne/lt/le/gt/ge(<sortable>, <sortable>)     # ==, !=, <, <=, >, >=
    -<func>    = op.itemgetter/attrgetter/methodcaller(<el>)      # [index/key], .<str>, .<str>()
    +<func>    = op.itemgetter/attrgetter/methodcaller(<obj>)     # [index/key], .name, .name()
     
    @@ -2889,7 +2887,7 @@ From 77d247cb4381aad7784d0fc73eef508402eae9f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Apr 2022 11:45:17 +0200 Subject: [PATCH 038/638] Bitwise Operators, Datetime, OS Commands --- README.md | 10 +++++----- index.html | 14 +++++++------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 144a3385b..3e64659a6 100644 --- a/README.md +++ b/README.md @@ -537,8 +537,8 @@ from random import random, randint, choice, shuffle, gauss, seed = & # And (0b1100 & 0b1010 == 0b1000). = | # Or (0b1100 | 0b1010 == 0b1110). = ^ # Xor (0b1100 ^ 0b1010 == 0b0110). - = << n_bits # Left shift (>> for right). - = ~ # Not (also: - - 1). + = << n_bits # Left shift. Use >> for right. + = ~ # Not. Also - - 1. ``` @@ -645,11 +645,11 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary ### Format ```python ->>> dt = datetime.strptime('2015-05-14 23:39:00.00 +02:00', '%Y-%m-%d %H:%M:%S.%f %z') +>>> dt = datetime.strptime('2015-05-14 23:39:00.00 +2000', '%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" ``` -* **`'%Z'` only accepts `'UTC/GMT'` and local timezone's code. `'%z'` also accepts `'±HHMM'`.** +* **`'%Z'` only accepts `'UTC/GMT'` and local timezone's code. `'%z'` also accepts `'±02:00'`.** * **For abbreviated weekday and month use `'%a'` and `'%b'`.** ### Arithmetics @@ -1718,7 +1718,7 @@ shutil.rmtree() # Deletes the directory. ### Shell Commands ```python = os.popen('') # Executes command in sh/cmd and returns its stdout pipe. - = .read() # Waits for EOF and returns result. Also readline/s(). + = .read(size=-1) # Reads 'size' chars or until EOF. Also readline/s(). = .close() # Closes the pipe. Returns None on success, int on error. ``` diff --git a/index.html b/index.html index 9bdd5173b..1b1d7ea8b 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -486,8 +486,8 @@

    Bitwise Operators

    <int> = <int> & <int>                    # And (0b1100 & 0b1010 == 0b1000).
     <int> = <int> | <int>                    # Or  (0b1100 | 0b1010 == 0b1110).
     <int> = <int> ^ <int>                    # Xor (0b1100 ^ 0b1010 == 0b0110).
    -<int> = <int> << n_bits                  # Left shift (>> for right).
    -<int> = ~<int>                           # Not (also: -<int> - 1).
    +<int> = <int> << n_bits                  # Left shift. Use >> for right.
    +<int> = ~<int>                           # Not. Also -<int> - 1.
     

    #Combinatorics

      @@ -572,13 +572,13 @@ <float> = <DTa>.timestamp() # Seconds since the Epoch, from DTa.
    -

    Format

    >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +02:00', '%Y-%m-%d %H:%M:%S.%f %z')
    +

    Format

    >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +2000', '%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"
     
      -
    • '%Z' only accepts 'UTC/GMT' and local timezone's code. '%z' also accepts '±HHMM'.
    • +
    • '%Z' only accepts 'UTC/GMT' and local timezone's code. '%z' also accepts '±02:00'.
    • For abbreviated weekday and month use '%a' and '%b'.

    Arithmetics

    <D/DT>   = <D/DT>  ± <TD>                   # Returned datetime can fall into missing hour.
    @@ -1445,7 +1445,7 @@
     shutil.rmtree(<path>)               # Deletes the directory.
     

    Shell Commands

    <pipe> = os.popen('<command>')      # Executes command in sh/cmd and returns its stdout pipe.
    -<str>  = <pipe>.read()              # Waits for EOF and returns result. Also readline/s().
    +<str>  = <pipe>.read(size=-1)       # Reads 'size' chars or until EOF. Also readline/s().
     <int>  = <pipe>.close()             # Closes the pipe. Returns None on success, int on error.
     
    @@ -2887,7 +2887,7 @@ From 9f1e91149072a768ac62cb5a5db585b77f49c731 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 20 Apr 2022 13:09:44 +0200 Subject: [PATCH 039/638] Datetime --- README.md | 2 +- index.html | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3e64659a6..f32489365 100644 --- a/README.md +++ b/README.md @@ -649,7 +649,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary >>> dt.strftime("%A, %dth of %B '%y, %I:%M%p %Z") "Thursday, 14th of May '15, 11:39PM UTC+02:00" ``` -* **`'%Z'` only accepts `'UTC/GMT'` and local timezone's code. `'%z'` also accepts `'±02:00'`.** +* **`'%Z'` only accepts `'UTC/GMT'` and local timezone's code. `'%z'` also accepts `'±HH:MM'`.** * **For abbreviated weekday and month use `'%a'` and `'%b'`.** ### Arithmetics diff --git a/index.html b/index.html index 1b1d7ea8b..4065966b7 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -578,7 +578,7 @@
      -
    • '%Z' only accepts 'UTC/GMT' and local timezone's code. '%z' also accepts '±02:00'.
    • +
    • '%Z' only accepts 'UTC/GMT' and local timezone's code. '%z' also accepts '±HH:MM'.
    • For abbreviated weekday and month use '%a' and '%b'.

    Arithmetics

    <D/DT>   = <D/DT>  ± <TD>                   # Returned datetime can fall into missing hour.
    @@ -2887,7 +2887,7 @@
      
     
       
     
    
    From 1d552e4c7619b64821f0e31e1f4b5fa00a0dd28b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 20 Apr 2022 16:43:53 +0200
    Subject: [PATCH 040/638] Regex, Exceptions
    
    ---
     README.md  | 12 ++++++------
     index.html | 16 ++++++++--------
     parse.js   |  4 ++--
     3 files changed, 16 insertions(+), 16 deletions(-)
    
    diff --git a/README.md b/README.md
    index f32489365..73cb8a286 100644
    --- a/README.md
    +++ b/README.md
    @@ -378,16 +378,16 @@ import re
     ```
     
     ### Special Sequences
    -* **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.**
    -* **As shown below, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'` (the so-called separator characters).**
    -* **Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).**
    -
     ```python
     '\d' == '[0-9]'                                # Matches decimal characters.
     '\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
     '\s' == '[ \t\n\r\f\v]'                        # Matches whitespaces.
     ```
     
    +* **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.**
    +* **As shown above, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'` (the so-called separator characters).**
    +* **Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).**
    +
     
     Format
     ------
    @@ -1436,8 +1436,8 @@ BaseException
           +-- EOFError                # Raised by input() when it hits end-of-file condition.
           +-- LookupError             # Raised when a look-up on a collection fails.
           |    +-- IndexError         # Raised when a sequence index is out of range.
    -      |    +-- KeyError           # Raised when a dictionary key or set element is not found.
    -      +-- NameError               # Raised when a variable name is not found.
    +      |    +-- KeyError           # Raised when a dictionary key or set element is missing.
    +      +-- NameError               # Raised when an object is missing.
           +-- OSError                 # Errors such as “file not found” or “disk full” (see Open).
           |    +-- FileNotFoundError  # When a file or directory is requested but doesn't exist.
           +-- RuntimeError            # Raised by errors that don't fall into other categories.
    diff --git a/index.html b/index.html
    index 4065966b7..26ffda61b 100644
    --- a/index.html
    +++ b/index.html
    @@ -355,16 +355,16 @@
     <int>   = <Match>.end()                        # Returns exclusive end index of the match.
     
    -

    Special Sequences

      -
    • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
    • -
    • As shown below, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
    • -
    • Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
    • -
    '\d' == '[0-9]'                                # Matches decimal characters.
    +

    Special Sequences

    '\d' == '[0-9]'                                # Matches decimal characters.
     '\w' == '[a-zA-Z0-9_]'                         # Matches alphanumerics and underscore.
     '\s' == '[ \t\n\r\f\v]'                        # Matches whitespaces.
     
    - +
      +
    • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
    • +
    • As shown above, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
    • +
    • Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
    • +

    #Format

    <str> = f'{<el_1>}, {<el_2>}'
     <str> = '{}, {}'.format(<el_1>, <el_2>)
     
    @@ -1232,8 +1232,8 @@ ├── EOFError # Raised by input() when it hits end-of-file condition. ├── LookupError # Raised when a look-up on a collection fails. │ ├── IndexError # Raised when a sequence index is out of range. - │ └── KeyError # Raised when a dictionary key or set element is not found. - ├── NameError # Raised when a variable name is not found. + │ └── KeyError # Raised when a dictionary key or set element is missing. + ├── NameError # Raised when an object is missing. ├── OSError # Errors such as “file not found” or “disk full” (see Open). │ └── FileNotFoundError # When a file or directory is requested but doesn't exist. ├── RuntimeError # Raised by errors that don't fall into other categories. diff --git a/parse.js b/parse.js index 8eb91cbb1..f182b9e6a 100755 --- a/parse.js +++ b/parse.js @@ -234,8 +234,8 @@ const DIAGRAM_7_B = " ├── EOFError # Raised by input() when it hits end-of-file condition.\n" + " ├── LookupError # Raised when a look-up on a collection fails.\n" + " │ ├── IndexError # Raised when a sequence index is out of range.\n" + - " │ └── KeyError # Raised when a dictionary key or set element is not found.\n" + - " ├── NameError # Raised when a variable name is not found.\n" + + " │ └── KeyError # Raised when a dictionary key or set element is missing.\n" + + " ├── NameError # Raised when an object is missing.\n" + " ├── OSError # Errors such as “file not found” or “disk full” (see Open).\n" + " │ └── FileNotFoundError # When a file or directory is requested but doesn't exist.\n" + " ├── RuntimeError # Raised by errors that don't fall into other categories.\n" + From f03f5b6e7ea19e7b7b28dd021a78f95cf3d3186e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 2 May 2022 09:15:01 +0200 Subject: [PATCH 041/638] Paths, CSV --- README.md | 8 +++++++- index.html | 12 ++++++++---- parse.js | 2 ++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 73cb8a286..bcc760332 100644 --- a/README.md +++ b/README.md @@ -658,7 +658,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary = - # Returns the difference, ignoring time jumps. = - # Ignores time jumps if they share tzinfo object. = * # Also: = abs() and = ±% . - = / # How many weeks/years there are in TD. Also '//'. + = / # How many weeks/years there are in TD. Also //. ``` @@ -1637,6 +1637,11 @@ from glob import glob = path.isdir() # Or: .is_dir() ``` +```python + = os.stat() # Or: .stat() + = .st_mtime/st_size/… # Modification time, size in bytes, … +``` + ### DirEntry **Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.** @@ -1803,6 +1808,7 @@ import csv = next() # Returns next row as a list of strings. = list() # Returns a list of remaining rows. ``` +* **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#dataframe-plot-encode-decode) library.** * **File must be opened with a `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!** ### Write diff --git a/index.html b/index.html index 26ffda61b..1eb7ca135 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -585,7 +585,7 @@ <TD> = <D/DTn> - <D/DTn> # Returns the difference, ignoring time jumps. <TD> = <DTa> - <DTa> # Ignores time jumps if they share tzinfo object. <TD> = <TD> * <real> # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>. -<float> = <TD> / <TD> # How many weeks/years there are in TD. Also '//'. +<float> = <TD> / <TD> # How many weeks/years there are in TD. Also //.

    #Arguments

    Inside Function Call

    <function>(<positional_args>)                  # f(0, 0)
    @@ -1392,6 +1392,9 @@
     <bool> = path.isfile(<path>)        # Or: <DirEntry/Path>.is_file()
     <bool> = path.isdir(<path>)         # Or: <DirEntry/Path>.is_dir()
     
    +
    <stat> = os.stat(<path>)            # Or: <DirEntry/Path>.stat()
    +<real> = <stat>.st_mtime/st_size/…  # Modification time, size in bytes, …
    +

    DirEntry

    Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.

    <iter> = scandir(path='.')          # Returns DirEntry objects located at path.
     <str>  = <DirEntry>.path            # Returns whole path as a string.
     <str>  = <DirEntry>.name            # Returns final component as a string.
    @@ -1503,6 +1506,7 @@
     
      +
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
    • File must be opened with a 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!

    Write

    <writer> = csv.writer(<file>)       # Also: `dialect='excel', delimiter=','`.
    @@ -1879,7 +1883,7 @@
     
  • Coroutine definition starts with 'async' and its call with 'await'.
  • 'asyncio.run(<coroutine>)' is the main entry point for asynchronous programs.
  • Functions wait(), gather() and as_completed() can be used when multiple coroutines need to be started at the same time.
  • -
  • Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.
  • +
  • Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.
  • Runs a terminal game where you control an asterisk that must avoid numbers:

    import asyncio, collections, curses, curses.textpad, enum, random
     
     P = collections.namedtuple('P', 'x y')         # Position
    @@ -2887,7 +2891,7 @@
      
     
       
     
    diff --git a/parse.js b/parse.js
    index f182b9e6a..16a1fbe8d 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -461,6 +461,8 @@ function main() {
     function getMd() {
       var readme = readFile('README.md');
       var readme = readme.replace("#semaphore-event-barrier", "#semaphoreeventbarrier");
    +  var readme = readme.replace("#semaphore-event-barrier", "#semaphoreeventbarrier");
    +  var readme = readme.replace("#dataframe-plot-encode-decode", "#dataframeplotencodedecode");
       const converter = new showdown.Converter();
       return converter.makeHtml(readme);
     }
    
    From b7d73cb62705808fb79c887e8209dcbb15ba9ad3 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 18 May 2022 10:17:21 +0200
    Subject: [PATCH 042/638] Iterable Duck Types
    
    ---
     README.md  |  4 ++++
     index.html | 17 +++++++++++------
     parse.js   |  5 +++++
     3 files changed, 20 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index bcc760332..367853c7d 100644
    --- a/README.md
    +++ b/README.md
    @@ -1276,6 +1276,10 @@ class MySequence:
             return reversed(self.a)
     ```
     
    +#### Discrepancies between glossary definitions and abstract base classes:
    +* **Glossary defines iterable as any object with iter() or getitem() and sequence as any object with len() and getitem(). It does not define collection.**
    +* **Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has iter(), while ABC Collection checks for iter(), contains() and len().**
    +
     ### ABC Sequence
     * **It's a richer interface than the basic sequence.**
     * **Extending it generates iter(), contains(), reversed(), index() and count().**
    diff --git a/index.html b/index.html
    index 1eb7ca135..40fae20d4 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -1096,6 +1096,14 @@
    +

    Discrepancies between glossary definitions and abstract base classes:

      +
    • Glossary defines iterable as any object with iter() or getitem() and sequence as any object with len() and getitem(). It does not define collection.
    • +
    • Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has iter(), while ABC Collection checks for iter(), contains() and len().
    • +
    + + + +

    ABC Sequence

    • It's a richer interface than the basic sequence.
    • Extending it generates iter(), contains(), reversed(), index() and count().
    • @@ -1109,10 +1117,7 @@ return len(self.a) def __getitem__(self, i): return self.a[i] -
    - - -

    Table of required and automatically available special methods:

    ┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
    +

    Table of required and automatically available special methods:

    ┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
     ┃            │  Iterable  │ Collection │  Sequence  │ abc.Sequence ┃
     ┠────────────┼────────────┼────────────┼────────────┼──────────────┨
     ┃ iter()     │     !      │     !      │     ✓      │      ✓       ┃
    @@ -2891,7 +2896,7 @@
      
     
       
     
    diff --git a/parse.js b/parse.js
    index 16a1fbe8d..c8a117e5f 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -486,6 +486,7 @@ function modifyPage() {
       highlightCode();
       fixPandasDiagram();
       removePlotImages();
    +  fixABCSequenceDiv();
     }
     
     function changeMenu() {
    @@ -634,6 +635,10 @@ function removePlotImages() {
       $('img[alt="Covid Cases"]').remove();
     }
     
    +function fixABCSequenceDiv() {
    +  $('#abcsequence').parent().insertBefore($('#tableofrequiredandautomaticallyavailablespecialmethods').parent())
    +}
    +
     function updateDate(template) {
       const date = new Date();
       const date_str = date.toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'});
    
    From 73adfbd307c29d9ba19d231735236c77f7eb5c10 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 20 May 2022 09:47:56 +0200
    Subject: [PATCH 043/638] Type
    
    ---
     README.md  | 2 +-
     index.html | 6 +++---
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/README.md b/README.md
    index 367853c7d..b4796ad46 100644
    --- a/README.md
    +++ b/README.md
    @@ -262,7 +262,7 @@ from types import FunctionType, MethodType, LambdaType, GeneratorType, ModuleTyp
     ```
     
     ### Abstract Base Classes
    -**Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().**
    +**Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().**
     
     ```python
     >>> from collections.abc import Iterable, Collection, Sequence
    diff --git a/index.html b/index.html
    index 40fae20d4..288348883 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -263,7 +263,7 @@

    Some types do not have built-in names, so they must be imported:

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

    Abstract Base Classes

    Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter() while Collection ABC looks for methods iter(), contains() and len().

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

    Abstract Base Classes

    Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not. ABC can also manually decide whether or not a specific class is its virtual subclass, usually based on which methods the class has implemented. For instance, Iterable ABC looks for method iter(), while Collection ABC looks for iter(), contains() and len().

    >>> from collections.abc import Iterable, Collection, Sequence
     >>> isinstance([1, 2, 3], Iterable)
     True
     
    @@ -2896,7 +2896,7 @@ From 88f2965a4fc545c81021a1acaca22a2406fe9327 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 20 May 2022 10:12:24 +0200 Subject: [PATCH 044/638] Iterable Duck Types --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b4796ad46..5a90356b3 100644 --- a/README.md +++ b/README.md @@ -1278,7 +1278,7 @@ class MySequence: #### Discrepancies between glossary definitions and abstract base classes: * **Glossary defines iterable as any object with iter() or getitem() and sequence as any object with len() and getitem(). It does not define collection.** -* **Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has iter(), while ABC Collection checks for iter(), contains() and len().** +* **Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has method iter(), while ABC Collection checks for iter(), contains() and len().** ### ABC Sequence * **It's a richer interface than the basic sequence.** diff --git a/index.html b/index.html index 288348883..6247cf360 100644 --- a/index.html +++ b/index.html @@ -1098,7 +1098,7 @@

    Discrepancies between glossary definitions and abstract base classes:

    • Glossary defines iterable as any object with iter() or getitem() and sequence as any object with len() and getitem(). It does not define collection.
    • -
    • Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has iter(), while ABC Collection checks for iter(), contains() and len().
    • +
    • Passing ABC Iterable to isinstance() or issubclass() checks whether object/class has method iter(), while ABC Collection checks for iter(), contains() and len().
    From 27c0f1936d32ed773f548e4fae7fc86a7aaaddab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 23 May 2022 21:12:20 +0200 Subject: [PATCH 045/638] CSV --- README.md | 16 ++++++++-------- index.html | 20 ++++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 5a90356b3..ee6fde4b5 100644 --- a/README.md +++ b/README.md @@ -1824,12 +1824,12 @@ import csv * **File must be opened with a `'newline=""'` argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!** ### Parameters -* **`'dialect'` - Master parameter that sets the default values.** +* **`'dialect'` - Master parameter that sets the default values. String or a dialect object.** * **`'delimiter'` - A one-character string used to separate fields.** * **`'quotechar'` - Character for quoting fields that contain special characters.** -* **`'doublequote'` - Whether quotechars inside fields get doubled or escaped.** -* **`'skipinitialspace'` - Whether whitespace after delimiter gets stripped.** -* **`'lineterminator'` - Specifies how writer terminates rows.** +* **`'doublequote'` - Whether quotechars inside fields are/get doubled or escaped.** +* **`'skipinitialspace'` - Whether whitespace after delimiter gets stripped by reader.** +* **`'lineterminator'` - How writer terminates rows. Reader is hardcoded to '\r', '\n', '\r\n'.** * **`'quoting'` - Controls the amount of quoting: 0 - as necessary, 1 - all.** * **`'escapechar'` - Character for escaping quotechars if doublequote is False.** @@ -1850,16 +1850,16 @@ import csv ### Read Rows from CSV File ```python -def read_csv_file(filename): +def read_csv_file(filename, dialect='excel'): with open(filename, encoding='utf-8', newline='') as file: - return list(csv.reader(file)) + return list(csv.reader(file, dialect)) ``` ### Write Rows to CSV File ```python -def write_to_csv_file(filename, rows): +def write_to_csv_file(filename, rows, dialect='excel'): with open(filename, 'w', encoding='utf-8', newline='') as file: - writer = csv.writer(file) + writer = csv.writer(file, dialect) writer.writerows(rows) ``` diff --git a/index.html b/index.html index 6247cf360..ed7c15dd9 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -1523,12 +1523,12 @@
  • File must be opened with a 'newline=""' argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!
  • Parameters

      -
    • 'dialect' - Master parameter that sets the default values.
    • +
    • 'dialect' - Master parameter that sets the default values. String or a dialect object.
    • 'delimiter' - A one-character string used to separate fields.
    • 'quotechar' - Character for quoting fields that contain special characters.
    • -
    • 'doublequote' - Whether quotechars inside fields get doubled or escaped.
    • -
    • 'skipinitialspace' - Whether whitespace after delimiter gets stripped.
    • -
    • 'lineterminator' - Specifies how writer terminates rows.
    • +
    • 'doublequote' - Whether quotechars inside fields are/get doubled or escaped.
    • +
    • 'skipinitialspace' - Whether whitespace after delimiter gets stripped by reader.
    • +
    • 'lineterminator' - How writer terminates rows. Reader is hardcoded to '\r', '\n', '\r\n'.
    • 'quoting' - Controls the amount of quoting: 0 - as necessary, 1 - all.
    • 'escapechar' - Character for escaping quotechars if doublequote is False.

    Dialects

    ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
    @@ -1546,14 +1546,14 @@
     
     
     
    -

    Read Rows from CSV File

    def read_csv_file(filename):
    +

    Read Rows from CSV File

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

    Write Rows to CSV File

    def write_to_csv_file(filename, rows):
    +

    Write Rows to CSV File

    def write_to_csv_file(filename, rows, dialect='excel'):
         with open(filename, 'w', encoding='utf-8', newline='') as file:
    -        writer = csv.writer(file)
    +        writer = csv.writer(file, dialect)
             writer.writerows(rows)
     
    @@ -2896,7 +2896,7 @@ From ebad00587a95416c86aee2831f0e5901da27b7c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 28 May 2022 16:22:32 +0200 Subject: [PATCH 046/638] Paths, OS Commands --- README.md | 28 ++++++++++++++-------------- index.html | 32 ++++++++++++++++---------------- parse.js | 8 ++++---- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index ee6fde4b5..181598983 100644 --- a/README.md +++ b/README.md @@ -1647,7 +1647,7 @@ from glob import glob ``` ### DirEntry -**Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.** +**Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.** ```python = scandir(path='.') # Returns DirEntry objects located at path. @@ -1703,32 +1703,32 @@ import os, shutil, subprocess * **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).** ```python -os.chdir() # Changes the current working directory. -os.mkdir(, mode=0o777) # Creates a directory. Mode is in octal. -os.makedirs(, mode=0o777) # Creates all directories in the path. +os.chdir() # Changes the current working directory. +os.mkdir(, mode=0o777) # Creates a directory. Mode is in octal. +os.makedirs(, mode=0o777) # Creates dirs in path. Also: `exist_ok=False`. ``` ```python -shutil.copy(from, to) # Copies the file. 'to' can exist or be a dir. -shutil.copytree(from, to) # Copies the directory. 'to' must not exist. +shutil.copy(from, to) # Copies the file. 'to' can exist or be a dir. +shutil.copytree(from, to) # Copies the directory. 'to' must not exist. ``` ```python -os.rename(from, to) # Renames/moves the file or directory. -os.replace(from, to) # Same, but overwrites 'to' if it exists. +os.rename(from, to) # Renames/moves the file or directory. +os.replace(from, to) # Same, but overwrites 'to' if it exists. ``` ```python -os.remove() # Deletes the file. -os.rmdir() # Deletes the empty directory. -shutil.rmtree() # Deletes the directory. +os.remove() # Deletes the file. +os.rmdir() # Deletes the empty directory. +shutil.rmtree() # Deletes the directory. ``` ### Shell Commands ```python - = os.popen('') # Executes command in sh/cmd and returns its stdout pipe. - = .read(size=-1) # Reads 'size' chars or until EOF. Also readline/s(). - = .close() # Closes the pipe. Returns None on success, int on error. + = os.popen('') # Executes command in sh/cmd and returns its stdout pipe. + = .read(size=-1) # Reads 'size' chars or until EOF. Also readline/s(). + = .close() # Closes the pipe. Returns None on success, int on error. ``` #### Sends '1 + 1' to the basic calculator and captures its output: diff --git a/index.html b/index.html index ed7c15dd9..feacb8990 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -1400,7 +1400,7 @@
    <stat> = os.stat(<path>)            # Or: <DirEntry/Path>.stat()
     <real> = <stat>.st_mtime/st_size/…  # Modification time, size in bytes, …
     
    -

    DirEntry

    Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.

    <iter> = scandir(path='.')          # Returns DirEntry objects located at path.
    +

    DirEntry

    Unlike listdir(), scandir() returns DirEntry objects that cache isfile, isdir and on Windows also stat information, thus significantly increasing the performance of code that requires it.

    <iter> = scandir(path='.')          # Returns DirEntry objects located at path.
     <str>  = <DirEntry>.path            # Returns whole path as a string.
     <str>  = <DirEntry>.name            # Returns final component as a string.
     <file> = open(<DirEntry>)           # Opens the file and returns a file object.
    @@ -1436,25 +1436,25 @@
     

    Files and Directories

    • Paths can be either strings, Paths or DirEntry objects.
    • Functions report OS related errors by raising either OSError or one of its subclasses.
    • -
    os.chdir(<path>)                    # Changes the current working directory.
    -os.mkdir(<path>, mode=0o777)        # Creates a directory. Mode is in octal.
    -os.makedirs(<path>, mode=0o777)     # Creates all directories in the path.
    +
    os.chdir(<path>)                 # Changes the current working directory.
    +os.mkdir(<path>, mode=0o777)     # Creates a directory. Mode is in octal.
    +os.makedirs(<path>, mode=0o777)  # Creates dirs in path. Also: `exist_ok=False`.
     
    -
    shutil.copy(from, to)               # Copies the file. 'to' can exist or be a dir.
    -shutil.copytree(from, to)           # Copies the directory. 'to' must not exist.
    +
    shutil.copy(from, to)            # Copies the file. 'to' can exist or be a dir.
    +shutil.copytree(from, to)        # Copies the directory. 'to' must not exist.
     
    -
    os.rename(from, to)                 # Renames/moves the file or directory.
    -os.replace(from, to)                # Same, but overwrites 'to' if it exists.
    +
    os.rename(from, to)              # Renames/moves the file or directory.
    +os.replace(from, to)             # Same, but overwrites 'to' if it exists.
     
    -
    os.remove(<path>)                   # Deletes the file.
    -os.rmdir(<path>)                    # Deletes the empty directory.
    -shutil.rmtree(<path>)               # Deletes the directory.
    +
    os.remove(<path>)                # Deletes the file.
    +os.rmdir(<path>)                 # Deletes the empty directory.
    +shutil.rmtree(<path>)            # Deletes the directory.
     
    -

    Shell Commands

    <pipe> = os.popen('<command>')      # Executes command in sh/cmd and returns its stdout pipe.
    -<str>  = <pipe>.read(size=-1)       # Reads 'size' chars or until EOF. Also readline/s().
    -<int>  = <pipe>.close()             # Closes the pipe. Returns None on success, int on error.
    +

    Shell Commands

    <pipe> = os.popen('<command>')   # Executes command in sh/cmd and returns its stdout pipe.
    +<str>  = <pipe>.read(size=-1)    # Reads 'size' chars or until EOF. Also readline/s().
    +<int>  = <pipe>.close()          # Closes the pipe. Returns None on success, int on error.
     

    Sends '1 + 1' to the basic calculator and captures its output:

    >>> subprocess.run('bc', input='1 + 1\n', capture_output=True, text=True)
    @@ -2896,7 +2896,7 @@
      
     
       
     
    diff --git a/parse.js b/parse.js
    index c8a117e5f..f2e719e72 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -69,12 +69,12 @@ const DATACLASS =
       '<tuple> = (\'<attr_name>\', <type> [, <default_value>])';
     
     const SHUTIL_COPY =
    -  'shutil.copy(from, to)               # Copies the file. \'to\' can exist or be a dir.\n' +
    -  'shutil.copytree(from, to)           # Copies the directory. \'to\' must not exist.\n';
    +  'shutil.copy(from, to)            # Copies the file. \'to\' can exist or be a dir.\n' +
    +  'shutil.copytree(from, to)        # Copies the directory. \'to\' must not exist.\n';
     
     const OS_RENAME =
    -  'os.rename(from, to)                 # Renames/moves the file or directory.\n' +
    -  'os.replace(from, to)                # Same, but overwrites \'to\' if it exists.\n';
    +  'os.rename(from, to)              # Renames/moves the file or directory.\n' +
    +  'os.replace(from, to)             # Same, but overwrites \'to\' if it exists.\n';
     
     const TYPE =
       '<class> = type(\'<class_name>\', <tuple_of_parents>, <dict_of_class_attributes>)';
    
    From 5ed03387699add981ca495e593500f0457f7a0ee Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 31 May 2022 03:46:55 +0200
    Subject: [PATCH 047/638] Bytes, Profile
    
    ---
     README.md  | 14 +++++++-------
     index.html | 18 +++++++++---------
     2 files changed, 16 insertions(+), 16 deletions(-)
    
    diff --git a/README.md b/README.md
    index 181598983..9dc373757 100644
    --- a/README.md
    +++ b/README.md
    @@ -1946,7 +1946,7 @@ Bytes
      = bytes()          # Ints must be in range from 0 to 255.
      = bytes(, 'utf-8')          # Or: .encode('utf-8')
      = .to_bytes(n_bytes, …)     # `byteorder='big/little', signed=False`.
    - = bytes.fromhex('')         # Hex pairs can be separated by spaces.
    + = bytes.fromhex('')         # Hex pairs can be separated by whitespaces.
     ```
     
     ### Decode
    @@ -1954,7 +1954,7 @@ Bytes
       = list()                  # Returns ints in range from 0 to 255.
        = str(, 'utf-8')          # Or: .decode('utf-8')
        = int.from_bytes(, …)     # `byteorder='big/little', signed=False`.
    -'' = .hex()                  # Returns a string of hexadecimal pairs.
    +'' = .hex()                  # Returns hex pairs. Accepts `sep=`.
     ```
     
     ### Read Bytes from File
    @@ -2615,11 +2615,11 @@ Line #         Mem usage      Increment   Line Contents
     #### Generates a PNG image of the call graph with highlighted bottlenecks:
     ```python
     # $ pip3 install pycallgraph2
    -from pycallgraph2 import output, PyCallGraph
    -from datetime import datetime
    -filename = f'profile-{datetime.now():%Y%m%d%H%M%S}.png'
    -drawer = output.GraphvizOutput(output_file=filename)
    -with PyCallGraph(drawer):
    +# $ apt install graphviz
    +import pycallgraph2 as cg, datetime
    +filename = f'profile-{datetime.datetime.now():%Y%m%d%H%M%S}.png'
    +drawer = cg.output.GraphvizOutput(output_file=filename)
    +with cg.PyCallGraph(drawer):
         
     ```
     
    diff --git a/index.html b/index.html
    index feacb8990..6e8f2ba53 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -1618,13 +1618,13 @@

    Encode

    <bytes> = bytes(<coll_of_ints>)          # Ints must be in range from 0 to 255.
     <bytes> = bytes(<str>, 'utf-8')          # Or: <str>.encode('utf-8')
     <bytes> = <int>.to_bytes(n_bytes, …)     # `byteorder='big/little', signed=False`.
    -<bytes> = bytes.fromhex('<hex>')         # Hex pairs can be separated by spaces.
    +<bytes> = bytes.fromhex('<hex>')         # Hex pairs can be separated by whitespaces.
     

    Decode

    <list>  = list(<bytes>)                  # Returns ints in range from 0 to 255.
     <str>   = str(<bytes>, 'utf-8')          # Or: <bytes>.decode('utf-8')
     <int>   = int.from_bytes(<bytes>, …)     # `byteorder='big/little', signed=False`.
    -'<hex>' = <bytes>.hex()                  # Returns a string of hexadecimal pairs.
    +'<hex>' = <bytes>.hex()                  # Returns hex pairs. Accepts `sep=<str>`.
     

    Read Bytes from File

    def read_bytes(filename):
    @@ -2137,11 +2137,11 @@
          4        38.477 MiB      0.465 MiB       b = {*range(10000)}
     

    Call Graph

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

    # $ pip3 install pycallgraph2
    -from pycallgraph2 import output, PyCallGraph
    -from datetime import datetime
    -filename = f'profile-{datetime.now():%Y%m%d%H%M%S}.png'
    -drawer = output.GraphvizOutput(output_file=filename)
    -with PyCallGraph(drawer):
    +# $ apt install graphviz
    +import pycallgraph2 as cg, datetime
    +filename = f'profile-{datetime.datetime.now():%Y%m%d%H%M%S}.png'
    +drawer = cg.output.GraphvizOutput(output_file=filename)
    +with cg.PyCallGraph(drawer):
         <code_to_be_profiled>
     
    @@ -2896,7 +2896,7 @@ From 3ec57592a4f2927989fc1e3b72aaa23f06e151f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 1 Jun 2022 17:50:20 +0200 Subject: [PATCH 048/638] Mario --- README.md | 14 +++++++------- index.html | 18 +++++++++--------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 9dc373757..abfcf5224 100644 --- a/README.md +++ b/README.md @@ -3031,7 +3031,7 @@ from random import randint P = collections.namedtuple('P', 'x y') # Position D = enum.Enum('D', 'n e s w') # Direction -SIZE, MAX_SPEED = 50, P(5, 10) # Screen size, Speed limit +W, H, MAX_S = 50, 50, P(5, 10) # Width, Height, Max speed def main(): def get_screen(): @@ -3045,9 +3045,9 @@ def main(): Mario = dataclasses.make_dataclass('Mario', 'rect spd facing_left frame_cycle'.split()) return Mario(get_rect(1, 1), P(0, 0), False, it.cycle(range(3))) def get_tiles(): - positions = [p for p in it.product(range(SIZE), repeat=2) if {*p} & {0, SIZE-1}] + \ - [(randint(1, SIZE-2), randint(2, SIZE-2)) for _ in range(SIZE**2 // 10)] - return [get_rect(*p) for p in positions] + border = [(x, y) for x in range(W) for y in range(H) if x in [0, W-1] or y in [0, H-1]] + platforms = [(randint(1, W-2), randint(2, H-2)) for _ in range(W*H // 10)] + return [get_rect(x, y) for x, y in border + platforms] def get_rect(x, y): return pg.Rect(x*16, y*16, 16, 16) run(get_screen(), get_images(), get_mario(), get_tiles()) @@ -3067,7 +3067,7 @@ def update_speed(mario, tiles, pressed): x += 2 * ((D.e in pressed) - (D.w in pressed)) x -= (x > 0) - (x < 0) y += 1 if D.s not in get_boundaries(mario.rect, tiles) else (D.n in pressed) * -10 - mario.spd = P(*[max(-limit, min(limit, s)) for limit, s in zip(MAX_SPEED, P(x, y))]) + mario.spd = P(x=max(-MAX_S.x, min(MAX_S.x, x)), y=max(-MAX_S.y, min(MAX_S.y, y))) def update_position(mario, tiles): x, y = mario.rect.topleft @@ -3093,8 +3093,8 @@ def draw(screen, images, mario, tiles, pressed): screen.fill((85, 168, 255)) mario.facing_left = (D.w in pressed) if {D.w, D.e} & pressed else mario.facing_left screen.blit(images[get_marios_image_index() + mario.facing_left * 9], mario.rect) - for rect in tiles: - screen.blit(images[18 if {*rect.topleft} & {0, (SIZE-1)*16} else 19], rect) + for t in tiles: + screen.blit(images[18 if t.x in [0, (W-1)*16] or t.y in [0, (H-1)*16] else 19], t) pg.display.flip() if __name__ == '__main__': diff --git a/index.html b/index.html index 6e8f2ba53..0e5d53872 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -2461,7 +2461,7 @@ P = collections.namedtuple('P', 'x y') # Position D = enum.Enum('D', 'n e s w') # Direction -SIZE, MAX_SPEED = 50, P(5, 10) # Screen size, Speed limit +W, H, MAX_S = 50, 50, P(5, 10) # Width, Height, Max speed def main(): def get_screen(): @@ -2475,9 +2475,9 @@ Mario = dataclasses.make_dataclass('Mario', 'rect spd facing_left frame_cycle'.split()) return Mario(get_rect(1, 1), P(0, 0), False, it.cycle(range(3))) def get_tiles(): - positions = [p for p in it.product(range(SIZE), repeat=2) if {*p} & {0, SIZE-1}] + \ - [(randint(1, SIZE-2), randint(2, SIZE-2)) for _ in range(SIZE**2 // 10)] - return [get_rect(*p) for p in positions] + border = [(x, y) for x in range(W) for y in range(H) if x in [0, W-1] or y in [0, H-1]] + platforms = [(randint(1, W-2), randint(2, H-2)) for _ in range(W*H // 10)] + return [get_rect(x, y) for x, y in border + platforms] def get_rect(x, y): return pg.Rect(x*16, y*16, 16, 16) run(get_screen(), get_images(), get_mario(), get_tiles()) @@ -2497,7 +2497,7 @@ x += 2 * ((D.e in pressed) - (D.w in pressed)) x -= (x > 0) - (x < 0) y += 1 if D.s not in get_boundaries(mario.rect, tiles) else (D.n in pressed) * -10 - mario.spd = P(*[max(-limit, min(limit, s)) for limit, s in zip(MAX_SPEED, P(x, y))]) + mario.spd = P(x=max(-MAX_S.x, min(MAX_S.x, x)), y=max(-MAX_S.y, min(MAX_S.y, y))) def update_position(mario, tiles): x, y = mario.rect.topleft @@ -2523,8 +2523,8 @@ screen.fill((85, 168, 255)) mario.facing_left = (D.w in pressed) if {D.w, D.e} & pressed else mario.facing_left screen.blit(images[get_marios_image_index() + mario.facing_left * 9], mario.rect) - for rect in tiles: - screen.blit(images[18 if {*rect.topleft} & {0, (SIZE-1)*16} else 19], rect) + for t in tiles: + screen.blit(images[18 if t.x in [0, (W-1)*16] or t.y in [0, (H-1)*16] else 19], t) pg.display.flip() if __name__ == '__main__': @@ -2896,7 +2896,7 @@ From 26c8280269c845ce4f93dc31a2b3edbff9177ac4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 1 Jun 2022 17:57:54 +0200 Subject: [PATCH 049/638] Mario --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index abfcf5224..2e88e09d5 100644 --- a/README.md +++ b/README.md @@ -3036,7 +3036,7 @@ W, H, MAX_S = 50, 50, P(5, 10) # Width, Height, Max speed def main(): def get_screen(): pg.init() - return pg.display.set_mode((SIZE*16, SIZE*16)) + return pg.display.set_mode((W*16, H*16)) def get_images(): url = 'https://gto76.github.io/python-cheatsheet/web/mario_bros.png' img = pg.image.load(io.BytesIO(urllib.request.urlopen(url).read())) diff --git a/index.html b/index.html index 0e5d53872..b6c4ca98c 100644 --- a/index.html +++ b/index.html @@ -2466,7 +2466,7 @@ def main(): def get_screen(): pg.init() - return pg.display.set_mode((SIZE*16, SIZE*16)) + return pg.display.set_mode((W*16, H*16)) def get_images(): url = 'https://gto76.github.io/python-cheatsheet/web/mario_bros.png' img = pg.image.load(io.BytesIO(urllib.request.urlopen(url).read())) From 26f1eb967bd0dc330388c74545b2383ce672e00b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 2 Jun 2022 17:14:08 +0200 Subject: [PATCH 050/638] Image, Animation --- README.md | 8 ++++---- index.html | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 2e88e09d5..6c2712135 100644 --- a/README.md +++ b/README.md @@ -2742,8 +2742,8 @@ from PIL import Image ```python = .getpixel((x, y)) # Returns a pixel. .putpixel((x, y), ) # Writes a pixel to the image. - = .getdata() # Returns a sequence of pixels. -.putdata() # Writes a sequence of pixels. + = .getdata() # Returns a flattened sequence of pixels. +.putdata() # Writes a flattened sequence of pixels. .paste(, (x, y)) # Writes an image to the image. ``` @@ -2807,11 +2807,11 @@ Animation # $ pip3 install imageio from PIL import Image, ImageDraw import imageio -WIDTH, R = 126, 10 +WIDTH, HEIGHT, R = 126, 126, 10 frames = [] for velocity in range(1, 16): y = sum(range(velocity)) - frame = Image.new('L', (WIDTH, WIDTH)) + frame = Image.new('L', (WIDTH, HEIGHT)) draw = ImageDraw.Draw(frame) draw.ellipse((WIDTH/2-R, y, WIDTH/2+R, y+R*2), fill='white') frames.append(frame) diff --git a/index.html b/index.html index b6c4ca98c..97daad66d 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -2230,8 +2230,8 @@
    <int/tuple> = <Image>.getpixel((x, y))          # Returns a pixel.
     <Image>.putpixel((x, y), <int/tuple>)           # Writes a pixel to the image.
    -<ImagingCore> = <Image>.getdata()               # Returns a sequence of pixels.
    -<Image>.putdata(<list/ImagingCore>)             # Writes a sequence of pixels.
    +<ImagingCore> = <Image>.getdata()               # Returns a flattened sequence of pixels.
    +<Image>.putdata(<list/ImagingCore>)             # Writes a flattened sequence of pixels.
     <Image>.paste(<Image>, (x, y))                  # Writes an image to the image.
     
    <2d_array> = np.array(<Image_L>)                # Creates NumPy array from greyscale image.
    @@ -2282,11 +2282,11 @@
     

    #Animation

    Creates a GIF of a bouncing ball:

    # $ pip3 install imageio
     from PIL import Image, ImageDraw
     import imageio
    -WIDTH, R = 126, 10
    +WIDTH, HEIGHT, R = 126, 126, 10
     frames = []
     for velocity in range(1, 16):
         y = sum(range(velocity))
    -    frame = Image.new('L', (WIDTH, WIDTH))
    +    frame = Image.new('L', (WIDTH, HEIGHT))
         draw  = ImageDraw.Draw(frame)
         draw.ellipse((WIDTH/2-R, y, WIDTH/2+R, y+R*2), fill='white')
         frames.append(frame)
    @@ -2896,7 +2896,7 @@
      
     
       
     
    
    From 943248450798d1d1daa08ebc28ca03101b7d3f8b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Fri, 3 Jun 2022 23:00:31 +0200
    Subject: [PATCH 051/638] Class, Table, Wave
    
    ---
     README.md  | 11 ++++++-----
     index.html | 15 ++++++++-------
     2 files changed, 14 insertions(+), 12 deletions(-)
    
    diff --git a/README.md b/README.md
    index 6c2712135..f1982d447 100644
    --- a/README.md
    +++ b/README.md
    @@ -964,6 +964,7 @@ class :
     ```
     * **Return value of repr() should be unambiguous and of str() readable.**
     * **If only repr() is defined, it will also be used for str().**
    +* **Methods decorated with `'@staticmethod'` do not receive 'self' nor 'cls' as their first arg.**
     
     #### Str() use cases:
     ```python
    @@ -2400,7 +2401,7 @@ Table
     import csv, tabulate
     with open('test.csv', encoding='utf-8', newline='') as file:
         rows   = csv.reader(file)
    -    header = [a.title() for a in next(rows)]
    +    header = next(rows)
         table  = tabulate.tabulate(rows, header)
     print(table)
     ```
    @@ -2548,8 +2549,8 @@ def send_json(sport):
     >>> import threading, requests
     >>> threading.Thread(target=run, daemon=True).start()
     >>> url = 'http://localhost:8080/football/odds'
    ->>> data = {'team': 'arsenal f.c.'}
    ->>> response = requests.post(url, data=data)
    +>>> request_data = {'team': 'arsenal f.c.'}
    +>>> response = requests.post(url, data=request_data)
     >>> response.json()
     {'team': 'arsenal f.c.', 'odds': [2.09, 3.74, 3.68]}
     ```
    @@ -2891,7 +2892,7 @@ def write_to_wav_file(filename, float_samples, nchannels=1, sampwidth=2, framera
     ```
     
     ### Examples
    -#### Saves a sine wave to a mono WAV file:
    +#### Saves a 440 Hz sine wave to a mono WAV file:
     ```python
     from math import pi, sin
     samples_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000))
    @@ -3494,7 +3495,7 @@ import 
     ```python
     cdef   = 
     cdef [n_elements]  = [, , ...]
    -cdef  ( , ...):
    +cdef  ( , ...): …
     ```
     
     ```python
    diff --git a/index.html b/index.html
    index 97daad66d..6b762c32d 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -825,6 +825,7 @@
    • Return value of repr() should be unambiguous and of str() readable.
    • If only repr() is defined, it will also be used for str().
    • +
    • Methods decorated with '@staticmethod' do not receive 'self' nor 'cls' as their first arg.

    Str() use cases:

    print(<el>)
     f'{<el>}'
    @@ -1967,7 +1968,7 @@
     import csv, tabulate
     with open('test.csv', encoding='utf-8', newline='') as file:
         rows   = csv.reader(file)
    -    header = [a.title() for a in next(rows)]
    +    header = next(rows)
         table  = tabulate.tabulate(rows, header)
     print(table)
     
    @@ -2087,8 +2088,8 @@ >>> import threading, requests >>> threading.Thread(target=run, daemon=True).start() >>> url = 'http://localhost:8080/football/odds' ->>> data = {'team': 'arsenal f.c.'} ->>> response = requests.post(url, data=data) +>>> request_data = {'team': 'arsenal f.c.'} +>>> response = requests.post(url, data=request_data) >>> response.json() {'team': 'arsenal f.c.', 'odds': [2.09, 3.74, 3.68]}
    @@ -2354,7 +2355,7 @@ file.writeframes(b''.join(get_bytes(f) for f in float_samples))
    -

    Examples

    Saves a sine wave to a mono WAV file:

    from math import pi, sin
    +

    Examples

    Saves a 440 Hz sine wave to a mono WAV file:

    from math import pi, sin
     samples_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000))
     write_to_wav_file('test.wav', samples_f)
     
    @@ -2839,7 +2840,7 @@
  • Script needs to be saved with a 'pyx' extension.
  • cdef <ctype> <var_name> = <el>
     cdef <ctype>[n_elements] <var_name> = [<el_1>, <el_2>, ...]
    -cdef <ctype/void> <func_name>(<ctype> <arg_name_1>, ...):
    +cdef <ctype/void> <func_name>(<ctype> <arg_name_1>, ...): …
     
    @@ -2896,7 +2897,7 @@ From 62ed5162000710c04eb1f5ee6abfe5c64051c7a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 6 Jun 2022 16:48:33 +0200 Subject: [PATCH 052/638] Struct --- README.md | 6 +++--- index.html | 10 +++++----- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index f1982d447..fe07974ec 100644 --- a/README.md +++ b/README.md @@ -1776,7 +1776,7 @@ def write_to_json_file(filename, an_object): Pickle ------ -**Binary file format for storing objects.** +**Binary file format for storing Python objects.** ```python import pickle @@ -1976,7 +1976,7 @@ def write_bytes(filename, bytes_obj): Struct ------ * **Module that performs conversions between a sequence of numbers and a bytes object.** -* **System’s type sizes and byte order are used by default.** +* **System’s type sizes, byte order, and alignment rules are used by default.** ```python from struct import pack, unpack, iter_unpack @@ -1997,7 +1997,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' ``` ### Format -#### For standard type sizes start format string with: +#### For standard type sizes and manual alignment (padding) start format string with: * **`'='` - system's byte order (usually little-endian)** * **`'<'` - little-endian** * **`'>'` - big-endian (also `'!'`)** diff --git a/index.html b/index.html index 6b762c32d..fd8b44c1d 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -1486,7 +1486,7 @@ json.dump(an_object, file, ensure_ascii=False, indent=2)
    -

    #Pickle

    Binary file format for storing objects.

    import pickle
    +

    #Pickle

    Binary file format for storing Python objects.

    import pickle
     <bytes>  = pickle.dumps(<object>)
     <object> = pickle.loads(<bytes>)
     
    @@ -1640,7 +1640,7 @@

    #Struct

    • Module that performs conversions between a sequence of numbers and a bytes object.
    • -
    • System’s type sizes and byte order are used by default.
    • +
    • System’s type sizes, byte order, and alignment rules are used by default.
    from struct import pack, unpack, iter_unpack
     
    @@ -1655,7 +1655,7 @@ (1, 2, 3)
    -

    Format

    For standard type sizes start format string with:

      +

      Format

      For standard type sizes and manual alignment (padding) start format string with:

      • '=' - system's byte order (usually little-endian)
      • '<' - little-endian
      • '>' - big-endian (also '!')
      • @@ -2897,7 +2897,7 @@ From 13062b2dfeb2c6e69727c9ad832c188625dc7adb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 6 Jun 2022 16:54:54 +0200 Subject: [PATCH 053/638] Updated remove_links.py --- pdf/remove_links.py | 1 + 1 file changed, 1 insertion(+) diff --git a/pdf/remove_links.py b/pdf/remove_links.py index 8a35856ac..6a05afed0 100755 --- a/pdf/remove_links.py +++ b/pdf/remove_links.py @@ -17,6 +17,7 @@ 'Generators returned by the generator functions and generator expressions.': 'Generators returned by the generator functions (p. 4) and generator expressions (p. 11).', 'File objects returned by the open() function, etc.': 'File objects returned by the open() function (p. 22), etc.', 'Functions report OS related errors by raising either OSError or one of its subclasses.': 'Functions report OS related errors by raising OSError or one of its subclasses (p. 23).', + 'For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.': 'For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library (p. 46).', 'Bools will be stored and returned as ints and dates as ISO formatted strings.': 'Bools will be stored and returned as ints and dates as ISO formatted strings (p. 9).', 'An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable.': 'An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable (p. 25).', 'Asyncio module also provides its own Queue, Event, Lock and Semaphore classes.': 'Asyncio module also provides its own Queue, Event, Lock and Semaphore classes (p. 30).', From ec86a0e4d7df2566616d65afcb73f56b017e8adf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 6 Jun 2022 19:26:34 +0200 Subject: [PATCH 054/638] Command line arguments, CSV --- README.md | 11 ++++++----- index.html | 11 ++++++----- pdf/remove_links.py | 1 + 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index fe07974ec..6dd94a598 100644 --- a/README.md +++ b/README.md @@ -1542,9 +1542,9 @@ args = p.parse_args() # Exits on err value = args. ``` -* **Use `'help='` to set argument description.** +* **Use `'help='` to set argument description that will be displayed in help message.** * **Use `'default='` to set the default value.** -* **Use `'type=FileType()'` for files.** +* **Use `'type=FileType()'` for files. Also accepts 'encoding', but not 'newline'.** Open @@ -1813,8 +1813,9 @@ import csv = next() # Returns next row as a list of strings. = list() # Returns a list of remaining rows. ``` -* **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#dataframe-plot-encode-decode) library.** * **File must be opened with a `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!** +* **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#dataframe-plot-encode-decode) library.** +* **To print the table to console use [Tabulate](#table) library.** ### Write ```python @@ -1830,7 +1831,7 @@ import csv * **`'quotechar'` - Character for quoting fields that contain special characters.** * **`'doublequote'` - Whether quotechars inside fields are/get doubled or escaped.** * **`'skipinitialspace'` - Whether whitespace after delimiter gets stripped by reader.** -* **`'lineterminator'` - How writer terminates rows. Reader is hardcoded to '\r', '\n', '\r\n'.** +* **`'lineterminator'` - How writer terminates rows. Reader is hardcoded to '\n', '\r', '\r\n'.** * **`'quoting'` - Controls the amount of quoting: 0 - as necessary, 1 - all.** * **`'escapechar'` - Character for escaping quotechars if doublequote is False.** @@ -2980,7 +2981,7 @@ while all(event.type != pg.QUIT for event in pg.event.get()): = .collidepoint((x, y)) # Checks if rectangle contains a point. = .colliderect() # Checks if two rectangles overlap. = .collidelist() # Returns index of first colliding Rect or -1. - = .collidelistall() # Returns indexes of all colliding Rects. + = .collidelistall() # Returns indexes of all colliding rectangles. ``` ### Surface diff --git a/index.html b/index.html index fd8b44c1d..0e86d9964 100644 --- a/index.html +++ b/index.html @@ -1319,9 +1319,9 @@
      -
    • Use 'help=<str>' to set argument description.
    • +
    • Use 'help=<str>' to set argument description that will be displayed in help message.
    • Use 'default=<el>' to set the default value.
    • -
    • Use 'type=FileType(<mode>)' for files.
    • +
    • Use 'type=FileType(<mode>)' for files. Also accepts 'encoding', but not 'newline'.

    #Open

    Opens the file and returns a corresponding file object.

    <file> = open(<path>, mode='r', encoding=None, newline=None)
     
    @@ -1512,8 +1512,9 @@
      -
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
    • File must be opened with a 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!
    • +
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
    • +
    • To print the table to console use Tabulate library.

    Write

    <writer> = csv.writer(<file>)       # Also: `dialect='excel', delimiter=','`.
     <writer>.writerow(<collection>)     # Encodes objects using `str(<el>)`.
    @@ -1529,7 +1530,7 @@
     
  • 'quotechar' - Character for quoting fields that contain special characters.
  • 'doublequote' - Whether quotechars inside fields are/get doubled or escaped.
  • 'skipinitialspace' - Whether whitespace after delimiter gets stripped by reader.
  • -
  • 'lineterminator' - How writer terminates rows. Reader is hardcoded to '\r', '\n', '\r\n'.
  • +
  • 'lineterminator' - How writer terminates rows. Reader is hardcoded to '\n', '\r', '\r\n'.
  • 'quoting' - Controls the amount of quoting: 0 - as necessary, 1 - all.
  • 'escapechar' - Character for escaping quotechars if doublequote is False.
  • Dialects

    ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
    @@ -2425,7 +2426,7 @@
     
    <bool> = <Rect>.collidepoint((x, y))            # Checks if rectangle contains a point.
     <bool> = <Rect>.colliderect(<Rect>)             # Checks if two rectangles overlap.
     <int>  = <Rect>.collidelist(<list_of_Rect>)     # Returns index of first colliding Rect or -1.
    -<list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding Rects.
    +<list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding rectangles.
     

    Surface

    Object for representing images.

    <Surf> = pg.display.set_mode((width, height))   # Returns display surface.
     <Surf> = pg.Surface((width, height), flags=0)   # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
    diff --git a/pdf/remove_links.py b/pdf/remove_links.py
    index 6a05afed0..49c3e3736 100755
    --- a/pdf/remove_links.py
    +++ b/pdf/remove_links.py
    @@ -17,6 +17,7 @@
         'Generators returned by the generator functions and generator expressions.': 'Generators returned by the generator functions (p. 4) and generator expressions (p. 11).',
         'File objects returned by the open() function, etc.': 'File objects returned by the open() function (p. 22), etc.',
         'Functions report OS related errors by raising either OSError or one of its subclasses.': 'Functions report OS related errors by raising OSError or one of its subclasses (p. 23).',
    +    'To print the table to console use Tabulate library.': 'To print the table to console use Tabulate library (p. 34).',
         'For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.': 'For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library (p. 46).',
         'Bools will be stored and returned as ints and dates as ISO formatted strings.': 'Bools will be stored and returned as ints and dates as ISO formatted strings (p. 9).',
         'An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable.': 'An object with the same interface called ProcessPoolExecutor provides true parallelism by running a separate interpreter in each process. All arguments must be pickable (p. 25).',
    
    From f84d6b977f880572da64a66a64974ed3ac12913d Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Mon, 6 Jun 2022 23:34:02 +0200
    Subject: [PATCH 055/638] Regex, Format
    
    ---
     README.md  | 54 +++++++++++++++++++++++++++---------------------------
     index.html | 54 +++++++++++++++++++++++++++---------------------------
     2 files changed, 54 insertions(+), 54 deletions(-)
    
    diff --git a/README.md b/README.md
    index 6dd94a598..fb50f1557 100644
    --- a/README.md
    +++ b/README.md
    @@ -357,10 +357,10 @@ import re
       = re.split(, text, maxsplit=0)  # Use brackets in regex to include the matches.
      = re.search(, text)             # Searches for first occurrence of the pattern.
      = re.match(, text)              # Searches only at the beginning of the text.
    -  = re.finditer(, text)           # Returns all occurrences as match objects.
    +  = re.finditer(, text)           # Returns all occurrences as Match objects.
     ```
     
    -* **Argument 'new' can be a function that accepts a match object and returns a string.**
    +* **Argument 'new' can be a function that accepts a Match object and returns a string.**
     * **Search() and match() return None if they can't find a match.**
     * **Argument `'flags=re.IGNORECASE'` can be used with all functions.**
     * **Argument `'flags=re.MULTILINE'` makes `'^'` and `'$'` match the start/end of each line.**
    @@ -385,21 +385,21 @@ import re
     ```
     
     * **By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless `'flags=re.ASCII'` argument is used.**
    -* **As shown above, it restricts special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'` (the so-called separator characters).**
    +* **As shown above, it restricts all special sequence matches to the first 128 characters and prevents `'\s'` from accepting `'[\x1c-\x1f]'` (the so-called separator characters).**
     * **Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).**
     
     
     Format
     ------
     ```python
    - = f'{}, {}'
    - = '{}, {}'.format(, )
    + = f'{}, {}'            # Curly braces also accept expressions.
    + = '{}, {}'.format(, )  # Or: '{0}, {1}'.format(, )
    + = '%s, %s' % (, )      # Redundant and inferior C style formatting.
     ```
     
     ### Attributes
     ```python
    ->>> from collections import namedtuple
    ->>> Person = namedtuple('Person', 'name height')
    +>>> Person = collections.namedtuple('Person', 'name height')
     >>> person = Person('Jean-Luc', 187)
     >>> f'{person.height}'
     '187'
    @@ -409,40 +409,40 @@ Format
     
     ### General Options
     ```python
    -{:<10}                                     # '      '
    -{:^10}                                     # '      '
    -{:>10}                                     # '      '
    -{:.<10}                                    # '......'
    -{:0}                                       # ''
    +{:<10}                               # '      '
    +{:^10}                               # '      '
    +{:>10}                               # '      '
    +{:.<10}                              # '......'
    +{:0}                                 # ''
     ```
     * **Options can be generated dynamically: `f'{:{}[…]}'`.**
     * **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.**
     
     ### Strings
     ```python
    -{'abcde':10}                                   # 'abcde     '
    -{'abcde':10.3}                                 # 'abc       '
    -{'abcde':.3}                                   # 'abc'
    -{'abcde'!r:10}                                 # "'abcde'   "
    +{'abcde':10}                             # 'abcde     '
    +{'abcde':10.3}                           # 'abc       '
    +{'abcde':.3}                             # 'abc'
    +{'abcde'!r:10}                           # "'abcde'   "
     ```
     
     ### Numbers
     ```python
    -{123456:10}                                    # '    123456'
    -{123456:10,}                                   # '   123,456'
    -{123456:10_}                                   # '   123_456'
    -{123456:+10}                                   # '   +123456'
    -{123456:=+10}                                  # '+   123456'
    -{123456: }                                     # ' 123456'
    -{-123456: }                                    # '-123456'
    +{123456:10}                              # '    123456'
    +{123456:10,}                             # '   123,456'
    +{123456:10_}                             # '   123_456'
    +{123456:+10}                             # '   +123456'
    +{123456:=+10}                            # '+   123456'
    +{123456: }                               # ' 123456'
    +{-123456: }                              # '-123456'
     ```
     
     ### Floats
     ```python
    -{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%'
    +{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 presentation types:
    diff --git a/index.html b/index.html
    index 0e86d9964..300fbd6fc 100644
    --- a/index.html
    +++ b/index.html
    @@ -336,11 +336,11 @@
     <list>  = re.split(<regex>, text, maxsplit=0)  # Use brackets in regex to include the matches.
     <Match> = re.search(<regex>, text)             # Searches for first occurrence of the 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.
    +<iter>  = re.finditer(<regex>, text)           # Returns all occurrences as Match objects.
     
      -
    • Argument 'new' can be a function that accepts a match object and returns a string.
    • +
    • Argument 'new' can be a function that accepts a Match object and returns a string.
    • Search() and match() return None if they can't find a match.
    • Argument 'flags=re.IGNORECASE' can be used with all functions.
    • Argument 'flags=re.MULTILINE' makes '^' and '$' match the start/end of each line.
    • @@ -362,15 +362,15 @@
      • By default, decimal characters, alphanumerics and whitespaces from all alphabets are matched unless 'flags=re.ASCII' argument is used.
      • -
      • As shown above, it restricts special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
      • +
      • As shown above, it restricts all special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
      • Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
      -

      #Format

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

      #Format

      <str> = f'{<el_1>}, {<el_2>}'            # Curly braces also accept expressions.
      +<str> = '{}, {}'.format(<el_1>, <el_2>)  # Or: '{0}, {1}'.format(<el_1>, <el_2>)
      +<str> = '%s, %s' % (<el_1>, <el_2>)      # Redundant and inferior C style formatting.
       
      -

      Attributes

      >>> from collections import namedtuple
      ->>> Person = namedtuple('Person', 'name height')
      +

      Attributes

      >>> Person = collections.namedtuple('Person', 'name height')
       >>> person = Person('Jean-Luc', 187)
       >>> f'{person.height}'
       '187'
      @@ -378,36 +378,36 @@
       '187'
       
      -

      General Options

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

      General Options

      {<el>:<10}                               # '<el>      '
      +{<el>:^10}                               # '   <el>   '
      +{<el>:>10}                               # '      <el>'
      +{<el>:.<10}                              # '<el>......'
      +{<el>:0}                                 # '<el>'
       
      • Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
      • Adding '!r' before the colon converts object to string by calling its repr() method.
      -

      Strings

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

      Strings

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

      Numbers

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

      Numbers

      {123456:10}                              # '    123456'
      +{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'
      -{1.23456:10.3f}                                # '     1.235'
      -{1.23456:10.3e}                                # ' 1.235e+00'
      -{1.23456:10.3%}                                # '  123.456%'
      +

      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 presentation types:

      ┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
      
      From 1b6004bce5f1b9fca1eaa4edf213d70a178f66c0 Mon Sep 17 00:00:00 2001
      From: =?UTF-8?q?Jure=20=C5=A0orn?= 
      Date: Tue, 7 Jun 2022 00:28:57 +0200
      Subject: [PATCH 056/638] Numbers
      
      ---
       README.md  |  2 +-
       index.html | 10 +++++-----
       2 files changed, 6 insertions(+), 6 deletions(-)
      
      diff --git a/README.md b/README.md
      index fb50f1557..9054b8604 100644
      --- a/README.md
      +++ b/README.md
      @@ -484,7 +484,6 @@ Format
       
       Numbers
       -------
      -### Types
       ```python
             = int()       # Or: math.floor()
           = float()       # Or: 
      @@ -494,6 +493,7 @@ Numbers
       ```
       * **`'int()'` and `'float()'` raise ValueError on malformed strings.**
       * **Decimal numbers are stored exactly, unlike most floats where `'1.1 + 2.2 != 3.3'`.**
      +* **Floats can be compared with: `'math.isclose(, )'`.**
       * **Precision of decimal operations is set with: `'decimal.getcontext().prec = '`.**
       
       ### Basic Functions
      diff --git a/index.html b/index.html
      index 300fbd6fc..1ec7470ae 100644
      --- a/index.html
      +++ b/index.html
      @@ -54,7 +54,7 @@
       
       
         
      - +
      @@ -444,17 +444,17 @@ {90:X} # '5A'
      -

      #Numbers

      Types

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

      #Numbers

      <int>      = int(<float/str/bool>)       # Or: math.floor(<float>)
       <float>    = float(<int/str/bool>)       # Or: <real>e±<int>
       <complex>  = complex(real=0, imag=0)     # Or: <real> ± <real>j
       <Fraction> = fractions.Fraction(0, 1)    # Or: Fraction(numerator=0, denominator=1)
       <Decimal>  = decimal.Decimal(<str/int>)  # Or: Decimal((sign, digits, exponent))
      -
      - +
      • 'int(<str>)' and 'float(<str>)' raise ValueError on malformed strings.
      • Decimal numbers are stored exactly, unlike most floats where '1.1 + 2.2 != 3.3'.
      • +
      • Floats can be compared with: 'math.isclose(<float>, <float>)'.
      • Precision of decimal operations is set with: 'decimal.getcontext().prec = <int>'.

      Basic Functions

      <num> = pow(<num>, <num>)                # Or: <num> ** <num>
      @@ -2898,7 +2898,7 @@
        
       
         
       
      
      From 7de5aa4b9b1dab255c7d8334fccc9d8e815859d3 Mon Sep 17 00:00:00 2001
      From: =?UTF-8?q?Jure=20=C5=A0orn?= 
      Date: Tue, 7 Jun 2022 01:15:49 +0200
      Subject: [PATCH 057/638] Format
      
      ---
       README.md  | 51 +++++++++++++++++++++++++--------------------------
       index.html | 51 +++++++++++++++++++++++++--------------------------
       2 files changed, 50 insertions(+), 52 deletions(-)
      
      diff --git a/README.md b/README.md
      index 9054b8604..ee4e421d5 100644
      --- a/README.md
      +++ b/README.md
      @@ -392,9 +392,8 @@ import re
       Format
       ------
       ```python
      - = f'{}, {}'            # Curly braces also accept expressions.
      - = '{}, {}'.format(, )  # Or: '{0}, {1}'.format(, )
      - = '%s, %s' % (, )      # Redundant and inferior C style formatting.
      + = f'{}, {}'        # Or: '{}, {}'.format(, )
      + = '%s, %s' % (, )  # Redundant and inferior C style formatting.
       ```
       
       ### Attributes
      @@ -409,40 +408,40 @@ Format
       
       ### General Options
       ```python
      -{:<10}                               # '      '
      -{:^10}                               # '      '
      -{:>10}                               # '      '
      -{:.<10}                              # '......'
      -{:0}                                 # ''
      +{:<10}                           # '      '
      +{:^10}                           # '      '
      +{:>10}                           # '      '
      +{:.<10}                          # '......'
      +{:0}                             # ''
       ```
       * **Options can be generated dynamically: `f'{:{}[…]}'`.**
       * **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.**
       
       ### Strings
       ```python
      -{'abcde':10}                             # 'abcde     '
      -{'abcde':10.3}                           # 'abc       '
      -{'abcde':.3}                             # 'abc'
      -{'abcde'!r:10}                           # "'abcde'   "
      +{'abcde':10}                         # 'abcde     '
      +{'abcde':10.3}                       # 'abc       '
      +{'abcde':.3}                         # 'abc'
      +{'abcde'!r:10}                       # "'abcde'   "
       ```
       
       ### Numbers
       ```python
      -{123456:10}                              # '    123456'
      -{123456:10,}                             # '   123,456'
      -{123456:10_}                             # '   123_456'
      -{123456:+10}                             # '   +123456'
      -{123456:=+10}                            # '+   123456'
      -{123456: }                               # ' 123456'
      -{-123456: }                              # '-123456'
      +{123456:10}                          # '    123456'
      +{123456:10,}                         # '   123,456'
      +{123456:10_}                         # '   123_456'
      +{123456:+10}                         # '   +123456'
      +{123456:=+10}                        # '+   123456'
      +{123456: }                           # ' 123456'
      +{-123456: }                          # '-123456'
       ```
       
       ### Floats
       ```python
      -{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%'
      +{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 presentation types:
      @@ -476,9 +475,9 @@ Format
       
       ### Ints
       ```python
      -{90:c}                                   # 'Z'
      -{90:b}                                   # '1011010'
      -{90:X}                                   # '5A'
      +{90:c}                               # 'Z'
      +{90:b}                               # '1011010'
      +{90:X}                               # '5A'
       ```
       
       
      diff --git a/index.html b/index.html
      index 1ec7470ae..046c2da9f 100644
      --- a/index.html
      +++ b/index.html
      @@ -365,9 +365,8 @@
       
    • As shown above, it restricts all special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
    • Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
    -

    #Format

    <str> = f'{<el_1>}, {<el_2>}'            # Curly braces also accept expressions.
    -<str> = '{}, {}'.format(<el_1>, <el_2>)  # Or: '{0}, {1}'.format(<el_1>, <el_2>)
    -<str> = '%s, %s' % (<el_1>, <el_2>)      # Redundant and inferior C style formatting.
    +

    #Format

    <str> = f'{<el_1>}, {<el_2>}'        # Or: '{}, {}'.format(<el_1>, <el_2>)
    +<str> = '%s, %s' % (<el_1>, <el_2>)  # Redundant and inferior C style formatting.
     

    Attributes

    >>> Person = collections.namedtuple('Person', 'name height')
    @@ -378,36 +377,36 @@
     '187'
     
    -

    General Options

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

    General Options

    {<el>:<10}                           # '<el>      '
    +{<el>:^10}                           # '   <el>   '
    +{<el>:>10}                           # '      <el>'
    +{<el>:.<10}                          # '<el>......'
    +{<el>:0}                             # '<el>'
     
    • Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
    • Adding '!r' before the colon converts object to string by calling its repr() method.
    -

    Strings

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

    Strings

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

    Numbers

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

    Numbers

    {123456:10}                          # '    123456'
    +{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'
    -{1.23456:10.3f}                          # '     1.235'
    -{1.23456:10.3e}                          # ' 1.235e+00'
    -{1.23456:10.3%}                          # '  123.456%'
    +

    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 presentation types:

    ┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
    @@ -439,9 +438,9 @@
     
  • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
  • This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
  • -

    Ints

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

    Ints

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

    #Numbers

    <int>      = int(<float/str/bool>)       # Or: math.floor(<float>)
    
    From 4fddcbc9da46d4f000506b51856b7a13aca399a0 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 7 Jun 2022 14:19:33 +0200
    Subject: [PATCH 058/638] Updated pdf/README.md
    
    ---
     pdf/README.md | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/pdf/README.md b/pdf/README.md
    index 82f00bf04..038ecbf8f 100644
    --- a/pdf/README.md
    +++ b/pdf/README.md
    @@ -1,6 +1,6 @@
     How To Create PDF (on macOS)
     ============================
    -PDF file can also be purchased here: https://transactions.sendowl.com/products/78175486/4422834F/view
    +**PDF file can also be purchased here: https://transactions.sendowl.com/products/78175486/4422834F/view**
     
     
     Setup
    
    From d07ca15537bcbfa479789ec61924472c1d8da2e0 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 7 Jun 2022 14:42:42 +0200
    Subject: [PATCH 059/638] Format
    
    ---
     README.md  |  5 ++++-
     index.html |  4 +++-
     parse.js   | 26 ++++++--------------------
     3 files changed, 13 insertions(+), 22 deletions(-)
    
    diff --git a/README.md b/README.md
    index ee4e421d5..b286188b7 100644
    --- a/README.md
    +++ b/README.md
    @@ -398,7 +398,8 @@ Format
     
     ### Attributes
     ```python
    ->>> Person = collections.namedtuple('Person', 'name height')
    +>>> from collections import namedtuple
    +>>> Person = namedtuple('Person', 'name height')
     >>> person = Person('Jean-Luc', 187)
     >>> f'{person.height}'
     '187'
    @@ -457,7 +458,9 @@ Format
     |  5.6789      |   '5.6789'     |    '5.678900'  | '5.678900e+00' |  '567.890000%' |
     | 56.789       |  '56.789'      |   '56.789000'  | '5.678900e+01' | '5678.900000%' |
     +--------------+----------------+----------------+----------------+----------------+
    +```
     
    +```text
     +--------------+----------------+----------------+----------------+----------------+
     |              |  {:.2}  |  {:.2f} |  {:.2e} |  {:.2%} |
     +--------------+----------------+----------------+----------------+----------------+
    diff --git a/index.html b/index.html
    index 046c2da9f..3a7a6b23f 100644
    --- a/index.html
    +++ b/index.html
    @@ -369,7 +369,8 @@
     <str> = '%s, %s' % (<el_1>, <el_2>)  # Redundant and inferior C style formatting.
     
    -

    Attributes

    >>> Person = collections.namedtuple('Person', 'name height')
    +

    Attributes

    >>> from collections import namedtuple
    +>>> Person = namedtuple('Person', 'name height')
     >>> person = Person('Jean-Luc', 187)
     >>> f'{person.height}'
     '187'
    @@ -434,6 +435,7 @@
     ┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
     
    +
    
     
    • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
    • This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
    • diff --git a/parse.js b/parse.js index f2e719e72..41c707851 100755 --- a/parse.js +++ b/parse.js @@ -112,15 +112,6 @@ const DIAGRAM_1_A = '| | Iterable | Collection | Sequence |\n' + '+------------------+------------+------------+------------+\n'; -// const DIAGRAM_1_B = -// '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + -// '┃ │ Sequence │ Collection │ Iterable ┃\n' + -// '┠──────────────────┼────────────┼────────────┼────────────┨\n' + -// '┃ list, range, str │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ dict, set │ │ ✓ │ ✓ ┃\n' + -// '┃ iter │ │ │ ✓ ┃\n' + -// '┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛\n'; - const DIAGRAM_1_B = '┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓\n' + '┃ │ Iterable │ Collection │ Sequence ┃\n' + @@ -135,17 +126,6 @@ const DIAGRAM_2_A = '| | Number | Complex | Real | Rational | Integral |\n' + '+--------------------+----------+----------+----------+----------+----------+\n'; -// const DIAGRAM_2_B = -// '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + -// '┃ │ Integral │ Rational │ Real │ Complex │ Number ┃\n' + -// '┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨\n' + -// '┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ fractions.Fraction │ │ ✓ │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ float │ │ │ ✓ │ ✓ │ ✓ ┃\n' + -// '┃ complex │ │ │ │ ✓ │ ✓ ┃\n' + -// '┃ decimal.Decimal │ │ │ │ │ ✓ ┃\n' + -// '┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛\n'; - const DIAGRAM_2_B = '┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓\n' + '┃ │ Number │ Complex │ Real │ Rational │ Integral ┃\n' + @@ -201,6 +181,11 @@ const DIAGRAM_4_B = "┃ 56.789 │ '5.7e+01' │ '56.79' │ '5.68e+01' │ '5678.90%' ┃\n" + "┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛\n"; +const DIAGRAM_5_A = + "+--------------+----------------+----------------+----------------+----------------+\n" + + "| | {:.2} | {:.2f} | {:.2e} | {:.2%} |\n" + + "+--------------+----------------+----------------+----------------+----------------+\n"; + const DIAGRAM_6_A = '+------------+------------+------------+------------+--------------+\n' + '| | Iterable | Collection | Sequence | abc.Sequence |\n' + @@ -530,6 +515,7 @@ function updateDiagrams() { $(`code:contains(${DIAGRAM_2_A})`).html(DIAGRAM_2_B); $(`code:contains(${DIAGRAM_3_A})`).html(DIAGRAM_3_B); $(`code:contains(${DIAGRAM_4_A})`).html(DIAGRAM_4_B); + $(`code:contains(${DIAGRAM_5_A})`).remove(); $(`code:contains(${DIAGRAM_6_A})`).html(DIAGRAM_6_B); $(`code:contains(${DIAGRAM_7_A})`).html(DIAGRAM_7_B); $(`code:contains(${DIAGRAM_8_A})`).html(DIAGRAM_8_B); From 3d151bca6732a1fc8573b9163cb6cdfa972f89ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 7 Jun 2022 17:36:00 +0200 Subject: [PATCH 060/638] Pandas --- README.md | 4 ++++ index.html | 4 +++- parse.js | 10 +++++++++- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b286188b7..aef51702b 100644 --- a/README.md +++ b/README.md @@ -3178,7 +3178,9 @@ y 2 | sr.apply(…) | 3 | sum 3 | s 3 | | sr.agg(…) | | | | +-----------------+-------------+-------------+---------------+ +``` +```text +-----------------+-------------+-------------+---------------+ | | 'rank' | ['rank'] | {'r': 'rank'} | +-----------------+-------------+-------------+---------------+ @@ -3296,7 +3298,9 @@ b 3 4 | df.agg(…) | x 4 | sum 4 6 | x 4 | | | y 6 | | | +-----------------+-------------+-------------+---------------+ +``` +```text +-----------------+-------------+-------------+---------------+ | | 'rank' | ['rank'] | {'x': 'rank'} | +-----------------+-------------+-------------+---------------+ diff --git a/index.html b/index.html index 3a7a6b23f..f2160f31b 100644 --- a/index.html +++ b/index.html @@ -435,7 +435,7 @@ ┗━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━┛
    -
    
    +
     
    • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
    • This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
    • @@ -2592,6 +2592,7 @@ ┃ sr.transform(…) │ y 2 │ y 2 │ y 2 ┃ ┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    +
    • Last result has a hierarchical index. Use '<Sr>[key_1, key_2]' to get its values.
    @@ -2692,6 +2693,7 @@ ┃ │ │ b 2 2 │ ┃ ┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛
    +
    • Use '<DF>[col_key_1, col_key_2][row_key]' to get the fifth result's values.
    diff --git a/parse.js b/parse.js index 41c707851..e84051f12 100755 --- a/parse.js +++ b/parse.js @@ -331,6 +331,9 @@ const DIAGRAM_13_B = "┃ sr.transform(…) │ y 2 │ y 2 │ y 2 ┃\n" + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; +const DIAGRAM_14_A = + "| | 'rank' | ['rank'] | {'r': 'rank'} |"; + const DIAGRAM_15_A = '+------------------------+---------------+------------+------------+--------------------------+'; @@ -386,6 +389,9 @@ const DIAGRAM_16_B = "┃ │ │ b 2 2 │ ┃\n" + "┗━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━┛\n"; +const DIAGRAM_17_A = + "| | 'rank' | ['rank'] | {'x': 'rank'} |"; + const DIAGRAM_18_A = '| gb.agg(…) | x y | x y | x y | x |'; @@ -515,7 +521,7 @@ function updateDiagrams() { $(`code:contains(${DIAGRAM_2_A})`).html(DIAGRAM_2_B); $(`code:contains(${DIAGRAM_3_A})`).html(DIAGRAM_3_B); $(`code:contains(${DIAGRAM_4_A})`).html(DIAGRAM_4_B); - $(`code:contains(${DIAGRAM_5_A})`).remove(); + $(`code:contains(${DIAGRAM_5_A})`).parent().remove(); $(`code:contains(${DIAGRAM_6_A})`).html(DIAGRAM_6_B); $(`code:contains(${DIAGRAM_7_A})`).html(DIAGRAM_7_B); $(`code:contains(${DIAGRAM_8_A})`).html(DIAGRAM_8_B); @@ -524,8 +530,10 @@ function updateDiagrams() { $(`code:contains(${DIAGRAM_11_A})`).html(DIAGRAM_11_B); $(`code:contains(${DIAGRAM_12_A})`).html(DIAGRAM_12_B).removeClass("text").removeClass("language-text").addClass("python"); $(`code:contains(${DIAGRAM_13_A})`).html(DIAGRAM_13_B).removeClass("text").removeClass("language-text").addClass("python"); + $(`code:contains(${DIAGRAM_14_A})`).parent().remove(); $(`code:contains(${DIAGRAM_15_A})`).html(DIAGRAM_15_B).removeClass("text").removeClass("language-text").addClass("python"); $(`code:contains(${DIAGRAM_16_A})`).html(DIAGRAM_16_B).removeClass("text").removeClass("language-text").addClass("python"); + $(`code:contains(${DIAGRAM_17_A})`).parent().remove(); $(`code:contains(${DIAGRAM_18_A})`).html(DIAGRAM_18_B).removeClass("text").removeClass("language-text").addClass("python"); } From ff47ccf096fb88657048ee16df1e898cbb36bcb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 10 Jun 2022 03:25:36 +0200 Subject: [PATCH 061/638] Datetime --- README.md | 8 ++++---- index.html | 12 ++++++------ 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index aef51702b..8d619a999 100644 --- a/README.md +++ b/README.md @@ -604,7 +604,7 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary
    = datetime(year, month, day, hour=0, minute=0, second=0, ...) = timedelta(weeks=0, days=0, hours=0, minutes=0, seconds=0, ...) ``` -* **Use `'.weekday()'` to get the day of the week (Mon == 0).** +* **Use `'.weekday()'` to get the day of the week as an int, with Monday being 0.** * **`'fold=1'` means the second pass in case of time jumping back for one hour.** * **Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).** @@ -633,16 +633,16 @@ from dateutil.tz import UTC, tzlocal, gettz, datetime_exists, resolve_imaginary = DT.fromtimestamp() # Local time DTn from seconds since the Epoch. = DT.fromtimestamp(, ) # Aware datetime from seconds since the Epoch. ``` -* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by an arbitrary character. Offset is formatted as: `'HH:MM'`.** +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.mmmuuu[±HH:MM]'`, or both separated by an arbitrary character. All parts following hours are optional.** * **Python uses the Unix Epoch: `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** ### Decode ```python - = .isoformat(sep='T') # Also timespec='auto/hours/minutes/seconds'. + = .isoformat(sep='T') # Also timespec='auto/hours/minutes/seconds/…'. = .strftime('') # Custom string representation. = .toordinal() # Days since Gregorian NYE 1, ignoring time and tz. = .timestamp() # Seconds since the Epoch, from DTn in local tz. - = .timestamp() # Seconds since the Epoch, from DTa. + = .timestamp() # Seconds since the Epoch, from aware datetime. ``` ### Format diff --git a/index.html b/index.html index f2160f31b..c28a2c30e 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -536,7 +536,7 @@
      -
    • Use '<D/DT>.weekday()' to get the day of the week (Mon == 0).
    • +
    • Use '<D/DT>.weekday()' to get the day of the week as an int, with Monday being 0.
    • 'fold=1' means the second pass in case of time jumping back for one hour.
    • Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M).
    @@ -563,14 +563,14 @@
      -
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.ffffff[±<offset>]', or both separated by an arbitrary character. Offset is formatted as: 'HH:MM'.
    • +
    • ISO strings come in following forms: 'YYYY-MM-DD', 'HH:MM:SS.mmmuuu[±HH:MM]', or both separated by an arbitrary character. All parts following hours are optional.
    • Python uses the Unix Epoch: '1970-01-01 00:00 UTC', '1970-01-01 01:00 CET', …
    -

    Decode

    <str>    = <D/T/DT>.isoformat(sep='T')      # Also timespec='auto/hours/minutes/seconds'.
    +

    Decode

    <str>    = <D/T/DT>.isoformat(sep='T')      # Also timespec='auto/hours/minutes/seconds/…'.
     <str>    = <D/T/DT>.strftime('<format>')    # Custom string representation.
     <int>    = <D/DT>.toordinal()               # Days since Gregorian NYE 1, ignoring time and tz.
     <float>  = <DTn>.timestamp()                # Seconds since the Epoch, from DTn in local tz.
    -<float>  = <DTa>.timestamp()                # Seconds since the Epoch, from DTa.
    +<float>  = <DTa>.timestamp()                # Seconds since the Epoch, from aware datetime.
     

    Format

    >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +2000', '%Y-%m-%d %H:%M:%S.%f %z')
    @@ -2901,7 +2901,7 @@
      
     
       
     
    
    From babfda1dc9be144daf51affedb520020068838c7 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 11 Jun 2022 00:22:22 +0200
    Subject: [PATCH 062/638] Iterable duck types
    
    ---
     README.md  | 2 +-
     index.html | 6 +++---
     2 files changed, 4 insertions(+), 4 deletions(-)
    
    diff --git a/README.md b/README.md
    index 8d619a999..6538b50b4 100644
    --- a/README.md
    +++ b/README.md
    @@ -1286,7 +1286,7 @@ class MySequence:
     ### 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, abc.Sequence)'` would return False even if MySequence had all the methods defined.**
    +* **Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why `'issubclass(MySequence, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes any list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.**
     ```python
     from collections import abc
     
    diff --git a/index.html b/index.html
    index c28a2c30e..aa72eaaee 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -1109,7 +1109,7 @@

    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, abc.Sequence)' would return False even if MySequence had all the methods defined.
    • +
    • Unlike 'abc.Iterable' and 'abc.Collection', it is not a duck type. That is why 'issubclass(MySequence, abc.Sequence)' would return False even if MySequence had all the methods defined. It however recognizes any list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.
    from collections import abc
     
     class MyAbcSequence(abc.Sequence):
    @@ -2901,7 +2901,7 @@
      
     
       
     
    
    From c901e88f7f626850a52a41469b3fee5855e86c4b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 11 Jun 2022 00:29:24 +0200
    Subject: [PATCH 063/638] Iterable duck types
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 6538b50b4..5304c5304 100644
    --- a/README.md
    +++ b/README.md
    @@ -1286,7 +1286,7 @@ class MySequence:
     ### 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, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes any list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.**
    +* **Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why `'issubclass(MySequence, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.**
     ```python
     from collections import abc
     
    diff --git a/index.html b/index.html
    index aa72eaaee..42c4be497 100644
    --- a/index.html
    +++ b/index.html
    @@ -1109,7 +1109,7 @@
     

    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, abc.Sequence)' would return False even if MySequence had all the methods defined. It however recognizes any list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.
    • +
    • Unlike 'abc.Iterable' and 'abc.Collection', it is not a duck type. That is why 'issubclass(MySequence, abc.Sequence)' would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.
    from collections import abc
     
     class MyAbcSequence(abc.Sequence):
    
    From e5a85b342479e30b9e2159fde5e13b7119613870 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 11 Jun 2022 00:43:12 +0200
    Subject: [PATCH 064/638] Iterable duck types
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 5304c5304..c5c45e7b8 100644
    --- a/README.md
    +++ b/README.md
    @@ -1286,7 +1286,7 @@ class MySequence:
     ### 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, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.**
    +* **Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why `'issubclass(MySequence, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray, memoryview and deque, because they are registered as Sequence's virtual subclasses.**
     ```python
     from collections import abc
     
    diff --git a/index.html b/index.html
    index 42c4be497..69b329bef 100644
    --- a/index.html
    +++ b/index.html
    @@ -1109,7 +1109,7 @@
     

    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, abc.Sequence)' would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray and memoryview, because they are registered as Sequence's virtual subclasses.
    • +
    • Unlike 'abc.Iterable' and 'abc.Collection', it is not a duck type. That is why 'issubclass(MySequence, abc.Sequence)' would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray, memoryview and deque, because they are registered as Sequence's virtual subclasses.
    from collections import abc
     
     class MyAbcSequence(abc.Sequence):
    
    From f505d0beff74ee48cb4507028c4a264124ebbaa6 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 11 Jun 2022 00:52:37 +0200
    Subject: [PATCH 065/638] Duck types
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index c5c45e7b8..7869e0de6 100644
    --- a/README.md
    +++ b/README.md
    @@ -1094,7 +1094,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 the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.**
    +* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented.**
     * **Ne() automatically works on any object that has eq() defined.**
     
     ```python
    diff --git a/index.html b/index.html
    index 69b329bef..05fe4ed3f 100644
    --- a/index.html
    +++ b/index.html
    @@ -923,7 +923,7 @@
     

    #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 the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.
    • +
    • Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented.
    • Ne() automatically works on any object that has eq() defined.
    class MyComparable:
         def __init__(self, a):
    
    From 4cfa709f76939d4c1ed4e22a9c266bf9a431487b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 11 Jun 2022 01:57:12 +0200
    Subject: [PATCH 066/638] OS Commands
    
    ---
     README.md  | 2 +-
     index.html | 2 +-
     2 files changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/README.md b/README.md
    index 7869e0de6..c53c48c12 100644
    --- a/README.md
    +++ b/README.md
    @@ -1708,7 +1708,7 @@ import os, shutil, subprocess
     ```python
     os.chdir()                 # Changes the current working directory.
     os.mkdir(, mode=0o777)     # Creates a directory. Mode is in octal.
    -os.makedirs(, mode=0o777)  # Creates dirs in path. Also: `exist_ok=False`.
    +os.makedirs(, mode=0o777)  # Creates all path's dirs. Also: `exist_ok=False`.
     ```
     
     ```python
    diff --git a/index.html b/index.html
    index 05fe4ed3f..c15930cef 100644
    --- a/index.html
    +++ b/index.html
    @@ -1440,7 +1440,7 @@
     
  • Functions report OS related errors by raising either OSError or one of its subclasses.
  • os.chdir(<path>)                 # Changes the current working directory.
     os.mkdir(<path>, mode=0o777)     # Creates a directory. Mode is in octal.
    -os.makedirs(<path>, mode=0o777)  # Creates dirs in path. Also: `exist_ok=False`.
    +os.makedirs(<path>, mode=0o777)  # Creates all path's dirs. Also: `exist_ok=False`.
     
    From 3b8d61d4c073bfa20a4292a88baeb85f4ca5fa51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 11 Jun 2022 02:04:25 +0200 Subject: [PATCH 067/638] NumPy --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c53c48c12..c28dff00c 100644 --- a/README.md +++ b/README.md @@ -2656,7 +2656,7 @@ indexes = .argmin(axis) ``` * **Shape is a tuple of dimension sizes.** -* **Axis is an index of the dimension that gets collapsed. Leftmost dimension has index 0.** +* **Axis is an index of the dimension that gets aggregated. Leftmost dimension has index 0.** ### Indexing ```bash diff --git a/index.html b/index.html index c15930cef..8a3eabb8e 100644 --- a/index.html +++ b/index.html @@ -2168,7 +2168,7 @@
    • Shape is a tuple of dimension sizes.
    • -
    • Axis is an index of the dimension that gets collapsed. Leftmost dimension has index 0.
    • +
    • Axis is an index of the dimension that gets aggregated. Leftmost dimension has index 0.

    Indexing

    <el>       = <2d_array>[row_index, column_index]
     <1d_view>  = <2d_array>[row_index]
    
    From a3a87e099ab0fcbad81ae26bbd6cc9212aa7436e Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 11 Jun 2022 02:15:08 +0200
    Subject: [PATCH 068/638] Format
    
    ---
     README.md  | 50 +++++++++++++++++++++++++-------------------------
     index.html | 50 +++++++++++++++++++++++++-------------------------
     2 files changed, 50 insertions(+), 50 deletions(-)
    
    diff --git a/README.md b/README.md
    index c28dff00c..4dbb9ee4b 100644
    --- a/README.md
    +++ b/README.md
    @@ -392,8 +392,8 @@ import re
     Format
     ------
     ```python
    - = f'{}, {}'        # Or: '{}, {}'.format(, )
    - = '%s, %s' % (, )  # Redundant and inferior C style formatting.
    + = f'{}, {}'            # Or: '{}, {}'.format(, )
    + = '%s, %s' % (, )      # Redundant and inferior C style formatting.
     ```
     
     ### Attributes
    @@ -409,40 +409,40 @@ Format
     
     ### General Options
     ```python
    -{:<10}                           # '      '
    -{:^10}                           # '      '
    -{:>10}                           # '      '
    -{:.<10}                          # '......'
    -{:0}                             # ''
    +{:<10}                               # '      '
    +{:^10}                               # '      '
    +{:>10}                               # '      '
    +{:.<10}                              # '......'
    +{:0}                                 # ''
     ```
     * **Options can be generated dynamically: `f'{:{}[…]}'`.**
     * **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.**
     
     ### Strings
     ```python
    -{'abcde':10}                         # 'abcde     '
    -{'abcde':10.3}                       # 'abc       '
    -{'abcde':.3}                         # 'abc'
    -{'abcde'!r:10}                       # "'abcde'   "
    +{'abcde':10}                             # 'abcde     '
    +{'abcde':10.3}                           # 'abc       '
    +{'abcde':.3}                             # 'abc'
    +{'abcde'!r:10}                           # "'abcde'   "
     ```
     
     ### Numbers
     ```python
    -{123456:10}                          # '    123456'
    -{123456:10,}                         # '   123,456'
    -{123456:10_}                         # '   123_456'
    -{123456:+10}                         # '   +123456'
    -{123456:=+10}                        # '+   123456'
    -{123456: }                           # ' 123456'
    -{-123456: }                          # '-123456'
    +{123456:10}                              # '    123456'
    +{123456:10,}                             # '   123,456'
    +{123456:10_}                             # '   123_456'
    +{123456:+10}                             # '   +123456'
    +{123456:=+10}                            # '+   123456'
    +{123456: }                               # ' 123456'
    +{-123456: }                              # '-123456'
     ```
     
     ### Floats
     ```python
    -{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%'
    +{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 presentation types:
    @@ -478,9 +478,9 @@ Format
     
     ### Ints
     ```python
    -{90:c}                               # 'Z'
    -{90:b}                               # '1011010'
    -{90:X}                               # '5A'
    +{90:c}                                   # 'Z'
    +{90:b}                                   # '1011010'
    +{90:X}                                   # '5A'
     ```
     
     
    diff --git a/index.html b/index.html
    index 8a3eabb8e..b6bef04c2 100644
    --- a/index.html
    +++ b/index.html
    @@ -365,8 +365,8 @@
     
  • As shown above, it restricts all special sequence matches to the first 128 characters and prevents '\s' from accepting '[\x1c-\x1f]' (the so-called separator characters).
  • Use a capital letter for negation (all non-ASCII characters will be matched when used in combination with ASCII flag).
  • -

    #Format

    <str> = f'{<el_1>}, {<el_2>}'        # Or: '{}, {}'.format(<el_1>, <el_2>)
    -<str> = '%s, %s' % (<el_1>, <el_2>)  # Redundant and inferior C style formatting.
    +

    #Format

    <str> = f'{<el_1>}, {<el_2>}'            # Or: '{}, {}'.format(<el_1>, <el_2>)
    +<str> = '%s, %s' % (<el_1>, <el_2>)      # Redundant and inferior C style formatting.
     

    Attributes

    >>> from collections import namedtuple
    @@ -378,36 +378,36 @@
     '187'
     
    -

    General Options

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

    General Options

    {<el>:<10}                               # '<el>      '
    +{<el>:^10}                               # '   <el>   '
    +{<el>:>10}                               # '      <el>'
    +{<el>:.<10}                              # '<el>......'
    +{<el>:0}                                 # '<el>'
     
    • Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
    • Adding '!r' before the colon converts object to string by calling its repr() method.
    -

    Strings

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

    Strings

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

    Numbers

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

    Numbers

    {123456:10}                              # '    123456'
    +{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'
    -{1.23456:10.3f}                      # '     1.235'
    -{1.23456:10.3e}                      # ' 1.235e+00'
    -{1.23456:10.3%}                      # '  123.456%'
    +

    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 presentation types:

    ┏━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━┓
    @@ -440,9 +440,9 @@
     
  • When both rounding up and rounding down are possible, the one that returns result with even last digit is chosen. That makes '{6.5:.0f}' a '6' and '{7.5:.0f}' an '8'.
  • This rule only effects numbers that can be represented exactly by a float (.5, .25, …).
  • -

    Ints

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

    Ints

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

    #Numbers

    <int>      = int(<float/str/bool>)       # Or: math.floor(<float>)
    
    From d97a2158622b4f0b65ddf0ec223f6f9d0de4c7ed Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Tue, 14 Jun 2022 20:51:24 +0200
    Subject: [PATCH 069/638] Command line arguments, Struct, MemoryView
    
    ---
     README.md  | 33 ++++++++++++++++-----------------
     index.html | 48 +++++++++++++++++++++++++-----------------------
     parse.js   | 18 ++++++++++++++++++
     3 files changed, 59 insertions(+), 40 deletions(-)
    
    diff --git a/README.md b/README.md
    index 4dbb9ee4b..92254ab5b 100644
    --- a/README.md
    +++ b/README.md
    @@ -1546,7 +1546,7 @@ value = args.
     
     * **Use `'help='` to set argument description that will be displayed in help message.**
     * **Use `'default='` to set the default value.**
    -* **Use `'type=FileType()'` for files. Also accepts 'encoding', but not 'newline'.**
    +* **Use `'type=FileType()'` for files. Accepts 'encoding', but 'newline' is always None.**
     
     
     Open
    @@ -1672,7 +1672,7 @@ from pathlib import Path
     ```python
      = Path()                     # Returns relative cwd. Also Path('.').
      = Path.cwd()                 # Returns absolute cwd. Also Path().resolve().
    - = Path.home()                # Returns user's home directory.
    + = Path.home()                # Returns user's home directory (absolute).
      = Path(__file__).resolve()   # Returns script's path if cwd wasn't changed.
     ```
     
    @@ -1828,13 +1828,13 @@ import csv
     * **File must be opened with a `'newline=""'` argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!**
     
     ### Parameters
    -* **`'dialect'` - Master parameter that sets the default values. String or a dialect object.**
    +* **`'dialect'` - Master parameter that sets the default values. String or a Dialect object.**
     * **`'delimiter'` - A one-character string used to separate fields.**
     * **`'quotechar'` - Character for quoting fields that contain special characters.**
     * **`'doublequote'` - Whether quotechars inside fields are/get doubled or escaped.**
     * **`'skipinitialspace'` - Whether whitespace after delimiter gets stripped by reader.**
     * **`'lineterminator'` - How writer terminates rows. Reader is hardcoded to '\n', '\r', '\r\n'.**
    -* **`'quoting'` - Controls the amount of quoting: 0 - as necessary, 1 - all.**
    +* **`'quoting'` - 0: As necessary, 1: All, 2: All but numbers which are read as floats, 3: None.**
     * **`'escapechar'` - Character for escaping quotechars if doublequote is False.**
     
     ### Dialects
    @@ -1982,16 +1982,11 @@ Struct
     * **System’s type sizes, byte order, and alignment rules are used by default.**
     
     ```python
    -from struct import pack, unpack, iter_unpack
    +from struct import pack, unpack
    + = pack('',  [, ...])  # Packages arguments into bytes object.
    + = unpack('', )     # Use iter_unpack() for iterator of tuples.
     ```
     
    -```python
    -  = pack('',  [, , ...])
    -  = unpack('', )
    - = iter_unpack('', )
    -```
    -
    -### Example
     ```python
     >>> pack('>hhl', 1, 2, 3)
     b'\x00\x01\x00\x02\x00\x00\x00\x03'
    @@ -2001,12 +1996,15 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03'
     
     ### Format
     #### For standard type sizes and manual alignment (padding) start format string with:
    -* **`'='` - system's byte order (usually little-endian)**
    -* **`'<'` - little-endian**
    -* **`'>'` - big-endian (also `'!'`)**
    +* **`'='` - System's byte order (usually little-endian).**
    +* **`'<'` - Little-endian.**
    +* **`'>'` - Big-endian (also `'!'`).**
    +
    +#### Besides numbers, pack() and unpack() also support bytes objects as part of the seqence:
    +* **`'c'` - A bytes object with single element. Use `'x'` for pad byte.**
    +* **`'s'` - A bytes object with n elements.**
     
     #### Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:
    -* **`'x'` - pad byte**
     * **`'b'` - char (1/1)**
     * **`'h'` - short (2/2)**
     * **`'i'` - int (2/4)**
    @@ -2037,7 +2035,8 @@ Memory View
     * **A sequence object that points to the memory of another object.**
     * **Each element can reference a single or multiple consecutive bytes, depending on format.**
     * **Order and number of elements can be changed with slicing.**
    -* **Casting only works between char and other types and uses system's sizes and byte order.**
    +* **Casting only works between char and other types and uses system's sizes.**
    +* **Byte order is always determined by the system.**
     
     ```python
      = memoryview()  # Immutable if bytes, else mutable.
    diff --git a/index.html b/index.html
    index b6bef04c2..2007bd37f 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -1322,7 +1322,7 @@
    • Use 'help=<str>' to set argument description that will be displayed in help message.
    • Use 'default=<el>' to set the default value.
    • -
    • Use 'type=FileType(<mode>)' for files. Also accepts 'encoding', but not 'newline'.
    • +
    • Use 'type=FileType(<mode>)' for files. Accepts 'encoding', but 'newline' is always None.

    #Open

    Opens the file and returns a corresponding file object.

    <file> = open(<path>, mode='r', encoding=None, newline=None)
     
    @@ -1417,7 +1417,7 @@
    <Path> = Path()                     # Returns relative cwd. Also Path('.').
     <Path> = Path.cwd()                 # Returns absolute cwd. Also Path().resolve().
    -<Path> = Path.home()                # Returns user's home directory.
    +<Path> = Path.home()                # Returns user's home directory (absolute).
     <Path> = Path(__file__).resolve()   # Returns script's path if cwd wasn't changed.
     
    <Path> = <Path>.parent              # Returns Path without the final component.
    @@ -1526,13 +1526,13 @@
     
  • File must be opened with a 'newline=""' argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!
  • Parameters

      -
    • 'dialect' - Master parameter that sets the default values. String or a dialect object.
    • +
    • 'dialect' - Master parameter that sets the default values. String or a Dialect object.
    • 'delimiter' - A one-character string used to separate fields.
    • 'quotechar' - Character for quoting fields that contain special characters.
    • 'doublequote' - Whether quotechars inside fields are/get doubled or escaped.
    • 'skipinitialspace' - Whether whitespace after delimiter gets stripped by reader.
    • 'lineterminator' - How writer terminates rows. Reader is hardcoded to '\n', '\r', '\r\n'.
    • -
    • 'quoting' - Controls the amount of quoting: 0 - as necessary, 1 - all.
    • +
    • 'quoting' - 0: As necessary, 1: All, 2: All but numbers which are read as floats, 3: None.
    • 'escapechar' - Character for escaping quotechars if doublequote is False.

    Dialects

    ┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
     ┃                  │     excel    │   excel-tab  │     unix     ┃
    @@ -1643,26 +1643,25 @@
     

    #Struct

    • Module that performs conversions between a sequence of numbers and a bytes object.
    • System’s type sizes, byte order, and alignment rules are used by default.
    • -
    from struct import pack, unpack, iter_unpack
    +
    from struct import pack, unpack
    +<bytes> = pack('<format>', <el> [, ...])  # Packages arguments into bytes object.
    +<tuple> = unpack('<format>', <bytes>)     # Use iter_unpack() for iterator of tuples.
     
    -
    <bytes>  = pack('<format>', <num_1> [, <num_2>, ...])
    -<tuple>  = unpack('<format>', <bytes>)
    -<tuples> = iter_unpack('<format>', <bytes>)
    -
    -

    Example

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

    Format

    For standard type sizes and manual alignment (padding) start format string with:

      -
    • '=' - system's byte order (usually little-endian)
    • -
    • '<' - little-endian
    • -
    • '>' - big-endian (also '!')
    • -

    Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:

      -
    • 'x' - pad byte
    • +
    +

    Format

    For standard type sizes and manual alignment (padding) start format string with:

      +
    • '=' - System's byte order (usually little-endian).
    • +
    • '<' - Little-endian.
    • +
    • '>' - Big-endian (also '!').
    • +

    Besides numbers, pack() and unpack() also support bytes objects as part of the seqence:

      +
    • 'c' - A bytes object with single element. Use 'x' for pad byte.
    • +
    • '<n>s' - A bytes object with n elements.
    • +

    Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:

    • 'b' - char (1/1)
    • 'h' - short (2/2)
    • 'i' - int (2/4)
    • @@ -1671,7 +1670,9 @@

    Floating point types:

    • 'f' - float (4/4)
    • 'd' - double (8/8)
    • -
    +
    + + @@ -1691,7 +1692,8 @@
  • A sequence object that points to the memory of another object.
  • Each element can reference a single or multiple consecutive bytes, depending on format.
  • Order and number of elements can be changed with slicing.
  • -
  • Casting only works between char and other types and uses system's sizes and byte order.
  • +
  • Casting only works between char and other types and uses system's sizes.
  • +
  • Byte order is always determined by the system.
  • <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes, else mutable.
     <real>  = <mview>[<index>]                     # Returns an int or a float.
     <mview> = <mview>[<slice>]                     # Mview with rearranged elements.
    @@ -2195,7 +2197,7 @@
     right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]]  # Shape: (3, 3) <- !
     
    -

    3. If neither non-matching dimension has size 1, raise 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, raise 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],
    @@ -2901,7 +2903,7 @@
      
     
       
     
    diff --git a/parse.js b/parse.js
    index e84051f12..d4ecd754b 100755
    --- a/parse.js
    +++ b/parse.js
    @@ -76,6 +76,9 @@ const OS_RENAME =
       'os.rename(from, to)              # Renames/moves the file or directory.\n' +
       'os.replace(from, to)             # Same, but overwrites \'to\' if it exists.\n';
     
    +const STRUCT_FORMAT =
    +  '\'<n>s\'';
    +
     const TYPE =
       '<class> = type(\'<class_name>\', <tuple_of_parents>, <dict_of_class_attributes>)';
     
    @@ -478,6 +481,7 @@ function modifyPage() {
       fixPandasDiagram();
       removePlotImages();
       fixABCSequenceDiv();
    +  fixStructFormatDiv();
     }
     
     function changeMenu() {
    @@ -569,6 +573,7 @@ function fixHighlights() {
       $(`code:contains(make_dataclass(\'\')`).html(DATACLASS);
       $(`code:contains(shutil.copy)`).html(SHUTIL_COPY);
       $(`code:contains(os.rename)`).html(OS_RENAME);
    +  $(`code:contains(\'s\')`).html(STRUCT_FORMAT);
       $(`code:contains(\'\', , )`).html(TYPE);
       $(`code:contains(ValueError: malformed node)`).html(EVAL);
       $(`code:contains(pip3 install tqdm)`).html(PROGRESS_BAR);
    @@ -633,6 +638,19 @@ function fixABCSequenceDiv() {
       $('#abcsequence').parent().insertBefore($('#tableofrequiredandautomaticallyavailablespecialmethods').parent())
     }
     
    +function fixStructFormatDiv() {
    +  const div = $('#format-2').parent()
    +  $('#format-2').insertBefore(div)
    +  $('#forstandardtypesizesandmanualalignmentpaddingstartformatstringwith').parent().insertBefore(div)
    +}
    +
    +
    +function fixStructFormat() {
    +  const div = $('#format-2').parent()
    +  $('#format-2').insertBefore(div)
    +  $('#forstandardtypesizesandmanualalignmentpaddingstartformatstringwith').parent().insertBefore(div)
    +}
    +
     function updateDate(template) {
       const date = new Date();
       const date_str = date.toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'});
    
    From bb44b25b23b5d888852bf94203c1ec5c3cb06108 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Wed, 15 Jun 2022 02:53:31 +0200
    Subject: [PATCH 070/638] Command line arguments, OS Commands
    
    ---
     README.md  |  8 +++-----
     index.html | 19 +++++++++----------
     2 files changed, 12 insertions(+), 15 deletions(-)
    
    diff --git a/README.md b/README.md
    index 92254ab5b..6a7a184d2 100644
    --- a/README.md
    +++ b/README.md
    @@ -1546,7 +1546,7 @@ value = args.
     
     * **Use `'help='` to set argument description that will be displayed in help message.**
     * **Use `'default='` to set the default value.**
    -* **Use `'type=FileType()'` for files. Accepts 'encoding', but 'newline' is always None.**
    +* **Use `'type=FileType()'` for files. Accepts 'encoding', but not 'newline'.**
     
     
     Open
    @@ -1701,10 +1701,6 @@ OS Commands
     import os, shutil, subprocess
     ```
     
    -### Files and Directories
    -* **Paths can be either strings, Paths or DirEntry objects.**
    -* **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).**
    -
     ```python
     os.chdir()                 # Changes the current working directory.
     os.mkdir(, mode=0o777)     # Creates a directory. Mode is in octal.
    @@ -1726,6 +1722,8 @@ os.remove()                # Deletes the file.
     os.rmdir()                 # Deletes the empty directory.
     shutil.rmtree()            # Deletes the directory.
     ```
    +* **Paths can be either strings, Paths or DirEntry objects.**
    +* **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).**
     
     ### Shell Commands
     ```python
    diff --git a/index.html b/index.html
    index 2007bd37f..3b580390d 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -1322,7 +1322,7 @@
    • Use 'help=<str>' to set argument description that will be displayed in help message.
    • Use 'default=<el>' to set the default value.
    • -
    • Use 'type=FileType(<mode>)' for files. Accepts 'encoding', but 'newline' is always None.
    • +
    • Use 'type=FileType(<mode>)' for files. Accepts 'encoding', but not 'newline'.

    #Open

    Opens the file and returns a corresponding file object.

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

    #OS Commands

    import os, shutil, subprocess
     
    -

    Files and Directories

      -
    • Paths can be either strings, Paths or DirEntry objects.
    • -
    • Functions report OS related errors by raising either OSError or one of its subclasses.
    • -
    os.chdir(<path>)                 # Changes the current working directory.
    +
    os.chdir(<path>)                 # Changes the current working directory.
     os.mkdir(<path>, mode=0o777)     # Creates a directory. Mode is in octal.
     os.makedirs(<path>, mode=0o777)  # Creates all path's dirs. Also: `exist_ok=False`.
    -
    - - +
    shutil.copy(from, to)            # Copies the file. 'to' can exist or be a dir.
     shutil.copytree(from, to)        # Copies the directory. 'to' must not exist.
     
    @@ -1454,6 +1449,10 @@ os.rmdir(<path>) # Deletes the empty directory. shutil.rmtree(<path>) # Deletes the directory.
    +
      +
    • Paths can be either strings, Paths or DirEntry objects.
    • +
    • Functions report OS related errors by raising either OSError or one of its subclasses.
    • +

    Shell Commands

    <pipe> = os.popen('<command>')   # Executes command in sh/cmd and returns its stdout pipe.
     <str>  = <pipe>.read(size=-1)    # Reads 'size' chars or until EOF. Also readline/s().
     <int>  = <pipe>.close()          # Closes the pipe. Returns None on success, int on error.
    @@ -2903,7 +2902,7 @@ 

    Format

    -

    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 the function is called.

    from functools import wraps
     
     def debug(func):
         @wraps(func)
    @@ -1559,7 +1559,7 @@
             writer.writerows(rows)
     
    -

    #SQLite

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

    Connect

    Opens a connection to the database file. Creates a new file if path doesn't exist.

    import sqlite3
    +

    #SQLite

    A server-less database engine that stores each database into a separate file.

    Connect

    Opens a connection to the database file. Creates a new file if path doesn't exist.

    import sqlite3
     <conn> = sqlite3.connect(<path>)                # Also ':memory:'.
     <conn>.close()                                  # Closes the connection.
     
    @@ -1643,8 +1643,8 @@
  • Module that performs conversions between a sequence of numbers and a bytes object.
  • System’s type sizes, byte order, and alignment rules are used by default.
  • from struct import pack, unpack
    -<bytes> = pack('<format>', <el> [, ...])  # Packages arguments into bytes object.
    -<tuple> = unpack('<format>', <bytes>)     # Use iter_unpack() for iterator of tuples.
    +<bytes> = pack('<format>', <el_1> [, ...])  # Packages arguments into bytes object.
    +<tuple> = unpack('<format>', <bytes>)       # Use iter_unpack() for iterator of tuples.
     
    @@ -1658,7 +1658,7 @@

    Format

    '<' - Little-endian.
  • '>' - Big-endian (also '!').
  • Besides numbers, pack() and unpack() also support bytes objects as part of the seqence:

      -
    • 'c' - A bytes object with single element. Use 'x' for pad byte.
    • +
    • 'c' - A bytes object with a single element. Use 'x' for pad byte.
    • '<n>s' - A bytes object with n elements.

    Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets:

    • 'b' - char (1/1)
    • @@ -2902,7 +2902,7 @@

      Format

    @@ -1266,11 +1267,8 @@ raise RuntimeError('None of above!')
    -

    User-defined Exceptions

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

    User-defined Exceptions

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

    #Exit

    Exits the interpreter by raising SystemExit exception.

    import sys
    @@ -2902,7 +2900,7 @@ 

    Format

    -

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

    +

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

    >>> C.mro()
     [<class 'C'>, <class 'A'>, <class 'B'>, <class 'object'>]
     
    From 1ea542ca1931d5bea6b8cfde8fc355eec88f46c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 17 Jun 2022 22:42:49 +0200 Subject: [PATCH 075/638] Class --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 089a718a6..18072d666 100644 --- a/README.md +++ b/README.md @@ -1815,7 +1815,7 @@ import csv ``` * **File must be opened with a `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!** * **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#dataframe-plot-encode-decode) library.** -* **To print the table to console use [Tabulate](#table) library.** +* **To print the table to the console use [Tabulate](#table) library.** ### Write ```python diff --git a/index.html b/index.html index 2bc7ae5d1..d4ef62a8c 100644 --- a/index.html +++ b/index.html @@ -1514,7 +1514,7 @@
    • File must be opened with a 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
    • -
    • To print the table to console use Tabulate library.
    • +
    • To print the table to the console use Tabulate library.

    Write

    <writer> = csv.writer(<file>)       # Also: `dialect='excel', delimiter=','`.
     <writer>.writerow(<collection>)     # Encodes objects using `str(<el>)`.
    
    From 96d976786e6b6849e5545baf3c04c9ea85b00868 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sun, 19 Jun 2022 04:27:28 +0200
    Subject: [PATCH 076/638] Arguments
    
    ---
     README.md           |  6 +++---
     index.html          | 10 +++++-----
     pdf/remove_links.py |  2 +-
     3 files changed, 9 insertions(+), 9 deletions(-)
    
    diff --git a/README.md b/README.md
    index 18072d666..2c4122ffe 100644
    --- a/README.md
    +++ b/README.md
    @@ -679,8 +679,8 @@ def f():                      # def f(x, y):
     def f():                         # def f(x=0, y=0):
     def f(, ):      # def f(x, y=0):
     ```
    -* **A function has its default values evaluated when it's first encountered in the scope.**
    -* **Any changes to default values that are mutable will persist between invocations.**
    +* **Value of a default argument is evaluated when function is first encountered in the scope.**
    +* **If this value is a mutable object, then all its mutations will persist between invocations.**
     
     
     Splat Operator
    @@ -1814,8 +1814,8 @@ import csv
        = list()           # Returns a list of remaining rows.
     ```
     * **File must be opened with a `'newline=""'` argument, or newlines embedded inside quoted fields will not be interpreted correctly!**
    -* **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#dataframe-plot-encode-decode) library.**
     * **To print the table to the console use [Tabulate](#table) library.**
    +* **For XML and binary Excel files (xlsx, xlsm and xlsb) use [Pandas](#dataframe-plot-encode-decode) library.**
     
     ### Write
     ```python
    diff --git a/index.html b/index.html
    index d4ef62a8c..f4b182168 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -601,8 +601,8 @@
      -
    • A function has its default values evaluated when it's first encountered in the scope.
    • -
    • Any changes to default values that are mutable will persist between invocations.
    • +
    • Value of a default argument is evaluated when function is first encountered in the scope.
    • +
    • If this value is a mutable object, then all its mutations will persist between invocations.

    #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}
    @@ -1513,8 +1513,8 @@
     
     
    • File must be opened with a 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!
    • -
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.
    • To print the table to the console use Tabulate library.
    • +
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.

    Write

    <writer> = csv.writer(<file>)       # Also: `dialect='excel', delimiter=','`.
     <writer>.writerow(<collection>)     # Encodes objects using `str(<el>)`.
    @@ -2902,7 +2902,7 @@ 

    Format

      -
    • Value of a default argument is evaluated when function is first encountered in the scope.
    • -
    • If this value is a mutable object, then all its mutations will persist between invocations.
    • +
    • Default values are evaluated when function is first encountered in the scope.
    • +
    • Any mutations of mutable default values will persist between invocations.

    #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}
    
    From e7c1d50e067732a6fe7e91ff405c21c4e610b61c Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Mon, 20 Jun 2022 22:20:07 +0200
    Subject: [PATCH 078/638] A lot of changes in Arguments and Inline
    
    ---
     README.md  | 66 ++++++++++++++++++++++----------------------
     index.html | 80 +++++++++++++++++++++++++++---------------------------
     2 files changed, 73 insertions(+), 73 deletions(-)
    
    diff --git a/README.md b/README.md
    index 5b1ae77a2..950b10575 100644
    --- a/README.md
    +++ b/README.md
    @@ -668,16 +668,16 @@ Arguments
     ---------
     ### Inside Function Call
     ```python
    -()                  # f(0, 0)
    -()                     # f(x=0, y=0)
    -(, )  # f(0, y=0)
    +func()                           # func(1, 2)
    +func()                              # func(x=1, y=2)
    +func(, )           # func(1, y=2)
     ```
     
     ### 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 func(): ...                  # def func(x, y): ...
    +def func(): ...                     # def func(x=0, y=0): ...
    +def func(, ): ...  # def func(x, y=0): ...
     ```
     * **Default values are evaluated when function is first encountered in the scope.**
     * **Any mutations of mutable default values will persist between invocations.**
    @@ -712,39 +712,39 @@ def add(*a):
     
     #### Legal argument combinations:
     ```python
    -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(*, 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)
    -def f(*args, z):            # 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)
     ```
     
     ```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)
    +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
    -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)
    -def f(*args, y, **kwargs):  # f(x=1, y=2, z=3) | f(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)
    +def f(*args, y, **kwargs): ...  # f(x=1, y=2, z=3) | f(1, y=2, z=3)
     ```
     
     ### Other Uses
     ```python
    -  = [* [, ...]]
    -   = {* [, ...]}
    - = (*, [...])
    -  = {** [, ...]}
    +  = [* [, ...]]    # Or: list() [+ ...]
    + = (*, [...])     # Or: tuple() [+ ...]
    +   = {* [, ...]}    # Or: set() [| ...]
    +  = {** [, ...]}    # Or: dict(** [, ...])
     ```
     
     ```python
    -head, *body, tail = 
    +head, *body, tail =      # Also `head, *body = ` and `*body, tail = `.
     ```
     
     
    @@ -752,16 +752,16 @@ Inline
     ------
     ### Lambda
     ```python
    - = lambda: 
    - = lambda , : 
    + = lambda:                            # A single statement function.
    + = lambda , :           # Also accepts default arguments.
     ```
     
     ### Comprehensions
     ```python
    - = [i+1 for i in range(10)]                         # [1, 2, ..., 10]
    -  = {i for i in range(10) if i > 5}                  # {6, 7, 8, 9}
    - = (i+5 for i in range(10))                         # (5, 6, ..., 14)
    - = {i: i*2 for i in range(10)}                      # {0: 0, 1: 2, ..., 9: 18}
    + = [i+1 for i in range(10)]                         # Or: [1, 2, ..., 10]
    + = (i for i in range(10) if i > 5)                  # Or: iter([6, 7, 8, 9])
    +  = {i+5 for i in range(10)}                         # Or: {5, 6, ..., 14}
    + = {i: i*2 for i in range(10)}                      # Or: {0: 0, 1: 2, ..., 9: 18}
     ```
     
     ```python
    @@ -771,9 +771,9 @@ Inline
     
     ### Map, Filter, Reduce
     ```python
    - = map(lambda x: x + 1, range(10))                  # (1, 2, ..., 10)
    - = filter(lambda x: x > 5, range(10))               # (6, 7, 8, 9)
    -  = reduce(lambda out, x: out + x, range(10))        # 45
    + = map(lambda x: x + 1, range(10))                  # Or: iter([1, 2, ..., 10])
    + = filter(lambda x: x > 5, range(10))               # Or: iter([6, 7, 8, 9])
    +  = reduce(lambda out, x: out + x, range(10))        # Or: 45
     ```
     * **Reduce must be imported from the functools module.**
     
    @@ -1064,7 +1064,7 @@ from dataclasses import make_dataclass
     
     #### Rest of type annotations (CPython interpreter ignores them all):
     ```python
    -def func(:  [= ]) -> :
    +def func(:  [= ]) -> : ...
     : typing.List/Set/Iterable/Sequence/Optional[]
     : typing.Dict/Tuple/Union[, ...]
     ```
    diff --git a/index.html b/index.html
    index 8c71ccd11..da52fc716 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -589,15 +589,15 @@ <float> = <TD> / <TD> # How many weeks/years there are in TD. Also //.
    -

    #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)
    +

    #Arguments

    Inside Function Call

    func(<positional_args>)                           # func(1, 2)
    +func(<keyword_args>)                              # func(x=1, y=2)
    +func(<positional_args>, <keyword_args>)           # func(1, y=2)
     
    -

    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):
    +

    Inside Function Definition

    def func(<nondefault_args>): ...                  # def func(x, y): ...
    +def func(<default_args>): ...                     # def func(x=0, y=0): ...
    +def func(<nondefault_args>, <default_args>): ...  # def func(x, y=0): ...
     
      @@ -622,48 +622,48 @@
      >>> add(1, 2, 3)
       6
       
      -

      Legal argument combinations:

      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)
      +

      Legal argument combinations:

      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)
      +
      def f(*args): ...               # f(1, 2, 3)
      +def f(x, *args): ...            # f(1, 2, 3)
      +def f(*args, z): ...            # f(1, 2, z=3)
       
      -
      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(**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)
      -def f(*args, y, **kwargs):  # f(x=1, y=2, z=3) | f(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)
      +def f(*args, y, **kwargs): ...  # f(x=1, y=2, z=3) | f(1, y=2, z=3)
       
      -

      Other Uses

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

      Other Uses

      <list>  = [*<coll.> [, ...]]    # Or: list(<collection>) [+ ...]
      +<tuple> = (*<coll.>, [...])     # Or: tuple(<collection>) [+ ...]
      +<set>   = {*<coll.> [, ...]}    # Or: set(<collection>) [| ...]
      +<dict>  = {**<dict> [, ...]}    # Or: dict(**<dict> [, ...])
       
      -
      head, *body, tail = <collection>
      +
      head, *body, tail = <coll.>     # Also `head, *body = <coll.>` and `*body, tail = <coll.>`.
       
      -

      #Inline

      Lambda

      <func> = lambda: <return_value>
      -<func> = lambda <arg_1>, <arg_2>: <return_value>
      +

      #Inline

      Lambda

      <func> = lambda: <return_value>                           # A single statement function.
      +<func> = lambda <arg_1>, <arg_2>: <return_value>          # Also accepts default arguments.
       
      -

      Comprehensions

      <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}
      +

      Comprehensions

      <list> = [i+1 for i in range(10)]                         # Or: [1, 2, ..., 10]
      +<iter> = (i for i in range(10) if i > 5)                  # Or: iter([6, 7, 8, 9])
      +<set>  = {i+5 for i in range(10)}                         # Or: {5, 6, ..., 14}
      +<dict> = {i: i*2 for i in range(10)}                      # Or: {0: 0, 1: 2, ..., 9: 18}
       
      >>> [l+r for l in 'abc' for r in 'abc']
       ['aa', 'ab', 'ac', ..., 'cc']
       
      -

      Map, Filter, Reduce

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

      Map, Filter, Reduce

      <iter> = map(lambda x: x + 1, range(10))                  # Or: iter([1, 2, ..., 10])
      +<iter> = filter(lambda x: x > 5, range(10))               # Or: iter([6, 7, 8, 9])
      +<obj>  = reduce(lambda out, x: out + x, range(10))        # Or: 45
       
        @@ -903,7 +903,7 @@ <class> = make_dataclass('<class_name>', <coll_of_tuples>) <tuple> = ('<attr_name>', <type> [, <default_value>])
      -

      Rest of type annotations (CPython interpreter ignores them all):

      def func(<arg_name>: <type> [= <obj>]) -> <type>:
      +

      Rest of type annotations (CPython interpreter ignores them all):

      def func(<arg_name>: <type> [= <obj>]) -> <type>: ...
       <var_name>: typing.List/Set/Iterable/Sequence/Optional[<type>]
       <var_name>: typing.Dict/Tuple/Union[<type>, ...]
       
      @@ -2370,7 +2370,8 @@

      Format

      'test.wav', samples_f)

      -

      Plays a WAV file:

      # $ pip3 install simpleaudio
      +

      Plays a WAV file:

      # $ sudo apt install libasound2-dev
      +# $ pip3 install simpleaudio
       from simpleaudio import play_buffer
       with wave.open('test.wav', 'rb') as file:
           p = file.getparams()
      @@ -2378,11 +2379,10 @@ 

      Format

      Text to Speech

      # $ pip3 install pyttsx3
      +

      Text to Speech

      # $ sudo apt install espeak ffmpeg libespeak1
      +# $ pip3 install pyttsx3
       import pyttsx3
      -engine = pyttsx3.init()
      -engine.say('Sally sells seashells by the seashore.')
      -engine.runAndWait()
      +pyttsx3.speak(<str>)                            # Reads the string while blocking.
       

      #Synthesizer

      Plays Popcorn by Gershon Kingsley:

      # $ pip3 install simpleaudio
      @@ -2902,7 +2902,7 @@ 

      Format

      -

      Plays a WAV file:

      # $ sudo apt install libasound2-dev
      -# $ pip3 install simpleaudio
      +

      Plays a WAV file:

      # $ pip3 install simpleaudio
       from simpleaudio import play_buffer
       with wave.open('test.wav', 'rb') as file:
           p = file.getparams()
      @@ -2379,10 +2378,11 @@ 

      Format

      Text to Speech

      # $ sudo apt install espeak ffmpeg libespeak1
      -# $ pip3 install pyttsx3
      +

      Text to Speech

      # $ pip3 install pyttsx3
       import pyttsx3
      -pyttsx3.speak(<str>)                            # Reads the string while blocking.
      +engine = pyttsx3.init()
      +engine.say('Sally sells seashells by the seashore.')
      +engine.runAndWait()
       

      #Synthesizer

      Plays Popcorn by Gershon Kingsley:

      # $ pip3 install simpleaudio
      
      From c15942fc77de427ff59429f9594e3ac290029009 Mon Sep 17 00:00:00 2001
      From: =?UTF-8?q?Jure=20=C5=A0orn?= 
      Date: Tue, 21 Jun 2022 15:24:37 +0200
      Subject: [PATCH 080/638] Arguments, Exceptions, Profiling
      
      ---
       README.md  |  19 ++++---
       index.html |  33 ++++++------
       parse.js   | 148 +++++++++++++++++++++++++++++++++++++++++++++++++++++
       3 files changed, 173 insertions(+), 27 deletions(-)
      
      diff --git a/README.md b/README.md
      index 950b10575..62ad69e7f 100644
      --- a/README.md
      +++ b/README.md
      @@ -668,9 +668,9 @@ Arguments
       ---------
       ### Inside Function Call
       ```python
      -func()                           # func(1, 2)
      -func()                              # func(x=1, y=2)
      -func(, )           # func(1, y=2)
      +func()                           # func(0, 0)
      +func()                              # func(x=0, y=0)
      +func(, )           # func(0, y=0)
       ```
       
       ### Inside Function Definition
      @@ -744,7 +744,7 @@ def f(*args, y, **kwargs): ...  # f(x=1, y=2, z=3) | f(1, y=2, z=3)
       ```
       
       ```python
      -head, *body, tail =      # Also `head, *body = ` and `*body, tail = `.
      +head, *body, tail =      # Head or tail can be omitted.
       ```
       
       
      @@ -1398,10 +1398,10 @@ finally:
       
       ### Catching Exceptions
       ```python
      -except :
      -except  as :
      -except (, [...]):
      -except (, [...]) as :
      +except : ...
      +except  as : ...
      +except (, [...]): ...
      +except (, [...]) as : ...
       ```
       * **Also catches subclasses of the exception.**
       * **Use `'traceback.print_exc()'` to print the error message to stderr.**
      @@ -2615,8 +2615,7 @@ Line #         Mem usage      Increment   Line Contents
       ### Call Graph
       #### Generates a PNG image of the call graph with highlighted bottlenecks:
       ```python
      -# $ pip3 install pycallgraph2
      -# $ apt install graphviz
      +# $ pip3 install pycallgraph2; brew/apt install graphviz
       import pycallgraph2 as cg, datetime
       filename = f'profile-{datetime.datetime.now():%Y%m%d%H%M%S}.png'
       drawer = cg.output.GraphvizOutput(output_file=filename)
      diff --git a/index.html b/index.html
      index 3f3bfb1e9..fea01b9f7 100644
      --- a/index.html
      +++ b/index.html
      @@ -54,7 +54,7 @@
       
       
         
      - +
      @@ -589,9 +589,9 @@ <float> = <TD> / <TD> # How many weeks/years there are in TD. Also //.
      -

      #Arguments

      Inside Function Call

      func(<positional_args>)                           # func(1, 2)
      -func(<keyword_args>)                              # func(x=1, y=2)
      -func(<positional_args>, <keyword_args>)           # func(1, y=2)
      +

      #Arguments

      Inside Function Call

      func(<positional_args>)                           # func(0, 0)
      +func(<keyword_args>)                              # func(x=0, y=0)
      +func(<positional_args>, <keyword_args>)           # func(0, y=0)
       
      @@ -645,7 +645,7 @@ <dict> = {**<dict> [, ...]} # Or: dict(**<dict> [, ...])
      -
      head, *body, tail = <coll.>     # Also `head, *body = <coll.>` and `*body, tail = <coll.>`.
      +
      head, *body, tail = <coll.>     # Head or tail can be omitted.
       

      #Inline

      Lambda

      <func> = lambda: <return_value>                           # A single statement function.
       <func> = lambda <arg_1>, <arg_2>: <return_value>          # Also accepts default arguments.
      @@ -790,7 +790,7 @@
       

    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 debug(print_result=False):
         def decorator(func):
             @wraps(func)
             def out(*args, **kwargs):
    @@ -1200,10 +1200,10 @@
     
  • Code inside the 'else' block will only be executed if 'try' block had no exceptions.
  • Code inside the 'finally' block will always be executed (unless a signal is received).
  • -

    Catching Exceptions

    except <exception>:
    -except <exception> as <name>:
    -except (<exception>, [...]):
    -except (<exception>, [...]) as <name>:
    +

    Catching Exceptions

    except <exception>: ...
    +except <exception> as <name>: ...
    +except (<exception>, [...]): ...
    +except (<exception>, [...]) as <name>: ...
     
      @@ -1936,7 +1936,7 @@

      Format

      2 - W//2, curses.LINES//2 - H//2) while True: screen.erase() - curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W) + curses.textpad.rectangle(screen, offset.y-1, offset.x-1, offset.y+H, offset.x+W) for id_, p in state.items(): screen.addstr(offset.y + (p.y - state['*'].y + H//2) % H, offset.x + (p.x - state['*'].x + W//2) % W, str(id_)) @@ -2140,8 +2140,7 @@

      Format

      Call Graph

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

      # $ pip3 install pycallgraph2
      -# $ apt install graphviz
      +

      Call Graph

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

      # $ pip3 install pycallgraph2; brew/apt install graphviz
       import pycallgraph2 as cg, datetime
       filename = f'profile-{datetime.datetime.now():%Y%m%d%H%M%S}.png'
       drawer = cg.output.GraphvizOutput(output_file=filename)
      @@ -2479,8 +2478,8 @@ 

      Format

      'Mario', 'rect spd facing_left frame_cycle'.split()) return Mario(get_rect(1, 1), P(0, 0), False, it.cycle(range(3))) def get_tiles(): - border = [(x, y) for x in range(W) for y in range(H) if x in [0, W-1] or y in [0, H-1]] - platforms = [(randint(1, W-2), randint(2, H-2)) for _ in range(W*H // 10)] + border = [(x, y) for x in range(W) for y in range(H) if x in [0, W-1] or y in [0, H-1]] + platforms = [(randint(1, W-2), randint(2, H-2)) for _ in range(W*H // 10)] return [get_rect(x, y) for x, y in border + platforms] def get_rect(x, y): return pg.Rect(x*16, y*16, 16, 16) @@ -2528,7 +2527,7 @@

      Format

      in pressed) if {D.w, D.e} & pressed else mario.facing_left screen.blit(images[get_marios_image_index() + mario.facing_left * 9], mario.rect) for t in tiles: - screen.blit(images[18 if t.x in [0, (W-1)*16] or t.y in [0, (H-1)*16] else 19], t) + screen.blit(images[18 if t.x in [0, (W-1)*16] or t.y in [0, (H-1)*16] else 19], t) pg.display.flip() if __name__ == '__main__': @@ -2902,7 +2901,7 @@

      Format

    -

    #Format

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

    #Format

    <str> = f'{<el_1>}, {<el_2>}'            # Curly brackets can also contain expressions.
    +<str> = '{}, {}'.format(<el_1>, <el_2>)  # Or: '{0}, {a}'.format(<el_1>, a=<el_2>)
     <str> = '%s, %s' % (<el_1>, <el_2>)      # Redundant and inferior C style formatting.
     
    -

    Attributes

    >>> from collections import namedtuple
    ->>> Person = namedtuple('Person', 'name height')
    +

    Attributes

    >>> Person = collections.namedtuple('Person', 'name height')
     >>> person = Person('Jean-Luc', 187)
     >>> f'{person.height}'
     '187'
    @@ -673,7 +673,7 @@
     <bool> = all(<collection>)                                # Is True for all elements or empty.
     
    -

    Conditional Expression

    <obj> = <exp_if_true> if <condition> else <exp_if_false>
    +

    Conditional Expression

    <obj> = <exp_if_true> if <condition> else <exp_if_false>  # Only one expression gets evaluated.
     
    >>> [a if a else 'zero' for a in (0, 1, 2, 3)]
    @@ -1513,7 +1513,7 @@
     
     
    • File must be opened with a 'newline=""' argument, or newlines embedded inside quoted fields will not be interpreted correctly!
    • -
    • To print the table to the console use Tabulate library.
    • +
    • To print the spreadsheet to the console use Tabulate library.
    • For XML and binary Excel files (xlsx, xlsm and xlsb) use Pandas library.

    Write

    <writer> = csv.writer(<file>)       # Also: `dialect='excel', delimiter=','`.
    @@ -2379,9 +2379,9 @@ 

    Format

    Text to Speech

    # $ pip3 install pyttsx3
     import pyttsx3
    -engine = pyttsx3.init()
    -engine.say('Sally sells seashells by the seashore.')
    -engine.runAndWait()
    +<Engine> = pyttsx3.init()                       # Returns a new Engine.
    +<Engine>.say(<str>)                             # Stages the string to be read.
    +<Engine>.runAndWait()                           # Reads all staged strings while blocking.
     

    #Synthesizer

    Plays Popcorn by Gershon Kingsley:

    # $ pip3 install simpleaudio
    @@ -2901,7 +2901,7 @@ 

    Format

    -

    #Set

    <set> = set()
    +

    #Set

    <set> = set()                                   # {} returns a dictionary.
     
    <set>.add(<el>)                                 # Or: <set> |= {<el>}
    @@ -647,50 +647,50 @@
     
     
    head, *body, tail = <coll.>     # Head or tail can be omitted.
     
    -

    #Inline

    Lambda

    <func> = lambda: <return_value>                           # A single statement function.
    -<func> = lambda <arg_1>, <arg_2>: <return_value>          # Also accepts default arguments.
    +

    #Inline

    Lambda

    <func> = lambda: <return_value>                     # A single statement function.
    +<func> = lambda <arg_1>, <arg_2>: <return_value>    # Also accepts default arguments.
     
    -

    Comprehensions

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

    Comprehensions

    <list> = [i+1 for i in range(10)]                   # Or: [1, 2, ..., 10]
    +<iter> = (i for i in range(10) if i > 5)            # Or: iter([6, 7, 8, 9])
    +<set>  = {i+5 for i in range(10)}                   # Or: {5, 6, ..., 14}
    +<dict> = {i: i*2 for i in range(10)}                # Or: {0: 0, 1: 2, ..., 9: 18}
     
    >>> [l+r for l in 'abc' for r in 'abc']
     ['aa', 'ab', 'ac', ..., 'cc']
     
    -

    Map, Filter, Reduce

    <iter> = map(lambda x: x + 1, range(10))                  # Or: iter([1, 2, ..., 10])
    -<iter> = filter(lambda x: x > 5, range(10))               # Or: iter([6, 7, 8, 9])
    -<obj>  = reduce(lambda out, x: out + x, range(10))        # Or: 45
    +

    Map, Filter, Reduce

    <iter> = map(lambda x: x + 1, range(10))            # Or: iter([1, 2, ..., 10])
    +<iter> = filter(lambda x: x > 5, range(10))         # Or: iter([6, 7, 8, 9])
    +<obj>  = reduce(lambda out, x: out + x, range(10))  # Or: 45
     
    • Reduce must be imported from the functools module.
    -

    Any, All

    <bool> = any(<collection>)                                # Is `bool(el)` True for any element.
    -<bool> = all(<collection>)                                # Is True for all elements or empty.
    +

    Any, All

    <bool> = any(<collection>)                          # Is `bool(el)` True for any element.
    +<bool> = all(<collection>)                          # Is True for all elements or empty.
     
    -

    Conditional Expression

    <obj> = <exp_if_true> if <condition> else <exp_if_false>  # Only one expression gets evaluated.
    +

    Conditional Expression

    <obj> = <exp> if <condition> else <exp>             # Only one expression gets evaluated.
     
    >>> [a if a else 'zero' for a in (0, 1, 2, 3)]
     ['zero', 1, 2, 3]
     

    Named Tuple, Enum, Dataclass

    from collections import namedtuple
    -Point = namedtuple('Point', 'x y')
    -point = Point(0, 0)
    +Point = namedtuple('Point', 'x y')                  # Tuple's subclass with named elements.
    +point = Point(0, 0)                                 # Tuple with x and y attributes.
     
    from enum import Enum
    -Direction = Enum('Direction', 'n e s w')
    -direction = Direction.n
    +Direction = Enum('Direction', 'n e s w')            # Enum with n, e, s and w members.
    +direction = Direction.n                             # Member with name and value attributes.
     
    from dataclasses import make_dataclass
    -Creature = make_dataclass('Creature', ['loc', 'dir'])
    -creature = Creature(point, direction)
    +Player = make_dataclass('Player', ['loc', 'dir'])   # Class with init, repr and eq methods.
    +player = Player(point, direction)                   # Object with loc and dir attributes.
     

    #Imports

    import <module>            # Imports a built-in or '<module>.py'.
     import <package>           # Imports a built-in or '<package>/__init__.py'.
    @@ -2901,7 +2901,7 @@ 

    Format

    -

    #Tuple

    Tuple is an immutable and hashable list.

    <tuple> = ()
    +

    #Tuple

    Tuple is an immutable and hashable list.

    <tuple> = ()                                # Or: tuple()
     <tuple> = (<el>,)                           # Or: <el>,
     <tuple> = (<el_1>, <el_2> [, ...])          # Or: <el_1>, <el_2> [, ...]
     
    @@ -1852,7 +1852,7 @@

    Format

    >>> 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.
     
    @@ -1866,7 +1866,7 @@

    Format

    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.
     
    @@ -2379,9 +2379,9 @@

    Format

    Text to Speech

    # $ pip3 install pyttsx3
     import pyttsx3
    -<Engine> = pyttsx3.init()                       # Returns a new Engine.
    -<Engine>.say(<str>)                             # Stages the string to be read.
    -<Engine>.runAndWait()                           # Reads all staged strings while blocking.
    +engine = pyttsx3.init()
    +engine.say('Sally sells seashells by the seashore.')
    +engine.runAndWait()
     

    #Synthesizer

    Plays Popcorn by Gershon Kingsley:

    # $ pip3 install simpleaudio
    @@ -2901,7 +2901,7 @@ 

    Format

    <str>  = str(<Path>)                # Returns path as a string.
    -<file> = open(<Path>)               # Opens the file and returns a file object.
    +<file> = open(<Path>)               # Also <Path>.read/write_text/bytes().
     

    #OS Commands

    import os, shutil, subprocess
     
    From fe9a0d123fe6ec15e2279298e0670ff064e962f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 26 Jun 2022 11:22:37 +0200 Subject: [PATCH 086/638] Inline --- README.md | 12 ++++++------ index.html | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index cd4e101c1..4e7f9e196 100644 --- a/README.md +++ b/README.md @@ -796,20 +796,20 @@ Inline ### Named Tuple, Enum, Dataclass ```python from collections import namedtuple -Point = namedtuple('Point', 'x y') # Tuple's subclass with named elements. -point = Point(0, 0) # Tuple with x and y attributes. +Point = namedtuple('Point', 'x y') # Creates a tuple's subclass. +point = Point(0, 0) # Returns its instance. ``` ```python from enum import Enum -Direction = Enum('Direction', 'n e s w') # Enum with n, e, s and w members. -direction = Direction.n # Member with name and value attributes. +Direction = Enum('Direction', 'n e s w') # Creates an enum. +direction = Direction.n # Returns its member. ``` ```python from dataclasses import make_dataclass -Player = make_dataclass('Player', ['loc', 'dir']) # Class with init, repr and eq methods. -player = Player(point, direction) # Object with loc and dir attributes. +Player = make_dataclass('Player', ['loc', 'dir']) # Creates a class. +player = Player(point, direction) # Returns its instance. ``` diff --git a/index.html b/index.html index 53a8553cd..6a01b81d1 100644 --- a/index.html +++ b/index.html @@ -680,17 +680,17 @@ ['zero', 1, 2, 3]

    Named Tuple, Enum, Dataclass

    from collections import namedtuple
    -Point = namedtuple('Point', 'x y')                  # Tuple's subclass with named elements.
    -point = Point(0, 0)                                 # Tuple with x and y attributes.
    +Point = namedtuple('Point', 'x y')                  # Creates a tuple's subclass.
    +point = Point(0, 0)                                 # Returns its instance.
     
    from enum import Enum
    -Direction = Enum('Direction', 'n e s w')            # Enum with n, e, s and w members.
    -direction = Direction.n                             # Member with name and value attributes.
    +Direction = Enum('Direction', 'n e s w')            # Creates an enum.
    +direction = Direction.n                             # Returns its member.
     
    from dataclasses import make_dataclass
    -Player = make_dataclass('Player', ['loc', 'dir'])   # Class with init, repr and eq methods.
    -player = Player(point, direction)                   # Object with loc and dir attributes.
    +Player = make_dataclass('Player', ['loc', 'dir'])   # Creates a class.
    +player = Player(point, direction)                   # Returns its instance.
     

    #Imports

    import <module>            # Imports a built-in or '<module>.py'.
     import <package>           # Imports a built-in or '<package>/__init__.py'.
    
    From 3f51fe4ea25d0f6e0ffab1093979f2d3c74b4365 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Mon, 27 Jun 2022 06:36:26 +0200
    Subject: [PATCH 087/638] JSON, Pickle, Pygame
    
    ---
     README.md  | 16 ++++++++--------
     index.html | 20 ++++++++++----------
     2 files changed, 18 insertions(+), 18 deletions(-)
    
    diff --git a/README.md b/README.md
    index 4e7f9e196..f7b53b1df 100644
    --- a/README.md
    +++ b/README.md
    @@ -1755,8 +1755,8 @@ JSON
     
     ```python
     import json
    -    = json.dumps(, ensure_ascii=True, indent=None)
    - = json.loads()
    +    = json.dumps()    # Converts object to JSON string.
    + = json.loads()       # Converts JSON string to object.
     ```
     
     ### Read Object from JSON File
    @@ -1780,8 +1780,8 @@ Pickle
     
     ```python
     import pickle
    -  = pickle.dumps()
    - = pickle.loads()
    +  = pickle.dumps()  # Converts object to bytes.
    + = pickle.loads()   # Converts bytes to object.
     ```
     
     ### Read Object from File
    @@ -2985,8 +2985,8 @@ while all(event.type != pg.QUIT for event in pg.event.get()):
     ### Surface
     **Object for representing images.**
     ```python
    - = pg.display.set_mode((width, height))   # Returns display surface.
    - = pg.Surface((width, height), flags=0)   # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
    + = pg.display.set_mode((width, height))   # Returns a display surface.
    + = pg.Surface((width, height))            # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
      = pg.image.load('')                # Loads the image. Format depends on source.
      = .subsurface()              # Returns a subsurface.
     ```
    @@ -3007,8 +3007,8 @@ from pygame.transform import scale, ...
     ```python
     from pygame.draw import line, ...
     line(, color, (x1, y1), (x2, y2), width)  # Draws a line to the surface.
    -arc(, color, , from_rad, to_rad)    # Also: ellipse(, color, )
    -rect(, color, )                     # Also: polygon(, color, points)
    +arc(, color, , from_rad, to_rad)    # Also: ellipse(, color, , width=0)
    +rect(, color, , width=0)            # Also: polygon(, color, points, width=0)
     ```
     
     ### Font
    diff --git a/index.html b/index.html
    index 6a01b81d1..960485f28 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -1471,8 +1471,8 @@

    #JSON

    Text file format for storing collections of strings and numbers.

    import json
    -<str>    = json.dumps(<object>, ensure_ascii=True, indent=None)
    -<object> = json.loads(<str>)
    +<str>    = json.dumps(<object>)    # Converts object to JSON string.
    +<object> = json.loads(<str>)       # Converts JSON string to object.
     
    @@ -1487,8 +1487,8 @@

    #Pickle

    Binary file format for storing Python objects.

    import pickle
    -<bytes>  = pickle.dumps(<object>)
    -<object> = pickle.loads(<bytes>)
    +<bytes>  = pickle.dumps(<object>)  # Converts object to bytes.
    +<object> = pickle.loads(<bytes>)   # Converts bytes to object.
     
    @@ -2429,8 +2429,8 @@

    Format

    # Returns index of first colliding Rect or -1. <list> = <Rect>.collidelistall(<list_of_Rect>) # Returns indexes of all colliding rectangles. -

    Surface

    Object for representing images.

    <Surf> = pg.display.set_mode((width, height))   # Returns display surface.
    -<Surf> = pg.Surface((width, height), flags=0)   # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
    +

    Surface

    Object for representing images.

    <Surf> = pg.display.set_mode((width, height))   # Returns a display surface.
    +<Surf> = pg.Surface((width, height))            # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
     <Surf> = pg.image.load('<path>')                # Loads the image. Format depends on source.
     <Surf> = <Surf>.subsurface(<Rect>)              # Returns a subsurface.
     
    @@ -2447,8 +2447,8 @@

    Format

    from pygame.draw import line, ... line(<Surf>, color, (x1, y1), (x2, y2), width) # Draws a line to the surface. -arc(<Surf>, color, <Rect>, from_rad, to_rad) # Also: ellipse(<Surf>, color, <Rect>) -rect(<Surf>, color, <Rect>) # Also: polygon(<Surf>, color, points) +arc(<Surf>, color, <Rect>, from_rad, to_rad) # Also: ellipse(<Surf>, color, <Rect>, width=0) +rect(<Surf>, color, <Rect>, width=0) # Also: polygon(<Surf>, color, points, width=0)

    Font

    <Font> = pg.font.SysFont('<name>', size)        # Loads the system font or default if missing.
     <Font> = pg.font.Font('<path>', size)           # Loads the TTF file. Pass None for default.
    @@ -2901,7 +2901,7 @@ 

    Format

    -

    #Tuple

    Tuple is an immutable and hashable list.

    <tuple> = ()                                # Or: tuple()
    -<tuple> = (<el>,)                           # Or: <el>,
    -<tuple> = (<el_1>, <el_2> [, ...])          # Or: <el_1>, <el_2> [, ...]
    +

    #Tuple

    Tuple is an immutable and hashable list.

    <tuple> = ()                        # Empty tuple.
    +<tuple> = (<el>,)                   # Or: <el>,
    +<tuple> = (<el_1>, <el_2> [, ...])  # Or: <el_1>, <el_2> [, ...]
     
    @@ -198,16 +198,15 @@ 1 >>> getattr(p, 'y') 2 ->>> p._fields # Or: Point._fields -('x', 'y')
    -

    #Range

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

    #Range

    An immutable and hashable sequence of evenly spaced integers.

    <range> = range(to_exclusive)                         # `list(range(3))        == [0, 1, 2]`
    +<range> = range(from_inclusive, to_exclusive)         # `list(range(1, 4))     == [1, 2, 3]`
    +<range> = range(from_inclusive, to_exclusive, ±step)  # `list(range(3, 0, -1)) == [3, 2, 1]`
     
    +
    from_inclusive = <range>.start
     to_exclusive   = <range>.stop
     
    @@ -229,10 +228,10 @@ <iter> = cycle(<collection>) # Repeats the sequence endlessly.
    <iter> = chain(<coll_1>, <coll_2> [, ...])  # Empties collections in order (figuratively).
    -<iter> = chain.from_iterable(<collection>)  # Empties collections inside a collection in order.
    +<iter> = chain.from_iterable(<coll>)        # Empties collections inside a collection in order.
     
    <iter> = islice(<coll>, to_exclusive)       # Only returns first 'to_exclusive' elements.
    -<iter> = islice(<coll>, from_inclusive, …)  # `to_exclusive, step_size`.
    +<iter> = islice(<coll>, from_inclusive, …)  # `to_exclusive, +step`.
     

    #Generator