2024年12月2日 星期一

flask 連線遠端 mysql 主機

在上一篇文章中

我們已經安裝好一台 ubuntu 20.04 並安裝了 mySQL ,版本是 8.0.44

現在我們在另一台電腦(windows)上開發 flask


一個最簡單的 flask 寫法如下

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
return 'Welcome to My Watchlist!'

if __name__ == '__main__':
app.run(debug=True)

然後需要安裝 mySQL client 的套件,我選的套件是 mysql-connector-python

所以安裝方法就是  pip install mysql-connector-python

這裡有個坑,套件名稱千萬不要打成 mysql-connector

延伸閱讀


安裝好之後可以把程式改成下面這樣

from flask import Flask
import mysql.connector
from mysql.connector import Error

app = Flask(__name__)

# Establish the connection
def get_db_connection():
try:
conn = mysql.connector.connect(
user='mike',
password='pass',
host='192.168.0.31',
port=3306,
database='ocrDB',
autocommit=True
)
return conn
except Error as e:
print(f"Error: {e}")
return None


@app.route('/')
def hello():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('SHOW TABLES')
tables = cursor.fetchall()
cursor.close()
conn.close()
return 'Welcome to My Watchlist!'


if __name__ == '__main__':
app.run(debug=True)

然後執行,觸發 def hello() 就會報錯了

詢問 chatgpt 後歸納成幾個原因

Summary of Steps to Resolve:

  1. Ensure MySQL is running on 192.168.0.31.
  2. Open port 3306 on the firewall of the MySQL server.
  3. Update MySQL bind-address in the configuration to allow remote connections.
  4. Grant remote access privileges to the MySQL user.

1. 在 mySQL 安裝的 ubuntu 上輸入 sudo service mysql status 即可確認 

2. 這邊 chatgpt 丟出了一句 sudo ufw allow 3306

首先 ufw 應該是預設有安裝的,但我們可以檢查一下狀態

$ ufw enable            // 啟動防火牆,執行後開機也會自動啟動

$ ufw disable           // 關閉防火牆

$ ufw status            // 查看防火牆狀態

$ ufw status verbose    // 查看防火牆詳細狀態

基本上就是把 3306 port 打開,這部分沒啥問題

延伸閱讀


3. 這邊 chatgpt 說

On the MySQL server, check the MySQL configuration file (my.cnf or my.ini), usually located in /etc/mysql/my.cnf or /etc/my.cnf (depending on the distribution). Ensure that the bind-address is set to either 0.0.0.0 or the specific server IP. Example:

bind-address = 0.0.0.0

沒問題,就按照它說的去改

在我的環境中,設定檔是位於 /etc/mysql/my.cnf

改好之後重新啟動 mySQL

sudo systemctl restart mysql

然後 mySQL 就掛了!

google 一下發現有人說你得寫成下面這樣才行

[mysqld]
bind-address = 0.0.0.0

存檔,重啟 mySQL 就成功了

延伸閱讀


4. 在上一篇文章我們就有授權給 remote user 了

所以這部分沒問題

順道一提這個 database='ocrDB' 是我事先在 ubuntu 上用 mySQL command line 開好的

改到目前這樣就可以用 debug 模式看到 cursor 拿回來的 table 是空的 (因為還沒開 table)

沒有 error 出現,可以順利跑完

以上,做個初學者紀錄,這篇就講到這


2024年11月21日 星期四

Ubuntu 20.04 安裝 MySQL server

sudo apt-get update

sudo apt install mysql-server

裝完後可以用以下指令查看狀態

sudo service mysql status


然後執行

sudo mysql_secure_installation

它會問幾個問題

1. would you like to setup validate password component?

2. remove anonymous users?

3. disallow root login remotely?

4. remove test database and access to it?

照直覺選一選就好


查看 mysql 版本

sudo mysqladmin -p -u root version

查看本地 ip

hostname -I

登入 mysql

sudo mysql -u root -p

預設密碼是空的,所以直接按 enter 就可以


進入 mysql 後

列出所有 database

mysql> show databases;

查詢使用者

mysql> SELECT user FROM mysql.user;

