From de1f11380cdaa01f68bbe8f68261b3176c9024ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 28 Jul 2021 20:03:59 +0200 Subject: [PATCH 001/660] Updated parse.js documentation --- .gitignore | 3 +++ parse.js | 12 +++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..b8ffe08f2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +package-lock.json + diff --git a/parse.js b/parse.js index c760811a9..69f53d0ea 100755 --- a/parse.js +++ b/parse.js @@ -1,12 +1,18 @@ #!/usr/bin/env node // Usage: node parse.js +// // Script that creates index.html out of web/template.html and README.md. // It is written in JS because this code used to be executed on the client side. -// To install dependencies run: -// $ npm install -g jsdom jquery showdown highlightjs -// If running on Mac and modules can't be found after installation add: +// To install the Node.js and npm run: +// $ sudo apt install nodejs npm # On macOS use `brew install ...` instead. +// To install dependencies globally, run: +// $ npm install -g jsdom jquery showdown highlightjs@9.12.0 +// If running on macOS and modules can't be found after installation add: // export NODE_PATH=/usr/local/lib/node_modules // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'. +// To avoid problems with permissions and path variables, install modules +// into project's directory using: +// $ npm install jsdom jquery showdown highlightjs@9.12.0 const fs = require('fs'); From 6b23015f735d6080670dd358bb6f61cc9a828580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 28 Jul 2021 20:15:25 +0200 Subject: [PATCH 002/660] Updated parse.js documentation --- parse.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/parse.js b/parse.js index 69f53d0ea..aaba64012 100755 --- a/parse.js +++ b/parse.js @@ -13,6 +13,9 @@ // To avoid problems with permissions and path variables, install modules // into project's directory using: // $ npm install jsdom jquery showdown highlightjs@9.12.0 +// It is also advisable to add a script into .git/hooks directory, that will run +// this script before every commit. It should be named 'pre-commit' and it should +// contain the following line: `./parse.js`. const fs = require('fs'); From 332bf7e913a7849943c77824425e4b30afe1876a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 29 Jul 2021 00:58:34 +0200 Subject: [PATCH 003/660] Removed .gitignore --- .gitignore | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .gitignore diff --git a/.gitignore b/.gitignore deleted file mode 100644 index b8ffe08f2..000000000 --- a/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ -package-lock.json - From 1fa9a9939b3ebb086a041d1a021d89f372f308d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 11 Aug 2021 21:18:55 +0200 Subject: [PATCH 004/660] Parse.js now automatically updates the date of index.html --- index.html | 6 +++--- parse.js | 26 ++++++++++++++++++++++---- web/template.html | 2 +- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/index.html b/index.html index bc964be98..e62fe063f 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
- +
@@ -3005,8 +3005,8 @@ diff --git a/parse.js b/parse.js index aaba64012..ab5bdbe32 100755 --- a/parse.js +++ b/parse.js @@ -2,20 +2,25 @@ // Usage: node parse.js // // Script that creates index.html out of web/template.html and README.md. +// // It is written in JS because this code used to be executed on the client side. // To install the Node.js and npm run: // $ sudo apt install nodejs npm # On macOS use `brew install ...` instead. +// // To install dependencies globally, run: // $ npm install -g jsdom jquery showdown highlightjs@9.12.0 +// // If running on macOS and modules can't be found after installation add: // export NODE_PATH=/usr/local/lib/node_modules // to the ~/.bash_profile or ~/.bashrc file and run '$ bash'. +// // To avoid problems with permissions and path variables, install modules // into project's directory using: // $ npm install jsdom jquery showdown highlightjs@9.12.0 -// It is also advisable to add a script into .git/hooks directory, that will run -// this script before every commit. It should be named 'pre-commit' and it should -// contain the following line: `./parse.js`. +// +// It is also advisable to add a Bash script into .git/hooks directory, that will +// run this script before every commit. It should be named 'pre-commit' and it +// should contain the following line: `./parse.js`. const fs = require('fs'); @@ -408,7 +413,8 @@ function main() { const html = getMd(); initDom(html); modifyPage(); - const template = readFile('web/template.html'); + var template = readFile('web/template.html'); + template = updateDate(template); const tokens = template.split('
'); const text = `${tokens[0]} ${document.body.innerHTML} ${tokens[1]}`; writeToFile('index.html', text); @@ -580,6 +586,18 @@ function removePlotImages() { $('img[alt="Covid Cases"]').remove(); } + +function updateDate(template) { + const date = new Date(); + const date_str = date.toLocaleString('en-us', {month: 'long', day: 'numeric', year: 'numeric'}); + template = template.replace('May 20, 2021', date_str); + template = template.replace('May 20, 2021', date_str); + return template; +} + + +// UTIL + function readFile(filename) { try { return fs.readFileSync(filename, 'utf8'); diff --git a/web/template.html b/web/template.html index d508fa55b..8db5fe75e 100644 --- a/web/template.html +++ b/web/template.html @@ -235,7 +235,7 @@ From dd37505f3fc1c80bef73d9c5ec798a7dc49c550d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Oct 2021 01:22:39 +0200 Subject: [PATCH 005/660] Inline --- README.md | 22 +++++++++++----------- index.html | 26 +++++++++++++------------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 19637c4ad..26e451a55 100644 --- a/README.md +++ b/README.md @@ -732,10 +732,10 @@ def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3 ### Other Uses ```python - = [* [, ...]] - = {* [, ...]} - = (*, [...]) - = {** [, ...]} + = [* [, ...]] + = {* [, ...]} + = (*, [...]) + = {** [, ...]} ``` ```python @@ -774,8 +774,8 @@ Inline ### Any, All ```python - = any() # False if empty. - = all(el[1] for el in ) # True if empty. + = any() # Is `bool(el)` True for any element. + = all() # Is True for all elements or empty. ``` ### Conditional Expression @@ -788,11 +788,11 @@ Inline ['zero', 1, 2, 3] ``` -### Namedtuple, Enum, Dataclass +### Named Tuple, Enum, Dataclass ```python from collections import namedtuple -Point = namedtuple('Point', 'x y') -point = Point(0, 0) +Point = namedtuple('Point', 'x y') +point = Point(0, 0) ``` ```python @@ -803,8 +803,8 @@ direction = Direction.n ```python from dataclasses import make_dataclass -Creature = make_dataclass('Creature', ['loc', 'dir']) -creature = Creature(Point(0, 0), Direction.n) +Creature = make_dataclass('Creature', ['loc', 'dir']) +creature = Creature(point, direction) ``` diff --git a/index.html b/index.html index e62fe063f..6a3e2e703 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
- +
@@ -786,10 +786,10 @@ def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) -

