網頁

2020年3月23日 星期一

mysql 操作

$ sudo mysql -u root -p
[sudo] password for user: 輸入 os root 密碼
Enter password: 輸入 mysql root 密碼

顯示所有 database
> show databases;

進入某個資料庫
> use db_name;

顯示 資料庫內 所有資料表
> show tables;

顯示 資料表的欄位
> describe tab_name;
顯示 資料表的欄位細節
> show full columns from tab_name;

顯示所有使用者
> describe mysql.user;
> select host, user from mysql.user;

顯示使用者權限
> describe mysql.db;
> select host, db, user from mysql.db;

顯示 grant 的權限
> show grants for 'user'@'%';
> show grants for 'user'@'localhost';

建立使用者
> create user 'user'@'hostname' identified by 'password';
hostname 可以為 ip 或 % 表示任何ip
刪除使用者
> drop user 'user'@'hostname';

grant 權限
> grant all on db_name.* to 'user'@'localhost';
移除 grant 權限
> revoke all privileges on db_name.table from 'user'@'hostname';

建立資料庫
> create database db_name;
刪除資料庫
> drop database db_name;

建立資料表
> create table tab_name (
  id int not null auto_increment,
  name varchar(50) not null,
  desc varchar(200),
  price int not null,
  primary key(id)
);
刪除資料表
> drop table tab_name;

執行 sql 檔
> source file.sql
> \. file.sql
shell 直接執行 sql
$ mysql -u root -p < file.sql

執行 shell
> system ls
> \! ls

ubuntu eclipse install

參考 Ubuntu 1804 桌面版 Eclipse + JSP 學習記錄
$ java -version
openjdk version "11.0.6" 2020-01-14
OpenJDK Runtime Environment (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1)
OpenJDK 64-Bit Server VM (build 11.0.6+10-post-Ubuntu-1ubuntu118.04.1, mixed mode, sharing)
$ sudo update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      manual mode
  2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode

Press <enter> to keep the current choice[*], or type selection number:
$ vi ~/.bashrc
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
export CLASSPATH=.:${JAVA_HOME}/lib
export PATH=${JAVA_HOME}/bin:${PATH}
$ source ~/.bashrc
到網頁 https://www.eclipse.org/
找到要下載的 linux 64 bit 版本 https://www.eclipse.org/downloads/download.php?file=/oomph/epp/2020-03/R/eclipse-inst-linux64.tar.gz
$ cd Downloads/
$ tar xvf eclipse-inst-linux64.tar.gz
$ cd eclipse-installer/
為避免
Caused by: java.io.FileNotFoundException: /home/user1/Downloads/eclipse-installer/configuration/org.eclipse.osgi/.manager/.fileTableLock (Permission denied)
$ sudo chown -RH mark: configuration/
有人使用 $ sudo ./eclipse-inst, 但安裝完成後,只能用 $ sudo ./eclipse 啟動
$ ./eclipse 會出現 /root/.p2/pool/plugins/org.eclipse.equinox.launcher.gtk.linuxx86_64.1.1.1100.v20190907-0426: cannot open shared object file: Permission denied
$ ./eclipse-inst
選擇 Eclipse IDE for Enterprise Java Developers
選擇 java 版本和安裝路徑
$ sudo rm -rf eclipse-installer/ eclipse-inst-linux64.tar.gz
$ cd

安裝桌面啟動捷徑
$ vi ~/.local/share/applications/eclipse.desktop
[Desktop Entry]
Type=Application
Name=Eclipse
Comment=Eclipse Integrated Development Environment
Icon=/home/user1/eclipse/jee-2020-03/eclipse/icon.xpm
Exec=/home/user1/eclipse/jee-2020-03/eclipse/eclipse
Terminal=false
Categories=Development
StartupWMClass=Eclipse

$ chmod +x ~/.local/share/applications/eclipse.desktop
重新開機
按 Search, 找 Eclipse, 按右鍵, Add to Favorites

Eclipse 設定 Tomcat server
$ wget http://ftp.tc.edu.tw/pub/Apache/tomcat/tomcat-9/v9.0.33/bin/apache-tomcat-9.0.33.tar.gz
$ tar xvf apache-tomcat-9.0.33.tar.gz
開啟 eclipse
Window/Preferences
Server/Runtime Environment
按 Add, 選擇 Apache Tomcat v9.0
設定 Tomcat installation directory: 到剛才解壓縮的路徑
Window/Show View/Other...
選擇 Servers
按 ProjectExplorer/Servers/Tomcat v9.0 Server at localhost-config/server.xml
修改 port

建立 Eclipse 專案
File/New/Dynamic Web Project
輸入專案名稱
在 Web Module 頁中,將 Generate web.xml deployment descriptor 打勾
Project Explorer/專案名稱/WebContent 右鍵 New/JSP File

下載 gson-2.8.6.jar 到 專案下的 WEB-INF/lib 下


處理 json

Project Explorer/專案名稱 右鍵 Export/WAR file

2020年3月19日 星期四

install tomcat at ubuntu

參考 How to Install Tomcat 9 on Ubuntu 18.04

$ sudo apt update
$ sudo apt install default-jdk
$ sudo useradd -r -m -U -d /opt/tomcat -s /bin/false tomcat
$ cd /tmp
$ wget http://ftp.tc.edu.tw/pub/Apache/tomcat/tomcat-9/v9.0.33/bin/apache-tomcat-9.0.33.tar.gz -P /tmp
$ sudo tar xf /tmp/apache-tomcat-9.0.33.tar.gz -C /opt/tomcat
$ sudo ln -s /opt/tomcat/apache-tomcat-9.0.33/ /opt/tomcat/latest
$ sudo chown -RH tomcat: /opt/tomcat/latest
$ sudo sh -c 'chmod +x /opt/tomcat/latest/bin/*.sh'
$ sudo vi /etc/systemd/system/tomcat.service
[Unit]
Description=Tomcat 9 servlet container
After=network.target

[Service]
Type=forking

User=tomcat
Group=tomcat

Environment="JAVA_HOME=/usr/lib/jvm/default-java"
Environment="JAVA_OPTS=-Djava.security.egd=file:///dev/urandom -Djava.awt.headless=true"

Environment="CATALINA_BASE=/opt/tomcat/latest"
Environment="CATALINA_HOME=/opt/tomcat/latest"
Environment="CATALINA_PID=/opt/tomcat/latest/temp/tomcat.pid"
Environment="CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC"

ExecStart=/opt/tomcat/latest/bin/startup.sh
ExecStop=/opt/tomcat/latest/bin/shutdown.sh

[Install]
WantedBy=multi-user.target

$ sudo systemctl daemon-reload
$ sudo systemctl start tomcat
$ sudo systemctl status tomcat
$ sudo systemctl enable tomcat

$ sudo vi /opt/tomcat/latest/conf/tomcat-users.xml
<tomcat-users>
  <role rolename="admin-gui"/>
  <role rolename="manager-gui"/>
  <user username="admin" password="YourPassword" roles="admin-gui,manager-gui"/>
</tomcat-users>

$ sudo systemctl restart tomcat
網頁開啟 http://localhost:8080

參考 Nginx + Tomcat 使用 Https
$ vi /etc/nginx/sites-available/default
upstream tomcat_server {
        server 127.0.0.1:8080 weight=1;
}
server {
        listen 8443 ssl default_server;
        listen [::]:8443 ssl default_server;
        ssl_certificate /home/user1/Data/webapi/openssl/web1/server.crt;
        ssl_certificate_key /home/user1/Data/webapi/openssl/web1/server.key;

        location ^~ /test/ {
                proxy_redirect off;
                proxy_set_header Host $host:$server_port;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                # for https
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_pass http://tomcat_server;
        }
}

$ sudo systemctl reload nginx.service

$ sudo vi /opt/tomcat/latest/conf/server.xml
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
        <Value className="org.apache.catalina.valves.RemoteIpValve"
            remoteIpHeader="X-Forwarded-For"
            protocolHeader="X-Forwarded-Proto"
            protocolHeaderHttpsValue="https"
            httpsServerPort="8443"
        />
      </Host>

$ sudo systemctl restart tomcat

$ sudo mkdir /opt/tomcat/laest/webapps/test
$ sudo vi /opt/tomcat/latest/webapps/test/index.jsp
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="theme-color" content="#000000">
    <title>React App</title>
  </head>
  <body>
    <div id="root">
        Hello world
    </div>
  </body>
</html>

$ sudo mkdir /opt/tomcat/laest/webapps/test/WEB-INF
$ sudo vi /opt/tomcat/latest/webapps/test/WEB-INF/web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
</web-app>


2020年3月18日 星期三

https on nginx and python flask

