From 99e545ba54669274a775d91afddd9da0c9c207d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 22 Dec 2021 13:55:17 +0100 Subject: [PATCH 001/643] Plotly --- README.md | 3 ++- index.html | 7 ++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 0ca6cce5f..76ac31d16 100644 --- a/README.md +++ b/README.md @@ -3436,7 +3436,8 @@ def display_data(df): figure.update_layout( yaxis1=dict(title='Total Cases', rangemode='tozero'), yaxis2=dict(title='%', rangemode='tozero', overlaying='y', side='right'), - legend=dict(x=1.1) + legend=dict(x=1.1), + height=450 ).show() if __name__ == '__main__': diff --git a/index.html b/index.html index 38732fd92..c12d42bfa 100644 --- a/index.html +++ b/index.html @@ -50,7 +50,7 @@
- +
@@ -2782,7 +2782,8 @@ figure.update_layout( yaxis1=dict(title='Total Cases', rangemode='tozero'), yaxis2=dict(title='%', rangemode='tozero', overlaying='y', side='right'), - legend=dict(x=1.1) + legend=dict(x=1.1), + height=450 ).show() if __name__ == '__main__': @@ -2869,7 +2870,7 @@ From 3f5b66c67ca9bd92932f8f4db27f7dd44e0cc08a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 22 Dec 2021 15:13:22 +0100 Subject: [PATCH 002/643] Datetime --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 76ac31d16..26d9f3b47 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).** +* **TD converts and normalizes args to ±days, seconds (< 86 400) and microseconds (< 1M).** ### Now ```python diff --git a/index.html b/index.html index c12d42bfa..2fca51f4d 100644 --- a/index.html +++ b/index.html @@ -530,7 +530,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).
  • +
  • TD converts and normalizes args 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.

From 9682a9d8489fd64b5ce65ece8e96c0b738797bf6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jure=20=C5=A0orn?= 
Date: Fri, 24 Dec 2021 12:00:00 +0100
Subject: [PATCH 003/643] Pandas

---
 README.md  | 4 ++--
 index.html | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/README.md b/README.md
index 26d9f3b47..98581c3da 100644
--- a/README.md
+++ b/README.md
@@ -3204,8 +3204,8 @@ b  3  4
 ```python
     = .set_index(column_key)          # Replaces row keys with values from a column.
     = .reset_index()                  # Moves row keys to a column named index.
-    = .filter('', axis=1)      # Only keeps columns whose key matches the regex.
-    = .melt(id_vars=column_key/s)     # Converts DataFrame from wide to long format.
+    = .sort_index(ascending=True)     # Sorts rows by row keys.
+    = .sort_values(column_key/s)      # Sorts rows by the passed column/s.
 ```
 
 #### Merge, Join, Concat:
diff --git a/index.html b/index.html
index 2fca51f4d..85c64927a 100644
--- a/index.html
+++ b/index.html
@@ -2591,8 +2591,8 @@
 
<DF>    = <DF>.set_index(column_key)          # Replaces row keys with values from a column.
 <DF>    = <DF>.reset_index()                  # Moves row keys to a column named index.
-<DF>    = <DF>.filter('<regex>', axis=1)      # Only keeps columns whose key matches the regex.
-<DF>    = <DF>.melt(id_vars=column_key/s)     # Converts DataFrame from wide to long format.
+<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'])
    x  y 

From cc7400c55f71763201dafa9ed5fd2275a138446a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jure=20=C5=A0orn?= 
Date: Fri, 24 Dec 2021 15:30:50 +0100
Subject: [PATCH 004/643] Changed default dark theme

---
 index.html                |  19 +-
 parse.js                  |   7 +-
 web/default_dark3.min.css |   1 +
 web/style_dark3.css       | 461 ++++++++++++++++++++++++++++++++++++++
 web/template.html         |   8 +-
 5 files changed, 484 insertions(+), 12 deletions(-)
 create mode 100644 web/default_dark3.min.css
 create mode 100644 web/style_dark3.css

diff --git a/index.html b/index.html
index 85c64927a..f105eb13b 100644
--- a/index.html
+++ b/index.html
@@ -14,10 +14,14 @@
 
   

#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 025/643] 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 026/643] 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 027/643] 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 028/643] 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 029/643] 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 030/643] 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 031/643] 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 032/643] 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 033/643] 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 034/643] 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 035/643] 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 036/643] 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 037/643] 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 038/643] 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 039/643] 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 040/643] 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 041/643] 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 042/643] 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 043/643] 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 044/643] 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 045/643] 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 046/643] 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 047/643] 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 048/643] 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 049/643] 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 050/643] 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 051/643] 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 052/643] 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 053/643] 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 054/643] 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 055/643] 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 056/643] 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 057/643] 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 058/643] 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 059/643] 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 060/643] 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 061/643] 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 062/643] 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 063/643] 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 064/643] 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 065/643] 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 066/643] 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 067/643] 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 068/643] 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 069/643] 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 070/643] 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 071/643] 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 072/643] 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 073/643] 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 074/643] 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 075/643] 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 080/643] 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 081/643] 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 083/643] 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 085/643] 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 091/643] 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 092/643] 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