Other Uses

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

Other Uses

<list>  = [*<collection> [, ...]]
+<set>   = {*<collection> [, ...]}
+<tuple> = (*<collection>, [...])
+<dict>  = {**<dict> [, ...]}
 
head, *body, tail = <collection>
@@ -816,8 +816,8 @@
 
  • Reduce must be imported from functools module.
-

Any, All

<bool> = any(<collection>)                                # False if empty.
-<bool> = all(el[1] for el in <collection>)                # True if 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>
@@ -826,9 +826,9 @@
 
>>> [a if a else 'zero' for a in (0, 1, 2, 3)]
 ['zero', 1, 2, 3]
 
-

Namedtuple, Enum, Dataclass

from collections import namedtuple
-Point     = namedtuple('Point', 'x y')
-point     = Point(0, 0)
+

Named Tuple, Enum, Dataclass

from collections import namedtuple
+Point = namedtuple('Point', 'x y')
+point = Point(0, 0)
 
from enum import Enum
@@ -836,8 +836,8 @@
 direction = Direction.n
 
from dataclasses import make_dataclass
-Creature  = make_dataclass('Creature', ['loc', 'dir'])
-creature  = Creature(Point(0, 0), Direction.n)
+Creature = make_dataclass('Creature', ['loc', 'dir'])
+creature = Creature(point, direction)
 