上面這個寫法是去 mysql 這個 database 的 user table 撈 user 欄位

所以也可以先

mysql> USE mysql

然後就可以寫成

mysql> Select user FROM user;

如果想查詢這個 database 有哪些 table 可以用下列指令

mysql> show full tables;

mysql> show tables;


開一個新的 database

mysql> CREATE DATABASE ooxx;

開一個新的 user,這裡示範的 user 叫 mike,而密碼就是 password

mysql> CREATE USER 'mike'@'localhost' IDENTIFIED BY 'password';

如果這個 user 會遠端登入的話,可以寫成下面這樣

mysql> CREATE USER 'mike'@'%' IDENTIFIED BY 'password';

如果出現下面這個 error 表示你的密碼不符合規範

ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

可以使用下面這列來看目前的密碼規範

mysql> SHOW VARIABLES LIKE 'validate_password%';

就我自己來說,我改了下面兩列

mysql> SET GLOBAL validate_password.length = 4;

mysql> SET GLOBAL validate_password.policy=LOW;

然後可以修改使用者密碼如下列

mysql> ALTER USER 'mike'@'%' IDENTIFIED BY 'pass';


如果要把剛才開的 database ooxx的權限給 mike 的話

mysql> GRANT ALL PRIVILEGES ON ooxx.* TO 'mike'@'%';

或著當初開 database 時就是用 mike 的身分去開的話,就會自動給權限

延伸閱讀


最後別忘了

mysql> FLUSH PRIVILEGES;


下次要使用 mike 登入時就可以使用下列指令

sudo mysql -u mike -p

然後它會問你密碼你再輸入 pass (剛才 mike 的密碼已經改成 pass)

或是可以直接輸入

sudo mysql -u mike -ppass

注意最後 -ppass 沒有空格,而且會跳出警告建議你不要直接打出密碼

這篇大概就這樣

2024年8月16日 星期五

Ubuntu 20.04 安裝 ASUS TUF Gaming B650m PLUS WiFi 驅動程式

簡單來說

這張板子安裝了Ubuntu 20.04 後,找不到 wifi 選項

幸好插上實體網路線還能用

一般來說就是沒驅動程式

上網 google 這板子用哪個 wifi 晶片還找不到

一直到 ASUS 的驅動程式下載網頁才看到晶片名稱

https://www.asus.com/tw/motherboards-components/motherboards/tuf-gaming/tuf-gaming-b650m-plus-wifi/helpdesk_download?model2Name=TUF-GAMING-B650M-PLUS-WIFI


Realtek RTL8852BE WiFi driver V6001.15.124.0 For Windows 10/11 64-bit.
版本 6001.15.124.0
6.15 MB
2022/09/13

Please install the corresponding driver according to the WIFI/BT chip on your motherboard.

知道晶片名稱再來下關鍵字就簡單多了

找到下面兩篇

https://blog.csdn.net/qq_75220669/article/details/137251306

https://ubuntuforums.org/showthread.php?t=2484689

為避免以後連結失效

這裡將需要的步驟複製貼上

sudo apt update
sudo apt install git make gcc bc

查看核心版本

uname -r

低於 5.18 => https://github.com/HRex39/rtl8852be.git

高於 5.18=> https://github.com/HRex39/rtl8852be.git -b dev


git clone https://github.com/HRex39/rtl8852be.git
cd rtl8852be
make    /*  如果要 multi-thread build 的話,輸入 make -j$(nproc)  */
sudo make install
sudo modprobe 8852be


走完步驟 WiFi 就可以使用了


2024年6月18日 星期二

pyinstaller 打包 mmcv 相關的 exe 可能會遇到的問題

打包完後要執行時遇到了一個問題如下

FileNotFoundError: [Errno 2] No such file or directory: '/home/XXX/tmp-dir/_MEIkGapxs/yapf_third_party/_ylib2to3/Grammar.txt'

上網查到了這篇

https://blog.csdn.net/weixin_44243859/article/details/131890088

為了怕以上連結失效,這邊稍微重複一下內容

說是 pyinstaller 沒有自帶該第三方庫文件的hook的時候,就會導致這個包文件不被打包進來,解決辦法,寫個 hook,然後放進 pyinstaller 的 hooks 裡面,hook 文件的命名規範為: hook-yapf_third_party.py