建立 python flask 的網頁伺服器
$ cat server.py
@app.route('/api/PostTime', methods=['POST'])
def post_time():
    print(request.headers)
    print(request.json)
    result = '\n'.join([request.json['updDate'],
            request.json['camera']])
    print(result)
    return str(result)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port="5000", debug=True,
            # 下兩行可以啟動 https
            #ssl_context=("/home/user1/Data/webapi/openssl/web1/server.crt",
            #    "/home/user1/Data/webapi/openssl/web1/server.key")
            )

$ python3 server.py

$ cat PostTime.py
import requests
import os

data = {
    'updDate': '2019-01-02T15:10:11',
    'camera': 'A001',
}

os.environ['REQUESTS_CA_BUNDLE'] = '/home/user1/Data/webapi/openssl/ca/cacert.pem'
#url = 'https://127.0.0.1:5000/api/PostTime'
url = 'https://127.0.0.1:8443/api/PostTime'
headers = {'Content-Type': 'application/json'}
response = requests.post(url=url,
        headers=headers,
        #verify=False,
        json=data)
if response.ok:
    print("PostTime ok")
    print(response.status_code)
    print(response.text)
else:
    print(response.status_code)
    print(response.text)

$ python3 PostTime.py

# cat /etc/nginx/sites-available/config
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        listen 8443 ssl default_server;
        listen [::]:8443 ssl default_server;
        ssl_certificate /home/user1/Data/webapi/openssl/web1/server.crt;
        ssl_certificate_key /home/user1/Data/webapi/openssl/web1/server.key;
        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location ^~ /api/ {
                # 當 https 由 nginx 管控,python flask 就要走一般的 http
                proxy_pass http://127.0.0.1:5000;
                proxy_set_header Host $host;
        }
        # 設定上傳限制
        client_max_body_size 10M;
}

重新啟動 nginx
# sudo nginx -s reload

2020年3月12日 星期四

git & VS2017

在網站上 New Repository
VisualStudioTest

> mkdir VisualStudioTest
> cd VisualStudioTest
> git init
> git remote add origin http://ip:port/username/VisualStudioTest.git
> git remote -v

編輯 .git\config 將, 避免 push 時,出現 403
[remote "origin"]
url = http://192.168.0.101:8080/user/VisualStudioTest.git
改為
[remote "origin"]
url = http://mark1@192.168.0.101:8080/user/VisualStudioTest.git

開啟 VS2017
New Project
Location: VisualStudioTest 的上層目錄
Solution name: VisualStudioTest
Create directory for solution 要勾選

在 TeamExplorer 頁籤上 可以看到 VisualStudioTest
雙按 VisualStudioTest
選 Settings/Git/Repository Settings
按 Ignore & Attributes Files/Ignore File/Add
TeamExplorer /Sync
TeamExplorer /Changes
在 Changes 的目錄下按右鍵 選 Stage
輸入 commit
按 Commit Staged
按 Synchronization/Outgoing Commits/Push 上傳至網站


2020年3月11日 星期三

frp 應用

cp frps /opt/bin

frps.ini
[common]
bind_port = 7000
dashboard_port = 7001
dashboard_user = user
dashboard_pwd = password

用 nobody 開機自動執行
/etc/systemd/system/frps.service
[Unit]
Description=FRP Server Daemon

[Service]
Type=simple
ExecStartPre=-/usr/sbin/setcap cap_net_bind_service=+ep /opt/bin/frps
ExecStart=/opt/bin/frps -c /opt/etc/frps.ini
Restart=always
RestartSec=20s
User=nobody
PermissionsStartOnly=true
LimitNOFILE=infinity

[Install]
WantedBy=multi-user.target

sudo systemctl start frps
sudo systemctl enable frps

frpc.ini
[common]
server_addr = digichance11.vigorddns.com
server_port = 7000
login_fail_exit = false

[vnc]
type = tcp
local_ip = 127.0.0.1
local_port = 8088
remote_port = 2172

開機自動執行
ftpc.vbs
set ws=Wscript.CreateObject("Wscript.Shell")
ws.Run "C:\frp_0.31.2_windows_386\frpc.exe -c C:\frp_0.31.2_windows_386\frpc.ini", 0
gpedit.msc
本機電腦 原則/電腦設定/指令碼 - (啟動/關機)
啟動/內容
新增 ftpc.vbs

frpc.bat
REM 雙擊執行,不顯示視窗
@echo off
if "%1" == "h" goto begin
mshta vbscript:createobject("wscript.shell").run("""%~nx0"" h",0)(window.close)&&exit

:begin
frpc.exe -c frpc.ini

連線 vnc 時,出現下列錯誤
Local loop-back connections are disabled.
在視窗右下角 vnc icon 按滑鼠右鍵/Admin Properties/滑鼠左鍵
打勾 Allow Loopback Connections


2020年3月3日 星期二

git 學習筆記 5, remote and github

git clone URL
預設遠端名為 origin
只抓取 master, 其餘 branch 不下載

git remote show <origin>
git remote add <name> URL
git remote rename <a> <b>

更改 remote
git remote set-url <name> URL

git branch -a
顯示所有 branch
git remote show origin
顯示 origin 資訊

參與修改 branch_a
git checkout origin/branch_a
切換到遠端的 branch_a
git checkout -b branch_a
在此建立一個同名的 branch

pull 範例,pull 等於 fetch + rebase
git fetch origin
取得遠端 origin 的更新, origin/master 往前走了
git checkout master
git rebase origin/master
將本地的更新插入 origin/master

git push <remote> <local branch>:<remote branch>
git push <remote> :<remote branch>
刪除 remote branch

fork on github
在 github 上產生 fork (需要有 github 的帳號)
$ git clone https://github.com:user/repository.git
clone 自己在 github 上產生的 fork repository
$ git remote add upstream https://github.com:ori_user/repository.git
下載 upstream 上的所有 branch
$ git fetch upstream
切換至 develop
$ git checkout develop
若本地的 develop 比 upstream/develop 慢
$ git rebase upstream/develop
$ git checkout -b fix_branch
更新開發端成最新
更改程式
$ git add your_modify
$ git commit
$ git push origin fix_branch:fix_branch
到 github 網頁(user) Repository
進入 Pull Requests, 按下 New Pull Request
選擇 merge into: develop ... pull from: fix_branch
按 Create pull request
到 github 網頁(ori_user)
按 pull request, 找到剛才的 pull request, 點選進入
要 merge, 按 Merge Pull Request
不要 merge, 按下 Close
$ git checkout develop
$ git fetch upstream
$ git rebase upstream/develop
$ git push origin develop
$ git push origin :fix_branch
$ git branch -d fix_branch

git 學習筆記 4, branch checkout merge

checkout 移動 HEAD
git checkout hash
移動 HEAD 到 hash commit
git checkout file
將檔案還原到 HEAD 狀態,放棄修改

預設的 branch 為 master

git branch
顯示所有 branch

git branch new_branch
新建一個 branch, 但 HEAD 沒有轉移,需要自己執行下列命令
git branch new_branch hash
在 hash commit 上建立 new_branch
git checkout new_branch
可用下列命令取代上兩個命令
git checkout -b new_branch

HEAD 必須和 branch 掛勾,
如 checkout 到舊的 commit, 若要以此為基準修改,則馬上執行
git checkout -b new_branch

git branch -d del_branch
刪除 branch
但刪除前需要 checkout 到別的 branch,不能刪除目前的 branch
刪除前會判斷目前的 branch 和要刪的 branch 是否需要 merge
若需要 merge, 則會失敗, 若不 merge 要直接刪,則用
git branch -D del_branch

git checkout branch_a
git merge branch_b
Fast-forward
git merge branch_b --no-ff
no Fast-forward
若有衝突(conflict), 可查看 git status
衝突解決用 git commit
放棄 merge, 使用 git merge --abort

vi conflict_file
<<<<<<< HEAD
在 HEAD 修改的內容
=======
在 branch_b 修改的內容
>>>>>>> branch_b

git mergetool
會顯示 branch_a, base_of_a_b, branch_b
還有要 merge 的檔

git add conflict_file
git commit


2020年3月2日 星期一

git 學習筆記 3

git hash 可以只使用 6 個字元

HEAD
Branch
Tag (版本)
Remote

git log --oneline
git log -n3
git log -n3 hash

git log HEAD^^
一個 ^ 表示往前一個, 兩個^ 表示往前兩個
git log HEAD~8
~8 表示往前8個

git log --oneline file
專門針對一個 file

git log --stat file
git log --patch file

git log -S token
git log --patch -S token
有修改 token 的地方

git diff
比較 unstage 和 HEAD 的差異
git diff --staged
比較 staged 和 HEAD 的差異
git diff hash file
比較 unstage 和 hash 版本的差異
git diff hash1 hash2
比較兩次 commit 的差異

git add -p
...
Stage this hunk [y,n,q,a,d,s,e,?]?
q: 離開
a: 加入全部
y: 加入
n: 不加入
s: 分段
K: 上一段
e: 編輯
移除 -, 將 '-' 換成 ' '
移除 +, 將整行刪除

git commit --amend
隱藏舊的 commit, 用新的 commit 取代

git 學習筆記 2

git commit message 有一個 50/72 法則
第一行部要超過 50字
其餘不要超過 72字

1. Issue
2. Problem, 如何重現問題
3. Cause
4. Fix

.gitignore
參考 GitHub gitignore

Git 檔案的四種狀態
1.未追蹤(Untracked files):在版本提交後才又加進來的檔案,這些檔案並沒有被GIT所追蹤控管
2.已更改(Changes not staged for commit):已提交版本後,卻又再次修改,這些檔案會被丟回工作目錄(WD)
3.等待提交(Changes to be committed):在工作目錄(WD)的檔案執行git add後,會放在暫存區(Stage)。這些放在暫存區的檔案狀態便是等待提交囉!不論檔案是新增,修改,或刪除整個檔案,都是用 git add。
4.已提交(Committed):在暫存區(Stage)的檔案執行git commit後,檔案便置於儲存區(Repo),這些放在儲存區的檔案即是已提交的狀態。

git reset HEAD file
將 file 由 stage 返回 unstage
git reset --hard HEAD
連檔案也回復,即修改消失

git 學習筆記 1

參考書 Git - Book

mark@mark-z390-u:~/Data/git_test$ mkdir sample; cd sample
mark@mark-z390-u:~/Data/git_test/sample$ git init
Initialized empty Git repository in /home/mark/Data/git_test/sample/.git/
mark@mark-z390-u:~/Data/git_test/sample$ ls -al
total 12
drwxrwxr-x 3 mark mark 4096 Feb 29 10:06 .
drwxrwxr-x 3 mark mark 4096 Feb 29 10:05 ..
drwxrwxr-x 7 mark mark 4096 Feb 29 10:06 .git
mark@mark-z390-u:~/Data/git_test/sample$ vim README.md
mark@mark-z390-u:~/Data/git_test/sample$ git add README.md
mark@mark-z390-u:~/Data/git_test/sample$ git commit
*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: unable to auto-detect email address (got 'mark@mark-z390-u.(none)')
mark@mark-z390-u:~/Data/git_test/sample$ git config --global user.email "mark@mark-z390-u"
mark@mark-z390-u:~/Data/git_test/sample$ git config --global user.name "mark"
mark@mark-z390-u:~/Data/git_test/sample$ git config --global core.editor vim
mark@mark-z390-u:~/Data/git_test/sample$ git config --global merge.tool vimdiff
mark@mark-z390-u:~/Data/git_test/sample$ git config --global color.ui true
mark@mark-z390-u:~/Data/git_test/sample$ git config --global alias.st status
mark@mark-z390-u:~/Data/git_test/sample$ git st
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

new file:   README.md

mark@mark-z390-u:~/Data/git_test/sample$ 
mark@mark-z390-u:~/Data/git_test/sample$ git config --list --show-origin
file:/home/mark/.gitconfig      user.email=mark@mark-z390-u
file:/home/mark/.gitconfig      user.name=mark
file:/home/mark/.gitconfig      core.editor=vim
file:/home/mark/.gitconfig      merge.tool=vimdiff
file:/home/mark/.gitconfig      color.ui=true
file:/home/mark/.gitconfig      alias.st=status
file:.git/config        core.repositoryformatversion=0
file:.git/config        core.filemode=true
file:.git/config        core.bare=false
file:.git/config        core.logallrefupdates=true
mark@mark-z390-u:~/Data/git_test/sample$ cat ~/.gitconfig 
[user]
email = mark@mark-z390-u
name = mark
[core]
editor = vim
[merge]
tool = vimdiff
[color]
ui = true
[alias]
st = status
mark@mark-z390-u:~/Data/git_test/sample$ 

2020年3月1日 星期日

vim 區塊編輯 和 多視窗

區塊編輯
<Ctrl>+v 進入區塊編輯
上下左右 選取區塊
I 編輯
c 替換
d 刪除
<Esc> 離開區塊編輯, 離開後才顯示


多視窗移動
<Ctrl>+w
h: 左移視窗
j: 下移視窗
k: 上移視窗
l: 又移視窗