diff --git a/README.md b/README.md index fb956c1..6687a4c 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ value = .pop(key) # Removes item or raises KeyErro ### Counter ```python >>> from collections import Counter ->>> colors = ['blue', 'red', 'blue', 'red', 'blue'] +>>> colors = ['blue', 'blue', 'blue', 'red', 'red'] >>> counter = Counter(colors) >>> counter['yellow'] += 1 Counter({'blue': 3, 'red': 2, 'yellow': 1}) @@ -377,7 +377,7 @@ import re ``` ### Special Sequences -* **By default digits, whitespaces and alphanumerics from all alphabets are matched, unless `'flags=re.ASCII'` argument is used.** +* **By default digits, alphanumerics and whitespaces from all alphabets are matched, unless `'flags=re.ASCII'` argument is used.** * **Use a capital letter for negation.** ```python '\d' == '[0-9]' # Matches any digit. @@ -442,7 +442,7 @@ Format #### Comparison of presentation types: ```text +---------------+-----------------+-----------------+-----------------+-----------------+ -| | {} | {:f} | {:e} | {:%} | +| | {} | {:f} | {:e} | {:%} | +---------------+-----------------+-----------------+-----------------+-----------------+ | 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' | | 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' | @@ -456,7 +456,7 @@ Format ``` ```text +---------------+-----------------+-----------------+-----------------+-----------------+ -| | {:.2} | {:.2f} | {:.2e} | {:.2%} | +| | {:.2} | {:.2f} | {:.2e} | {:.2%} | +---------------+-----------------+-----------------+-----------------+-----------------+ | 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' | | 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' | @@ -541,7 +541,7 @@ shuffle() Combinatorics ------------- * **Every function returns an iterator.** -* **If you want to print the iterator, you need to pass it to the list() function!** +* **If you want to print the iterator, you need to pass it to the list() function first!** ```python from itertools import product, combinations, combinations_with_replacement, permutations @@ -1093,7 +1093,7 @@ class MyComparable: ```python class MyHashable: def __init__(self, a): - self._a = copy.deepcopy(a) + self._a = a @property def a(self): return self._a @@ -1146,7 +1146,7 @@ class Counter: ``` #### Python has many different iterator objects: -* **Objects returned by the [iter()](#iterator) function, such as list\_iterator and set\_iterator.** +* **Iterators returned by the [iter()](#iterator) function, such as list\_iterator and set\_iterator.** * **Objects returned by the [itertools](#itertools) module, such as count, repeat and cycle.** * **Generators returned by the [generator functions](#generator) and [generator expressions](#comprehension).** * **File objects returned by the [open()](#open) function, etc.** @@ -1170,7 +1170,7 @@ class Counter: ``` ### Context Manager -* **Enter() should lock the resources and (optionally) return an object.** +* **Enter() should lock the resources and optionally return an object.** * **Exit() should release the resources.** * **Any exception that happens inside the with block is passed to the exit() method.** * **If it wishes to suppress the exception it must return a true value.** @@ -1205,8 +1205,9 @@ class MyIterable: def __init__(self, a): self.a = a def __iter__(self): - for el in self.a: - yield el + return iter(self.a) + def __contains__(self, el): + return el in self.a ``` ```python @@ -1336,7 +1337,7 @@ from functools import partial LogicOp = Enum('LogicOp', {'AND': partial(lambda l, r: l and r), 'OR' : partial(lambda l, r: l or r)}) ``` -* **Another solution in this particular case is to use built-in functions `'and_'` and `'or_'` from the module [operator](#operator).** +* **Another solution in this particular case is to use built-in functions and\_() and or\_() from the module [operator](#operator).** Exceptions @@ -1419,7 +1420,7 @@ BaseException +-- StopIteration # Raised by next() when run on an empty iterator. +-- TypeError # Raised when an argument is of wrong type. +-- ValueError # When an argument is of right type but inappropriate value. - +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails. + +-- UnicodeError # Raised when encoding/decoding strings to/from bytes fails. ``` #### Collections and their exceptions: @@ -1589,7 +1590,7 @@ from glob import glob ``` ```python - = getcwd() # Returns current working directory. + = getcwd() # Returns the current working directory. = path.join(, ...) # Joins two or more pathname components. = path.abspath() # Returns absolute path. ``` @@ -1663,7 +1664,7 @@ from pathlib import Path OS Commands ----------- ### Files and Directories -* **Paths can be either strings, Paths, or DirEntry objects.** +* **Paths can be either strings, Paths or DirEntry objects.** * **Functions report OS related errors by raising either OSError or one of its [subclasses](#exceptions-1).** ```python @@ -1671,7 +1672,7 @@ import os, shutil ``` ```python -os.chdir() # Changes current working directory. +os.chdir() # Changes the current working directory. os.mkdir(, mode=0o777) # Creates a directory. Mode is in octal. ``` @@ -1787,7 +1788,7 @@ import csv .writerow() # Encodes objects using `str()`. .writerows() # Appends multiple rows. ``` -* **File must be opened with `'newline=""'` argument, or an extra '\r' will be added to every '\n' on platforms that use '\r\n' linendings!** +* **File must be opened with `'newline=""'` argument, or an extra '\r' will be added to every '\n' on platforms that use '\r\n' line endings!** ### Parameters * **`'dialect'` - Master parameter that sets the default values.** @@ -1846,9 +1847,9 @@ db.close() ### Read **Returned values can be of type str, int, float, bytes or None.** ```python - = db.execute('') # Can raise sqlite3.OperationalError. + = db.execute('') # Raises a subclass of sqlite3.Error. = .fetchone() # Returns next row. Also next(). - = .fetchall() # Returns remaining rows. + = .fetchall() # Returns remaining rows. Also list(). ``` ### Write @@ -1889,7 +1890,7 @@ db.executemany('', ) # Runs execute() many times. from mysql import connector db = connector.connect(host=, user=, password=, database=) = db.cursor() -.execute('') # Only cursor has execute method. +.execute('') # Raises a subclass of mysql.connector.Error. .execute('', ) # Replaces '%s's in query with values. .execute('', ) # Replaces '%()s's with values. ``` @@ -1958,7 +1959,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' ``` ### Format -#### For standard sizes start format string with: +#### For standard type sizes start format string with: * **`'='` - native byte order** * **`'<'` - little-endian** * **`'>'` - big-endian (also `'!'`)** @@ -1982,8 +1983,9 @@ Array ```python from array import array - = array('', ) # Array from coll. of numbers. + = array('', ) # Array from collection of numbers. = array('', ) # Array from bytes object. + = array('', ) # Treats array as a sequence of numbers. = bytes() # Or: .tobytes() ``` diff --git a/index.html b/index.html index 33dd4ba..43e70ce 100644 --- a/index.html +++ b/index.html @@ -279,7 +279,7 @@ value = <dict>.pop(key) for k, v in <dict>.items() if k in keys} # Returns a dictionary, filtered by keys.

Counter

>>> from collections import Counter
->>> colors = ['blue', 'red', 'blue', 'red', 'blue']
+>>> colors = ['blue', 'blue', 'blue', 'red', 'red']
 >>> counter = Counter(colors)
 >>> counter['yellow'] += 1
 Counter({'blue': 3, 'red': 2, 'yellow': 1})
@@ -484,7 +484,7 @@ to_exclusive   = <range>.stop
 

Special Sequences

    -
  • By default digits, whitespaces and alphanumerics from all alphabets are matched, unless 'flags=re.ASCII' argument is used.
  • +
  • By default digits, alphanumerics and whitespaces from all alphabets are matched, unless 'flags=re.ASCII' argument is used.
  • Use a capital letter for negation.
'\d' == '[0-9]'                                # Matches any digit.
 '\w' == '[a-zA-Z0-9_]'                         # Matches any alphanumeric.
@@ -533,7 +533,7 @@ to_exclusive   = <range>.stop
 

Comparison of presentation types:

+---------------+-----------------+-----------------+-----------------+-----------------+
-|               |     {<real>}    |    {<real>:f}   |    {<real>:e}   |    {<real>:%}   |
+|               |    {<float>}    |   {<float>:f}   |   {<float>:e}   |   {<float>:%}   |
 +---------------+-----------------+-----------------+-----------------+-----------------+
 |   0.000056789 |    '5.6789e-05' |     '0.000057'  |  '5.678900e-05' |     '0.005679%' |
 |   0.00056789  |    '0.00056789' |     '0.000568'  |  '5.678900e-04' |     '0.056789%' |
