From 932c09d9c660d3f89532b8cd268441faae9d9f5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 15 Sep 2024 13:01:44 +0200 Subject: [PATCH 01/28] Toc, List, Dictionary, Set --- README.md | 32 +++++++++++++++++++------------- index.html | 51 +++++++++++++++++++++++++-------------------------- parse.js | 5 ++--- 3 files changed, 46 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index e589e468a..412d87572 100644 --- a/README.md +++ b/README.md @@ -28,21 +28,25 @@ if __name__ == '__main__': # Skips next line if file was imported. List ---- +```python + = [, , ...] # Creates new list. Also list(). +``` + ```python = [index] # First index is 0. Last -1. Allows assignments. - = [] # Or: [from_inclusive : to_exclusive : ±step] + = [] # Also [from_inclusive : to_exclusive : ±step]. ``` ```python -.append() # Or: += [] -.extend() # Or: += +.append() # Appends element to the end. Also += []. +.extend() # Appends elements to the end. Also += . ``` ```python -.sort() # Sorts in ascending order. +.sort() # Sorts elements in ascending order. .reverse() # Reverses the list in-place. - = sorted() # Returns a new sorted list. - = reversed() # Returns reversed iterator. + = sorted() # Returns new list with sorted elements. + = reversed() # Returns reversed iterator of elements. ``` ```python @@ -70,6 +74,10 @@ list_of_chars = list() Dictionary ---------- +```python + = {key_1: val_1, key_2: val_2, ...} # Use `[key]` to get or set the value. +``` + ```python = .keys() # Coll. of keys that reflects changes. = .values() # Coll. of values that reflects changes. @@ -98,20 +106,19 @@ value = .pop(key) # Removes item or raises KeyErro ### Counter ```python +# $ pip3 install ipython; ipython >>> from collections import Counter >>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red']) >>> counter['yellow'] += 1 ->>> print(counter) -Counter({'blue': 3, 'red': 2, 'yellow': 1}) ->>> counter.most_common()[0] -('blue', 3) +>>> print(counter.most_common()) +[('blue', 3), ('red', 2), ('yellow', 1)] ``` Set --- ```python - = set() # `{}` returns a dictionary. + = {, , ...} # Use `set()` for empty set. ``` ```python @@ -135,8 +142,7 @@ Set ``` ### Frozen Set -* **Is immutable and hashable.** -* **That means it can be used as a key in a dictionary or as an element in a set.** +**Is immutable and hashable, meaning it can be used as a key in dict or as el in set.** ```python = frozenset() ``` diff --git a/index.html b/index.html index 3c707b57a..821a00bac 100644 --- a/index.html +++ b/index.html @@ -54,12 +54,12 @@
- +

Comprehensive Python Cheatsheet


#Contents

ToC = {
+
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, Import, Decorator, Class, Duck_Types, Enum, Exception],
@@ -89,8 +89,7 @@
     '7. Libraries':   [Progress_Bar, Plot, Table, Console_App, GUI, Scraping, Web, Profile],
     '8. Multimedia':  [NumPy, Image, Animation, Audio, Synthesizer, Pygame, Pandas, Plotly]
 }
-
- + @@ -100,17 +99,19 @@ main() # Runs `def main(): ...` function. -

#List

<el>   = <list>[index]          # First index is 0. Last -1. Allows assignments.
-<list> = <list>[<slice>]        # Or: <list>[from_inclusive : to_exclusive : ±step]
+

#List

<list> = [<el_1>, <el_2>, ...]  # Creates new list. Also list(<collection>).
 
-
<list>.append(<el>)             # Or: <list> += [<el>]
-<list>.extend(<collection>)     # Or: <list> += <collection>
+
<el>   = <list>[index]          # First index is 0. Last -1. Allows assignments.
+<list> = <list>[<slice>]        # Also <list>[from_inclusive : to_exclusive : ±step].
 
