Python FAQ
井民全, jing, mqjing@gmail.com
Python sheet (view)
Table of contents
5. Transfer the script to exe 12
12.3. Blind Source Separation 158
1. Coding Style & Tutorial
[style] Google Python Style Guide
[style] PEP8
[style] Python Hearder Format (ref)
[doc] python-cheatsheet (ref)
[cpython] The Cpython internal (ref)
[cpython] Allison Kaptur - Bytes in the Machine: Inside the CPython interpreter - PyCon 2015 (ref)
[cpython] Lecture 8 - User-defined classes and objects (ref)
2. Utility
[py3clean, clean] How to clean *.pyc, *.pyo and __pycache__
3. Pylint
[pylint, init] How to let the the pylint focus on your project, .pylintrc
[pylint, test module]
[pylint, vscode, plugin] vscode-python-docstring
[pylint, docstring] What is docstring (ref)
[pylint, disable] How to locally disable pylint message?
4. Pytest
[pytest] MUST READ (ref)
[pytest, tutorial] Good Integration Practices (ref)
[packaging, example] How to write a module based package (ref)(view)(blog)
[pytest, cmd, module] How to pytest a specific tests within a module
[pytest, cmd, function] How to pytest a specific test function
[pytest, cmd, method] How to pytest a specific test method
[pytest, naming rule] How to let your testing module be discovered
[pytest, layout]
[pytest, setup] Setup
[pytest, test] 如何存取放在 test 裡的公用 module, utility.py (view)
[pytest, test] 如何存取目標待測 module (view)
[pytest, vscode] 使用 VSCode 進行 pytest 自動測試與除錯你的自動測試程式 (view)
[pytest, package] How to install your dev package for test (view) (ref)
[pytest, searching] How pytest search the module? (ref)
[pytest, config] Where is the config file for pytest
[pytest, qt] The Pytest-QT (ref)
[pytest, class] How to group multiple tests in a class (view) (ref) (blog)
[pytest, menu] How to test by menu
[pytest, button, mouse] How to simulate user mouse click (ref)
[pytest, edit, char] How to simulate user key in character
[pytest, key, enter] How to key the Enter
[method, inject] How to inject a method to object (ref)
[method, override] 透過覆蓋的方式, 直接避免了使用者介入. How to dynamically override a instance's method (ref)
5. Transfer the script to exe
[pyinstaller] Pyinstaller (ref)
6. Tox
[tox, tox.ini] A basic setup file to tox (blog)
7. Environment
[AI] 最簡單的方式安裝 AI 開發環境 (view)
[core] Python official site (ref)
[doc] Language Document (ref)
[install, opencv] How to install Anaconda with OpenCV (view)
jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
[install, jupyter, python kernel] How to install the python execution backend (view)
[install, scipy] How to install Scipy (view)
[install, ide, activepython] liClips (ref), ActivePython (ref)
[install, ide, spyder] spyder (ref) (installation) (download)
[ide, code, hotkey] remove whole line (ref)
Ctrl + Shift + K
[ide, code, hotkey] Shift left/right
[conda, install] How to install conda (ref)
[conda, upgrade] How to upgrade conda?
[conda, env, create] How to create an environment
[conda, env, clone] How to clone an envirnonment (ref)
[conda, env, remove] How to remove an environment
[conda, env, rename] How to rename an envorinment (ref)
[conda, env, list] How to list all envoronment
[conda, env, activate] How to activate an environment
source activate venv_demo
[conda, env, deactivate] How to deactivate an environment (ref)
conda deactivate
[conda, package, install] How to install package using conda
conda install pandas
[vscode-insiders]
[vscode, install] How to install vscode
[vscode, uninstall] How to uninstall vscode
[vscode, goto] How to launch vscode at specified line
[vscode, package, setting sync] How to sync every setting for your VSCode?
Extension: Settings Sync
Login: [Extensions] -> [Settings Sync] -> Logiin with Github
Download: F1: Sync download & Sync Upload
Auto Setup: Shift + Alt + D
[vscode, upgrade] How to upgrade vscode
[vscode, env] How to debug your python code with vscode in a specified conda environment
[vscode, short, method] How to show class and method list
Ctrl + Shfit +O AND :
[vscode, package] Popular extension for Python
Trailing Spaces
Anaconda extension
Indent-Rainbow
Hightlight-icemode, ice-liu
GitLens, Eric Amodio
[vscode, debug] How to write a vscode launch.json for debug your python code
[vscode, keymap] How to setup the vscode keymap as Visual Studio
[vscode, keymap, sublime]
Remove line: Ctrl + X
Move cursor to left: Ctrl + Left Arrow
[pip, install] How to install the latest version of package
[pip, package, list] How to list the out the packages installed in your environment
pip freeze
[nvidia, cuda, install] How to install nvidia cuda package (ref)
[cython, concept] Cython is a compiler which compiles Python-like code files to C code. Still, ‘’Cython is not a Python to C translator’‘. That is, it doesn’t take your full program and “turns it into C” – rather, the result makes full use of the Python runtime environment. (Ref)
[cython, pyx] cython 可以直接編譯成 binary,用 C 或 python 都可以直接使用
[cython, py] python 可以直接編譯成 binary, 用 python 調用 (用 C 調用?)
[cython, opt] How to use Python 3 syntax to compile the code?
cython -3
[cython] cython 是用來加速關鍵片段,把熱區用 cython 重寫,產生 python module ,讓傳統 python 呼叫,https://en.m.wikipedia.org/wiki/Cython
[cython] How to use Cython to transfer Python to C code (view)
[cython, so] 直接使用編譯出來的 python modle (view)
Q: 如果要被轉換的 module_a.py 裡面有呼叫 module_b.py, 會不會有問題?
Q: 如果目錄中有 .py 和 .so, 系統會選那一個執行? => 選 .so
[cython, c] How to use Cython modoule from C (view)
[cython, pyx] How to invoke pyx code from C (view)
[cython, python] How to invoke python code from C using cython (view)
build.sh
[cython, python] 直接在 Cython 中, 混合 Python code (view)
[cython, app] How to create a standalone Python code using cython (view) (ref 使用範例: 包含 msvc project), 不錯的解說 (ref), 但沒提到 numpy 找不到的問題
目前: 如果 python 有 import numpy 就會找不到, The generated C-code always looks up the modules in the original python site-packages dir (ref)
[cython, android] Cython on Android (ref)
[ipython, check] How to know if your code is executed in Jupyter notebook? (ref)
[platform] How to check the running platform such as ios or Android (ref)
[core] Python official site (link)
[ide, all in one] Anaconda (link)
[ide] spyder (ref) (installation) (download)
matplotlib (view) (installation) (plotfile_demo)
[iso 8601 date format] csv plot (view)
8. Package
8.1. Conda
[conda, list] List all installed packages
conda list
[conda, install] Install a package
[conda, remove] remove a package
8.2. pip
[package, version] How to get the package version (ref)
print (np.__version__)
[conda, pip] Install pip in conda environment
[pip vs. pip3] (ref)
[pip, list] How to list packages that pip maintain
pip list
[pip, install] How to install package
pip install package-name
[pip, install, dev] How to install the package in develop mode
[pip, uninstall] How to uninstall a package
[pip, show] How to show a package detail information
[xxxxxx, pip3, upgrade] How to upgrade the pip (ref) xxxxxxx
8.3. Import
[module, init] How to use __init__
[module, path, get, imort] How to ge the module path name (ref)
[import] How to use import that scope in class
[import] How to get module object by giving a path with file name? (ref)
8.4. Packaging to library
[packaging, layout] The regular pakcage sourcelayout (ref)
[packaging, layout] The native namepsace package source layout (PEP420) (import system)(ref)
setup.py
9. Language
[arg] How to get the argument from command line (view)
[chinese in code] How to add utf-8 character in python (ref)
[comment] How to add comment -- ' ' ' enclosed for multi-line comment OR # (ref)
[comment] comment example
9.1. Comment
[comment, one line] #
[comment, multi-line] 雙引號 x 3 ex: """
10. Enum
[ennum, create] How to create enumerate type (ref)
10.1. Variable
[var, static] How to define a static varialbe in python (ref)
[var, type] How to determine the type of a variable
type(variable)
[var, naming, _] What is the meaning of a underscope symbol, _ (ref)
For storing the value of last expression in interpreter
[global] How to use global variable in function
[global, files] How to use global variable in multiple files (ref)
[nan] How to check NaN
[int, max] What is the maximun value for an integer
[list, add] list add (view)
10.2. Scope
[with] What is with keyword in Python -- 讓 with 下面的 code 可以安全地執行, 無論如何都可以受到 with 後面的 object 控制 (ref)
10.3. Module
[function, class, method] How to list all declared functions, classes, methods for a given package/module?
10.4. Class
[class, path] How to get path where the class located
[import] How to use relative method to import a python module? (view)
[class, type] How to check the instance type?
[class, subclass] How to determine whether a class is subclass?
[class, static method] How to declar a static method in class (ref)
[class, class method] How to declare a class method (ref)
[class, class method] How to get the class method name?
[class, class variable] How to declare/access a class variable
[class, import] 如何 import 一個內部使用的 package
Hint: 盡量包在 function 內
[constructor, super] How to use super (ref)
[class, super] How to invoke super method
[class, variable, permission] private, protected, public variable
Privated variabne: __variable__
Protected variable: _variable_
Public variable: variable
[class, name] How to get class name
[class, list] How to list classes for giving a module name
[class, method, name] How to get the current function name or method name (ref)
[class, method, invoke] How to invoke a method by it's name
[class, to_string] Python to_string method
10.5. Time
[time, local] How to get the local time
[time, utc] How to get UTC time (ref)
[datetime, start] How to get the start daytime
[time, range] How to get a day range from 00:00:00 ~ 23:59:59
[time, range] How to get a month range from yyyy:mm:day=1,00:00:00 ~ yyyy:mm:"end_of_day", 23:59:59
[time, range] How to get year range yyyy:mm=1:day=1,00:00:00 ~ yyyy:"end_of_month":"end_of_day", 23:59:59
[timezone, list] How to list all timezone
[timezone, list] How to get the timezone
[QTimeEdit, set] How to set the QTimeEdit (ref)
10.6. String
[string, format] lots of string format (ref)
[string, format] How to show a float value with limited digitial
[string, array] How to create a string array (ref)
[string, replace] Search and replace a string in file (view)
[string ,remove] How to remove the leading spaces from a string (ref)
[string ,remove] How to remove the latest spaces from a string (ref)
[string, split] How to split the string by {+ or -} characters (ref)
[string, count] Counting b in a (ref)
[string, parser, SafeConfigParser] How to parsing ini format configure file using SafeConfigParser (view)
[string, parser, configobj] How to use configobj to parse INI-based configuration file -- for vmx format (view)
[string, parser, extract number] How to extract number from a string (view)
[string, parser, string2num] How to conver string 2 number
[string, inverse] How to inverse a string? (ref)
[string, regular expression] How to parse a prefix sting follow a number end such as level_1, level_2, etc... (ref)
[string, regular expression, num] How to parse the nubmer from a string
[string, re, 1/2] How to parse the factors from a string
[string, regular expression, hh:mm:ss] How to parsing the time format string
[string, split] How to split a string with multiple separators (ref)
[string, parser, awk] How to split a string like awk (view)
[string, parser, visualstudio version] How to extract version number from a string (view)
[string, parser, grep] How to implement grep from python (ref)
[string, parser, sed] How is the sed function in Python (ref)
[string, endwith] How to use end with (ref)
str.endswith(suffix[, start[, end]])
[string, suffix] How to remove the suffix (ref)
[string, split] How to split a string
[string, join] How to join the string list to sentance
[string, format] How to format the output (ref)
[string, format] How to format a string with padding and aligning (ref)
[string, contains] How to determine a substring in a string?
[string, decode] How to decode a byte literial ascii string to unicode string? (ref)
10.7. Exception
[exception, raise] throw exception (ref)
[exception, catch] How to catch IndexError (ref)
[call stack] How to print the call stack when exception (ref)
10.8. File I/O
[print, \n] Print without endline (ref)
[read, input] How to get input from user -- age = input("Your age? ") (ref)
[read, line] How to read line by line from a file
(ref)
[serialization] How to serialize the data
[pathlib, path, home] How to get the home directory
[pathlib, path, create] How to create a path object (ref)
[folder, create] How to create a folder if it does not exist (ref)
[pathlib, string] How to represent a pathlib object to a posix string (ref)
[pathlib, folder] How to get the folder name from a giving file (ref)
[pathlib, list] How to list files (ref)
[pathlib, list, suffix] How to list files for giving a specified suffix?
[pathlib, list, nest] How to find a set of file for given the directory and all subdirectories, recursively (ref)
[pathlib, file, suffix] How to remove all suffix for a given file path (ref)
[patlib, check, exist] How to chec a file or folder exists (ref)
[os, check, exist] How to check a file exists (view)
[os, path, current] How to get the current working directory (view)
cwd = os.getcwd()
[write, line] How to write a line (view)
[xml, walk] Walk Through a XML File (view)
[json, read] How to read a json file
[json, read, panda] How to read a json file, the panda way
[json, read, ijson] How to read a json file, the ijson way, high speed, iterative, big json (ref)
[json, write, dict2json] How to write a json file
[ext, remove] How to remove the file extension
[filename, get filename] How to get the filename from full path file name
[binary, read/write] How to read/write binary file (view)
[filelist, get] How to get a file list (ref)
[file, list, walk, pathlib] How to get file list
[file, list, walk, os] How to get file list which name matched patten (view)
[file, rename] How to rename a file
[path, current path] How to get the current path
top = os.getcwd()
[list2array] How to conver a string list to string array
[list2file] How to write a list to file
[csv, array2csv] How to write a numpy array to csv file (view)
[csv, list2csv] How to conver a string list to a csv file
[csv, read] How to read csv file (view)
[csv, write] How to write a csv file
[csv, read, partial] How to read a csv file row by row -- 最簡單的方法處理大 csv 檔案讀取 (ref)
[csv, read, partial] How to read a csv file only specified row (ref 不滿意的方法)
[csv, read] How to read a csv file row by row (ref)
[csv, read, panda] pd version (ref)
milk_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/monthly-milk-production-pounds.csv')
[csv, read, panda] read csv, named the column, and print
[csv, list, panda] How to conver a csv file to list
[csv, fullfilename, filename] How to conver a fullfilename file into filename csv file (view)
[csv, csv2dataframe] How to conver csv file to dataframe?
[panda, append row, dict] How to insert a dataframe to dataframe
[panda, row num] How to get the row number from a given data frame
[panda, row] How to get a row data by given index
一次讀一批 patch 出來
[generator, h5py] How to use h5py for training on large datasets (ref)
問題: 巨大的 training set 無法一次載入進行 training
作法/觀念: 搭配 HDF5 檔案格式 和 data generator 方式, 一個 batch 一個 batch 的把資料餵給 model, 可以讓 model 多線程平行載入資料並且一個 batch 一個 batch 的訓練巨大 training set. 記憶體只需要 batch 的量. 非常好用.
[hdf5, panda] Table format (ref)
[hdf5, panda] Read/Write hdf (ref)
[h5py, append write/batch read] Append write to h5py file (view)
[file, create] If the file does not at local, dowload it (view)
[file, folder] Get the folder name by giving the full file name
[file, walk] List files from a specific top folder (ref)
[file, rename] How to reanme files -- os.rename(file, strNewFileName) (view)
[find, glob] How to get *.dat from a given folder
[find, fnmatch] How to find a file from a given folder
[find, fnmatch] How to find a set of find from a given folder
[folder, create] How to create a new folder if it does not exist (ref)
[folder, cur] How to know current folder -- os.getcwd()
[path, parse] Splitting a Path into list of terms, 依照 '_' 分隔完整檔名 (view)
[path, norm] Get the normalized path name -- os.path.normpath(path) (ref)
[path, get] How to get the module path name (ref)
print('os.path.dirname(strFullFilename) = ', os.path.dirname(strFullFilename))
[module, path, get, imort] How to ge the module path name (ref)
[folder, rename] How to rename a folder by given the file in that (view)
[folder, parsing] Splitting a Path into list of terms (view)
[excel, write] How to create a Excel file by Python (view)
[excel, write, dict2excel] How to write a Excel file from dictionary (view)
[path, filename] How to get filename for a given path
[zipfile, extract] How to extract a passwd encrpyted zip file
10.9. Network
[network, connect] How to check if there is a connection (ref)
[mac, address] How to get mac address (ref)
10.10. Device I/O
[serial] How to access the serial port using Python
[rs232, check] How to check the connection for a RS232 to usb device? (blog)
[usb, printer] How to print chinese text to escpos print using pyusb (view)
[usb, printer] How to print chinese text to escpos print using python-escpos (view)
10.11. Function
[fun, arg, list] How to pass a list to function (view)
[main, arg, parse] How to use argparse? (view)
Visual Studio Code Debug
[import, path] Import the packages located at the relative folder
[function, library] 把 function 整理在一個地方
[function, name] How to get the current function name or method name (ref)
[function, arg, variable number] How to pass variable number of arguments to function (ref)
[function, show_error]
[function, arg, array] How to pass an array to function (view)
[function, arg, 2d array] How to pass a 2d array to function (view)
[function, def] How to declare a function (view)
[function, invoke] How to call a function by its name
[function, return, multi] How to return multiple values for a function (ref)
10.12. Condition
[switch] How to implement switch in Python (ref)
10.13. Loop
[for, loop] How to generate i in 0, 1, 2, 3, ... len(array) (ref)
for i in range(len(x))
for i in range (50)
[for, loop] How to generate i in 0, 1, 2, 3
range(start, stop, step])
[for, continue] How to use continue in loop? -- loop
[for, iterate, array] How to iterate over array (ref)
10.14. boolean
[boolean, not] How to use not operator in Python (view)
[boolean, or] How to use or operator? -- (ref)
[boolean, None] How to determine None ? -- if x is None: (ref)
10.15. List
[list, create ,1d, append] How to create a 1D list with 40 elements (view)
[list, create, append] How to create an list contains sequencs [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], ..., etc] (view)
[list, remove] How to remove the first element from the list (ref)
[list, copy] What's different between shallow copy and deep copy for a list? (ref)
[list, list2array] How to create an array from a given list (view)
[list, interleave] How to create a list by interleaving zeros to a given list
[list, transpose] How to transpose a 2D list (ref)
[list, add] How to sum of two lists (ref)
[list, add, scale] How to add a integer to each element of the list (ref)
10.16. Tuple
[tuple, create] How to create a tuple with only element?
The most important difference between a list and a tuple is mutability. Unlike lists, tuples are immutable i.e. they can’t be modified [ref].
10.17. Set
[set, create] How to create an empty set?
10.18. Dict
[dict, update] How to update the dictionary (view)
[dict] how to use dict (view)
[dict, diff] How to get the difference between dictionaries (ref) (best)
[dict, list2dict] How to conver a list to dict
[dict2list] How to cover a dictionary data to a 2D list
[dict, merge] How to merge two dictionaries? (ref)
[dict, key] How to get the latest key?
[dict, key, index] How to get the key index for giving a key to a dictionary(ref)
[dict, key, value] How to get the key for giving a name from dictionary (ref)
[dict, key, sorted] How to get a sorted key list from dictionary
[dict, dict2df] How to create a dataframe from dict
[dict, dict2df] How to conver a dict to dataframe
[dict, dict2dataframe, report] Use dataframe to report
[dict, dataframe2dict, df2dict] How to convert a dataframe to dict (ref)
[dict, two dim] How to create a two dimension dictionary
[list2file] How to write a list to file
[dict, key, list] How to list the keys from a dictionary? (ref)
[dict, key, exist] How to determine a dictionary has a key?
[dict, key] 動態給 key
[dict, key, value] How to switch a dictionary key value paire (ref)
[dict, key, name] How to change the dictionary key name (ref)
[list, key-value] How to get a list from a dictionary where the value > 1
[dict2csv] How to write a dict datatype to csv file
10.19. Panda, DataFrame
[lib, analysis] The data analysis library -- Pandas (ref)
[df, create] How to create a dataframe (ref)
[df, select, row, col] How to get the col serials (ref)
[csv, read, panda] read csv, named the column, and print
[df, access] How to access row
[dataframe2list] How to convert values to list (ref)
[panda, nan] How to determine nan for missing values (ref)
10.20. Array
10.20.1. Definition
# 注意: dimenaion 跟 shape 不一樣, 有各自的定義
[ndarray] the ndarray is the Numpy array
[axis] the order of indexing into the array (ref)
Result
[dimension] the number of axes (dimensions) of the array. the rank of axis (ref)
[dimension] How to get the dimension of an array -- x.ndim (view)
[shape] a tube indicating the number of elements along each axis of array (ref)
[shape] How to get the shape of an array -- print('array.shape = ', 'array.shape)
10.20.2. Create 1d
[0d, create, ()] How to create a zero-dimensional array (view)
[length, 1d] How to get the length of an array -- len(your_array)
[1d, create, 1x1] How to create an one-dimensional array with zero values (view)
[1d, create, 1x1] How to create an one-dimension array with shape (1, ) (view)
[1d, create, 1x3] How to create an one-dimension array with shape (3, )
[1d, create, 1xN, zeros] How to create 1xN zero array
[1d, create, 1xN, zeros, int type] How to create a 1xN int zero array
[1d, create, 1xN, linspace] How to setup a linespace array (view) (ref)
myArray = linespace(start, stop, N)
[1d, create, 1xN, arange] How to get an array of evenly spaced values (view)
A_1234 = np.arange(1, 10, 1)
np.arange(start, end, interval)
[array, create ,1d] How to create a 1D array with 40 elements (view)
10.20.3. Create 2d
[2d, create, 3xn] How to create a 2D list with row = 3
[2d, create, rolxcol] How to create a 2D list with variable list elements? (view)
[2d, create, 2x3] How to create a 2x3 array
[2d, create, 2d] How to create a 2D array (view)
[2d, create, shape] How to create a 2D array for giving a shape
[2d, create] How to create a 2D array (view)
[2d, create] How to construct an 2d array from two Python lists (view)
[2d, create, (0, 0)] How to create a two-dimensional array with shape (0,0)
[2d, create, (1, 1)] How to create a two-dimensional array with shape (1,1) (view)
[2d, create, (2, 3)] How to create a two-dimensional array with shape (2, 3) (view)
[2d, create, (N, 1)] How to create a two-dimensional array with shape (N, 1) in random nums
[2d, create, concatenation] How to concate two 1D array to 2D array -- np.c_ (ref) -- insert column
[array, col] How to grab an entire column, column vector (view)
[array, col, 20] How to get 20 elements from a column (view)
[2d, combine] How to generate a 2d array by combining two arrays -- c = np.vstack((a_2x3, b_2x3)) => c_4x3 (view)
[2d, 1D -> 2D, reshape] reshape((3, 2)) -- Create 2D array from a 1D array (view)
3x2 三個 兩個成員的陣列
[2d -> 1d, reveal] How to create a contiguous flattened 1d array from input -- reveal (ref)
10.20.4. Basic OPs
[code] How to break your long line python code into multiple lines? (ref)
[index] python array 接受 -1 index. 最後一項 (ref)
[size] The total number of elements of the array. This is equal to the product of the elements of shape
[dim, add] How to add an additional dimension to numpy array (ref)
有時候, 不想要批次丟進去處理, 只想要單筆資料進行預測. 這時, 你會需要把讀進來的單筆 sample x 做 dimension extension, 然後餵給訓練好的模型做預測. 下面的方法, 是把 (2, 3) shape 的 x, 變成 (1, 2, 3) 的 X.
[len] How to get array length (ref)
[append] How to append a number to numpy array
[list, histogram] How to get the max occurence element for a given list
[array, mean] How to get the mean for a giving array (view)
[access, two list] How to iteratly two lists
[vstack] How to use vstck
[slice] How to get a slice from an array (ref)
[foreach] How to evaluate the elements for an array (view)
[trans, Nx1 -> 1xN] How to transfer a Nx1 array to 1xN array (view)
[transpose, 1xN -> Nx1] How to transfer a 1xN array to Nx1 array (view)
[transpose, list-> n x 1] How to trans a list to nx1 array where each element is 1 dimension
[transpose, list -> n x m] How to cut your long sample list into n vector where each element has m dimension
Purpose: 把一長串的 sample list 切割成整齊的 n 個 m 長度 sample 陣列
[access, N-by-1] How to access the element of N-by-1array
kk[1,0] = 123
[access, column] How to write data to the column of array (view)
[array, add] How to get add between element of array (view)
C = A + B
[array, subarray] How to get sub-elements of array
取得前面 N-1 筆資料 (去除最後一筆資料):
a[ : -1]
取得後面 N-1 筆資料
A[1:]
[count, if] How to count the element if condition is true
Purpose: Calcuating the class ratio in traning set for evaluating the balance issue
[string array] How to create a string array (view)
[squeeze] What is squeeze for array -- 把外面 (最左邊) 拔掉 (view)
[aggregate, zip] How to aggregates elements from each of the iterables (ref)
[set, value, multi] How to setup a valutes to multiple indexs in array (ref)
[reverse] How to reverse the permutation of the value of array (ref)
[iterate] How to iterate all members of array (ref)
[slice, subarray, strip, 1d] How to strip a 4-element 1D subarray from an array -- data_1D(0: 4) (view)
[remove, 2d] 如何修改 2D array, 移除後面 row, 只留下 row 0 (ref)
[subarray, strip, 1d] How to strip the last elemnt from an array? -- [:-1] (view)
[subarray, strip] How to extract elements from the begining to the position N (excluded) (view)
s = wave.ys[:N]
[subarray, strip] How to extract elements from the position N (include) to End (view)
s = wave.ys[N:]
[col] How to grab an entire column, column vector -- Col0= Array2D[:,0] (view)
[col] How to get the column vector from 2D numpy array (view)
[col, 20] How to get the column list from a 2D array (view)
[2d, column] How to get the column list from a 2D array (view)
[array, row] How to get the row vector from 2D array -- points_2d[0, :]
把 : 當 * 理解就可以了.
[array, transpose] How to transpose an 2d array (view)
[mean] How to get the mean for a giving array (view)
[array, sum of square] 用內積來做串列的平方和 (view)
[array, rms] How to calcuating the power value of a signal, python (view)
[array, normalized, 單邊 feature scaling] How to normalize a wave array so the maximum amplitude is +amp or -amp (view)
[array, normalized, standard score, zscore] How to normalized a wave array using standard score way (view)
[two array, max difference] How to get the maximun difference value for giving two arrays
[average] How to calcuate the avg value by specified index
[length, numpy] How to get the length for a given numpy array -- var.size
[array, max] How to get maximum value for a given array (ref)
[array, max] How to get the index of the max for a given array (ref)
[array, majority] How to get the majority value for a given array (view)
[array, outlier] How to remove the outlier (view)
[array/list, if-where] get a list from an another list or dictionary where condition is true
10.21. List comprehension
[index, enumerate] enumerate the list element
[index, select, array] 回傳 array values by given an index array
[array, condition] 從一個 array 中, 取出符合條件的數值, 建立另一個 array
[create, array] 有幾個成員, 就有幾個數值
[批次取值] 取出那些大於 value 陣列
[match] 取出 list 中, match 的項目
[list, interval] How to get the interval list for given a number list
[array, diff] How to calcuate different betwen elements in array (ref)
[max, lambda] Find max of element of list of dictionaries
[min, lambda] Customizde min
[nearest, min, lambda] 給一個 list B, 從 list A 中, 取出跟 list B 最近的那些點
[median] Get the median value from lists of dictionaries with the key
[avg ] 計算那些 valid = 1 的那些數值平均值
[批次改值] 把陣列中偶數的變成 1, 奇數變成 0 (ref)
[批次改值] 把陣列中, 數值 > 5 的保留, 其餘設定變成 0 (ref)
[filter] 把 list 中, 內容在 a, b 之間的數值, 挑出來
[nearest] How to get the neaset value list for giving a value list (ref)
10.22. Generator
[iterable, yield] What is yield in Python (ref)
Iteratorable datatype 可以讓我們存取資料, 可是這些資料都必須放在記憶體中, 這是一個問題. 如果我們自訂的大批複合型資料集合體, 也想擁有讓別人 for each 等 iteration 功能, 就直接使用 yield 建立一個集合體.
[建立資料集合] 用 yield 建立一個 iterable data type, 存放一堆可以 iterate 的資料集合
然後你就可以存取
10.23. Serial
[array2serail] How to conver array to serial (view)
ps = pd.Series(data)
[rs232] How to access RS232
10.24. Plot
[data] 如何選擇不同的圖來分析你的資料 (ref)
[plt, site] matplotlib official page (view) (installation) (plotfile_demo)
[plt, title] How to setup the window title
[plt, plt] How to show the current figurat at a specified location (ref)
[plt, zoom] How to perset the zoom for the plt view
[matplotlib, version] How to check the matplotlib version (view)
[matplotlib, animation] A tutorial (ref)
[matplotlib, upgrade] How to upgrade matplotlib (ref)
[plt, loc] How to move the plot to the location
Ugly
[pandas] http://pandas.pydata.org/ (ref)
+
[plot.ly] the official site (ref)
[seaborn] the tutorial site (ref)
[ipython, jupyter] iPhython Node Sample (ref)
[draw, line] How to draw a line
[draw, text] How to draw text (ref)
[pdf, read] How to extract text from pdf
[pdf, plot] How to plot your data into pdf file (view)
觀念: 只要設定 plt.subplot(211) 就可以在任何地方畫圖
[pdf, title] How to control title's location
ax.set_title('I', y=0)
[plt, x, y] How to draw a (x, y) data point (ref)
[line, data] draw line for giving a serial data
[line, 2point] draw line for giving two points
[line, draw] How to draw a line by giving two points (view)
[line, dimension] How to show a 1D sequence and give show dimension (view)
[line, width] How to setup the line width
[3d, pixel] How to plot pixels in 3D (ref)
[marker] How to draw a cross marker on the figure (ref) (all valid markers)
[plot, text] How to plot a text on ax?
[marker, style] How many marker style
[marker, label, legend] How to plot the lengend for a marker? (ref)
F
[circle] How to draw circles (view)
[fig] How to get the current figure
[ax] How to get the current axis
[ax, range] How to change the axes range (view)
[circle, examples] Lots of circle examples (ref)
[animation, move circle] How to move a circle (view)
[animation, move circle] How to move a circle around a center (view)
[animation, rain] How to use matplotlib animation (view)
[animation, examples] Lots of animation examles (ref)
[ax, clean] How to clean the screen -- gca(), ax.cla()
[ax, range] How to setup axis range -- ax.set_xlim(0,10), ax.set_ylim(0,10)
[opt, curve_fit] How to use curve_fit function to evalute a curve (view)
[date format] csv plot (view)
[subplot, y, x] 把圖畫在 x, y 位置上 (ref)
[multi-axes] create axes, draw, and then add it to fig
最簡單的範例取得 figure 上的 ax list, 讓我們可以不斷的追加繪製圖形上去
[multi-axes] How to create sub-plots share x-axis (ref)
fig, (ax0, ax1, ax2) = plt.subplots(nrows = 3, figsize = (15, 10), sharex = True)
[sine wave, pyplot] How to draw a sin wave with frequency f0 in N samples (view)
[distri, pyplot] How to draw the normal distribution in shape of N, (N, 1), (N, 4) samples (view)
A normal distribution in shape of (N, 4)
10.25. Process/Thread
[time] Calcuating the time for your code (ref)
[time, get] Get the time text
[subprocess, check_output] How to launch git-bash.exe to run script by checkout_out method
[subprocess, shell, bash] How to calling an external command in Python -- subprocess (view)
os.system vs. subprocess (ref)
[process, exit] How to exit the program -- sys.exit(0) (ref)
[process, pool] How to create a multiprocess tasks to separatly core
[thread, sync] Avoiding random crashes when multithreading Qt (ref) (code)
[thread, pyqt5] Multithreading PyQt applications with QThreadPool (ref)
[thread, pyqt5] Long run task without impact GUI (view)
[thread] How to run a specified function every second in another thread(view)
10.26. Async
Trio (ref)
10.27. Google
[google, sheets] How do access google sheets (ref)
10.28. Others
[perf] Performance (ref)
[ctype] How to call c (ref)
[mail, attachment] How to get all attachments for a given email address (view)
[sys, exit] 回傳給自動測試 script 你的結果
[api, pyplot] Where is the pyplot api (ref)
[api, artists] Where is the artist api (ref)
[debug] How to debug the scipy
ipython --pylab
Print "patch.center=", patch.center
How to install Scipy (view)
LDAP (ref)
[git, tag] How to get the tag information from git (ref)
[check version, git, commit] How to check version? (ref)
[process] How to launch a process (ref)
[os, system] How to determine os?
[os, Windows] How to determine Windows ?
[os, RaspberryPI] How to determine RaspberryPi
[os, execv] How to restart a Python script itself (ref)
[timer] How to use timer
[max, lambda] how to find the max value for a giving dictionary array
[max, dict] Get the dictionary with the max key value in a list of dictionary
[google, sheets] How to access google spreadsheet -- pygsheets (ref)
[google, sheets] How to access google spreadsheet -- gsheet(view) (ref)
Note:
安全性: secret.json 不能流出去, 所以應該要讓程式執行在 Google Cloud Function
[google, sheets, keys] How to create a new keys to the service account for the project
11. Image Processing
11.1. Library
Python Imaging Library (PIL)
11.2. FAQ
[install, opencv] How to install Anaconda with OpenCV (view)
[image, load & show] How to load and show an image (view)
[image, save] How to save an image to png file (view)
[image, plt, show] How to use matplot to show an image (view)
[image, colormap] How to use color map for an image data (view)
[convert, bgr -> rgb] How to conver the BGR image to RGB image (ref)
[camera, capture] How to capture a frame from default camera (view)
[video, playback] How to play a video (view)
[video, save, xvid] How to save a video in XVID (view)
[image, contour] How to get the contour from an image (view)
[image, contour, CHAIN_APPROX_NONE] How to use APPROX_NONE mode to get the contour from an image (view)
[image, contour, moment] How to get the all moments from an image (view)
[image, contour, features] How to get the contour features for an image (view)
[image, contour, approx] How to get an approximation contour for a giving contour (view)
[camera, calibration] How is the Camera calibration (draft)
12. Signal Processing
12.1. KB
示波器運作原理 (ref)
甚麼叫做設計系統? => 輸入 x[n] 已知, 輸出已知 y[n], 計算或產生 system
(Edit)
訊號處理算法
計算的數值範圍
[read] 資料讀進來後, 一律進行 normalize +Amp or -Amp (+1 or -1)
[計算] 在浮點數下進行計算 (移植才需要考慮 QF 形式)
[out] 一律 quanta 到 2^15-1 (ex: 以 16-bit 音訊)
移植 QF format 的作法
首先製作 float 數版本
一行替換後, 立刻比對
[q-format]
[operator] 請用人家的 + - * / 作法, 不要自己弄, 除非你很清楚你在做的東西
[migration] 從浮點數版本一行一行新增, 比對兩者數值是否一樣 (寫程式比對, 不一樣, 要跳出來看)
[精確度問題] 要考慮精確度遺失下, 造成的音質損失
[精確度問題] 面對精確度問題時, 應該要先變成大的, 然後再做運算. 這樣才不會有溢位的問題.
(long)x * y
[dsp, signal, sampling] How to build the secret rabbit library for resampling operation (view)
[signal, dc offset] How to remove DC offset signal (ref)
[signal, kalman] (ref)
如何辨識一個訊號的亂度
12.2. Filter
[filter, design, tuto] A tutorial on adaptive filter (ref)
Linear system and signal, z-transform
Active control for noise cancelation
[filter]
Highpass: 0.05Hz, 0.08Hz, 0.1Hz
Lowpass: 30Hz, 40Hz, 45Hz, 70Hz, 75Hz, 100Hz, 150Hz, 200Hz
Bandstop: 50Hz, 60Hz
肌電濾波: 20Hz ~ 500Hz
[filter, IIR vs. FIR] What's different between IIR and FIR (view)
[filter, IIR, real-time] IIR low-pass, high-pass, and band-pass real-time process filters
[filter, notch, Q-factor] A Q-factor cauclator for notch filter (ref)
注意: Python iirnotch 的 Q-factor 參數: 計算方式是倒數, 即 W0/BW (參考文件為: BW/ W0)
[filter, lowpass, numpy] How to implement a lowpass filter in numpy (FIR) (ref)
Delay 的探討: 長度為 M 的 FIR filter delay 為 (N-1)/2, 故 N = 51 的 filter, delay 為 25. 若要補償 delay, 只要 shift 25 點即可.
[filter, lowpass, thinkdsp] How to implement a lowpass filter in ThinkDSP (view)
[filter, highpass, scipy] How to create a high-pass filter using scipy.signal (ref)
[filter, lowpass, scipy] How to implement a filter using scipy.signal (view) (view)
[filter, bandpass, hw] How to implement a bandpass filter using OP AMP (ref)
[filter, bandpass, ButterworthBandpass, scipy] How to use ButterworthBandpass (view)
[filter, bandpass, thinkdsp] How to implement a general bandpass filter (view)
[filter, B, D, W] What's frequency of B, D, W
B: 20 ~ 200Hz
D: 200 ~ 600Hz
W: low pass < 1KHz
[Mel-Filters] The Mel-Filters Analysis for a singal (ref. slides)
Human concentrates on only certain frequency components
[filtfilt, lfilter] What's different between lfilter and filtfilt (ref)
filtfilt: 不能用在 real-time filtering, 因為有 filtering backward in time 的 zero-phase 處理
lfilter: 可以是用 real-time filter, 但一定有 delay
12.3. Blind Source Separation
ICA (ref)
12.4. Noise
[noise, noise control]
[noise, noise management]
[noise, noise source]
[noise, basic] Distribution, Correlation, Relationship between power and frequency
Distribution: the distribution of a random signal (ex: Gaussian noise)
Correlation: is each value in the signal independent of the others, or are these dependencies between them? (ex: Brownian noise)
Relationship between Power and Fequency: (ex: pink noise)
the power is inversely related to frequency;
[noise, white noise] Noise with equal power at all frequencies
The integrated spectrum,
[noise, uniform] A noise signal that contains random values from a uniform distribution; that is, every value in the range is equally likely
[noise, uncorrelated noise] The samples are jointly independant of one another. Ex white noise. The values are independent; that is, knowing one value provides no information about the others
[noise, uncorrelated uniform noise] a.k.a. UU noise.
Waveform
Power Spectrum
[noise, brownian noise] each value is the sum of the previous value and a random “step”. The samples are dependant on the preceding value.
Wave form
How to create? generate uncorrelated random steps and then add them up.
[noise, ecg] ECG 訊號的雜訊總分類
ECG Filters: (Ref)
Baseline wonder removing (IIR)
Polynormial Filter
Powerline interference
Muscle noise filtering
[smooth] How to smooth a 1D signal (ref)
[noise, suppression] Noise Suppression using 1d media filter (ref)
[noise, suppression] Savitzky-Golay filter (blog)
[morphology, dilation] How to use ndimage grey morphology (view)
[noise, smooth]
[noise, filter] Removed the noise, Validation of Automated Arrhythmia Detection for Holter ECG (ref)
[noise, spline] Spline interpolation in 1-d: Procedural (ref)
[noise, level] Measure the noise level (ref)
[noise, uncorrelated uniform, thinkdsp] How to create an uncorrelated uniform , UU noise (view)
Waveform: random
Power Spectrum : random
[noise, uncorrelated gaussian] How to create an Uncorrelated Gaussian Noise (view)
[noise, pink] How to create a pink noise (view)
[signal, filter] residual_analysis (ref)
找趨勢
12.5. I/O
[wav, file2wave, load, play, thinkdsp] How to load a wave file and play it using ThinkDSP (view)
[wav, file2data, load, play] How to load a wave file and play it (view)
[wav, file2data] How to load the wave signal from file, thinkdsp (view)
[wav, play] How to play a wave signal using thinkdsp module, thinkdsp (view)
[wav, save] How to save the wave signal to file, thinkdsp (view)
[wav, data2wave] How to save the wave signal to WAV file via wave package (ref)
[wave, data2wave] How to write multi-channel data to wave file (view)
[wav, wave2data, read, nparray] How to read wave file to numpy array (view)
[wave, data2wave] How to create a wave object from nparray data (view)
[wave, wave2csv] How to save the wave object to csv file (view)
[wave, csv2wave] How to load a wave object from a csv file (view)
[wav, wave2Audio] How to create an audio object from a wave object (view)
audio = Audio(data=wave.ys, rate=wave.framerate)
[audio, data2Audio] How to create an audio object from data array (view)
audio = Audio(data=wave.ys, rate=wave.framerate)
[ecg, wave] How to show whdb ECG wave by thinkdsp (view)
12.6. Find Peak
[signal, peak, nparray, pickutils] How to find the peaks for a given np array data (view), [peak, detector] PickUtils (ref) (conda package) (doc)
[signal, peak, wav, peakutil] How to find the peaks for a given wave (view)
[peak, detector, pickutils] PickUtils (ref) (doc) (conda package)
[peak, detector] Detection of peaks in data** by Marcos Duarte (ref)(home)
[peak, analysis] 分析 peak 後, 策略取 peak (view)
Peak 可能一群落在同一個波組 => 在同一個山裡面的 peak, 取最高的那個
Peak 落在不同的波組 => 真正的山峰間的 peak
[peak] Removed the noise, Validation of Automated Arrhythmia Detection for Holter ECG (ref)
讓 threshold 隨著原始波型變化改變, 調整增加或減少.
12.7. Others
[dsp, book] Hayes, Monson H., Statistical Digital Signal Processing and Modeling, John Wiley & Sons, 1996, 493–552.
[dsp, book] Haykin, Simon, Adaptive Filter Theory, Prentice-Hall, Inc., 1996
[dsp, book, api] ThinkDSP API (ref)
[dsp, lecture] DSP Lecture 1 (video)
[speech, course] CMU Speech Processing Course (ref)
[env, thinkdsp, env] How to setup the development environmnet for the book "Think DSP" (view)
[lib, analysis, LibROSA] The music and audio analysis library -- LibROSA, MFCC, Spectrum (ref) (ref2)
conda install -c conda-forge librosa
[lib, sound, python] Basic Sound Processing in Python (video)
[lib, dsp] Think DSP (ref)
[lib, dsp] Python Adaptive Signal Processing package (ref)
[lms, matlab, tutorial] Signal Enhancement Using LMS and Normalized LMS (ref)
[beamforming, doc] Using Acoustic Beamforming for Pass-By Noise Source Detection (ref)
Spatial resolution, dynamic resolution, cable length, acceptable frequency
Sound waves can be treated as planar, meaning that if the sound source were centered in front of the microphone array, it would reach all microphones at the same time.
Microphone array configuration
[wav, format] The PCM wave format (view)
[signal, cycle] What is cycle? --- a full repetition of the signal
[signal, period] What is period? --- the duration of each cycle
[signal, freq] What is frequency? -- the number of cycle per second
[signal, fft] 傅立葉轉換的原理 -- 把訊號貼到圓周上來尋找重複的 pattern, 當猜測訊號的 pattern 和待測訊號本身週期一致或有關係時 (即猜測剪下來的訊號長度與訊號本身週期一致時), 在圓這個模型所形成的圖形會 "對齊". 當猜測的頻率和真正訊號的頻率不同時, 就會散亂. 用重心位置來量化評估對齊和散亂的程度, 達到頻率預測的目的. (ref)
[signal, phase] What is the phase for a wave (view) -- Phase is the position of a point in time on a wavefrom cycle
[signal, phase] How to show a wave in different phrases (view)
[sampling rate] How to change the sampling rate
[music, pitch] What is pitch? --- a perceptual property to judge sounds as "higher" and "lower" in the sense associated with musical melodies. defines the specific frequencies of particular pitches. (ref)
(ref)
C4=261.63
D4=293.66
E4=329.63
F=293.66
G=392
A=440
B=493.88
[signal, pitch] How to create pitch signals (view)
[spectrum, integrated spectrum] is a function of frequency, f , that shows the cumulative power in the spectrum up to f
Purpose: we can see the relationship between power and frequency more clearly [ref: thinking in DSP charpter 4]
[signal, correlation] two variables correlation means that if you know that value of one, you have some infomation about the other.
[approximation, poly] How to use polynomial approximation (view)
[sound, pressure level, spl] A sound wave in a transmission medium causes a deviation (sound pressure, a dynamic pressure) in the local ambient pressure, a static pressure. It is usually expressed in db SPL. (ref)
[sound, sound pressure meter] A device that measure the presure level caused by sound.
[Ambient Microphone] A device used to pick up background sound in the conference room
[audio, acoustic duct model]
[audio, acoustic echo cancellation] 在免持聽筒的通訊環境中,從遠方傳來的語音經擴音器放出來後,原訊號會經由多重路徑的反射,進入近端的麥克風,再傳回遠端,造成遠端之使用者聽到自己的迴音,形成通話之困擾;迴音消除技術之功用即在於消除此聲學上反射造成之迴音,改善通訊品質. 做法: 是在近端的麥克風做訊號處理, 減去 遠端的人聲音, 再傳出去. 遠端因此不會聽到自己的聲音 (ref: opensource)
[echo cancelation, psychoacoustic masking] 心理聲學遮蔽
[feedback, neutralization]
Pich shift
https://www.kvraudio.com/forum/viewtopic.php?p=6662670
[matlab] https://www.mathworks.com/examples/audio-system/mw/audio_product-audioPitchShifterExample-delay-based-pitch-shifter
[paper] http://dafx.labri.fr/main/papers/p007.pdf
http://iq12.com/old_blog/2009/08/25/real-time-pitch-shifting/
[anc, ambient noise sources]
[anc, reference mic] the measure the noise near the headset
[anc, error mic] perceive the error between the noise source and he inverse signal. Moniting the performance of the ANC system.
[anc, canceling loud speaker]
[anc, sampling delay] the delay caused by sampling rate
[mic, survey] Lots of microphone for recording environment sound (ref)
[mic, Omnidirectional] receiving signals from or transmitting in all directions.
WM-60A (ref), (freq. response)
[impulse response] a IRF of a dynamic system is its output when presented with a brief input signal, called an impluse (ref)
[snr] What's different between RMS and peak current value (view)
[snr, doc] A BLIND SIGNAL LOCALIZATION AND SNR ESTIMATION METHOD (ref)
[snr] How to calcuate the SNR value for a given signal and noise (view)
[signal, custom, class] How to create a class for customized signal (view)
[signal, custom, class] How to create a signal that frequence changes in time (view)
[signal, frame rate] How to get the framerate (view)
[signal, envelope, hilbert] How to get the Hilbert envelop for an AM module source (view)
[plot, color, thinkdsp] How to plot a line with color, thinkdsp -- wavevar.plot(color='#045a8d') or plot(color='0.7') (view)
[window, function] How to implement a moving window function (view)
[thinkdsp, wave] How to plot a wave object (view)
[wave, plot, pyplot] How to plot wave data using plot (view)
[plot, sign, sin, thinkdsp] How to plot a wave using thinkdsp module (view)
[signal, power spectrum, thinkdsp] How to get the power spectrum for a given signal (view)
[signal, power spectrum, scipy] How to get the power spectrum for a given signal (view)
[signal, power spectrum, tool] How to show the power spectrum from a wav file -- audacity
[signal, spectrum -> wav] How to convert the sepctrum to wave (view)
[signal, wave -> spectrogram, scipy] How to show the power spectrogram for a given wave (view)
[ecg, spectgrogram, scipy] 顯示 whdp ECG 搭配 specgrogram 一起看 (view)
[signal, wav -> spectrum, spectrogram, thinkdsp] How to show the power spectrum for a given wav using python (view)
[signal, spectrogram, tool, app] spek, ubuntu
[signal, envlope] How to create the Spectral envlop form for a given wave (view)
[signal, downsample, matlab] How to decrease the sampling rate (ref)
[audo] Plotting wave form and spectrogram
[wavelet] How to use wavelet decomposition to ECG
[Cepstral Analysis] The Cepstral Analysis for a signal (ref. slides)
Ocean wave analysis (view)
,
[benchmark, mse] How to calcuating the MSE (view)
[benchmark, power, rms] How to calcuating the power value of a signal (view)
[benchmark, calibration] 平均聲壓的測定方法_Measurement_Procedure -- CNS8466 (pdf)
聲壓變動檢驗的規格
放置 microphone 的數目
如何計算平均聲壓值
頻譜水平軸的刻度: 125Hz, 250Hz, ...
應該紀錄的項目
White noise 測試實驗設計
[matlab, signal, bandpass, filter, sos] How to design a bandpass filter by giving second-order section matrix values (view)
[matlab, signa, tool, filterdesigner] The matlab filter designer tool (ref)
13. Math
[linear algebra] 超棒的線性代數課程, 有豐富的 python 範例, 影片教學 (ref)
[log] What is the value of log(0) -- - (view)
[latex, tutorial] (ref)
[latex, linefeed] How to line feed in Latex -- \\
[lastex, blank[ How to instart a blank character -- \quad
[signal, autoregressive] the value of the noise at time t depends only on its previous values and on a random disturbance.
[signal, noisy signal] contains both the desired signal and an added noise component
[num, positive] Positive number (ref)
x > 0
A number is positive if it is greater than zero
[num, non-negative] Non-negtive number (ref)
x >= 0
A number is non-negative if it is greater than or equal to zero
[set, convex set] Convex Set (ref)
區域中的任兩點所形成的直線, 在那直線上的任一個點也屬於該集合
In Euclidean space, a convex set is the region such that, for every pair of points within the region, every point on the straight line segment that joins the pair of points is also within the region
(ok), (false)
[scale mapping] How to implement scale mapping (ref)
[order, partial order] The partial order set (ref)
A set having comparable elements, where the relation "less than or equal" can be used
(ref)
[order, bound] What is the lower bound (ref)
if you have a partially ordered set K (a set having comparable elements, where the relation "less than or equal" can be used), the lower bound is an element of K which is less than or equal to every element of S.
S={2,4,8,12}, 1 is the lower bound of S
[relation, bound, infimum] What is the infimum
The maximum lower bound
S={2,4,8,12}, 2 is the infimum of S
You can find an infinity of lower bound, but there is only one infimum
[relation, bound, supremum] What is the supremum
The upper bound
[function, epigraph] Epigraph function (ref)
a function f : Rn→R is the set of points lying on or above its graph
(ref)
Think of it as filling it with water but the water cannot overflow so it adds up vertically when it reaches the limits of the function
[function, convex, def] Convex function (ref)
A function is convex if you can trace a line between two of its points without crossing the function line
,
Convex function has global minimum
[function, convex, check] How to check a function is convex (ref)
By checking the Hessian matrix whether a positive semi-definite matrix
[function, concave, def] A concave function (ref)
A function f is concave if −f is convex
[function, opt, def] What is optimazation problem (ref)
Basically, it says in mathematical notation that the optimal value is the infimum of f(x) with all the constraints respected
[function, opt, objective] What is the objective function
f is called the objective function (it is also sometimes called the cost function). By changing x (the optimization variable) we wish to find a value x∗ for which f is at its minimum.
An optimization problem is typically written:
(ref)
[function, opt, constraint, equ] What is the Equality Constraint
(ref)
[function, opt, constraint, inequ] What is the Inequqality Constraint?
(ref)
[function, opt, constraint, combine] What is the Combiation Constraint?
[function, opt, feasible region] What is the feasible region (ref)
A feasible region, feasible set, search space, or solution space is the set of all possible points (sets of values of the choice variables) of an optimization problem that satisfy the problem's constraints, potentially including inequalities, equalities, and integer constraints.
[function, opt, Lagrange multipliers] What is the Lagrange Multipliers (ref)
Idea:
在 限制條件 g(x, y) 下, 尋找 objective function f(x, y) 的最低值, Lagrange 發現, 最低值會出現在沿著 g(x, y) 的途徑上, 兩個function 的 gradient 方向平行的地方.
Is a strategy for finding the local maxima and minima of a function subject to equality constraints. (Wikipedia)
What did Lagrange find? He found that the minimum of f(x,y) under the constraint g(x,y)=0 is obtained when their gradients point in the same direction
圓是 function = x^2 + y^2, 顏色越深數值越低. 右上角的直線是 x + y - 1 = 0 的 constraint. Lagrange 發現在最小值會出現在兩個圖的 gradient 方向一致的地方.
We can see that the is only one point where two vectors point in the same direction: it is the minimum of the objective function, under the constraint.
手動模擬 Lagrange: 先從最上面的那個點開始, 沿著藍色的 constraint 線, 如果往左, 你會發現 objective function 的 gradient 方向漸漸往左 (這不是好的方向), 沿著藍線往右移動, objective function 的 gradient 方向漸漸與白色的 constraint 方向差距縮小. 但是若一直往右移動, 會發現 objective function 的 gradient 又開始與 constraint 方向越差越遠. 當你到達一個點 gradient 差距最小的地方, 就是最小點. (ref)
Lagrange 基本上就是在找 (objective function 與 constraint function 相同方向或平行方向的 (x, y) 位置) (ref). λ 是 Lagrante multiplier, 為了處理兩個 gradient functions 不同大小的問題.
[opt, lagrange, paper] Lagrange Multipliers Tutorial in the Context of Support Vector Machines (ref)
[gradient] can be visualized as a vector field, with the arrow pointing in the direction where the function is increasing (function 增加的方向) (ref)
[linear algebra, vector] a vector has a magnitude and a direction
[linear algebra, normal, def] Normal vector
A vector that is orthogonal (perpendicular) to the plane (ref)
[linear algebra, hyperplane, normal] hyperplane 方程式 Wx +b 中, 為何 W 向量永遠 normal 於該 hyperplane?
因為這個 hyperplane 就是藉由這個 normal vector W 所定義出來的 (ref)
[linear algebra, orthognal] How to calcuate the orthogonal projection of a vector x onto y -- z=(u⋅x)u (view)
[linear algebra, positive definite] What is positive definite matrix (view) (ref)
The symmetric matrix A is positive definite.
All eigenvalues of A are positive.
All the leading principal minors of A are positive.
There exists nonsingular square matrix B such that A=B⊺B
[linear algebra, positive semi-definite] What is positive semi-definite (view) (ref)
Usage: 評估一個多變數 function 的一階微分 = 0 的位置, 為全域最小值. 只要判斷它的 Hessian 矩陣是否為 positive semidefinite 即可.
The symmetric matrix A is positive semi-definite.
All eigenvalues of A are non-negative.
All the principal minors of A are nonnegative.
There exists B such that A=B⊺B
[linear equ] 計算直線方程式 -- 兩點 (view)
[distance, line, point] The shortest distance between a point and a line (video)
[degree] How to get degree from a set of points
14. Authentication
LDAP (ref)
15. Debug
[debug] How to debug the scipy
ipython --pylab
Print "patch.center=", patch.center
[vscode, break] How to setup a conditional break for a python code (ref)
Expression condition: The breakpoint will be hit whenever the expression evaluates to true.
16. PyQt5
[tool, designer] How to launch the QT designer?
Ubuntu: designer
Mac: open - a Designer
[pyqt5, version] How to check the pyqt version
16.1. Signal & Slot
[signal, tutorial] qt4, Development/Tutorials/Python introduction to signals and slots (ref)
[signal, sender] How to get the signal emitter
16.2. Layout
[QLayout, contructor] What's different between QVBoxLayout() and QVBoxLayout(self)?
[QLayout, align] How to align the component from top (ref)
[QLayout, replace] How to replace a widget A to widget B in a layout?
[QLayout, change] How to replace the old layout for the widget (ref)
[QLayout, update] How to notify the layout manager to update the geometric (ref) (setFixedSize)
[QLayout, area] Get the content area for a layout manager
[QLayout, space] How to setup the margins and space between managed widgets (ref)
[QGridLayout] How to use QGridLayout to manage components
[QGridLayout, ratio] 如何建立兩個元件, 一個佔自己容器 1/4 高度, 另一個佔自己容器 3/4 高度.
16.3. Style, Skin
[official] all compoent example (ref)
[comment] What is the comment for the sheetstyle?
[set] How to set the style for all QTableWidget objects
[load] How to load the style from file
16.4. Drag & Drop
[drag, button] How to implement a drag move button
Ref, work
[drag, resize, button, layout] How to implement a drage movable button by customized layout (view)
[drag, label] How to implement a drag&drop function between application (ref)
[drag, button]
16.5. Cursor
[cursor, get] How to get QWidget cursor? (ref)
[cursor, set] How to set the QCursor?
16.6. Digital
[digital] 最簡單的方式顯示數字 (blog)
16.7. Console
16.8. QWidget
[QWidget, title] How to get the Widget Text (ref)
[QWidget, size] How to get the size of the widget? (view)
[QWidget, size, set] How to set the maximun size for a QWidget instance?
[QWidget, size, max] How to show the maximum size of a QWidget instance
[QWidget, event, resize] Handle the resize
16.9. QPushButton
[QPushButton, customized] How to customized a QPushButton
[QPushButton, image] How to create an image button (ref)
[QPushButton, sender] How to get the calling object from clicked event emited?
[QPushButton, style] How to setup QPushButton Style
[QPushButton, shadow] How to setup a shadow effect for the QPushButton (ref)
[QPushButton, text, html] How to set rich text button (ref)
[QPushButton, hover] How to get the mouse hover event for the QPushButton (ref)
[QPushButton, paint] How to show a crossed-dash lines on button?
[QPushButton, paint] How to draw a rectangle on button (ref)
16.10. QStackedWidget
[qstackedwidget] How to use QStackedWidget
16.11. QTabWidget
[QTabWidget, example] An example of QTabWidget for Config panel (view)
[QTabWidget, tab, height] How to get the QTabBar height for a QTabWidget? (ref)
[QTabWidget, event] How to catch the current changed event (ref)
[QTabWidget, index] How to get the current tab index
[QTabWidget, index, switch] How to switch the Tab (ref)
16.12. QTableWidget
[QtableWidget, refresh] How to refresh the QTableWidget column width to the contents (blog)
[QTableWidget, Item] How to update the Table content (view)
[QTableWidget, Item] How to select the Table Item
[QTableWidget, header, col, name] How to setup the column name? (view)
[QTableWidget, header, style, font] How to change the header font size (ref)
[QTableWidget, header, style] How to set the font and size for a specified table column (ref)
[QTableWidget, scroll] How to scroll to the button (ref)
[QTableWidget, checkbox] How to add a checkbox to table (ref)
[QTableWidget, qcheckbox] How to customized the checkbox that located in the QTable
[QTableWidget, focus] How to focus the latest item
[QTableWidget, scrollbar, width] How to enlarge the width for the vertical scrollbar (ref)
[cell, style] How to enable and setup the alternative color for a QTableWidget?
[cell, style, color, focus] How to change the cell color when the mouse hover? (ref)
[cell, style, bg-color] How to setup the QTableItemWidget bg color style?
[cell, style, font, size] How to setup the QTableItemWidget font size?
[cell, window, size] How to resize the QTableItemWidget width to fit the QTableWidget size? (ref)
16.13. QMainWindow
16.14. QMenu
[QMenu] How to add a memu to your application? (ref)
[QAction] How to get the action by given its name (view)
[QAction] How to trigger a menu action
16.15. QMessagebox
[messagebox, question] How to create a question message box (ref)
[message, warning] How to create a warning message box
[message, info] How to show an information message box
16.16. QLabel
[label, create] How to create a QLabel
[label, style] How to setup the QLabel style
[label, circle] How to draw a circle label (ref)
16.17. QLineEdit
[qlineedit, create] How to create an QLineEdit for passwd
[QLineEdit, hint] How to makes the line edit display a grayed-out placeholder text
[QLineEdit, textEdited] How to handle the textEdited event?
[QLineEdit, editingFinished] How to handle the editingFinished signal
16.18. QComBox
[combox, create]
[QComboBox, hint] How to makes the line edit display a grayed-out placeholder text
[QComboBox, textEdited] How to handle the textEdited event?
16.19. QDialog
[qdialog, create] How to create a Modaless QDialog window (ref)
Modeless Dialog: that operates independently of other windows
Modal Dialog: that blocks input to other visible windows in the same application
[qdialog, bt, size] How to change the button size in a dialog
[qdialog, bt, text] How to change qdialog OK button text (ref)
[qdialog, bt, override] How to override the accept method for QDialog (ref)
A
17. MongoDb
[db, check] How to check if data exists
[db, add] How to add a record to database
[db, del] How to remove a recrod from database
[db, update] How to update a record
[db, replace] How to replace a record
18. Web Automation
Examples (ref)
[find, caption] find element by caption
[browser, maximum] How to maximum the browser
[browser, scroll] Auto scroll the element to visiable (ref)
[webelement, scroll] How to scrll the web element to the center (ref)
[ui-datepicker] How to setup yyyy-mm-date
[wait] How to wait for ready (ref)
[pop, alert] How to handle alrt window
[html, parsing] BeautifulSoap -- 網頁剖析 Html (ref)
[WebElement, get value] How to get the WebElement value after sending keys
[WebElement, select all] How to clean the text first and then input text? (ref)
19. Optimal
作法