@@ -547,7 +547,7 @@ to_exclusive   = <range>.stop
 
+---------------+-----------------+-----------------+-----------------+-----------------+
-|               |   {<float>:.2}  |   {<real>:.2f}  |   {<real>:.2e}  |   {<real>:.2%}  |
+|               |   {<float>:.2}  |  {<float>:.2f}  |  {<float>:.2e}  |  {<float>:.2%}  |
 +---------------+-----------------+-----------------+-----------------+-----------------+
 |   0.000056789 |    '5.7e-05'    |       '0.00'    |    '5.68e-05'   |       '0.01%'   |
 |   0.00056789  |    '0.00057'    |       '0.00'    |    '5.68e-04'   |       '0.06%'   |
@@ -613,7 +613,7 @@ shuffle(<list>)
 
 

#Combinatorics

  • Every function returns an iterator.
  • -
  • If you want to print the iterator, you need to pass it to the list() function!
  • +
  • If you want to print the iterator, you need to pass it to the list() function first!
from itertools import product, combinations, combinations_with_replacement, permutations
 
@@ -1041,7 +1041,7 @@ Z = dataclasses.make_dataclass('Z', [That is why Python automatically makes classes unhashable if you only implement eq().
class MyHashable:
     def __init__(self, a):
-        self._a = copy.deepcopy(a)
+        self._a = a
     @property
     def a(self):
         return self._a
@@ -1093,7 +1093,7 @@ Z = dataclasses.make_dataclass('Z', [1, 2, 3)
 

Python has many different iterator objects:

    -
  • Objects returned by the iter() function, such as list_iterator and set_iterator.
  • +
  • Iterators returned by the iter() function, such as list_iterator and set_iterator.
  • Objects returned by the itertools module, such as count, repeat and cycle.
  • Generators returned by the generator functions and generator expressions.
  • File objects returned by the open() function, etc.
  • @@ -1116,7 +1116,7 @@ Z = dataclasses.make_dataclass('Z', [1, 2, 3)

Context Manager

    -
  • Enter() should lock the resources and (optionally) return an object.
  • +
  • Enter() should lock the resources and optionally return an object.
  • Exit() should release the resources.
  • Any exception that happens inside the with block is passed to the exit() method.
  • If it wishes to suppress the exception it must return a true value.
  • @@ -1144,8 +1144,9 @@ Hello World! def __init__(self, a): self.a = a def __iter__(self): - for el in self.a: - yield el + return iter(self.a) + def __contains__(self, el): + return el in self.a
@@ -1265,7 +1266,7 @@ LogicOp = Enum('LogicOp', {'and_' and 'or_' from the module operator. +
  • Another solution in this particular case is to use built-in functions and_() and or_() from the module operator.
  • #Exceptions

    Basic Example

    try:
         <code>
    @@ -1333,7 +1334,7 @@ error_msg = traceback.format_exception(exc_type, <name>, <name>.__tr
           +-- StopIteration           # Raised by next() when run on an empty iterator.
           +-- TypeError               # Raised when an argument is of wrong type.
           +-- ValueError              # When an argument is of right type but inappropriate value.
    -           +-- UnicodeError       # Raised when encoding/decoding strings from/to bytes fails.
    +           +-- UnicodeError       # Raised when encoding/decoding strings to/from bytes fails.
     

    Collections and their exceptions:

    +-----------+------------+------------+------------+
    @@ -1469,7 +1470,7 @@ value = args.<name>
     from glob import glob
     
    -
    <str>  = getcwd()                   # Returns current working directory.
    +
    <str>  = getcwd()                   # Returns the current working directory.
     <str>  = path.join(<path>, ...)     # Joins two or more pathname components.
     <str>  = path.abspath(<path>)       # Returns absolute path.
     
    @@ -1516,14 +1517,14 @@ value = args.<name> <file> = open(<Path>) # Opens the file and returns file object.

    #OS Commands

    Files and Directories

      -
    • Paths can be either strings, Paths, or DirEntry objects.
    • +
    • Paths can be either strings, Paths or DirEntry objects.
    • Functions report OS related errors by raising either OSError or one of its subclasses.
    import os, shutil
     
    -
    os.chdir(<path>)                    # Changes current working directory.
    +
    os.chdir(<path>)                    # Changes the current working directory.
     os.mkdir(<path>, mode=0o777)        # Creates a directory. Mode is in octal.
     
    shutil.copy(from, to)               # Copies the file. 'to' can be a directory.
    @@ -1603,7 +1604,7 @@ CompletedProcess(args=['bc', 'newline=""' argument, or an extra '\r' will be added to every '\n' on platforms that use '\r\n' linendings!
    +
  • File must be opened with 'newline=""' argument, or an extra '\r' will be added to every '\n' on platforms that use '\r\n' line endings!
  • Parameters

    • 'dialect' - Master parameter that sets the default values.
    • @@ -1649,9 +1650,9 @@ db.close() -

      Read

      Returned values can be of type str, int, float, bytes or None.

      <cursor> = db.execute('<query>')                # Can raise sqlite3.OperationalError.
      +

      Read

      Returned values can be of type str, int, float, bytes or None.

      <cursor> = db.execute('<query>')                # Raises a subclass of sqlite3.Error.
       <tuple>  = <cursor>.fetchone()                  # Returns next row. Also next(<cursor>).
      -<list>   = <cursor>.fetchall()                  # Returns remaining rows.
      +<list>   = <cursor>.fetchall()                  # Returns remaining rows. Also list(<cursor>).
       
      @@ -1684,7 +1685,7 @@ db.executemany('<query>', <coll_of_abo from mysql import connector db = connector.connect(host=<str>, user=<str>, password=<str>, database=<str>) <cursor> = db.cursor() -<cursor>.execute('<query>') # Only cursor has execute method. +<cursor>.execute('<query>') # Raises a subclass of mysql.connector.Error. <cursor>.execute('<query>', <list/tuple>) # Replaces '%s's in query with values. <cursor>.execute('<query>', <dict/namedtuple>) # Replaces '%(<key>)s's with values.
      @@ -1735,11 +1736,11 @@ db = connector.connect(host=<str>, user=<str>, password=<str>, (1, 2, 3)
    -

    Format

    For standard sizes start format string with:

      +

      Format

      For standard type sizes start format string with:

      • '=' - native byte order
      • '<' - little-endian
      • '>' - big-endian (also '!')
      • -

      Integer types. Use a capital letter for unsigned type. Standard sizes are in brackets:

        +

      Integer types. Use a capital letter for unsigned type. Standard sizes are in brackets:

      • 'x' - pad byte
      • 'b' - char (1)
      • 'h' - short (2)
      • @@ -1757,8 +1758,9 @@ db = connector.connect(host=<str>, user=<str>, password=<str>,

        #Array

        List that can only hold numbers of a predefined type. Available types and their sizes in bytes are listed above.

        from array import array
        -<array> = array('<typecode>', <collection>)    # Array from coll. of numbers.
        +<array> = array('<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.
         <bytes> = bytes(<array>)                       # Or: <array>.tobytes()
         
        diff --git a/pdf/how_to_create_pdf.md b/pdf/how_to_create_pdf.md index 64f2d7d..c0d0be9 100644 --- a/pdf/how_to_create_pdf.md +++ b/pdf/how_to_create_pdf.md @@ -21,7 +21,7 @@ Printing to PDF * Run `./parse.js` again. * Open `index.html` in text editor and first remove element `


        ` before the `

        Libraries

        `. * Then replace the footer and last three `
        ` elements with contents of `pdf/index_for_pdf_print.html` file and save. -* Change all links in text to normal text. They can be found with this regex: `.*a href.*`. +* Change all links in text to normal text and optionally add a page number after '(p. )'. Links can be found with this regex: `.*a href.*`. * Open `index.html` in Chrome. * Change brightness of elements by right clicking on them and selecting inspect. Then click on the rectangle that represents color and toggle the color space to HSLA by clicking on the button with two vertical arrows. * Change lightness (L) percentage to: @@ -43,7 +43,7 @@ Adding headers and footers to PDF (the same for both files) * In 'Change page size' section select 'A4' for 'Page Sizes' set 'XOffset' to '0.1 in' and select page range All. * Select 'Edit PDF' tab and add headers and footers by clicking 'Header & Footer' button, selecting a preset from 'Saved Settings' dropdown menu and clicking ok. Repeat the process for each preset. * If presets get lost, the font and the margins are as follow: Borders: left-line: 0.6, left-text: 0.8, top-line: 11.4, bottom-text: 0.27, right-text-odd: 0.57, font-name: menlo, font-size: 8. -* Set title and author by selecting 'File/Propertiess...'. +* Set title and author by selecting 'File/Properties...'. * Save. Printing the PDF diff --git a/web/script_2.js b/web/script_2.js index 2a41d3f..00aeabd 100644 --- a/web/script_2.js +++ b/web/script_2.js @@ -105,12 +105,12 @@ const DIAGRAM_4_B = const DIAGRAM_5_A = "+---------------+-----------------+-----------------+-----------------+-----------------+\n" + - "| | {} | {:f} | {:e} | {:%} |\n" + + "| | {} | {:f} | {:e} | {:%} |\n" + "+---------------+-----------------+-----------------+-----------------+-----------------+\n"; const DIAGRAM_5_B = "┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓\n" + - "┃ │ {<real>} │ {<real>:f} │ {<real>:e} │ {<real>:%} ┃\n" + + "┃ │ {<float>} │ {<float>:f} │ {<float>:e} │ {<float>:%} ┃\n" + "┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨\n" + "┃ 0.000056789 │ '5.6789e-05' │ '0.000057' │ '5.678900e-05' │ '0.005679%' ┃\n" + "┃ 0.00056789 │ '0.00056789' │ '0.000568' │ '5.678900e-04' │ '0.056789%' ┃\n" + @@ -124,12 +124,12 @@ const DIAGRAM_5_B = const DIAGRAM_6_A = "+---------------+-----------------+-----------------+-----------------+-----------------+\n" + - "| | {:.2} | {:.2f} | {:.2e} | {:.2%} |\n" + + "| | {:.2} | {:.2f} | {:.2e} | {:.2%} |\n" + "+---------------+-----------------+-----------------+-----------------+-----------------+\n"; const DIAGRAM_6_B = "┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓\n" + - "┃ │ {<float>:.2} │ {<real>:.2f} │ {<real>:.2e} │ {<real>:.2%} ┃\n" + + "┃ │ {<float>:.2} │ {<float>:.2f} │ {<float>:.2e} │ {<float>:.2%} ┃\n" + "┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨\n" + "┃ 0.000056789 │ '5.7e-05' │ '0.00' │ '5.68e-05' │ '0.01%' ┃\n" + "┃ 0.00056789 │ '0.00057' │ '0.00' │ '5.68e-04' │ '0.06%' ┃\n" + @@ -183,7 +183,7 @@ const DIAGRAM_8_B = " ├── StopIteration # Raised by next() when run on an empty iterator.\n" + " ├── TypeError # Raised when an argument is of wrong type.\n" + " └── ValueError # When an argument is of right type but inappropriate value.\n" + - " └── UnicodeError # Raised when encoding/decoding strings from/to bytes fails.\n"; + " └── UnicodeError # Raised when encoding/decoding strings to/from bytes fails.\n"; const DIAGRAM_9_A = '+------------------+--------------+--------------+--------------+\n' +