-
<list>.sort()                   # Sorts in ascending order.
+
<list>.append(<el>)             # Appends element to the end. Also <list> += [<el>].
+<list>.extend(<collection>)     # Appends elements to the end. Also <list> += <coll>.
+
+
<list>.sort()                   # Sorts elements in ascending order.
 <list>.reverse()                # Reverses the list in-place.
-<list> = sorted(<collection>)   # Returns a new sorted list.
-<iter> = reversed(<list>)       # Returns reversed iterator.
+<list> = sorted(<collection>)   # Returns new list with sorted elements.
+<iter> = reversed(<list>)       # Returns reversed iterator of elements.
 
sum_of_elements  = sum(<collection>)
 elementwise_sum  = [sum(pair) for pair in zip(list_a, list_b)]
@@ -132,11 +133,13 @@
 <list>.remove(<el>)             # Removes first occurrence of the item or raises ValueError.
 <list>.clear()                  # Removes all items. Also works on dictionary and set.
 
-

#Dictionary

<view> = <dict>.keys()                          # Coll. of keys that reflects changes.
-<view> = <dict>.values()                        # Coll. of values that reflects changes.
-<view> = <dict>.items()                         # Coll. of key-value tuples that reflects chgs.
+

#Dictionary

<dict> = {key_1: val_1, key_2: val_2, ...}      # Use `<dict>[key]` to get or set the value.
 
+
<view> = <dict>.keys()                          # Coll. of keys that reflects changes.
+<view> = <dict>.values()                        # Coll. of values that reflects changes.
+<view> = <dict>.items()                         # Coll. of key-value tuples that reflects chgs.
+
value  = <dict>.get(key, default=None)          # Returns default if key is missing.
 value  = <dict>.setdefault(key, default=None)   # Returns and writes default if key is missing.
 <dict> = collections.defaultdict(<type>)        # Returns a dict with default value `<type>()`.
@@ -151,16 +154,15 @@
 {k for k, v in <dict>.items() if v == value}    # Returns set of keys that point to the value.
 {k: v for k, v in <dict>.items() if k in keys}  # Filters the dictionary by keys.
 
-

Counter

>>> from collections import Counter
+

Counter

# $ pip3 install ipython; ipython
+>>> from collections import Counter
 >>> counter = Counter(['blue', 'blue', 'blue', 'red', 'red'])
 >>> counter['yellow'] += 1
->>> print(counter)
-Counter({'blue': 3, 'red': 2, 'yellow': 1})
->>> counter.most_common()[0]
-('blue', 3)
+>>> print(counter.most_common())
+[('blue', 3), ('red', 2), ('yellow', 1)]
 
-

#Set

<set> = set()                                   # `{}` returns a dictionary.
+

#Set

<set> = {<el_1>, <el_2>, ...}                   # Use `set()` for empty set.
 
<set>.add(<el>)                                 # Or: <set> |= {<el>}
@@ -177,10 +179,7 @@
 <set>.remove(<el>)                              # Raises KeyError if missing.
 <set>.discard(<el>)                             # Doesn't raise an error.
 
-

Frozen Set

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

Frozen Set

Is immutable and hashable, meaning it can be used as a key in dict or as el in set.

<frozenset> = frozenset(<collection>)
 
@@ -2931,7 +2930,7 @@

Format

Contents

