From c41c5b2ad3d97db9a5a9708ff70d0eaa3939a0dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 11 Oct 2023 05:23:22 +0200 Subject: [PATCH 001/359] String and Regex update --- README.md | 34 ++++++++++++++++++---------------- index.html | 46 +++++++++++++++++++++------------------------- 2 files changed, 39 insertions(+), 41 deletions(-) diff --git a/README.md b/README.md index ba3d0bdea..cf2ac92d0 100644 --- a/README.md +++ b/README.md @@ -300,9 +300,11 @@ True String ------ +**Immutable sequence of characters.** + ```python = .strip() # Strips all whitespace characters from both ends. - = .strip('') # Strips all passed characters from both ends. + = .strip('') # Strips passed characters. Also lstrip/rstrip(). ``` ```python @@ -321,6 +323,7 @@ String ``` ```python + = .lower() # Changes the case. Also upper/capitalize/title(). = .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times. = .translate() # Use `str.maketrans()` to generate table. ``` @@ -329,38 +332,37 @@ String = chr() # Converts int to Unicode character. = ord() # Converts Unicode character to int. ``` -* **Also: `'lstrip()'`, `'rstrip()'` and `'rsplit()'`.** -* **Also: `'lower()'`, `'upper()'`, `'capitalize()'` and `'title()'`.** +* **Use `'unicodedata.normalize("NFC", )'` on strings that may contain characters like `'Ö'` before comparing them, because they can be stored as one or two characters.** ### Property Methods -```text -+---------------+----------+----------+----------+----------+----------+ -| | [ !#$%…] | [a-zA-Z] | [¼½¾] | [²³¹] | [0-9] | -+---------------+----------+----------+----------+----------+----------+ -| isprintable() | yes | yes | yes | yes | yes | -| isalnum() | | yes | yes | yes | yes | -| isnumeric() | | | yes | yes | yes | -| isdigit() | | | | yes | yes | -| isdecimal() | | | | | yes | -+---------------+----------+----------+----------+----------+----------+ +```python + = .isdecimal() # Checks for [0-9]. + = .isdigit() # Checks for [²³¹] and isdecimal(). + = .isnumeric() # Checks for [¼½¾] and isdigit(). + = .isalnum() # Checks for [a-zA-Z] and isnumeric(). + = .isprintable() # Checks for [ !#$%…] and isalnum(). + = .isspace() # Checks for [ \t\n\r\f\v\x1c-\x1f\x85\xa0…]. ``` -* **`'isspace()'` checks for whitespaces: `'[ \t\n\r\f\v\x1c-\x1f\x85\xa0\u1680…]'`.** Regex ----- +**Functions for regular expression matching.** + ```python import re +``` + +```python = re.sub(, new, text, count=0) # Substitutes all occurrences with 'new'. = re.findall(, text) # Returns all occurrences as strings. = re.split(, text, maxsplit=0) # Add brackets around regex to include matches. - = re.search(, text) # Searches for first occurrence of the pattern. + = re.search(, text) # First occurrence of the pattern or None. = re.match(, text) # Searches only at the beginning of the text. = re.finditer(, text) # Returns all occurrences as Match objects. ``` * **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.** * **Argument `'flags=re.DOTALL'` makes `'.'` also accept the `'\n'`.** diff --git a/index.html b/index.html index 998f95eca..869da710d 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -290,10 +290,11 @@ ┃ decimal.Decimal │ ✓ │ │ │ │ ┃ ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛ -

#String

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

#String

Immutable sequence of characters.

<str>  = <str>.strip()                       # Strips all whitespace characters from both ends.
+<str>  = <str>.strip('<chars>')              # Strips passed characters. Also lstrip/rstrip().
 
+
<list> = <str>.split()                       # Splits on one or more whitespace characters.
 <list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
 <list> = <str>.splitlines(keepends=False)    # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
@@ -305,42 +306,37 @@
 <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.
 
-
<str>  = <str>.replace(old, new [, count])   # Replaces 'old' with 'new' at most 'count' times.
+
<str>  = <str>.lower()                       # Changes the case. Also upper/capitalize/title().
+<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.
 
<str>  = chr(<int>)                          # Converts int to Unicode character.
 <int>  = ord(<str>)                          # Converts Unicode character to int.
 
    -
  • Also: 'lstrip()', 'rstrip()' and 'rsplit()'.
  • -
  • Also: 'lower()', 'upper()', 'capitalize()' and 'title()'.
  • +
  • Use 'unicodedata.normalize("NFC", <str>)' on strings that may contain characters like 'Ö' before comparing them, because they can be stored as one or two characters.
-

Property Methods

┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
-┃               │ [ !#$%…] │ [a-zA-Z] │  [¼½¾]   │  [²³¹]   │  [0-9]   ┃
-┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
-┃ isprintable() │    ✓     │    ✓     │    ✓     │    ✓     │    ✓     ┃
-┃ isalnum()     │          │    ✓     │    ✓     │    ✓     │    ✓     ┃
-┃ isnumeric()   │          │          │    ✓     │    ✓     │    ✓     ┃
-┃ isdigit()     │          │          │          │    ✓     │    ✓     ┃
-┃ isdecimal()   │          │          │          │          │    ✓     ┃
-┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
+

Property Methods

<bool> = <str>.isdecimal()                   # Checks for [0-9].
+<bool> = <str>.isdigit()                     # Checks for [²³¹] and isdecimal().
+<bool> = <str>.isnumeric()                   # Checks for [¼½¾] and isdigit().
+<bool> = <str>.isalnum()                     # Checks for [a-zA-Z] and isnumeric().
+<bool> = <str>.isprintable()                 # Checks for [ !#$%…] and isalnum().
+<bool> = <str>.isspace()                     # Checks for [ \t\n\r\f\v\x1c-\x1f\x85\xa0…].
 
-
    -
  • 'isspace()' checks for whitespaces: '[ \t\n\r\f\v\x1c-\x1f\x85\xa0\u1680…]'.
  • -
-

#Regex

import re
-<str>   = re.sub(<regex>, new, text, count=0)  # Substitutes all occurrences with 'new'.
+

#Regex

Functions for regular expression matching.

import re
+
+ + +
<str>   = re.sub(<regex>, new, text, count=0)  # Substitutes all occurrences with 'new'.
 <list>  = re.findall(<regex>, text)            # Returns all occurrences as strings.
 <list>  = re.split(<regex>, text, maxsplit=0)  # Add brackets around regex to include matches.
-<Match> = re.search(<regex>, text)             # Searches for first occurrence of the pattern.
+<Match> = re.search(<regex>, text)             # First occurrence of the pattern or None.
 <Match> = re.match(<regex>, text)              # Searches only at the beginning of the text.
 <iter>  = re.finditer(<regex>, text)           # Returns all occurrences as Match objects.
-
- +
  • Argument '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.
  • Argument 'flags=re.DOTALL' makes '.' also accept the '\n'.
  • @@ -2929,7 +2925,7 @@

    Format

-

Write Rows to CSV File

def write_to_csv_file(filename, rows, dialect='excel', **params):
-    with open(filename, 'w', encoding='utf-8', newline='') as file:
+

Write Rows to CSV File

def write_to_csv_file(filename, rows, mode='w', dialect='excel', **params):
+    with open(filename, mode, encoding='utf-8', newline='') as file:
         writer = csv.writer(file, dialect, **params)
         writer.writerows(rows)
 
@@ -1979,7 +1979,7 @@

Format

#Curses

Runs a basic file explorer in the terminal:

import curses, os
+

#Curses

Runs a basic file explorer in the console:

import curses, os
 from curses import A_REVERSE, KEY_DOWN, KEY_UP, KEY_LEFT, KEY_RIGHT, KEY_ENTER
 
 def main(screen):
@@ -2141,7 +2141,7 @@ 

Format

Call and Flame Graphs

$ pip3 install gprof2dot snakeviz; apt/brew install graphviz
 $ tail -n 4 test.py > test.py
 $ python3 -m cProfile -o test.prof test.py
-$ gprof2dot -f pstats test.prof | dot -Tpng -o test.png; xdg-open/open test.png
+$ gprof2dot -f pstats test.prof | dot -T png -o test.png; xdg-open/open test.png
 $ snakeviz test.prof
 
@@ -2262,7 +2262,7 @@

Format

<Image> = <Image>.filter(<Filter>) # `<Filter> = ImageFilter.<name>([<args>])` <Image> = <Enhance>.enhance(<float>) # `<Enhance> = ImageEnhance.<name>(<Image>)`

-
<array> = np.array(<Image>)                       # Creates NumPy array from the image.
+
<array> = np.array(<Image>)                       # Creates a NumPy array from the image.
 <Image> = Image.fromarray(np.uint8(<array>))      # Use <array>.clip(0, 255) to clip values.
 

Modes

    @@ -2638,7 +2638,7 @@

    Format

    <Sr/DF> = <DF>[column_key/s] # Or: <DF>.column_key <DF> = <DF>[row_bools] # Keeps rows as specified by bools. -<DF> = <DF>[<DF_of_bools>] # Assigns NaN to values that are False in bools. +<DF> = <DF>[<DF_of_bools>] # Assigns NaN to items that are False in bools.

<DF>    = <DF> > <el/Sr/DF>                    # Returns DF of bools. Sr is treated as a row.
 <DF>    = <DF> + <el/Sr/DF>                    # Items with non-matching keys get value NaN.
@@ -2925,7 +2925,7 @@ 

Format

', ) # SQLite3/SQLAlchemy connection (see #SQLite). - = pd.read_clipboard() # Reads a copied table from the clipboard. ``` ```python @@ -3371,6 +3370,7 @@ c 7 8 6 = .groupby(column_key/s) # Splits DF into groups based on passed column. = .apply() # Maps each group. Func can return DF, Sr or el. = [column_key] # Single column GB. All operations return a Sr. + = .size() # A Sr of group sizes. Keys are group "names". ``` #### GroupBy — Aggregate, Transform, Map: diff --git a/index.html b/index.html index 73a8ad31e..5c7198ca8 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -2198,6 +2198,7 @@

Format

'obj[i, j]' to 'obj[(i, j)]'! +
  • ':' returns a slice of all dimension's indexes. Omitted dimensions default to ':'.
  • Any value that is broadcastable to the indexed shape can be assigned to the selection.
  • Broadcasting

    Set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.

    left  = [[0.1], [0.6], [0.8]]                           # Shape: (3, 1)
    @@ -2232,9 +2233,7 @@ 

    Format

    0. , 0.5, 0.7], [ 0.5, 0. , 0.2], [ 0.7, 0.2, 0. ]] ->>> i = np.arange(3) -[0, 1, 2] ->>> distances[i, i] = np.inf +>>> distances[range(3), range(3)] = np.inf [[ inf, 0.5, 0.7], [ 0.5, inf, 0.2], [ 0.7, 0.2, inf]] @@ -2253,11 +2252,11 @@

    Format

    # Selects format based on the path extension. <Image>.show() # Opens image in the default preview app.

    -
    <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 flattened view of the pixels.
    -<Image>.putdata(<list/ImagingCore>)               # Writes a flattened sequence of pixels.
    -<Image>.paste(<Image>, (x, y))                    # Writes passed image to the image.
    +
    <int/tuple> = <Image>.getpixel((x, y))            # Returns pixel's color.
    +<Image>.putpixel((x, y), <int/tuple>)             # Changes pixel's color.
    +<ImagingCore> = <Image>.getdata()                 # Returns a flattened view of all pixels.
    +<Image>.putdata(<list/ImagingCore>)               # Updates pixels with a copy of the sequence.
    +<Image>.paste(<Image>, (x, y))                    # Draws passed image at specified location.
     
    <Image> = <Image>.filter(<Filter>)                # `<Filter> = ImageFilter.<name>([<args>])`
     <Image> = <Enhance>.enhance(<float>)              # `<Enhance> = ImageEnhance.<name>(<Image>)`
    @@ -2727,9 +2726,9 @@ 

    Format

    <DF> = pd.read_json/html('<str/path/url>') # Run `$ pip3 install beautifulsoup4 lxml`. -<DF> = pd.read_csv/pickle/excel('<path/url>') # Use `sheet_name=None` to get all Excel sheets. +<DF> = pd.read_csv('<path/url>') # Also `names=<list>, parse_dates=False`. +<DF> = pd.read_pickle/excel('<path/url>') # Use `sheet_name=None` to get all Excel sheets. <DF> = pd.read_sql('<table/query>', <conn.>) # SQLite3/SQLAlchemy connection (see #SQLite). -<DF> = pd.read_clipboard() # Reads a copied table from the clipboard.

    <dict> = <DF>.to_dict(['d/l/s/…'])             # Returns columns as dicts, lists or series.
     <str>  = <DF>.to_json/html/csv([<path>])       # Also to_markdown/latex([<path>]).
    @@ -2747,6 +2746,7 @@ 

    Format

    <GB> = <DF>.groupby(column_key/s) # Splits DF into groups based on passed column. <DF> = <GB>.apply(<func>) # Maps each group. Func can return DF, Sr or el. <GB> = <GB>[column_key] # Single column GB. All operations return a Sr. +<Sr> = <GB>.size() # A Sr of group sizes. Keys are group "names".

    GroupBy — Aggregate, Transform, Map:

    <DF> = <GB>.sum/max/mean/idxmax/all()          # Or: <GB>.agg(lambda <Sr>: <el>)
     <DF> = <GB>.rank/diff/cumsum/ffill()           # Or: <GB>.transform(lambda <Sr>: <Sr>)
    @@ -2925,7 +2925,7 @@ 

    Format

    @@ -2762,11 +2761,11 @@

    Format

    ┏━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━┓ ┃ │ 'sum''rank' │ ['rank'] │ {'x': 'rank'} ┃ ┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨ -┃ gb.agg(…) │ x y │ x y │ x y │ x ┃ -┃ │ z │ a 1 1 │ rank rank │ a 1 ┃ -┃ │ 3 1 2 │ b 1 1 │ a 1 1 │ b 1 ┃ -┃ │ 6 11 13 │ c 2 2 │ b 1 1 │ c 2 ┃ -┃ │ │ │ c 2 2 │ ┃ +┃ gb.agg(…) │ x y │ │ x y │ ┃ +┃ │ z │ x y │ rank rank │ x ┃ +┃ │ 3 1 2 │ a 1 1 │ a 1 1 │ a 1 ┃ +┃ │ 6 11 13 │ b 1 1 │ b 1 1 │ b 1 ┃ +┃ │ │ c 2 2 │ c 2 2 │ c 2 ┃ ┠─────────────────┼─────────────┼─────────────┼─────────────┼───────────────┨ ┃ gb.transform(…) │ x y │ x y │ │ ┃ ┃ │ a 1 2 │ a 1 1 │ │ ┃ @@ -2925,7 +2924,7 @@

    Format

    = - # Ignores jumps. Convert to UTC for actual delta. = - # Ignores time jumps if they share tzinfo object. = ± # Returned datetime can fall into missing hour. - = * # Also: = abs() and = ±% . + = * # Also: = abs() and = ±% . = / # How many weeks/years there are in TD. Also //. ``` diff --git a/index.html b/index.html index 38de5f700..069820740 100644 --- a/index.html +++ b/index.html @@ -579,7 +579,7 @@ <TD> = <D/DTn> - <D/DTn> # Ignores jumps. Convert to UTC for actual delta. <TD> = <DTa> - <DTa> # Ignores time jumps if they share tzinfo object. <D/DT> = <D/DT> ± <TD> # Returned datetime can fall into missing hour. -<TD> = <TD> * <int/float> # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>. +<TD> = <TD> * <float> # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>. <float> = <TD> / <TD> # How many weeks/years there are in TD. Also //. From 58ad56cb80be2d1073c31b31733b9cb40ec07f3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 12 Nov 2023 17:13:01 +0100 Subject: [PATCH 006/359] Plotly --- README.md | 20 +++++++++++--------- index.html | 24 +++++++++++++----------- web/covid_cases.js | 2 +- 3 files changed, 25 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 24e97c6f9..b9e7c5d61 100644 --- a/README.md +++ b/README.md @@ -3428,7 +3428,7 @@ import pandas as pd, plotly.express as ex #### Displays a line chart of total coronavirus deaths per million grouped by continent: ![Covid Deaths](web/covid_deaths.png) -
    +
    ```python covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv', @@ -3447,25 +3447,26 @@ ex.line(df, x='Date', y='Total Deaths per Million', color='Continent').show() #### Displays a multi-axis line chart of total coronavirus cases and changes in prices of Bitcoin, Dow Jones and gold: ![Covid Cases](web/covid_cases.png) -
    +
    ```python import pandas as pd, plotly.graph_objects as go def main(): - display_data(wrangle_data(*scrape_data())) + covid, bitcoin, gold, dow = scrape_data() + display_data(wrangle_data(covid, bitcoin, gold, dow)) def scrape_data(): - def scrape_covid(): + def get_covid_cases(): url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv' df = pd.read_csv(url, usecols=['location', 'date', 'total_cases']) return df[df.location == 'World'].set_index('date').total_cases - def scrape_yahoo(slug): - url = (f'https://query1.finance.yahoo.com/v7/finance/download/{slug}?' + def get_ticker(symbol): + url = (f'https://query1.finance.yahoo.com/v7/finance/download/{symbol}?' 'period1=1579651200&period2=9999999999&interval=1d&events=history') df = pd.read_csv(url, usecols=['Date', 'Close']) return df.set_index('Date').Close - out = scrape_covid(), scrape_yahoo('BTC-USD'), scrape_yahoo('GC=F'), scrape_yahoo('^DJI') + out = get_covid_cases(), get_ticker('BTC-USD'), get_ticker('GC=F'), get_ticker('^DJI') return map(pd.Series.rename, out, ['Total Cases', 'Bitcoin', 'Gold', 'Dow Jones']) def wrangle_data(covid, bitcoin, gold, dow): @@ -3485,8 +3486,9 @@ 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), - height=450 + legend=dict(x=1.08), + width=944, + height=423 ) figure.show() diff --git a/index.html b/index.html index 069820740..5c5251ff8 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -2786,7 +2786,7 @@

    Format

    '<path>') # Also <Figure>.show().

    -

    Displays a line chart of total coronavirus deaths per million grouped by continent:

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

    Displays a line chart of total coronavirus deaths per million grouped by continent:

    covid = pd.read_csv('https://covid.ourworldindata.org/data/owid-covid-data.csv',
                         usecols=['iso_code', 'date', 'total_deaths', 'population'])
     continents = pd.read_csv('https://gist.githubusercontent.com/stevewithington/20a69c0b6d2ff'
                              '846ea5d35e5fc47f26c/raw/country-and-continent-codes-list-csv.csv',
    @@ -2801,22 +2801,23 @@ 

    Format

    Displays a multi-axis line chart of total coronavirus cases and changes in prices of Bitcoin, Dow Jones and gold:

    import pandas as pd, plotly.graph_objects as go
    +

    Displays a multi-axis line chart of total coronavirus cases and changes in prices of Bitcoin, Dow Jones and gold:

    import pandas as pd, plotly.graph_objects as go
     
     def main():
    -    display_data(wrangle_data(*scrape_data()))
    +    covid, bitcoin, gold, dow = scrape_data()
    +    display_data(wrangle_data(covid, bitcoin, gold, dow))
     
     def scrape_data():
    -    def scrape_covid():
    +    def get_covid_cases():
             url = 'https://covid.ourworldindata.org/data/owid-covid-data.csv'
             df = pd.read_csv(url, usecols=['location', 'date', 'total_cases'])
             return df[df.location == 'World'].set_index('date').total_cases
    -    def scrape_yahoo(slug):
    -        url = (f'https://query1.finance.yahoo.com/v7/finance/download/{slug}?'
    +    def get_ticker(symbol):
    +        url = (f'https://query1.finance.yahoo.com/v7/finance/download/{symbol}?'
                    'period1=1579651200&period2=9999999999&interval=1d&events=history')
             df = pd.read_csv(url, usecols=['Date', 'Close'])
             return df.set_index('Date').Close
    -    out = scrape_covid(), scrape_yahoo('BTC-USD'), scrape_yahoo('GC=F'), scrape_yahoo('^DJI')
    +    out = get_covid_cases(), get_ticker('BTC-USD'), get_ticker('GC=F'), get_ticker('^DJI')
         return map(pd.Series.rename, out, ['Total Cases', 'Bitcoin', 'Gold', 'Dow Jones'])
     
     def wrangle_data(covid, bitcoin, gold, dow):
    @@ -2836,8 +2837,9 @@ 

    Format

    'Total Cases', rangemode='tozero'), yaxis2=dict(title='%', rangemode='tozero', overlaying='y', side='right'), - legend=dict(x=1.1), - height=450 + legend=dict(x=1.08), + width=944, + height=423 ) figure.show() @@ -2924,7 +2926,7 @@

    Format

    <Formatter> = logging.Formatter('<format>')          # Creates a Formatter.
    -<Handler> = logging.FileHandler(<path>)              # Creates a Handler.
    +<Handler> = logging.FileHandler(<path>, mode='a')    # Creates a Handler. Also `encoding=None`.
     <Handler>.setFormatter(<Formatter>)                  # Adds Formatter to the Handler.
     <Handler>.setLevel(<int/str>)                        # Processes all messages by default.
     <Logger>.addHandler(<Handler>)                       # Adds Handler to the Logger.
    @@ -2036,10 +2036,10 @@ 

    Format

    'handlers.RotatingFileHandler' creates and deletes log files based on 'maxBytes' and 'backupCount' arguments.

    Creates a logger that writes all messages to file and sends them to the root's handler that prints warnings or higher:

    >>> logger = logging.getLogger('my_module')
    ->>> handler = logging.FileHandler('test.log')
    +>>> handler = logging.FileHandler('test.log', encoding='utf-8')
     >>> formatter = logging.Formatter('%(asctime)s %(levelname)s:%(name)s:%(message)s')
    ->>> logger.addHandler(handler)
     >>> handler.setFormatter(formatter)
    +>>> logger.addHandler(handler)
     >>> logging.basicConfig(level='DEBUG')
     >>> logging.root.handlers[0].setLevel('WARNING')
     >>> logger.critical('Running out of disk space.')
    @@ -2926,7 +2926,7 @@ 

    Format

    = - # Ignores time jumps if they share tzinfo object. = ± # Returned datetime can fall into missing hour. = * # Also: = abs() and = ±% . - = / # How many weeks/years there are in TD. Also //. + = / # How many hours/weeks/years are in TD. Also //. ``` @@ -1459,7 +1459,7 @@ BaseException +-- OSError # Errors such as FileExistsError/PermissionError (see #Open). | +-- ConnectionError # Errors such as BrokenPipeError/ConnectionAbortedError. +-- RuntimeError # Raised by errors that don't fall into other categories. - | +-- NotImplementedErr # Can be raised by abstract methods or by unfinished code. + | +-- NotImplementedEr… # Can be raised by abstract methods or by unfinished code. | +-- RecursionError # Raised when the maximum recursion depth is exceeded. +-- StopIteration # Raised by next() when run on an empty iterator. +-- TypeError # Raised when an argument is of the wrong type. @@ -1482,7 +1482,7 @@ BaseException ```python raise TypeError('Argument is of the wrong type!') raise ValueError('Argument has the right type but an inappropriate value!') -raise RuntimeError('None of above!') +raise RuntimeError('I am too lazy to define my own exception!') ``` ### User-defined Exceptions diff --git a/index.html b/index.html index 7d8e0f6e3..d53c2c650 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -580,7 +580,7 @@ <TD> = <DTa> - <DTa> # Ignores time jumps if they share tzinfo object. <D/DT> = <D/DT> ± <TD> # Returned datetime can fall into missing hour. <TD> = <TD> * <float> # 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 hours/weeks/years are in TD. Also //.

    #Arguments

    Inside Function Call

    func(<positional_args>)                           # func(0, 0)
    @@ -1244,7 +1244,7 @@
           ├── OSError                 # Errors such as FileExistsError/PermissionError (see #Open).
           │    └── ConnectionError    # Errors such as BrokenPipeError/ConnectionAbortedError.
           ├── RuntimeError            # Raised by errors that don't fall into other categories.
    -      │    ├── NotImplementedErr  # Can be raised by abstract methods or by unfinished code.
    +      │    ├── NotImplementedEr…  # Can be raised by abstract methods or by unfinished code.
           │    └── RecursionError     # Raised when the maximum recursion depth is exceeded.
           ├── StopIteration           # Raised by next() when run on an empty iterator.
           ├── TypeError               # Raised when an argument is of the wrong type.
    @@ -1263,7 +1263,7 @@
     
     

    Useful built-in exceptions:

    raise TypeError('Argument is of the wrong type!')
     raise ValueError('Argument has the right type but an inappropriate value!')
    -raise RuntimeError('None of above!')
    +raise RuntimeError('I am too lazy to define my own exception!')
     

    User-defined Exceptions

    class MyError(Exception): pass
    @@ -2933,7 +2933,7 @@ 

    Format

    Inheritance

    class Person:
    -    def __init__(self, name, age):
    +    def __init__(self, name):
             self.name = name
    -        self.age  = age
     
     class Employee(Person):
    -    def __init__(self, name, age, staff_num):
    -        super().__init__(name, age)
    +    def __init__(self, name, staff_num):
    +        super().__init__(name)
             self.staff_num = staff_num
     
    From 8efaa5fd435e75ca38cf483a6b4304a69af0f334 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 7 Jan 2024 00:24:00 +0100 Subject: [PATCH 024/359] Switched Logging and Introspection, Array --- README.md | 55 +++++++++++++++++++++++++------------------------ index.html | 43 +++++++++++++++++++------------------- parse.js | 2 +- web/script_2.js | 6 +++--- 4 files changed, 54 insertions(+), 52 deletions(-) diff --git a/README.md b/README.md index c86b86a11..1c0737c97 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Contents **   ** **3. Syntax:** **         ** **[`Args`](#arguments)**__,__ **[`Inline`](#inline)**__,__ **[`Import`](#imports)**__,__ **[`Decorator`](#decorator)**__,__ **[`Class`](#class)**__,__ **[`Duck_Types`](#duck-types)**__,__ **[`Enum`](#enum)**__,__ **[`Exception`](#exceptions)**__.__ **   ** **4. System:** **        ** **[`Exit`](#exit)**__,__ **[`Print`](#print)**__,__ **[`Input`](#input)**__,__ **[`Command_Line_Arguments`](#command-line-arguments)**__,__ **[`Open`](#open)**__,__ **[`Path`](#paths)**__,__ **[`OS_Commands`](#os-commands)**__.__ **   ** **5. Data:** **             ** **[`JSON`](#json)**__,__ **[`Pickle`](#pickle)**__,__ **[`CSV`](#csv)**__,__ **[`SQLite`](#sqlite)**__,__ **[`Bytes`](#bytes)**__,__ **[`Struct`](#struct)**__,__ **[`Array`](#array)**__,__ **[`Memory_View`](#memory-view)**__,__ **[`Deque`](#deque)**__.__ -**   ** **6. Advanced:** **   ** **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Match_Stmt`](#match-statement)**__,__ **[`Introspection`](#introspection)**__,__ **[`Logging`](#logging)**__,__ **[`Coroutines`](#coroutines)**__.__ +**   ** **6. Advanced:** **   ** **[`Threading`](#threading)**__,__ **[`Operator`](#operator)**__,__ **[`Match_Stmt`](#match-statement)**__,__ **[`Logging`](#logging)**__,__ **[`Introspection`](#introspection)**__,__ **[`Coroutines`](#coroutines)**__.__ **   ** **7. Libraries:** **      ** **[`Progress_Bar`](#progress-bar)**__,__ **[`Plots`](#plot)**__,__ **[`Tables`](#table)**__,__ **[`Curses`](#curses)**__,__ **[`GUIs`](#pysimplegui)**__,__ **[`Scraping`](#scraping)**__,__ **[`Web`](#web)**__,__ **[`Profiling`](#profiling)**__.__ **   ** **8. Multimedia:** **  ** **[`NumPy`](#numpy)**__,__ **[`Image`](#image)**__,__ **[`Animation`](#animation)**__,__ **[`Audio`](#audio)**__,__ **[`Synthesizer`](#synthesizer)**__,__ **[`Pygame`](#pygame)**__,__ **[`Pandas`](#pandas)**__,__ **[`Plotly`](#plotly)**__.__ @@ -2037,6 +2037,7 @@ from array import array = array('', ) # Array from collection of numbers. = array('', ) # Array from bytes object. = array('', ) # Treats array as a sequence of numbers. +.fromfile(, n_items) # Appends items. Raises EOFError on end. = bytes() # Or: .tobytes() .write() # Writes array to the binary file. ``` @@ -2224,32 +2225,6 @@ match : ``` -Introspection -------------- -```python - = dir() # Names of local variables, functions, classes, etc. - = vars() # Dict of local variables, etc. Also locals(). - = globals() # Dict of global vars, etc. (incl. '__builtins__'). -``` - -```python - = dir() # Names of object's attributes (including methods). - = vars() # Dict of writable attributes. Also .__dict__. - = hasattr(, '') # Checks if getattr() raises an AttributeError. -value = getattr(, '') # Raises AttributeError if attribute is missing. -setattr(, '', value) # Only works on objects with '__dict__' attribute. -delattr(, '') # Same. Also `del .`. -``` - -```python - = inspect.signature() # Function's Signature object. - = .parameters # Dict of Parameter objects. - = .kind # Member of ParameterKind enum. - = .default # Default value or Parameter.empty. - = .annotation # Type or Parameter.empty. -``` - - Logging ------- ```python @@ -2303,6 +2278,32 @@ CRITICAL:my_module:Running out of disk space. ``` +Introspection +------------- +```python + = dir() # Names of local variables, functions, classes, etc. + = vars() # Dict of local variables, etc. Also locals(). + = globals() # Dict of global vars, etc. (incl. '__builtins__'). +``` + +```python + = dir() # Names of object's attributes (including methods). + = vars() # Dict of writable attributes. Also .__dict__. + = hasattr(, '') # Checks if getattr() raises an AttributeError. +value = getattr(, '') # Raises AttributeError if attribute is missing. +setattr(, '', value) # Only works on objects with '__dict__' attribute. +delattr(, '') # Same. Also `del .`. +``` + +```python + = inspect.signature() # Function's Signature object. + = .parameters # Dict of Parameter objects. + = .kind # Member of ParameterKind enum. + = .default # Default value or Parameter.empty. + = .annotation # Type or Parameter.empty. +``` + + Coroutines ---------- * **Coroutines have a lot in common with threads, but unlike threads, they only give up control when they call another coroutine and they don’t use as much memory.** diff --git a/index.html b/index.html index 4f71a5676..8c3eebedf 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -85,7 +85,7 @@ '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, Match_Stmt, Introspection, Logging, Coroutines], + '6. Advanced': [Threading, Operator, Match_Stmt, Logging, Introspection, Coroutines], '7. Libraries': [Progress_Bar, Plots, Tables, Curses, GUIs, Scraping, Web, Profiling], '8. Multimedia': [NumPy, Image, Animation, Audio, Synthesizer, Pygame, Pandas, Plotly] } @@ -1685,6 +1685,7 @@

    Format

    '<typecode>', <collection>) # Array from collection of numbers. <array> = array('<typecode>', <bytes>) # Array from bytes object. <array> = array('<typecode>', <array>) # Treats array as a sequence of numbers. +<array>.fromfile(<file>, n_items) # Appends items. Raises EOFError on end. <bytes> = bytes(<array>) # Or: <array>.tobytes() <file>.write(<array>) # Writes array to the binary file.

    @@ -1835,24 +1836,6 @@

    Format

    'README.md is a readme file that belongs to user gto.'

    -

    #Introspection

    <list> = dir()                             # Names of local variables, functions, classes, etc.
    -<dict> = vars()                            # Dict of local variables, etc. Also locals().
    -<dict> = globals()                         # Dict of global vars, etc. (incl. '__builtins__').
    -
    - -
    <list> = dir(<object>)                     # Names of object's attributes (including methods).
    -<dict> = vars(<object>)                    # Dict of writable attributes. Also <obj>.__dict__.
    -<bool> = hasattr(<object>, '<attr_name>')  # Checks if getattr() raises an AttributeError.
    -value  = getattr(<object>, '<attr_name>')  # Raises AttributeError if attribute is missing.
    -setattr(<object>, '<attr_name>', value)    # Only works on objects with '__dict__' attribute.
    -delattr(<object>, '<attr_name>')           # Same. Also `del <object>.<attr_name>`.
    -
    -
    <Sig>  = inspect.signature(<function>)     # Function's Signature object.
    -<dict> = <Sig>.parameters                  # Dict of Parameter objects.
    -<memb> = <Param>.kind                      # Member of ParameterKind enum.
    -<obj>  = <Param>.default                   # Default value or Parameter.empty.
    -<type> = <Param>.annotation                # Type or Parameter.empty.
    -

    #Logging

    import logging
     
    @@ -1896,6 +1879,24 @@

    Format

    #Introspection

    <list> = dir()                             # Names of local variables, functions, classes, etc.
    +<dict> = vars()                            # Dict of local variables, etc. Also locals().
    +<dict> = globals()                         # Dict of global vars, etc. (incl. '__builtins__').
    +
    + +
    <list> = dir(<object>)                     # Names of object's attributes (including methods).
    +<dict> = vars(<object>)                    # Dict of writable attributes. Also <obj>.__dict__.
    +<bool> = hasattr(<object>, '<attr_name>')  # Checks if getattr() raises an AttributeError.
    +value  = getattr(<object>, '<attr_name>')  # Raises AttributeError if attribute is missing.
    +setattr(<object>, '<attr_name>', value)    # Only works on objects with '__dict__' attribute.
    +delattr(<object>, '<attr_name>')           # Same. Also `del <object>.<attr_name>`.
    +
    +
    <Sig>  = inspect.signature(<function>)     # Function's Signature object.
    +<dict> = <Sig>.parameters                  # Dict of Parameter objects.
    +<memb> = <Param>.kind                      # Member of ParameterKind enum.
    +<obj>  = <Param>.default                   # Default value or Parameter.empty.
    +<type> = <Param>.annotation                # Type or Parameter.empty.
    +

    #Coroutines

    • Coroutines have a lot in common with threads, but unlike threads, they only give up control when they call another coroutine and they don’t use as much memory.
    • Coroutine definition starts with 'async' and its call with 'await'.
    • @@ -2932,7 +2933,7 @@

      Format

      - - +


    Libraries

    #Progress Bar

    # $ pip3 install tqdm
    @@ -2932,7 +2933,7 @@ 

    Format

    = - # Ignores jumps. Convert to UTC for actual delta. - = - # Ignores time jumps if they share tzinfo object. + = - # Ignores jumps if they share tzinfo object. = ± # Returned datetime can fall into missing hour. = * # Also: = abs() and = ±% . = / # How many hours/weeks/years are in TD. Also //. @@ -1951,26 +1951,26 @@ Bytes **Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.** ```python - = b'' # Only accepts ASCII characters and \x00-\xff. - = [] # 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. + = b'' # Only accepts ASCII characters and \x00-\xff. + = [] # 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. ``` ### Encode ```python - = 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 whitespaces. + = 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 whitespaces. ``` ### Decode ```python - = 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 hex pairs. Accepts `sep=`. + = 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 hex pairs. Accepts `sep=`. ``` ### Read Bytes from File @@ -2009,12 +2009,12 @@ 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.** +* **`'<'` - Little-endian (i.e. least significant byte first).** * **`'>'` - Big-endian (also `'!'`).** #### Besides numbers, pack() and unpack() also support bytes objects as part of the sequence: * **`'c'` - A bytes object with a single element. For pad byte use `'x'`.** -* **`'s'` - A bytes object with n elements.** +* **`'s'` - A bytes object with n elements (not effected by byte order).** #### Integer types. Use a capital letter for unsigned type. Minimum and standard sizes are in brackets: * **`'b'` - char (1/1)** @@ -2414,7 +2414,7 @@ plt.clf() # Clears the figure. Table ----- -#### Prints a CSV file as an ASCII table: +#### Prints a CSV spreadsheet to the console: ```python # $ pip3 install tabulate import csv, tabulate @@ -2676,7 +2676,7 @@ import numpy as np = np.tile/repeat(, [, axis]) # Tiles array or repeats its elements. ``` * **Shape is a tuple of dimension sizes. A 100x50 RGB image has shape (50, 100, 3).** -* **Axis is an index of the dimension that gets aggregated. Leftmost dimension has index 0. Summing the RGB image along axis 2 will return a greyscale image with shape (50, 100).** +* **Axis is an index of a dimension. Leftmost dimension has index 0. Summing the RGB image along axis 2 will return a greyscale image with shape (50, 100).** ### Indexing ```perl @@ -2858,21 +2858,21 @@ import wave ``` ```python - = wave.open('', 'rb') # Opens the WAV file. - = .getframerate() # Returns number of frames per second. - = .getnchannels() # Returns number of samples per frame. - = .getsampwidth() # Returns number of bytes per sample. - = .getparams() # Returns collection of listed params. - = .readframes(nframes) # Returns next n frames. All if -1. + = wave.open('', 'rb') # Opens the WAV file. + = .getframerate() # Returns number of frames per second. + = .getnchannels() # Returns number of samples per frame. + = .getsampwidth() # Returns number of bytes per sample. + = .getparams() # Returns namedtuple of all parameters. + = .readframes(nframes) # Returns next n frames. All if -1. ``` ```python - = wave.open('', 'wb') # Opens WAV file for writing. -.setframerate() # Pass 44100 for CD, 48000 for video. -.setnchannels() # Pass 1 for mono, 2 for stereo. -.setsampwidth() # Pass 2 for CD, 3 for hi-res sound. -.setparams() # Sets all parameters. -.writeframes() # Appends frames to the file. + = wave.open('', 'wb') # Creates/truncates a file for writing. +.setframerate() # Pass 44100 for CD, 48000 for video. +.setnchannels() # Pass 1 for mono, 2 for stereo. +.setsampwidth() # Pass 2 for CD, 3 for hi-res sound. +.setparams() # Sets all parameters. +.writeframes() # Appends frames to the file. ``` * **Bytes object contains a sequence of frames, each consisting of one or more samples.** * **In a stereo signal, the first sample of a frame belongs to the left channel.** @@ -3007,7 +3007,7 @@ while not pg.event.get(pg.QUIT): ```python = .collidepoint((x, y)) # Checks if rectangle contains the point. - = .colliderect() # Checks if two rectangles overlap. + = .colliderect() # Checks if the two rectangles overlap. = .collidelist() # Returns index of first colliding Rect or -1. = .collidelistall() # Returns indexes of all colliding rectangles. ``` @@ -3025,7 +3025,7 @@ while not pg.event.get(pg.QUIT): ```python .fill(color) # Tuple, Color('#rrggbb[aa]') or Color(). .set_at((x, y), color) # Updates pixel. Also .get_at((x, y)). -.blit(, (x, y)) # Draws passed surface to the surface. +.blit(, (x, y)) # Draws passed surface at specified location. ``` ```python @@ -3051,7 +3051,7 @@ rect(, color, , width=0) # Also polygon(, color, po ### Sound ```python = pg.mixer.Sound() # WAV file or bytes/array of signed shorts. -.play/stop() # Also .set_volume(). +.play/stop() # Also set_volume(), fadeout(msec). ``` ### Basic Mario Brothers Example @@ -3373,7 +3373,7 @@ c 7 8 6 = .groupby(column_key/s) # Splits DF into groups based on passed column. = .apply() # Maps each group. Func can return DF, Sr or el. = [column_key] # Single column GB. All operations return a Sr. - = .size() # A Sr of group sizes. Keys are group "names". + = .size() # A Sr of group sizes. Same keys as get_group(). ``` #### GroupBy — Aggregate, Transform, Map: diff --git a/index.html b/index.html index 269e48ff2..c0eaea6c1 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
    - +
    @@ -576,9 +576,9 @@
  • '%Z' accepts 'UTC/GMT' and local timezone's code and returns timezone's name, 'UTC[±HH:MM]' if timezone is nameless, or an empty string if datetime is naive.
  • Arithmetics

    <bool>   = <D/T/DTn> > <D/T/DTn>            # Ignores time jumps (fold attribute). Also ==.
    -<bool>   = <DTa>     > <DTa>                # Ignores time jumps if they share tzinfo object.
    +<bool>   = <DTa>     > <DTa>                # Ignores jumps if they share tz object. Broken ==.
     <TD>     = <D/DTn>   - <D/DTn>              # Ignores jumps. Convert to UTC for actual delta.
    -<TD>     = <DTa>     - <DTa>                # Ignores time jumps if they share tzinfo object.
    +<TD>     = <DTa>     - <DTa>                # Ignores jumps if they share tzinfo object.
     <D/DT>   = <D/DT>    ± <TD>                 # Returned datetime can fall into missing hour.
     <TD>     = <TD>      * <float>              # Also: <TD> = abs(<TD>) and <TD> = <TD> ±% <TD>.
     <float>  = <TD>      / <TD>                 # How many hours/weeks/years are in TD. Also //.
    @@ -1614,23 +1614,23 @@
     ┃ oracle     │ oracledb     │ oracledb │ www.pypi.org/project/oracledb    ┃
     ┗━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
     
    -

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

    #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 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.
     
    -

    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 whitespaces.
    +

    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 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 hex pairs. Accepts `sep=<str>`.
    +

    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 hex pairs. Accepts `sep=<str>`.
     

    Read Bytes from File

    def read_bytes(filename):
    @@ -1659,11 +1659,11 @@
     

    Format

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

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

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

    • 'c' - A bytes object with a single element. For pad byte use 'x'.
    • -
    • '<n>s' - A bytes object with n elements.
    • +
    • '<n>s' - A bytes object with n elements (not effected by byte order).

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

    • 'b' - char (1/1)
    • 'h' - short (2/2)
    • @@ -1987,7 +1987,7 @@

      Format

      # Clears the figure.

    -

    #Table

    Prints a CSV file as an ASCII table:

    # $ pip3 install tabulate
    +

    #Table

    Prints a CSV spreadsheet to the console:

    # $ pip3 install tabulate
     import csv, tabulate
     with open('test.csv', encoding='utf-8', newline='') as file:
         rows = list(csv.reader(file))
    @@ -2197,7 +2197,7 @@ 

    Format

    Indexing

    <el>       = <2d_array>[row_index, column_index]        # <3d_a>[table_i, row_i, column_i]
     <1d_view>  = <2d_array>[row_index]                      # <3d_a>[table_i, row_i]
    @@ -2341,19 +2341,19 @@ 

    Format

    #Audio

    import wave
     
    -
    <Wave>   = wave.open('<path>', 'rb')   # Opens the WAV file.
    -<int>    = <Wave>.getframerate()       # Returns number of frames per second.
    -<int>    = <Wave>.getnchannels()       # Returns number of samples per frame.
    -<int>    = <Wave>.getsampwidth()       # Returns number of bytes per sample.
    -<params> = <Wave>.getparams()          # Returns collection of listed params.
    -<bytes>  = <Wave>.readframes(nframes)  # Returns next n frames. All if -1.
    +
    <Wave>  = wave.open('<path>', 'rb')   # Opens the WAV file.
    +<int>   = <Wave>.getframerate()       # Returns number of frames per second.
    +<int>   = <Wave>.getnchannels()       # Returns number of samples per frame.
    +<int>   = <Wave>.getsampwidth()       # Returns number of bytes per sample.
    +<tuple> = <Wave>.getparams()          # Returns namedtuple of all parameters.
    +<bytes> = <Wave>.readframes(nframes)  # Returns next n frames. All if -1.
     
    -
    <Wave> = wave.open('<path>', 'wb')     # Opens WAV file for writing.
    -<Wave>.setframerate(<int>)             # Pass 44100 for CD, 48000 for video.
    -<Wave>.setnchannels(<int>)             # Pass 1 for mono, 2 for stereo.
    -<Wave>.setsampwidth(<int>)             # Pass 2 for CD, 3 for hi-res sound.
    -<Wave>.setparams(<params>)             # Sets all parameters.
    -<Wave>.writeframes(<bytes>)            # Appends frames to the file.
    +
    <Wave> = wave.open('<path>', 'wb')    # Creates/truncates a file for writing.
    +<Wave>.setframerate(<int>)            # Pass 44100 for CD, 48000 for video.
    +<Wave>.setnchannels(<int>)            # Pass 1 for mono, 2 for stereo.
    +<Wave>.setsampwidth(<int>)            # Pass 2 for CD, 3 for hi-res sound.
    +<Wave>.setparams(<tuple>)             # Sets all parameters.
    +<Wave>.writeframes(<bytes>)           # Appends frames to the file.
     
    • Bytes object contains a sequence of frames, each consisting of one or more samples.
    • @@ -2464,7 +2464,7 @@

      Format

      <bool> = <Rect>.collidepoint((x, y)) # Checks if rectangle contains the point. -<bool> = <Rect>.colliderect(<Rect>) # Checks if two rectangles overlap. +<bool> = <Rect>.colliderect(<Rect>) # Checks if the 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 rectangles.

    @@ -2478,7 +2478,7 @@

    Format

    <Surf>.fill(color) # Tuple, Color('#rrggbb[aa]') or Color(<name>). <Surf>.set_at((x, y), color) # Updates pixel. Also <Surf>.get_at((x, y)). -<Surf>.blit(<Surf>, (x, y)) # Draws passed surface to the surface. +<Surf>.blit(<Surf>, (x, y)) # Draws passed surface at specified location.

    from pygame.transform import scale, ...
     <Surf> = scale(<Surf>, (width, height))         # Returns scaled surface.
    @@ -2495,7 +2495,7 @@ 

    Format

    Sound

    <Sound> = pg.mixer.Sound(<path/file/bytes>)     # WAV file or bytes/array of signed shorts.
    -<Sound>.play/stop()                             # Also <Sound>.set_volume(<float>).
    +<Sound>.play/stop()                             # Also set_volume(<float>), fadeout(msec).
     

    Basic Mario Brothers Example

    import collections, dataclasses, enum, io, itertools as it, pygame as pg, urllib.request
    @@ -2761,7 +2761,7 @@ 

    Format

    <GB> = <DF>.groupby(column_key/s) # Splits DF into groups based on passed column. <DF> = <GB>.apply(<func>) # Maps each group. Func can return DF, Sr or el. <GB> = <GB>[column_key] # Single column GB. All operations return a Sr. -<Sr> = <GB>.size() # A Sr of group sizes. Keys are group "names". +<Sr> = <GB>.size() # A Sr of group sizes. Same keys as get_group().

    GroupBy — Aggregate, Transform, Map:

    <DF> = <GB>.sum/max/mean/idxmax/all()          # Or: <GB>.agg(lambda <Sr>: <el>)
     <DF> = <GB>.rank/diff/cumsum/ffill()           # Or: <GB>.transform(lambda <Sr>: <Sr>)
    @@ -2933,7 +2933,7 @@ 

    Format