from PyInstaller.utils.hooks import collect_data_files datas = collect_data_files("yapf_third_party")

以上就是這個 .py 的內容

但具體來說我還是不知道怎麼做

於是再查到了這篇

https://blog.csdn.net/cliffordl/article/details/138065845

看了這篇之後就明白很多

如果我要打包 main.py,然後我要讓他去 hook 一些 library

那我就在 main.py 旁邊開一個 hooks 資料夾

然後把上面的 hook-yapf_third_party.py 丟進這個資料夾

(其中 hook-xxx.py 的 xxx 就是 library 名稱)

然後在打包時加入 --additional-hooks-dir ./hooks

所以整個打包的指令就變成 

pyinstaller -F -c --additional-hooks-dir ./hooks main.py

這個問題這樣就解決了,然後接下來又遇到

ModuleNotFoundError: No module named 'mmcv._ext'

繼續上網查,發現這篇

https://blog.csdn.net/gc5218112/article/details/125172123

OK,他說要在 hiddenimports 加入 'mmcv', 'mmcv._ext'

找到 main.spec,照著加進去,然後執行

pyinstaller main.spec

問題也確實解決了,但這樣很不方便,我希望可以不要去改 .spec

所以這個命令可以寫成

pyinstaller -F -c --additional-hooks-dir ./hooks --hidden-import mmcv --hidden-import mmcv._ext main.py

這樣全部的問題都解決了,大功告成


2024年6月4日 星期二

ubuntu 20.04 安裝 CUDA 11.8 for RTX 4090

 先上個連結

https://gist.github.com/MihailCosmin/affa6b1b71b43787e9228c25fe15aeba?permalink_comment_id=4665431

上面這連結是在講 ubuntu 22.04 怎麼裝 CUDA 11.8

他的最後更新時間是 Oct 29, 2023

而現在是 June 04, 2024

NV Driver 版號又不太一樣了,在這紀錄一下踩坑紀錄

====================先照貼原本的內容====================

#!/bin/bash ### steps #### # verify the system has a cuda-capable gpu # download and install the nvidia cuda toolkit and cudnn # setup environmental variables # verify the installation ### ### to verify your gpu is cuda enable check lspci | grep -i nvidia ### If you have previous installation remove it first. sudo apt purge nvidia* -y sudo apt remove nvidia-* -y sudo rm /etc/apt/sources.list.d/cuda* sudo apt autoremove -y && sudo apt autoclean -y sudo rm -rf /usr/local/cuda* # system update sudo apt update && sudo apt upgrade -y # install other import packages sudo apt install g++ freeglut3-dev build-essential libx11-dev libxmu-dev libxi-dev libglu1-mesa libglu1-mesa-dev # first get the PPA repository driver sudo add-apt-repository ppa:graphics-drivers/ppa sudo apt update # find recommended driver versions for you ubuntu-drivers devices # install nvidia driver with dependencies sudo apt install libnvidia-common-515 libnvidia-gl-515 nvidia-driver-515 -y # reboot sudo reboot now # verify that the following command works nvidia-smi sudo wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin sudo mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /" # Update and upgrade sudo apt update && sudo apt upgrade -y # installing CUDA-11.8 sudo apt install cuda-11-8 -y # setup your paths echo 'export PATH=/usr/local/cuda-11.8/bin:$PATH' >> ~/.bashrc echo 'export LD_LIBRARY_PATH=/usr/local/cuda-11.8/lib64:$LD_LIBRARY_PATH' >> ~/.bashrc source ~/.bashrc sudo ldconfig # install cuDNN v11.8 # First register here: https://developer.nvidia.com/developer-program/signup CUDNN_TAR_FILE="cudnn-linux-x86_64-8.7.0.84_cuda11-archive.tar.xz" sudo wget https://developer.download.nvidia.com/compute/redist/cudnn/v8.7.0/local_installers/11.8/cudnn-linux-x86_64-8.7.0.84_cuda11-archive.tar.xz sudo tar -xvf ${CUDNN_TAR_FILE} sudo mv cudnn-linux-x86_64-8.7.0.84_cuda11-archive cuda # copy the following files into the cuda toolkit directory. sudo cp -P cuda/include/cudnn.h /usr/local/cuda-11.8/include sudo cp -P cuda/lib/libcudnn* /usr/local/cuda-11.8/lib64/ sudo chmod a+r /usr/local/cuda-11.8/lib64/libcudnn* # Finally, to verify the installation, check nvidia-smi nvcc -V # install Pytorch (an open source machine learning framework) pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118

====================以下是要更改的內容====================

# install nvidia driver with dependencies sudo apt install libnvidia-common-535 libnvidia-gl-535 nvidia-driver-535 -y

因為 driver 版本更新,這個時間點已經找不到 515 了

所以這邊把 515 改成 535


# verify that the following command works nvidia-smi sudo wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/cuda-ubuntu2204.pin sudo mv cuda-ubuntu2204.pin /etc/apt/preferences.d/cuda-repository-pin-600 sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/3bf863cc.pub sudo add-apt-repository "deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2204/x86_64/ /"

這邊講的都是 ubuntu 22.04

我要的版本是 20.04,可以去下面這個網址

https://developer.nvidia.com/cuda-11-8-0-download-archive

選擇 Linux -> x86_64 -> Ubuntu -> 20.04 -> deb(network)

他會列出 Installation Instructions 如下

wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2004/x86_64/cuda-keyring_1.0-1_all.debsudo dpkg -i cuda-keyring_1.0-1_all.deb
sudo apt-get update
sudo apt-get -y install cuda

注意上面最後這句還有坑

# installing CUDA-11.8 sudo apt install cuda-11-8 -y

如果不指定版本的話他預設裝的版本一直安裝失敗

後來找到有人說其實可以指定 driver 版本

可以寫成下列的樣子

# installing CUDA-11.8 sudo apt install cuda-11-8 cuda-drivers=535.161.08-1

後面的步驟就沒有不同了

照著複製貼上即可成功安裝


2023年5月2日 星期二

Find all Chinese text in a string using Python and Regex

參考網址

https://stackoverflow.com/questions/2718196/find-all-chinese-text-in-a-string-using-python-and-regex


python的字串都是unicode

而全部中文的範圍在0x4e00 ~ 0x9fff之間

所以一個字串你想要取其中的中文可以這樣寫
def get_chinese(self, text):
    result = re.findall(r'[\u4e00-\u9fff]+', text)
    output = "".join(result)
    return output

補充
這一個字串你想寫入cp950編碼的檔案
但有一些字不符合該怎麼做?

with open("cp950.txt", mode="w", encoding="cp950") as f:
    f.write(text)

如果都不處理的話你會得到
UnicodeEncodeError: 'cp950' codec can't encode character '\uff6d' in position 98: illegal multibyte sequence


其實只要像下面這樣做就可以了
encode_text = text.encode("cp950", "ignore")
decode_text = encode_text.decode("cp950", "ignore")
with open("cp950.txt", mode="w", encoding="cp950") as f:
    f.write(decode_text)

2022年12月27日 星期二

How to Fix Apple Magic Mouse 2 scroll does not work on win10, 解決Apple Magic Mouse 2在win10上滾輪不能用

首先,我的 Magic Mouse 2 型號是A1657

如果你有上網搜尋的話

很多人會叫你裝Boot Camp

譬如下面這個連結

https://support.apple.com/kb/DL1836?locale=zh_TW

但我裝了之後發現還是沒用

仔細查之後才發現這裡面的MouseDriver版本是4.0.0.1

所以我們要想辦法拿更新的 Boot Camp 6.x

到這個頁面

https://github.com/timsutton/brigadier/releases

下載他的brigadier.exe

然後打開命令列,cd到這個exe的位置

輸入brigadier.exe -m MacBookPro14,1

然後他就會下載相對應的 Boot Camp

我在這裡面找到新的MouseDriver是6.0.6200

裝了就能用了

你也可以參考下面這個網址

https://www.youtube.com/watch?v=tV5nfQA_8Ec&ab_channel=FilipLiter%C3%A1k