\n' + - '
ToC = {\n' +
+  '
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, Import, Decorator, Class, Duck_Types, Enum, Exception],\n' +
@@ -763,6 +761,7 @@ function insertLinks() {
 function unindentBanner() {
   const montyImg = $('img').first();
   montyImg.parent().addClass('banner');
+  montyImg.parent().css({"margin-bottom": "20px", "padding-bottom": "7px"})
   const downloadPraragrapth = $('p').first();
   downloadPraragrapth.addClass('banner');
 }

From 06bc3ec94fc9454adcf0c40f44b8fa9e76ba6d6e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jure=20=C5=A0orn?= 
Date: Wed, 2 Oct 2024 19:58:50 +0200
Subject: [PATCH 02/28] Format, Command line argumetns, Open, Web, Image

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

diff --git a/README.md b/README.md
index 3fa32085a..ae047b50f 100644
--- a/README.md
+++ b/README.md
@@ -412,7 +412,7 @@ Format
 {:.<10}                              # '......'
 {:0}                                 # ''
 ```
-* **Objects are rendered using `'format(, )'`.**
+* **Objects are rendered using `'format(, "")'`.**
 * **Options can be generated dynamically: `f'{:{}[…]}'`.**
 * **Adding `'='` to the expression prepends it to the output: `f'{1+1=}'` returns `'1+1=2'`.**
 * **Adding `'!r'` to the expression converts object to string by calling its [repr()](#class) method.**
@@ -1550,8 +1550,8 @@ p.add_argument('-', '--', type=)          # Option (defa
 p.add_argument('', type=, nargs=1)                    # Mandatory first argument.
 p.add_argument('', type=, nargs='+')                  # Mandatory remaining args.
 p.add_argument('', type=, nargs='?/*')                # Optional argument/s.
- = p.parse_args()                                           # Exits on parsing error.
-  = .                                            # Returns `()`.
+args  = p.parse_args()                                            # Exits on parsing error.
+ = args.                                               # Returns `()`.
 ```
 
 * **Use `'help='` to set argument description that will be displayed in help message.**
@@ -1591,7 +1591,7 @@ Open
 .seek(0)                      # Moves to the start of the file.
 .seek(offset)                 # Moves 'offset' chars/bytes from the start.
 .seek(0, 2)                   # Moves to the end of the file.
-.seek(±offset, )  # Anchor: 0 start, 1 current position, 2 end.
+.seek(±offset, origin)    # Origin: 0 start, 1 current position, 2 end.
 ```
 
 ```python
@@ -2568,7 +2568,7 @@ def serve_html(sport):
     return flask.render_template_string('

{{title}}

', title=sport) ``` * **Use `'render_template(filename, )'` to render file located in templates dir.** -* **To return an error code use `'abort()'` and to redirect use `'redirect()'`.** +* **To return an error code use `'abort()'` and to redirect use `'redirect("")'`.** * **`'request.args[]'` returns parameter from the query string (URL part after '?').** * **`'session[] = '` stores session data. Needs `'app.secret_key = '`.** @@ -2771,22 +2771,22 @@ from PIL import Image ```python = Image.new('', (width, height)) # Creates new image. Also `color=`. = Image.open() # Identifies format based on file's contents. - = .convert('') # Converts image to the new mode. + = .convert('') # Converts image to the new mode (see Modes). .save() # Selects format based on extension (PNG/JPG…). .show() # Opens image in the default preview app. ``` ```python - = .getpixel((x, y)) # Returns pixel's value (its color). -.putpixel((x, y), ) # Updates pixel's value. - = .getdata() # Returns a flattened view of pixel values. -.putdata() # Updates pixels with a copy of the sequence. + = .getpixel((x, y)) # Returns pixel's value (its color). + = .getdata() # Returns a flattened view of pixel values. +.putpixel((x, y), ) # Updates pixel's value. Clips passed int/s. +.putdata() # Updates pixels with a copy of the sequence. .paste(, (x, y)) # Draws passed image at the specified location. ``` ```python - = .filter() # ` = ImageFilter.()` - = .enhance() # ` = ImageEnhance.()` + = .filter() # Use ImageFilter.() for Filter. + = .enhance() # Use ImageEnhance.() for Enhance. ``` ```python @@ -2797,7 +2797,7 @@ from PIL import Image ### Modes * **`'L'` - Lightness (greyscale image). Each pixel is an int between 0 and 255.** * **`'RGB'` - Red, green, blue (true color image). Each pixel is a tuple of three ints.** -* **`'RGBA'` - RGB with alpha. Low alpha (i.e. forth int) makes pixel more transparent.** +* **`'RGBA'` - RGB with alpha. Low alpha (i.e. forth int) makes pixels more transparent.** * **`'HSV'` - Hue, saturation, value. Three ints representing color in HSV color space.** diff --git a/index.html b/index.html index 2d4c44002..3328dd41a 100644 --- a/index.html +++ b/index.html @@ -54,7 +54,7 @@
- +
@@ -380,7 +380,7 @@
    -
  • Objects are rendered using 'format(<el>, <options>)'.
  • +
  • Objects are rendered using 'format(<el>, "<options>")'.
  • Options can be generated dynamically: f'{<el>:{<str/int>}[…]}'.
  • Adding '=' to the expression prepends it to the output: f'{1+1=}' returns '1+1=2'.
  • Adding '!r' to the expression converts object to string by calling its repr() method.
  • @@ -1314,8 +1314,8 @@ p.add_argument('<name>', type=<type>, nargs=1) # Mandatory first argument. p.add_argument('<name>', type=<type>, nargs='+') # Mandatory remaining args. p.add_argument('<name>', type=<type>, nargs='?/*') # Optional argument/s. -<args> = p.parse_args() # Exits on parsing error. -<obj> = <args>.<name> # Returns `<type>(<arg>)`. +args = p.parse_args() # Exits on parsing error. +<obj> = args.<name> # Returns `<type>(<arg>)`.
    @@ -1349,7 +1349,7 @@

File Object

<file>.seek(0)                      # Moves to the start of the file.
 <file>.seek(offset)                 # Moves 'offset' chars/bytes from the start.
 <file>.seek(0, 2)                   # Moves to the end of the file.
-<bin_file>.seek(±offset, <anchor>)  # Anchor: 0 start, 1 current position, 2 end.
+<bin_file>.seek(±offset, origin)    # Origin: 0 start, 1 current position, 2 end.
 
@@ -2108,7 +2108,7 @@

Format

'render_template(filename, <kwargs>)' to render file located in templates dir. -
  • To return an error code use 'abort(<int>)' and to redirect use 'redirect(<url>)'.
  • +
  • To return an error code use 'abort(<int>)' and to redirect use 'redirect("<url>")'.
  • 'request.args[<str>]' returns parameter from the query string (URL part after '?').
  • 'session[<str>] = <obj>' stores session data. Needs 'app.secret_key = <str>'.
  • @@ -2264,18 +2264,18 @@

    Format

    <Image> = Image.new('<mode>', (width, height)) # Creates new image. Also `color=<int/tuple>`. <Image> = Image.open(<path>) # Identifies format based on file's contents. -<Image> = <Image>.convert('<mode>') # Converts image to the new mode. +<Image> = <Image>.convert('<mode>') # Converts image to the new mode (see Modes). <Image>.save(<path>) # Selects format based on extension (PNG/JPG…). <Image>.show() # Opens image in the default preview app.

    -
    <int/tuple> = <Image>.getpixel((x, y))          # Returns pixel's value (its color).
    -<Image>.putpixel((x, y), <int/tuple>)           # Updates pixel's value.
    -<ImagingCore> = <Image>.getdata()               # Returns a flattened view of pixel values.
    -<Image>.putdata(<list/ImagingCore>)             # Updates pixels with a copy of the sequence.
    +
    <int/tup> = <Image>.getpixel((x, y))            # Returns pixel's value (its color).
    +<ImgCore> = <Image>.getdata()                   # Returns a flattened view of pixel values.
    +<Image>.putpixel((x, y), <int/tuple>)           # Updates pixel's value. Clips passed int/s.
    +<Image>.putdata(<list/ImgCore>)                 # Updates pixels with a copy of the sequence.
     <Image>.paste(<Image>, (x, y))                  # Draws passed image at the specified location.
     
    -
    <Image> = <Image>.filter(<Filter>)              # `<Filter> = ImageFilter.<name>(<args>)`
    -<Image> = <Enhance>.enhance(<float>)            # `<Enhance> = ImageEnhance.<name>(<Image>)`
    +
    <Image> = <Image>.filter(<Filter>)              # Use ImageFilter.<name>(<args>) for Filter.
    +<Image> = <Enhance>.enhance(<float>)            # Use ImageEnhance.<name>(<Image>) for Enhance.
     
    <array> = np.array(<Image>)                     # Creates a 2d/3d NumPy array from the image.
     <Image> = Image.fromarray(np.uint8(<array>))    # Use `<array>.clip(0, 255)` to clip values.
    @@ -2283,7 +2283,7 @@ 

    Format

    Modes

    • 'L' - Lightness (greyscale image). Each pixel is an int between 0 and 255.
    • 'RGB' - Red, green, blue (true color image). Each pixel is a tuple of three ints.
    • -
    • 'RGBA' - RGB with alpha. Low alpha (i.e. forth int) makes pixel more transparent.
    • +
    • 'RGBA' - RGB with alpha. Low alpha (i.e. forth int) makes pixels more transparent.
    • 'HSV' - Hue, saturation, value. Three ints representing color in HSV color space.

    Examples

    Creates a PNG image of a rainbow gradient:

    WIDTH, HEIGHT = 100, 100
     n_pixels = WIDTH * HEIGHT
    @@ -2931,7 +2931,7 @@ 

    Format

    #Memory View

    A sequence object that points to the memory of another bytes-like object. Each element can reference a single or multiple consecutive bytes, depending on format. Order and number of elements can be changed with slicing.

    <mview> = memoryview(<bytes/bytearray/array>)  # Immutable if bytes is passed, else mutable.
    -<obj>   = <mview>[index]                       # Returns int/float. Bytes if format is 'c'.
    +<obj>   = <mview>[index]                       # Returns int or float. Bytes if format is 'c'.
     <mview> = <mview>[<slice>]                     # Returns memoryview with rearranged elements.
     <mview> = <mview>.cast('<typecode>')           # Only works between B/b/c and other types.
     <mview>.release()                              # Releases memory buffer of the base object.
     
    -
    <bytes> = bytes(<mview>)                       # Returns a new bytes object.
    +
    <bytes> = bytes(<mview>)                       # Returns a new bytes object. Also bytearray().
     <bytes> = <bytes>.join(<coll_of_mviews>)       # Joins memoryviews using bytes as a separator.
     <array> = array('<typecode>', <mview>)         # Treats memoryview as a sequence of numbers.
     <file>.write(<mview>)                          # Writes `bytes(<mview>)` to the binary file.
    
    From 335fcd1db84c4549811a246e4774aac40996486a Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Thu, 3 Oct 2024 17:34:28 +0200
    Subject: [PATCH 04/28] Audio
    
    ---
     README.md  | 42 +++++++++++++++++++++---------------------
     index.html | 44 ++++++++++++++++++++++----------------------
     parse.js   | 18 ++++++++++++++++--
     3 files changed, 59 insertions(+), 45 deletions(-)
    
    diff --git a/README.md b/README.md
    index 4054d36c3..867c839d5 100644
    --- a/README.md
    +++ b/README.md
    @@ -2867,7 +2867,7 @@ import wave
     ```
     
     ```python
    -  = wave.open('', 'rb')   # Opens the WAV file.
    +  = wave.open('')         # Opens the WAV file for reading.
        = .getframerate()       # Returns number of frames per second.
        = .getnchannels()       # Returns number of samples per frame.
        = .getsampwidth()       # Returns number of bytes per sample.
    @@ -2880,7 +2880,7 @@ import wave
     .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.
    +.setparams()             # Tuple must contain all parameters.
     .writeframes()           # Appends frames to the file.
     ```
     * **Bytes object contains a sequence of frames, each consisting of one or more samples.**
    @@ -2904,28 +2904,28 @@ import wave
     ```python
     def read_wav_file(filename):
         def get_int(bytes_obj):
    -        an_int = int.from_bytes(bytes_obj, 'little', signed=(sampwidth != 1))
    -        return an_int - 128 * (sampwidth == 1)
    -    with wave.open(filename, 'rb') as file:
    -        sampwidth = file.getsampwidth()
    +        an_int = int.from_bytes(bytes_obj, 'little', signed=(p.sampwidth != 1))
    +        return an_int - 128 * (p.sampwidth == 1)
    +    with wave.open(filename) as file:
    +        p = file.getparams()
             frames = file.readframes(-1)
    -    bytes_samples = (frames[i : i+sampwidth] for i in range(0, len(frames), sampwidth))
    -    return [get_int(b) / pow(2, sampwidth * 8 - 1) for b in bytes_samples]
    +    bytes_samples = (frames[i : i + p.sampwidth] for i in range(0, len(frames), p.sampwidth))
    +    return [get_int(b) / pow(2, p.sampwidth * 8 - 1) for b in bytes_samples], p
     ```
     
     ### Write Float Samples to WAV File
     ```python
    -def write_to_wav_file(filename, float_samples, nchannels=1, sampwidth=2, framerate=44100):
    +def write_to_wav_file(filename, samples_f, p=None, nchannels=1, sampwidth=2, framerate=44100):
         def get_bytes(a_float):
             a_float = max(-1, min(1 - 2e-16, a_float))
    -        a_float += sampwidth == 1
    -        a_float *= pow(2, sampwidth * 8 - 1)
    -        return int(a_float).to_bytes(sampwidth, 'little', signed=(sampwidth != 1))
    +        a_float += p.sampwidth == 1
    +        a_float *= pow(2, p.sampwidth * 8 - 1)
    +        return int(a_float).to_bytes(p.sampwidth, 'little', signed=(p.sampwidth != 1))
    +    if p is None:
    +        p = wave._wave_params(nchannels, sampwidth, framerate, 0, 'NONE', 'not compressed')
         with wave.open(filename, 'wb') as file:
    -        file.setnchannels(nchannels)
    -        file.setsampwidth(sampwidth)
    -        file.setframerate(framerate)
    -        file.writeframes(b''.join(get_bytes(f) for f in float_samples))
    +        file.setparams(p)
    +        file.writeframes(b''.join(get_bytes(f) for f in samples_f))
     ```
     
     ### Examples
    @@ -2936,12 +2936,12 @@ samples_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100_000))
     write_to_wav_file('test.wav', samples_f)
     ```
     
    -#### Adds noise to the mono WAV file:
    +#### Adds noise to the WAV file:
     ```python
    -from random import random
    -add_noise = lambda value: value + (random() - 0.5) * 0.03
    -samples_f = (add_noise(f) for f in read_wav_file('test.wav'))
    -write_to_wav_file('test.wav', samples_f)
    +from random import uniform
    +samples_f, params = read_wav_file('test.wav')
    +samples_f = (f + uniform(-0.05, 0.05) for f in samples_f)
    +write_to_wav_file('test.wav', samples_f, params)
     ```
     
     #### Plays the WAV file:
    diff --git a/index.html b/index.html
    index fd1a4f9c1..408be5b0e 100644
    --- a/index.html
    +++ b/index.html
    @@ -54,7 +54,7 @@
     
     
       
    - +
    @@ -2340,7 +2340,7 @@

    Format

    #Audio

    import wave
     
    -
    <Wave>  = wave.open('<path>', 'rb')   # Opens the WAV file.
    +
    <Wave>  = wave.open('<path>')         # Opens the WAV file for reading.
     <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.
    @@ -2351,7 +2351,7 @@ 

    Format

    # 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>.setparams(<tuple>) # Tuple must contain all parameters. <Wave>.writeframes(<bytes>) # Appends frames to the file.