A comparison/callable function is any callable that accepts two arguments, compares them, and returns a negative number for less-than, zero for equality,
example:
python
importfunctoolsdefmycmp(student1,student2):print("comparing ",student1," and ",student2)ifstudent1.age>student2.age:return1elifstudent1.name<student2.name:return-1else:return0print(sorted([student("James",12),student("Mike",11)],key=functools.cmp_to_key(mycmp)))
Iterator
term:: An iterator is a Python object that implements a specific interface. iter___ return instance of iterator and next() method steps the iterator on cycle and return a value to next object
id:: 65137d16-a06a-40e4-b28e-5fa4474017d5
- Another using reduce to implement #Trie [[DSA/Trie]]
- python
Trie=lambda:defaultdict(Trie)#constructor return default dicttrie=Trie()# dict to lambdaEND=True# Insert words into the triewords=["apple","banana","apricot","bear","beach"]forwordinwords:reduce(dict.__getitem__,word,trie)[END]=word
- e.g. word ‘apple’. then trie[‘a’] dict{‘p’: dict{‘p’: dict{‘l’: dict{‘e’: dict{True:’apple’}}}}}
- Zip
- creates an iterator that will aggregate elements from zero to more iterables.
- zip([1, 2]); zip([1, 2], [‘a’, ‘b’])
- zip most useful to create <>
- List comprehensions
id:: 650c181a-1ea2-475c-a09b-35a4aa6ecd39
[x * y for x, y in zip([1, 2, 3], [3, 4, 5])]
-
- Heap #heapq
- Operations:
- peek: there are no peek, use heap[0] instead
- heappush
- heappop
- python
- heappushpop(heap, item) push item and pop and return top element
- heapify(x) : transform list x to heap, inplace O(n)
- heapreplace(heap, item) pop smallest item and push new item, raise error if empty. It is efficient for fixed size heap. It works like poppush
- merge: merge multiple sorted input into a single sorted. It return a iterable(not al ist)
- nlargest & nsmallest: return list of n largest/smallest elements, Equivalent to: sorted(iterable, key=key, reverse=True/False)[:n]
- Counter
- Python’s Counter: The Pythonic Way to Count Objects – Real Python
- counter.update(): the implementation provided by Counter adds existing counts together. It also creates new key-count pairs when necessary.
- python
>>>fromcollectionsimportCounter>>>letters=Counter({"i":4,"s":4,"p":2,"m":1})>>>letters.update("missouri")>>>lettersCounter({'i':6,'s':6,'p':2,'m':2,'o':1,'u':1,'r':1})>>>sales=Counter(apple=25,orange=15,banana=12)>>># Use a counter>>>monday_sales=Counter(apple=10,orange=8,banana=3)>>>sales.update(monday_sales)>>>salesCounter({'apple':35,'orange':23,'banana':15})
- keys(): list of all keys
- values(): list of all values
- python
cnt=Counter("AABC")total=sum(cnt.values())# 4
- most_ common() This method returns a list of (object, count) sorted by the objects’ current count
-
- Enum
- python
fromenumimportEnum# class syntaxclassColor(Enum):RED=1GREEN=2BLUE=3# functional syntax 👍Color=Enum('Color',['RED','GREEN','BLUE'])my_color=Color.RED
In many languages direct access to attributes is highly discouraged Instead the convention is to make the attribute private, and create public getter and setter methods
- auto values
- enum.auto() generate a auto values for enum
- MetaProgramming
- type
- type is a class
``` python
class type:
def __init__(self):
在空值初识话数据
def __new__(self):
# __new__ from object
创建->创建类
```
- create a class with `type`: `type(class_name, class_base, class_dict)`
- `type` allow you create new class programmly
Metaclass
The class used to create a class, is called metaclass of that class, e.g. MyType is metaclass of Person
By dflt, type is used to create a new class, but now if metaclass specified, it will be replace type
- If Base class created with metaclass, all child/grandchild class of Base will be create with same metaclass
- ((652124f8-b924-4054-8d9b-e56256794d28))
-
defrespond(language):matchlanguage:case"Java"|"Javascript":# multiple pattern matchreturn"Love those braces!"case"Python":return"I'm a lumberjack and I don't need no braces"case_:#defaultreturn"I have no clue!"
defop(command):matchcommand:case["move",("F"|"B"|"L"|"R")asdirection]:returnsymbols[direction]case"pick":returnsymbols["pick"]case"drop":returnsymvols["drop"]case_:raiseValueError(f"{command} does not compute!")
To extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon “;”, and continuation character slash “\”.
For string you can use ''' or """ for a multiple line string
list=[5,4,3,2,1]print('Initializing a list using the\ Implicit multi-line statement',list)g="""geeksforgeeks"""# Initializing a mathematical expression# using the Implicit multi-line statement.add=(50+40-52)ifa \
andb:pass
Variable Naming
((6505ac52-5d0c-4272-8c97-ea3ab05e7dcd))
Condition Expression
5 < a < 7 vs 5<a and a<7
ternary
b = 1 if a < 5 else 2
var = exp1 if con-exp2 else exp2
Continue, break, while, else, try, catch, finally
The continue statement skips the current iteration of a loop and continues with the next iteration.
finally will be executed even with continue|break
loop altogether, and the program continues after the loop. aka goto loop_exit
Inside try-except-finally
# in a for Statementforxinrange(2):try:print('trying...')continue#breakprint('still trying...')except:print('Something went wrong.')finally:print('Done!')print('Loop ended.')# Prints trying...# Prints Done!# Prints trying...# Prints Done!# Prints Loop ended.
- finally clause is executed before starting(break; exit) the next iteration.
- break with for/while-else
- If the loop terminates prematurely with break, the else clause won’t be executed.
``` python
# Break the for loop at 'blue'
colors = ['red', 'green', 'blue', 'yellow']
for x in colors:
if x == 'blue':
break
print(x)
else:
print('Done!') #will never executed
# Prints red green
```
Variable
Everything is object
e.g. int is
Python Garbage Collection
Viewing reference counts in Python
>>>importsys>>>a='my-string'>>>sys.getrefcount(a)>>>dela# set ref count to 0>>>importgc>>>gc.get_count()(595,2,1)>>>gc.collect()577>>>gc.get_count()(18,0,0)
- Disabling the garbage collector
- Dismissing Python Garbage Collection at Instagram | by Instagram Engineering | Instagram Engineering
- When share memory or object reused repeatedly disable GC can save
- Python object id() is used to get location of a object
- Type
- Python is Dynamic typed, use type() to get object type
- Python access variable data value through reference. Object can bind to different type (change reference) durning execution
- Mutable vs immutable
- ((650790fd-e50a-4807-9705-97324dbb967b))
- Inmutable: create a new object if value changed, id(my_var) changes when value changed.
- Why it is important?
- Side-effect
- performance
- Notes
- mutable can change id. E.g. list.appen(val) vs list += [val] vs list = list+[val]. The last list=list+[val] creates a new object
- use append or += when possible
- A immutable object can have mutable objects
``` python
t = ([1], [3])
t[0].append(2)
```
- immutable are safe from unintended side-effect (e.g. func call)
- to prevent side-effect, use copy() to shallow copy a mutable object(e.g. list)
- Share reference
python share reference by default
((65079bf5-d1fd-48ef-aa24-680ec28b97cd))
With mutable objects e.g. list, Python will NEVER create shared reference. This may confusing with
a=[1,2]b=a#referencec=[1,2]#does not share with a/[1,2]
- Python pr-create values [-5, 256] so if value in that range, it will share reference
- Equality
- is identity operator id(a) == id(b)
- Sample
a=10b=aaisba==ba=[1]b=[1]aisnotb
- All objects of None are same. Same id and same value a is None
- Numbers
- Python does handle allication memory/bytes for numbers based on the value, e.g. use 160 bytes
- The larger the number the more memory
- floor is largest(in stardard number order)
floor(3.3)->3floor(-3.3)->-4
- / divide -> float
- // divide floor -> int
- % reminder -> int
- int(10.9) -> truncation 10
- Integer / int
- constructor int(10.1); int(True); int(Decimal("10.2")); int("10")
- With Base. int("1010", 2) ; int("1010", base=2)
- bin() -> "0b1010"; oct() -> "0o12"; hex() -> "0xa"
- sign(x): 1 if x >= 0 else -1
- Rational and Fraction
- Franction
-
FromfactionsimportFractionFraction(3,4)#3/4 numerartor, denominatorFraction(3.4)Fraction('3.4')Fraction('3.4')*Fraction(3.4)Fraction(math.sqrt(2))# will be comnIn[17]:y=Fraction(sqrt(2))In[18]:yOut[18]:Fraction(6369051672525773,4503599627370496)y.limit_denominator(10)
- use y.limit_{ denominator(10)} to round denominator to close to 10
- Float
- IEEE 754 double-precision binary float aka binary 64
- sing 1bit
- exponent 11bit
- significant 52 bit
- Equality
- math.isclose(a, b, *, rel_tol=1e - 9, abs_tol=0.0)
- e.g. math.isclose(3.3, 1+2.3000)
- round(val, digits) e.g. round(3.1415, 2) -> 3.14
- You should always use isclose for compare float
- Float to int
- truncation|math.trunc(), floor, ceiling, rounding
- trunc keep the int part. same as int(val)
- floor largest integer LE to the val
- ceiling min{i >= x}
- round(val, n). closest multiple of 10^{ -n} , n default to 0 so round(val) -> int(val)
- round(1.25, 1) -> 1.2 (to nearest val with even least significant digit)
- Banker’s Rounding
- decimal
- Unlike floats, Python represents decimal numbers exactly. And the exactness carries over into arithmetic
- Decimal always associates with a context that controls the following aspects:
- Precision during an arithmetic operation (default 28)
- Rounding algorithm
- Sample
``` python
import decimal
from decimal import Decimal
decimal.getcontext().prec = 2
pi = Decimal('3.14159')
print( pi * radius * radius )
pi = Decimal(sign, (d1, d2, d3, ...), exp)
pi = Decimal (0, (3, 1, 3, 1, 5), 4)
10.0 == Decimal('10.0') # .0 will be use
0.1 != Decimal('0.1') # print('{:.20f}'.format(0.1)) 0.10000000000000000555
```
- Decimal arithmetic operators
- `//` and `%`
- `Decimal(a)//Decimal(b)` -> `trunc(a/b)`
Complex number
use cmath
Boolean
Boolean is subclass of int but it is used in totally different way. Every object in python has a truth value (truthiness)
You can use both a==True and a is True because it is singleton
Truthy
All objects are True except
None
False
classes implement __bool__ or __len__ that return False or 0.
Default of __bool__ is return self != 0
e.g. bool(100) will execute int(100).__bool__() and therefore return result of 100 != 0
Be care that when short-circuited, part of the expression may not executed
Logic operations
X or Y is equal to X if X else Y
x=32y=7print(xory)# 32x=0y='abc'print(xory)# abc
- X and YX if not X else Y
-
x = 10
y = x and 20/x # y = 2
z = (s and s[0]) or '' # if s: return s[0]; else return ''
- Comparison operators
- chained comparisons
- In Python, chaining comparison operators is a way to simplify multiple comparison operations by stringing them together using logical operators. This is also known as “chained comparisons” or “chained comparison operators”.
- a==b==c
- a<b<c
- a<b>c
- a>b<c
- a<b<c<d
-
exp1=a<=b<c>disnoteisf
- Function
- Argument and parameter
- Positional and keyword arguments
- It following C++ rule. If a positional parameter is defined with default value, every positional parameter after it must given a default value
defmyfun(a,b=100,c=0):# a positionalpassmyfun(1)myfun(1,2)myfun(1,2,3)
- keyword argument
-
myfun(a=1,b=2,c=3)my(1,2,c=3)myfun(1,c=2)#b skipped and will use default value of 100myfun(c=3,a=1,b=2)# it is ok not follow same ordermyfun(a=1,2,3)# ❌not correct, the rest after `a=1` must be named
- Function arguments list is ((650994bb-61c3-4e01-b5a0-e7eeda531610))
- *arg to accept variable length arguments
- example
``` python
def func(a, b, c)
pass
l = [1, 2, 3]
func(*l) #unpack l from list to numbers
def func2(a, b, *args)
print(a, b, args)
func2(10, 20, 1, 2, 3) # 10, 20 (1, 2, 3)
def avg((args):
return args and xxxxsum(args)/len(args)
```
- all arguments after `*arg` must be ^^keyword^^ arugments
``` python
def func2(a, b, *args, d)
print(a, b, args)
func(1, 2, 3, 4, d=5)
```
- ^^*^^ without name `def func(*, d)` means there are no more positional args, you must provides keyword arguments
- it means you can not pass arguments other than <<keyword argument>>
- e.g `func(d=32)`
- ^^/^^ : `def mod(x, y, /)` means x, and y are << position ONLY parameters >>
**kwargs to unpack dict
used to group keywords arguments
can be spicified even if positional arguments not been exausted
- you can not do this: func(a, b, **, ***kwargs)
- Default arguments #pitfall
- It created once, the value should be treat as const. If you need the argument to be variable, e.g. datetime.now() do not use default argument.
- Solution: default to None
- Another case, if initialize a default parameter with collection (e.g. list, dict). As same reason above, it will freeze a collection object to variable, if the function reused, the collection object will be resused and it may have incorrect values
- Solution: default to Nono, not empty collection
- sample:
``` python
def func(l =[]):
l.appen(1)
return l
print(func())
print(func()) # 1, 1
```
- This can also be used for recursion remember the results #memoization
- factorial example:
``` python
def factorial(n, cache={}):
if n<1:
return 1
elif n in cache:
return cache[n]
else:
k = factorial(n-1)*n
cache[n]=n*factorial(n-1)
return k
```
- First-Class Functions
- High order functions
- A function take parameter of another function as arguments
- Docstring PEP 257
- 🧑🏫A **docstring** is a string literal that occurs as the ^^first statement^^ (exclude comments) in a module, function, class, or method definition. Such a docstring becomes the _{ doc _ special} attribute of that object.
- function docstr stored in function. _ doc _
- Sample:
defroot():"""Return the pathname of the KOS root directory."""global_kos_rootif_kos_root:return_kos_root...deffunction(a,b):"""function(a, b) -> list"""defcomplex(real=0.0,imag=0.0):"""Form a complex number. Keyword arguments: real -- the real part (default 0.0) imag -- the imaginary part (default 0.0) """
- Annotations PEP 3107
- 🧑🏫Function annotations are arbitrary python expressions that are associated with various part of functions.
- Benefit: help string(e.g. with sphinx), compile check
- it stored in __annotations__ in K:V format
- <>
- type hints is one form of annotations
- Sample:
any objects implements __call__ <>
- {{embed(((6506c411-3211-4b0c-9647-637d211344b3)))}}
- Partial function
samples:
-
python
from functools import partial
# A normal function
def f(a, b, c, x):
return 1000*a + 100*b + 10*c + x
# A partial function that calls f with
# a as 3, b as 1 and c as 4.
g = partial(f, 3, 1, 4)
# Calling g()
print(g(5))
# A partial function with b = 1 and c = 2
add_part = partial(add, c = 2, b = 1)
# Calling partial function
print(add_part(3))
- Closure
- Abstract
- Questions, keywords and cues
:questions-keywords-cues:
- What do I already know?
- Strengths and weaknesses?
- When to apply this theory?
- How valid are the research methods?
- How strong is the evidence?
- How logical is the argument?
- How does this fit in to other research in the field?
- What do I need to find out next?
:END:
- When to apply this?
-
- abstract & reflect
org
:main-idea-checkbox:
- What is this aims?
- What is the their research question?
- What is the author arguing?
- What is their answer to the question?
- What points support their argument?
- What are their main reasons?
- What evidence have they used to support their argument?
- What’s the significance of these facts?
- What principle are they based on?
- How can I apply them? How do they fit in with what I already know?
- What’s beyond them?
- What're supporting details and explanations?
:END:
- Main points
- 📖 Scope
- Scopes and namespace
-
- It is important when a symbol is hide/blocked by another symbol
- built-in scope
- print, True, False etc are located in bult-in scope. If a symbol is not in module scope or current LEG, search in built-in scope. This is #LEGB
- Local Scope
- inside a function. So it also called function local scope
- Enclosing Scope
- nonlocal scope
- nonlocal
- The nonlocal keyword is used in nested functions to declare that a variable refers to a variable in the nearest enclosing scope that is not global. This means if you have a nested function and you want to modify a variable from the outer (enclosing) function, you’d use nonlocal. Sometime the nonlocal variable also been called free variable
- free variable
- Use the keyword nonlocal to declare that the variable is not local.
- When nonlocal can be omitted
- if it is read after write or read only, you can skip nonlocal keyword
- nested function create an outer and inner scope, use nonlocal keyword to refer to the outer scope instead of create a new local variable
defouter():string="Favtutor"# Local Variabledefinner():nonlocalstring#declaring a non local variablestring="Python Favtutor Classes"# Overwriting value of a variable stringprint("inner function:",string)inner()print("outer function:",string)outer()
- Global scope
- A variable created in the main body of the Python code is a global variable and belongs to the global scope. aka module scope or file scope. It spans a single file only
- Global Keyword
- If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.
- The global keyword makes the variable global.
``` python
def myfunc():
global x # create a global variable
x = 300
myfunc()
print(x)
```
- Global and local
The main difference is that Global is used to access and modify global variables from within a function, while nonlocal is used to access and modify variables from the nearest enclosing scope that is not global.
when python encounter a func definition at compile time. It scans for labels/var that have assigned to them anywhere in the function. If the label has not been specified as global it is a local
Var referenced but not assigned anywhere in the func will not be local and python at runtime look for them in enclosing scopes
Nonlocal declarations in a local scope do not require the variable to be pre-bound (it declared in outer scope), which is another fundamental distinction between them. These variables must already have been bound in the surrounding namespace(outer function) to avoid syntax errors.
While a nonlocal statement allows for the alteration of an enclosing scope variable in the local scope, a global statement allows for the modification of a global variable in the local scope. Nonlocal variables must already exist, although global variables can be declared with brand-new variables.
Sample
a=10deff3():globalaa=100# this refer to the a at line 1deff4():print(a)# this refer to a at next line and will throw a runtime errora=100
- del a symbol in current scope
- e.g
print=lambdan:print(2**n)print(3)delprint
- Cell object
- Cell objects are used to implement variables referenced by multiple scopes. For each such variable, a cell object is created to store the value; the local variables of each stack frame that references the value contains a reference to the cells from outer scopes which also use that variable. When the value is accessed, the value contained in the cell is used instead of the cell object itself. This de-referencing of the cell object requires support from the generated byte-code; these are not automatically de-referenced when accessed. Cell objects are not likely to be useful elsewhere.
- ((650f9ddb-a02a-45cf-9524-8c395f42f66e))
- Cell is important to understand free variables used in closure
- 📖 Closure
- When closure created, it put the nonlocal and global variable into a dict ((650f9d5c-c95d-41d3-8f60-6d6ada6c32f2)) and closure can be introspect with __closure__
- if there is no ((65100808-8929-4581-a57b-c1f9470e4eb6)) there is no closure
- Use closure to remember state
- ((650fb53c-bad9-4c9b-87c7-acc3a3d2a8b8))
- When counter() created a closure. It include a reference to counter/cell. So each time fn() called, count will change
- Multiple instance of Closures
- Each time create a new closure, a new scope/env/capture will also created.
- The reason n is 3 for each adder closure is:
- n is a share scope object in for loop
- it does not recreated each time
- each adder has a ((650f9d5c-c95d-41d3-8f60-6d6ada6c32f2)) which is reference to n
- It is important to know closure scope value is stored in ((650f9d5c-c95d-41d3-8f60-6d6ada6c32f2)) and store reference, when the value reference pointing to changed, closure value will also change .
- Python does not evaluate free vars n until adders[i] func is called. And all of then refer to same n(3) when it is called
- Replace Class with closure
- In many cases, the only reason we might have a single-method class is to store additional state for the use in method.
- A request class
:howto-recite:
Cover the notetaking column with a sheet of paper. Then, looking at the questions or cue-words in the question and cue column only, say aloud, in your own words, the answers to the questions, facts, or ideas indicated by the cue-words.
:END:
-
- Summary
- main points
-
Decorator
Abstract
The outer function is called the decorator, which takes the original function as an argument and returns a modified version of it.
So, in the most basic sense, a decorator is a callable that returns a callable.
((65101822-3477-4dbd-bf27-c6d41cb38579))
Questions, keywords and cues
```org
:questions-keywords-cues:
What do I already know?
Strengths and weaknesses?
When to apply this theory?
How valid are the research methods?
How strong is the evidence?
How logical is the argument?
How does this fit in to other research in the field?
org
:main-idea-checkbox:
- What is this aims?
- What is the their research question?
- What is the author arguing?
- What is their answer to the question?
- What points support their argument?
- What are their main reasons?
- What evidence have they used to support their argument?
- What’s the significance of these facts?
- What principle are they based on?
- How can I apply them? How do they fit in with what I already know?
- What’s beyond them?
- What're supporting details and explanations?
:END:
- Main points
- 📖 Define a decorator
- Using nested functions
defcounter(fn):count=0definner(*args,**kwargs):nonlocalcountcount+=1print('Function {0} was called {1} times'.format(fn.__name__,count))returnfn(*args,**kwargs)returninnerdefadd(a,b=0):"return sun of two integers"returna+badd=counter(add)add(1,2)# Function add was called 1 times 3
- Pythonic way
@counterdefmult(a:float,b:float=1,c:float=1)->float:"mult return products of three number"returna*b*c
- There is a minor problems that mult is no longer mult after wrapped by operator. The __doc__ and __name__ changed. That when @wraps is needed
defcounter(fn):count=0@wraps(fn)definner(*args,**kwargs):nonlocalcountcount+=1print("{0} was called {1} times".format(fn.__name__,count))returninner
It is same as this:
defcounter(fn):count=0definner(*args,**kwargs):nonlocalcountcount+=1print("{0} was called {1} times".format(fn.__name__,count))inner.__name__=fn.__name__inner.__doc__=fn.__doc__returninner
And also this:
defcounter(fn):count=0definner(*args,**kwargs):nonlocalcountcount+=1print("{0} was called {1} times".format(fn.__name__,count))inner=wrap(fn)(inner)returninner
-
- 📖 Decorator with parameters (Decorator factory)
- Decorator with parameters are wrapper around existing decorators. Decorator returns closure but decorator with parameters returns decorator.
- A timer decorator with parameters
# name factory is decorator factory which accepts parametersdeffactory(number):# name timer is actual decoratordeftimer(fn):fromtimeimportperf_counter# name inner is closuredefinner(*args,**kwargs):total_time=0foriinrange(number):start_time=perf_counter()to_execute=fn(*args,**kwargs)end_time=perf_counter()execution_time=end_time-start_timetotal_time+=execution_timeaverage_time=total_time/numberprint('{0} took {1:.8f}s on an average to execute (tested for {2} times)'.format(fn.__name__,execution_time,number))returnto_executereturninnerreturntimer@factory(50)deffunction_1():foriinrange(1000000):pass@factory(5)deffunction_2():foriinrange(10000000):passfunction_1()function_2()
- Recites
:howto-recite:
Cover the notetaking column with a sheet of paper. Then, looking at the questions or cue-words in the question and cue column only, say aloud, in your own words, the answers to the questions, facts, or ideas indicated by the cue-words.
:END:
``` python
d1={1:1}
d2={1:1, 2:2}
d3={1:2: 3:3}
d = {**d1, **d, **d3} # duplicated value will be overwrote
```
nested unpacking
a,*b,(c,d,e)=[1,2,3,'XYZ']# b = [2, 3], c = X ...
- Ignore some of fields when unpack
a,*_,c=(1,2,3,4,5)# -> c = 5a,*ignore,c=(1,2,3,4,5)# -> c = 5
- Named Tuple
- namedtuple is a class factory return a subclass of tuple. You need a class_{ name} and array of element names to create it. The name can also be a string of space or , separated words
Syntax:
TupleClass=namedtuple(class_name,['array','elements','string','format'])TupleClass=namedtuple(class_name,'string of names')# SamplePoint=namedtuple('Point',['x','y'])# Now Point is a classp1=Point(1,3)print(p1.x,p1.y)p1=Point(x=1,y=3)
- Name tuple is tuple so it can use all tuple operations
- Optimization
- Object Interning In Python
- Object interning is a technique used in Python to optimize memory usage and improve performance by reusing immutable objects instead of creating new instances. It is particularly useful for strings, integers and user-defined objects. By interning objects, Python can store only one copy of each distinct object in memory reducing memory consumption and speeding up operations that rely on object comparisons.
- Syntax:
importsysinterned_string=sys.intern(“string_to_intern”)interned_string2=sys.intern(“string_to_intern”)interned_stringisinterned_string2# faster than str cmp
- All identifiers are interned
- Peephole
- In Peephole optimization, Python optimizes code either by pre-calculating constant expressions or by membership tests (converting mutable data structures to immutable data structures.)
- Peephole Optimization in Python
- Find what is pre-calculation by using
your_obj.__code__.co_consts
-
-
-
-
-
### Usage
1. remove all empty
2. it allows arguments e.g. \'abbabbacdef\'.strip(\'ab\'). it remove both `a` and `b` (the sequence does not matter)
### exampls
Lock
** Optimistic Locking
*** With Optimistic Locking, there is always one attribute in your DynamoDB table that will act as a “/version number./” It can be a nano-id, an integer, or a timestamp. The version number associated with the record must also be sent when clients request data.
*** When client modifies the data. The version number present on the client side must be the same as the item’s version number present in the table item. If it is the same, it means that no other user has changed the record, allowing the write to go through. However, if the version numbers are different, it’s likely that another user has already updated the record, causing DynamoDB to reject your write by throwing the exception - ConditionalCheckFailedException. You can retrieve the item again (with newly updated data) and retry your update when this happens.
** Pessimistic Locking
*** Pessimistic Locking is another strategy used by DynamoDB to prevent concurrent updates to a particular row. It use DynamoDB Transactions API
*** typescript
pldebugger require recompile with postgresql source code. A little bit hard to setup.
Lucky enough, debian provides already compiled version.
Strech: version 10
Buster: version 12
FROMpostgres:12MAINTAINERray@ray-xENVPG_MAJOR12ENVPG_VERSION12.3-1.pgdg100+1
# Install the postgresql debuggerRUNapt-getupdate\&&apt-getinstall-y--no-install-recommends\postgresql-$PG_MAJOR-pldebugger
EXPOSE5432
Start the docker and you should see:
pgdbg |
pgdbg | PostgreSQL Database directory appears to contain a database; Skipping initialization
pgdbg |
pgdbg | 2020-06-11 03:00:46.211 UTC [1] LOG: starting PostgreSQL 12.3 (Debian 12.3-1.pgdg100+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 8.3.0-6) 8.3.0, 64-bit
pgdbg | 2020-06-11 03:00:46.211 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
pgdbg | 2020-06-11 03:00:46.211 UTC [1] LOG: listening on IPv6 address "::", port 5432
pgdbg | 2020-06-11 03:00:46.214 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
pgdbg | 2020-06-11 03:00:46.290 UTC [26] LOG: database system was shut down at 2020-06-21 03:00:32 UTC
pgdbg | 2020-06-11 03:00:46.314 UTC [1] LOG: database system is ready to accept connections
Notes that the logs began with pgdbg instead of postgres
To debug with dbeaver, install extension :
CREATEEXTENSIONpldbgapi;
Install debug extension in dbeaver (if not yet)
Help -> Install new software
Search and install debugger Click “ok”, “accept”, “confirm”… to install
After restart dbeaver, you should see a debug icon:
Create a demo sql:
CREATESCHEMAtest;DROPfunctionifexiststest.somefunc(varinteger);CREATEFUNCTIONtest.somefunc(varinteger)RETURNSintegerAS$$DECLAREquantityinteger:=30+var;BEGINRAISENOTICE'Quantity here is %',quantity;--在这里的数量是30quantity:=50;---- 创建一个子块--DECLAREquantityinteger:=80;BEGINRAISENOTICE'Quantity here is %',quantity;--在这里的数量是80END;RAISENOTICE'Quantity here is %',quantity;--在这里的数量是50RETURNquantity;END;$$LANGUAGEplpgsql;SELECTtest.somefunc(12);
Configure a debug session:
Specify database, function, aurgument: