# Python

## Lambda

<https://medium.com/better-programming/how-to-use-lambda-expressions-in-python-a96330b513d4>

### Lambda Example - 模擬 switch

在Python中缺少其它語言中的switch陳述句，以下結合字典物件與lambda模擬switch的示範

```python
score = int(input('請輸入分數：'))
level = score // 10
{
    10 : lambda: print('Perfect'),
    9  : lambda: print('A'),
    8  : lambda: print('B'),
    7  : lambda: print('C'),
    6  : lambda: print('D')
}.get(level, lambda: print('E'))()
```

在上例中，字典物件中的值的部份是lambda所建立的函式物件，你使用get()方法指定鍵，如果有符合的鍵，就傳回對應的函式物件並執行，否則就傳回get()第二個引數所指定的函式並執行，這模擬了switch中default的陳述。

## List (Slicing)

<https://railsware.com/blog/python-for-machine-learning-indexing-and-slicing-for-lists-tuples-strings-and-other-sequential-types/>

## Import

### Python的import陷阱

<https://pyliaorachel.github.io/blog/tech/python/2017/09/15/pythons-import-trap.html>

## Flask

### Get parameter

```python
from flask import Flask, request
app = Flask(__name__)

@app.route('/')
def hello_world():
	paramStr = request.args.get('paramStr',type = str) 
	return paramStr
```

Input:

> &#x20;<http://127.0.0.1:5000/?paramStr=test123中文>

Output:

```
test123中文
```

### Allow Cross-origin AJAX

**Handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX**

```bash
pip install -U flask-cors
```

**Simple Usage**

```python
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"
```

<https://flask-cors.readthedocs.io/en/latest/>

### Flask-Session

#### Managing Session Data in Flask with Flask-Session & Redis

<https://hackingandslacking.com/managing-flask-session-variables-f4c5ccef54c0>

### run with https

<https://stackoverflow.com/questions/28579142/attributeerror-context-object-has-no-attribute-wrap-socket/28590266#28590266>

```
if __name__ == "__main__":
    context = ('cert.crt', 'key.key')
    app.run(host='0.0.0.0', port=80, ssl_context=context, threaded=True, debug=True)
```

```python
if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080, ssl_context=('/etc/letsencrypt/live/mdminhazulhaque.io/fullchain.pem', '/etc/letsencrypt/live/mdminhazulhaque.io/privkey.pem'))
```

### validate https cert

<https://bits.mdminhazulhaque.io/python/run-flask-app-with-let's-encrypt-ssl-certificate.html>

```bash
openssl s_client -quiet -connect mdminhazulhaque.io:8080
```

```python
openssl s_client -quiet -connect emsd-voicebot-webhook.abapi.info:80
```

I got `errno=0` which means Flask is working fine with SSL. :D

## PEP8 standards - Style Guide

{% embed url="<https://www.python.org/dev/peps/pep-0008/>" %}

## Logging

### Good logging practice

{% embed url="<https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/>" %}

```python
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

logger.info('Start reading database')
# read database here
records = {'john': 55, 'tom': 66}
logger.debug('Records: %s', records)
logger.info('Updating records ...')
# update records here
logger.info('Finish updating records')
```

Output:

```python
INFO:__main__:Start reading database
INFO:__main__:Updating records ...
INFO:__main__:Finish updating records
```

change the logger level to DEBUG and see the output again

```python
logging.basicConfig(level=logging.DEBUG)
```

Output:

```python
INFO:__main__:Start reading database
DEBUG:__main__:Records: {'john': 55, 'tom': 66}
INFO:__main__:Updating records ...
INFO:__main__:Finish updating records
```

### logging 教學

{% embed url="<https://stackoverflow.max-everyday.com/2017/10/python-logging/>" %}

## Numpy

### Tips

{% embed url="<https://blog.csdn.net/u010412858/article/details/75988767>" %}

## Pandas

### Tips

{% embed url="<https://medium.com/@b89202027_37759/實用但常忘記的pandas-dataframe常用指令-1-976f48eb2bd5>" %}

## Tips

### Determine if variable is defined

`'a' in vars() or 'a' in globals()`

if you want to be pedantic, you can check the builtins too\
`'a' in vars(__builtins__)`

{% embed url="<https://stackoverflow.com/questions/1592565/determine-if-variable-is-defined-in-python>" %}

## Code Example

### list of dictionaries search

```python
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

people = [
    {'name': "Tom", 'age': 10},
    {'name': "Mark", 'age': 5},
    {'name': "Pam", 'age': 7}
]

def searchListDict(dataList, key='name', value=None):
    '''
    Searching a list of Dictionaries
    2018-05-16

    Param:  List of Dictionaries
    Return: Dictionary
    '''
    try:
        for l in dataList:
            if l[key] == value:
                return l

        logger.info('No Matching')
        return None # return None if finised looping & no matching

    except:
        logger.error('ERROR:', exc_info=True)

person = searchListDict(people, key='name', value='Pamx')
print(person)
```

### min(None, x)

```python
min(filter(lambda x: x is not None, lst)) if any(lst) else None
```

```python
In [3]: lst = [None, 1, None]

In [4]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[4]: 1

In [5]: lst = [-4, None, 11]

In [6]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[6]: -4

In [7]: lst = [0, 7, -79]

In [8]: min(filter(lambda x: x is not None, lst)) if any(lst) else None
Out[8]: -79

In [9]: lst = [None, None, None]

In [10]: min(filter(lambda x: x is not None, lst)) if any(lst) else None

In [11]: print(min(filter(lambda x: x is not None, lst)) if any(lst) else None)
None
```

<https://stackoverflow.com/questions/6254871/python-minnone-x>

```python
import numpy as np

lst = [1, 2, 3, 4, 5, None]

x = np.array(lst, dtype=np.float64)
print(x)
# array([  1.,   2.,   3.,   4.,   5.,  nan])
```

<https://stackoverflow.com/questions/46025724/getting-max-value-from-a-list-with-none-elements>

### Get Max Value in Dict

```python
def keywithmaxval(d):
     """ a) create a list of the dict's keys and values; 
         b) return the key with the max value"""  
     v=list(d.values())
     k=list(d.keys())
     return k[v.index(max(v))]
```

<https://stackoverflow.com/questions/268272/getting-key-with-maximum-value-in-dictionary>

## Tools

### Visual Studio Code

<https://code.visualstudio.com/>

#### Top 10 Visual Studio Code extensions for Python development

&#x20;<https://boostlog.io/@kazup01/top-10-visual-studio-code-extensions-for-python-development-5a8fdc46a7e5b7008ae1db2f>

#### 8 VS Code Extensions You Might Love

<https://medium.com/better-programming/8-vs-code-extensions-you-might-love-eba03d85fd4f>

#### Setting Sync

<https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync>

#### Kite

<https://kite.com>

### Automated RESTful API testing

#### Tavern

<https://taverntesting.github.io/examples>

## Protect code

{% embed url="<https://bits.theorem.co/protecting-a-python-codebase/>" %}

{% embed url="<https://medium.com/@xpl/protecting-python-sources-using-cython-dcd940bb188e>" %}

{% embed url="<https://github.com/Falldog/pyconcrete>" %}

## Troubleshoot

### Mac OS X: ValueError: unknown locale: UTF-8

add these lines to your \~/.bash\_profile

{% code title="\~/.bash\_profile" %}

```bash
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

```

{% endcode %}

{% embed url="<https://coderwall.com/p/-k_93g/mac-os-x-valueerror-unknown-locale-utf-8-in-python>" %}

### ERROR: FutureWarning: Conversion of the second argument of issubdtype from \`float\` to \`np.floating\` is

FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from .\_conv import register\_converters as \_register\_converters

**Problem**: h5py issue (2.7.1

**Solution**: upgrade h5py (2.9.0)

```bash
pip install --upgrade h5py
```

### 17個新手常見的Python運行時錯誤

<https://www.oschina.net/question/89964_62779>

###

### ERROR:  ImportError: cannot import name 'Flask'

**Problem**: error while import '**flask**'

```python
>>> from flask import Flask
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/ryan/Python/github/flask/flask.py", line 9, in <module>
    from flask import Flask, jsonify, request, session
ImportError: cannot import name 'Flask'

```

**Solution**: The reason is your python file name is '**flask'** in same directory.

### Python的中文編碼處理

{% embed url="<https://in355hz.iteye.com/blog/1860787>" %}

## Library

### Python library 集合

{% embed url="<https://bigdatafinance.tw/index.php/tech/coding/265-python-github>" %}

<https://www.zhihu.com/question/24590883>

<https://kknews.cc/zh-hk/other/rb2m5m4.html>

## Reference:

### Deploying a Machine Learning Model as a REST API

<https://towardsdatascience.com/deploying-a-machine-learning-model-as-a-rest-api-4a03b865c166>

#### Flask設置返回json格式數據

{% embed url="<https://www.polarxiong.com/archives/Flask设置返回json格式.html>" %}

#### Multi-processing

{% embed url="<http://kdh74616.blogspot.com/2017/05/python-multiprocessing-pool.html>" %}

{% embed url="<https://www.dropbox.com/s/7elsfanwakjk19k/taiwan_xbrl_common.py?dl=0>" %}

{% embed url="<http://zwindr.blogspot.com/2017/04/python-multiprocessing.html>" %}

{% embed url="<https://dzone.com/articles/python-thread-part-1>" %}

{% embed url="<https://stackoverflow.com/questions/2905965/creating-threads-in-python>" %}

{% embed url="<https://thispointer.com/python-how-to-create-a-thread-to-run-a-function-in-parallel/>" %}

{% embed url="<https://www.shanelynn.ie/using-python-threading-for-multiple-results-queue/>" %}

### Web Scrapping

#### Parse Youtube link to iframe embeded code

<https://micawber.readthedocs.io/en/latest/>

#### Html2text - Convert HTML to Markdown-formatted text

<http://alir3z4.github.io/html2text/>

<https://github.com/Alir3z4/html2text/blob/master/docs/usage.md>

{% embed url="<https://pala.tw/python-web-crawler/>" %}

### Audio Steaming

<https://gist.github.com/hosackm/289814198f43976aff9b>