#Closure

We have a closure in Python when:

  • A nested function references a value of its enclosing function and then
  • @@ -3005,7 +3005,7 @@ From 19eb97ccf52601e83651a5e918d2d96df9e078c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Oct 2021 04:12:05 +0200 Subject: [PATCH 006/660] String --- README.md | 2 +- index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 26e451a55..79a3f9d10 100644 --- a/README.md +++ b/README.md @@ -308,7 +308,7 @@ String ```python = .split() # Splits on one or more whitespace characters. = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. - = .splitlines(keepends=False) # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'. + = .splitlines(keepends=False) # Splits on [\n\r\f\v\x1c\x1d\x1e\x85…] and \r\n. = .join() # Joins elements using string as a separator. ``` diff --git a/index.html b/index.html index 6a3e2e703..7afc768d0 100644 --- a/index.html +++ b/index.html @@ -449,7 +449,7 @@
    <list> = <str>.split()                       # Splits on one or more whitespace characters.
     <list> = <str>.split(sep=None, maxsplit=-1)  # Splits on 'sep' str at most 'maxsplit' times.
    -<list> = <str>.splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85] and '\r\n'.
    +<list> = <str>.splitlines(keepends=False)    # Splits on [\n\r\f\v\x1c\x1d\x1e\x85…] and \r\n.
     <str>  = <str>.join(<coll_of_strings>)       # Joins elements using string as a separator.
     
    <bool> = <sub_str> in <str>                  # Checks if string contains a substring.
    
    From 7af8bec7c34403de4d7c80a316de2f2ee815eb7e Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Jure=20=C5=A0orn?= 
    Date: Sat, 2 Oct 2021 03:05:05 +0200
    Subject: [PATCH 007/660] Curses
    
    ---
     README.md  | 4 ++--
     index.html | 8 ++++----
     2 files changed, 6 insertions(+), 6 deletions(-)
    
    diff --git a/README.md b/README.md
    index 79a3f9d10..57bbf577a 100644
    --- a/README.md
    +++ b/README.md
    @@ -2383,8 +2383,8 @@ def main(screen):
         while ch != ascii.ESC:
             height, _ = screen.getmaxyx()
             screen.clear()
    -        for y, a_path in enumerate(paths[first : first+height]):
    -            screen.addstr(y, 0, a_path, A_REVERSE * (selected == first + y))
    +        for y, filename in enumerate(paths[first : first+height]):
    +            screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y))
             ch = screen.getch()
             selected += (ch == KEY_DOWN) - (ch == KEY_UP)
             selected = max(0, min(len(paths)-1, selected))
    diff --git a/index.html b/index.html
    index 7afc768d0..009e5f7b9 100644
    --- a/index.html
    +++ b/index.html
    @@ -226,7 +226,7 @@
     
     
       
    - +
    @@ -2093,8 +2093,8 @@ while ch != ascii.ESC: height, _ = screen.getmaxyx() screen.clear() - for y, a_path in enumerate(paths[first : first+height]): - screen.addstr(y, 0, a_path, A_REVERSE * (selected == first + y)) + for y, filename in enumerate(paths[first : first+height]): + screen.addstr(y, 0, filename, A_REVERSE * (selected == first + y)) ch = screen.getch() selected += (ch == KEY_DOWN) - (ch == KEY_UP) selected = max(0, min(len(paths)-1, selected)) @@ -3005,7 +3005,7 @@ From 6344398401ca3b9c6466a53e95d966ed398e57ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Oct 2021 03:15:42 +0200 Subject: [PATCH 008/660] Fixed links at the top --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 57bbf577a..31722a497 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). +Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. ![Monty Python](web/image_888.jpeg) From fd773050e35876500b810ad4a84d23870320dcb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Oct 2021 03:20:15 +0200 Subject: [PATCH 009/660] Reverted link changes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 31722a497..57bbf577a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ Comprehensive Python Cheatsheet =============================== -Download text file, Buy PDF, Fork me on GitHub or Check out FAQ. +[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/main/README.md), [Buy PDF](https://transactions.sendowl.com/products/78175486/4422834F/view), [Fork me on GitHub](https://github.com/gto76/python-cheatsheet) or [Check out FAQ](https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions). ![Monty Python](web/image_888.jpeg) From bbde7a70b58ff97b8706e3734794fee4bf346737 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 4 Oct 2021 04:31:29 +0200 Subject: [PATCH 010/660] Format, Pygame --- README.md | 8 +++++--- index.html | 14 ++++++++------ 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 57bbf577a..7c213e3aa 100644 --- a/README.md +++ b/README.md @@ -412,18 +412,20 @@ Format {:.<10} # '......' {:0} # '' ``` -* **Use `'{:{}[...]}'` to set options dynamically.** +* **Options can be generated dynamically: `f'{:{}[…]}'`.** * **Adding `'!r'` before the colon converts object to string by calling its [repr()](#class) method.** ### Strings ```python -{'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' @@ -2950,7 +2952,7 @@ while all(event.type != pg.QUIT for event in pg.event.get()): **Object for representing images.** ```python = pg.display.set_mode((width, height)) # Returns display surface. - = pg.Surface((width, height), …) # New RGB surface. Add `pg.SRCALPHA` for RGBA. + = pg.Surface((width, height) [, flags]) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. = pg.image.load('') # Loads the image. Format depends on source. = .subsurface() # Returns a subsurface. ``` diff --git a/index.html b/index.html index 009e5f7b9..1d802bbef 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -537,15 +537,17 @@
    -
  • Use '{<el>:{<str/int/float>}[...]}' to set options dynamically.
  • +
  • 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'!r:10}                                 # "'abcde'   "
+

Strings

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

Numbers

{ 123456:10,}                                  # '   123,456'
+

Numbers

{ 123456:10}                                   # '    123456'
+{ 123456:10,}                                  # '   123,456'
 { 123456:10_}                                  # '   123_456'
 { 123456:+10}                                  # '   +123456'
 {-123456:=10}                                  # '-   123456'
@@ -2538,7 +2540,7 @@
 <list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding Rects.
 

Surface

Object for representing images.

<Surf> = pg.display.set_mode((width, height))   # Returns display surface.
-<Surf> = pg.Surface((width, height), …)         # New RGB surface. Add `pg.SRCALPHA` for RGBA.
+<Surf> = pg.Surface((width, height) [, flags])  # 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.
 
@@ -3005,7 +3007,7 @@ From a9454ebabd0fab409d71eec41eea1a6eade84593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=AD=E4=B9=9D=E9=BC=8E?= <109224573@qq.com> Date: Wed, 6 Oct 2021 10:21:42 +0800 Subject: [PATCH 011/660] subprocess.run: encoding -> text=True --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7c213e3aa..94f8ada68 100644 --- a/README.md +++ b/README.md @@ -1703,7 +1703,7 @@ import os #### 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, encoding='utf-8') +>>> run('bc', input='1 + 1\n', capture_output=True, text=True) CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='') ``` From 2be9c2df86dfd98a8ece1bfed24a2d255785f3ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Oct 2021 10:03:17 +0200 Subject: [PATCH 012/660] Format, Class, Enum, Exception --- README.md | 20 ++++++++++---------- index.html | 24 ++++++++++++------------ web/faq.html | 2 +- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 7c213e3aa..fde4a5d09 100644 --- a/README.md +++ b/README.md @@ -425,12 +425,12 @@ Format ### Numbers ```python -{ 123456:10} # ' 123456' -{ 123456:10,} # ' 123,456' -{ 123456:10_} # ' 123_456' -{ 123456:+10} # ' +123456' -{-123456:=10} # '- 123456' -{ 123456: } # ' 123456' +{123456:10} # ' 123456' +{123456:10,} # ' 123,456' +{123456:10_} # ' 123_456' +{123456:+10} # ' +123456' +{123456:=+10} # '+ 123456' +{123456: } # ' 123456' {-123456: } # '-123456' ``` @@ -1031,6 +1031,7 @@ class : : = : list/dict/set = field(default_factory=list/dict/set) ``` +* **For arbitrary type use `'typing.Any'`.** * **Objects can be made sortable with `'order=True'` and immutable with `'frozen=True'`.** * **For object to be hashable, all attributes must be hashable and frozen must be True.** * **Function field() is needed because `': list = []'` would make a list that is shared among all instances.** @@ -1333,9 +1334,9 @@ Cutlery = Enum('Cutlery', {'fork': 1, 'knife': 2, 'spoon': 3}) ```python from functools import partial LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), - 'OR' : partial(lambda l, r: l or r)}) + 'OR': partial(lambda l, r: l or r)}) ``` -* **Another solution in this particular case is to use functions and\_() and or\_() from the module [operator](#operator).** +* **Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.** Exceptions @@ -1362,7 +1363,7 @@ finally: ``` * **Code inside the `'else'` block will only be executed if `'try'` block had no exceptions.** -* **Code inside the `'finally'` block will always be executed.** +* **Code inside the `'finally'` block will always be executed (unless a signal is received).** ### Catching Exceptions ```python @@ -2131,7 +2132,6 @@ sorted_by_second = sorted(, key=op.itemgetter(1)) sorted_by_both = sorted(, key=op.itemgetter(1, 0)) product_of_elems = functools.reduce(op.mul, ) union_of_sets = functools.reduce(op.or_, ) -LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR': op.or_}) last_el = op.methodcaller('pop')() ``` diff --git a/index.html b/index.html index 1d802bbef..3326aeade 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
- +
@@ -546,12 +546,12 @@ {'abcde'!r:10} # "'abcde' "
-

Numbers

{ 123456:10}                                   # '    123456'
-{ 123456:10,}                                  # '   123,456'
-{ 123456:10_}                                  # '   123_456'
-{ 123456:+10}                                  # '   +123456'
-{-123456:=10}                                  # '-   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'
 
@@ -1025,6 +1025,7 @@
    +
  • For arbitrary type use 'typing.Any'.
  • Objects can be made sortable with 'order=True' and immutable with 'frozen=True'.
  • For object to be hashable, all attributes must be hashable and frozen must be True.
  • Function field() is needed because '<attr_name>: list = []' would make a list that is shared among all instances.
  • @@ -1291,11 +1292,11 @@

    User-defined functions cannot be values, so they must be wrapped:

    from functools import partial
     LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r),
    -                           'OR' : partial(lambda l, r: l or r)})
    +                           'OR':  partial(lambda l, r: l or r)})
     
      -
    • Another solution in this particular case is to use functions and_() and or_() from the module operator.
    • +
    • Member names are in all caps because trying to access a member that is named after a reserved keyword raises SyntaxError.

    #Exceptions

    Basic Example

    try:
         <code>
    @@ -1318,7 +1319,7 @@
     
     
    • Code inside the 'else' block will only be executed if 'try' block had no exceptions.
    • -
    • Code inside the 'finally' block will always be executed.
    • +
    • Code inside the 'finally' block will always be executed (unless a signal is received).

    Catching Exceptions

    except <exception>:
     except <exception> as <name>:
    @@ -1903,7 +1904,6 @@
     sorted_by_both   = sorted(<collection>, key=op.itemgetter(1, 0))
     product_of_elems = functools.reduce(op.mul, <collection>)
     union_of_sets    = functools.reduce(op.or_, <coll_of_sets>)
    -LogicOp          = enum.Enum('LogicOp', {'AND': op.and_, 'OR': op.or_})
     last_el          = op.methodcaller('pop')(<list>)
     

    #Introspection

    Inspecting code at runtime.

    Variables

    <list> = dir()                             # Names of local variables (incl. functions).
    @@ -3007,7 +3007,7 @@
      
     
       
     
    diff --git a/web/faq.html b/web/faq.html
    index 088ed6110..1c659c3c1 100644
    --- a/web/faq.html
    +++ b/web/faq.html
    @@ -1,5 +1,5 @@
     
    Python 2 or Python 3?
    -    Python 3.6 (Except for dataclasses and asyncio that require version 3.7). +    Python 3.7

    What is the best way to use it?
    From 85bbdb43d937a821556eb0a9dd0b1c6bba26c8ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 8 Oct 2021 17:24:07 +0200 Subject: [PATCH 013/660] Path, SQLite, Synthesizer --- README.md | 12 ++++++------ index.html | 16 ++++++++-------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index fde4a5d09..87e97d3e9 100644 --- a/README.md +++ b/README.md @@ -1645,7 +1645,7 @@ from pathlib import Path ``` ```python - = .parent # Returns Path without final component. + = .parent # Returns Path without the final component. = .name # Returns final component as a string. = .stem # Returns final component without extension. = .suffix # Returns final component's extension. @@ -1864,11 +1864,11 @@ import sqlite3 #### Or: ```python with : # Exits the block with commit() or rollback(), - .execute('') # depending on whether an exception occurred. + .execute('') # depending on whether any exception occurred. ``` ### Placeholders -* **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.** +* **Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.** * **Bools will be stored and returned as ints and dates as [ISO formatted strings](#encode).** ```python .execute('', ) # Replaces '?'s in query with values. @@ -2900,15 +2900,15 @@ Synthesizer import math, struct, simpleaudio from itertools import repeat, chain F = 44100 -P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,' -P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,' +P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,' +P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,' get_pause = lambda seconds: repeat(0, int(seconds * F)) sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F) get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F))) get_hz = lambda key: 8.176 * 2 ** (int(key) / 12) parse_note = lambda note: (get_hz(note[:2]), 1/4 if '♩' in note else 1/8) get_samples = lambda note: get_wave(*parse_note(note)) if note else get_pause(1/8) -samples_f = chain.from_iterable(get_samples(n) for n in f'{P1}{P1}{P2}'.split(',')) +samples_f = chain.from_iterable(get_samples(n) for n in f'{P1},{P1},{P2}'.split(',')) samples_b = b''.join(struct.pack('
    - +
    @@ -1540,7 +1540,7 @@ <Path> = Path.home() # Returns user's home directory. <Path> = Path(__file__).resolve() # Returns script's path if cwd wasn't changed.
    -
    <Path> = <Path>.parent              # Returns Path without final component.
    +
    <Path> = <Path>.parent              # Returns Path without the final component.
     <str>  = <Path>.name                # Returns final component as a string.
     <str>  = <Path>.stem                # Returns final component without extension.
     <str>  = <Path>.suffix              # Returns final component's extension.
    @@ -1698,11 +1698,11 @@
     

    Or:

    with <conn>:                                    # Exits the block with commit() or rollback(),
    -    <conn>.execute('<query>')                   # depending on whether an exception occurred.
    +    <conn>.execute('<query>')                   # depending on whether any exception occurred.
     

    Placeholders

      -
    • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.
    • +
    • Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetime.
    • Bools will be stored and returned as ints and dates as ISO formatted strings.
    <conn>.execute('<query>', <list/tuple>)         # Replaces '?'s in query with values.
     <conn>.execute('<query>', <dict/namedtuple>)    # Replaces ':<key>'s with values.
    @@ -2498,15 +2498,15 @@
     import math, struct, simpleaudio
     from itertools import repeat, chain
     F  = 44100
    -P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,,'
    -P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,,'
    +P1 = '71♩,69♪,,71♩,66♪,,62♩,66♪,,59♩,,'
    +P2 = '71♩,73♪,,74♩,73♪,,74♪,,71♪,,73♩,71♪,,73♪,,69♪,,71♩,69♪,,71♪,,67♪,,71♩,,'
     get_pause   = lambda seconds: repeat(0, int(seconds * F))
     sin_f       = lambda i, hz: math.sin(i * 2 * math.pi * hz / F)
     get_wave    = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F)))
     get_hz      = lambda key: 8.176 * 2 ** (int(key) / 12)
     parse_note  = lambda note: (get_hz(note[:2]), 1/4 if '♩' in note else 1/8)
     get_samples = lambda note: get_wave(*parse_note(note)) if note else get_pause(1/8)
    -samples_f   = chain.from_iterable(get_samples(n) for n in f'{P1}{P1}{P2}'.split(','))
    +samples_f   = chain.from_iterable(get_samples(n) for n in f'{P1},{P1},{P2}'.split(','))
     samples_b   = b''.join(struct.pack('<h', int(f * 30000)) for f in samples_f)
     simpleaudio.play_buffer(samples_b, 1, 2, F)
     
    @@ -3007,7 +3007,7 @@ From 4c53f911818aa09712bb2784b2a8a9ac6de40d11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 8 Oct 2021 17:29:36 +0200 Subject: [PATCH 014/660] Parsed changes to OS Commands --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index 94671a3b8..c9fca8bde 100644 --- a/index.html +++ b/index.html @@ -1579,7 +1579,7 @@

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

    >>> from subprocess import run
    ->>> run('bc', input='1 + 1\n', capture_output=True, encoding='utf-8')
    +>>> run('bc', input='1 + 1\n', capture_output=True, text=True)
     CompletedProcess(args='bc', returncode=0, stdout='2\n', stderr='')
     
    From ac54ab1e1ff2ce8e02970f255ffb654ce7d31fb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 13 Oct 2021 10:42:30 +0200 Subject: [PATCH 015/660] Input, Pygame --- README.md | 4 ++-- index.html | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c08762812..bbed66a37 100644 --- a/README.md +++ b/README.md @@ -1489,7 +1489,7 @@ Input ``` * **Trailing newline gets stripped.** * **Prompt string is printed to the standard output before reading input.** -* **Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.** +* **Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.** Command Line Arguments @@ -2952,7 +2952,7 @@ while all(event.type != pg.QUIT for event in pg.event.get()): **Object for representing images.** ```python = pg.display.set_mode((width, height)) # Returns display surface. - = pg.Surface((width, height) [, flags]) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. + = pg.Surface((width, height), flags=0) # New RGB surface. RGBA if `flags=pg.SRCALPHA`. = pg.image.load('') # Loads the image. Format depends on source. = .subsurface() # Returns a subsurface. ``` diff --git a/index.html b/index.html index c9fca8bde..14acf5f4b 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -1422,7 +1422,7 @@
    • Trailing newline gets stripped.
    • Prompt string is printed to the standard output before reading input.
    • -
    • Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.
    • +
    • Raises EOFError when user hits EOF (ctrl-d/ctrl-z⏎) or input stream gets exhausted.

    #Command Line Arguments

    import sys
     scripts_path = sys.argv[0]
    @@ -2540,7 +2540,7 @@
     <list> = <Rect>.collidelistall(<list_of_Rect>)  # Returns indexes of all colliding Rects.
     

    Surface

    Object for representing images.

    <Surf> = pg.display.set_mode((width, height))   # Returns display surface.
    -<Surf> = pg.Surface((width, height) [, flags])  # New RGB surface. RGBA if `flags=pg.SRCALPHA`.
    +<Surf> = pg.Surface((width, height), flags=0)   # 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.
     
    @@ -3007,7 +3007,7 @@ From dd2f928c29b7cc9c6c47831b317a93dbc4d63943 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 14 Oct 2021 14:56:22 +0200 Subject: [PATCH 016/660] Added Imports --- README.md | 11 +++++++++++ index.html | 13 +++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bbed66a37..82b99f930 100644 --- a/README.md +++ b/README.md @@ -810,6 +810,17 @@ creature = Creature(point, direction) ``` +Imports +------- +```python +import # Imports a built-in or '.py'. +import # Imports a built-in or '/__init__.py'. +import . # Imports a built-in or '/.py'. +``` +* **Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called `'__init__.py'` as a package.** +* **Running `'import '` does not automatically provide access to package's modules unless they are imported in its init script.** + + Closure ------- **We have a closure in Python when:** diff --git a/index.html b/index.html index 14acf5f4b..a652a550e 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -841,6 +841,15 @@ Creature = make_dataclass('Creature', ['loc', 'dir']) creature = Creature(point, direction)
+

#Imports

import <module>            # Imports a built-in or '<module>.py'.
+import <package>           # Imports a built-in or '<package>/__init__.py'.
+import <package>.<module>  # Imports a built-in or '<package>/<module>.py'.
+
+ +
    +
  • Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called '__init__.py' as a package.
  • +
  • Running 'import <package>' does not automatically provide access to package's modules unless they are imported in its init script.
  • +

#Closure

We have a closure in Python when:

  • A nested function references a value of its enclosing function and then
  • the enclosing function returns the nested function.
  • @@ -3007,7 +3016,7 @@
    - +
    From f340968b233f60114eee58bed6f58e0993cf46aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Oct 2021 12:33:14 +0200 Subject: [PATCH 017/660] Updated index --- index.html | 4 ++-- pdf/index_for_pdf.html | 1 + pdf/index_for_pdf_print.html | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/index.html b/index.html index a652a550e..1372d41dc 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@
    - +
    @@ -3016,7 +3016,7 @@
    - +
    diff --git a/pdf/index_for_pdf.html b/pdf/index_for_pdf.html index 192cb16f5..3593efe73 100644 --- a/pdf/index_for_pdf.html +++ b/pdf/index_for_pdf.html @@ -63,6 +63,7 @@

    H

    hexadecimal representation, 7, 8, 28

    I

    image, 35, 39-40, 42-43
    +imports, 12
    inline, 11-12, 15, 20
    input function, 22
    introspection, 31
    diff --git a/pdf/index_for_pdf_print.html b/pdf/index_for_pdf_print.html index 5d9519c36..1720a9692 100644 --- a/pdf/index_for_pdf_print.html +++ b/pdf/index_for_pdf_print.html @@ -63,6 +63,7 @@

    H

    hexadecimal representation, 7, 8, 28

    I

    image, 35, 39-40, 42-43
    +imports, 12
    inline, 11-12, 15, 20
    input function, 22
    introspection, 31
    From cae27c1fb3d6058749110dac65b166d9aeba33a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Oct 2021 17:18:42 +0200 Subject: [PATCH 018/660] Imports --- README.md | 5 +++-- index.html | 9 +++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 82b99f930..da01ea7b4 100644 --- a/README.md +++ b/README.md @@ -817,8 +817,9 @@ import # Imports a built-in or '.py'. import # Imports a built-in or '/__init__.py'. import . # Imports a built-in or '/.py'. ``` -* **Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called `'__init__.py'` as a package.** -* **Running `'import '` does not automatically provide access to package's modules unless they are imported in its init script.** +* **Package is a collection of modules, but it can also define its own objects.** +* **On a filesystem this corresponds to a directory of Python files with an optional init script.** +* **Running `'import '` does not automatically provide access to the package's modules unless they are explicitly imported in its init script.** Closure diff --git a/index.html b/index.html index 1372d41dc..2e416ed7e 100644 --- a/index.html +++ b/index.html @@ -226,7 +226,7 @@

    - +
    @@ -847,8 +847,9 @@
    -
  • Package is a collection of multiple modules, but it can also define its own objects. Python treats any directory containing a file called '__init__.py' as a package.
  • -
  • Running 'import <package>' does not automatically provide access to package's modules unless they are imported in its init script.
  • +
  • Package is a collection of modules, but it can also define its own objects.
  • +
  • On a filesystem this corresponds to a directory of Python files with an optional init script.
  • +
  • Running 'import <package>' does not automatically provide access to the package's modules unless they are explicitly imported in its init script.

#Closure

We have a closure in Python when: