2014年10月28日 星期二

sublime手動安裝packages

由於package install所抓的資源( https://sublime.wbond.net/channel.json )常常被牆住,所以需要手動下載package來手動裝
ps. liunx 由於找到這款 http://proxychains.sourceforge.net/ 類似proxifier的工具只能在指令上執行,沒法透過GUI設定

以安裝SFTP為例
下載 https://sublime.wbond.net/files/3-posix/SFTP.sublime-package
放到/home/xxx/.config/sublime-text-3/Installed Packages/ 資料夾下
重啟sublime

有些package( 像是GoSublime )看起來像是要解壓縮成資料夾放到/home/xxx/.config/sublime-text-3/Packages/ 中,看來手動安裝方法沒有一定...

手動安裝的教學網站
http://sublimetext.info/docs/en/extensibility/packages.html

2014年10月27日 星期一

arch linux xfce擷取螢幕

使用xfce4-screenshooter
https://wiki.archlinux.org/index.php/Taking_a_screenshot#Xfce_Screenshooter
1. 安裝xfce4-screenshooter
2. 開啟"設定值管理員" (Xfce4 ... )
3. 點擊"鍵盤"
4. 點擊"應用程式捷徑"
5. 加入(他會瀏覽/usr/bin 下面的指令)
6. 新增xfce4-screenshooter,榜定熱鍵PrtScn
- xfce4-screenshooter 可以設定幾秒後擷取螢幕,有助於擷取非即時的畫面
存檔位置:擷取後才選擇存哪裡

使用Shutter
存檔位置:預設存在你的家目錄下。ex. /home/david/

Arch使用MySQL原始碼安裝MySQL

因為 http://carlislebear.blogspot.jp/2014/10/install-schema-sync.html 這篇的關係,所以打算把MariaDB移除,手動安裝MySQL

參考連結:
http://shaurong.blogspot.jp/2014/08/mysql-5620targz-centos-70-x8664.html
http://blog.sina.com.cn/s/blog_606a23dd0101g1wr.html

0. 安裝cmake ( 自mysql5.5及以上的源程序包,不再包括configure文件,因此不能直接安装,需要使用cmake来进行安装 )
用pacman 直接安裝或上網找 cmake-xxx.pkg.tar.xz 下來再用pacman裝

1. 到MySQL官網下載MySQL Community Server 
Select Platform: 選擇Source Code

下載最下面的壓縮檔,mysql-5.6.21.tar.gz,並放到/usr/local/src下解壓縮,解壓縮出來要有 CMakeCache.txt 檔才對,INSTALL-SOURCE 4823行左右也有安裝教學

# Preconfiguration setup
shell> groupadd mysql
shell> useradd -r -g mysql mysql
# Beginning of source-build specific instructions
shell> tar zxvf mysql-VERSION.tar.gz #我解壓縮到/usr/local/src
shell> cd mysql-VERSION
shell> cmake .
shell> make #這步會很久,所花時間是用pacman、apt-get等管理工具不能比的
shell> make install #也很久
# End of source-build specific instructions
# Postinstallation setup
shell> cd /usr/local/mysql
shell> chown -R mysql .
shell> chgrp -R mysql .
shell> scripts/mysql_install_db --user=mysql
shell> chown -R root .
shell> chown -R mysql data
shell> bin/mysqld_safe --user=mysql &
# Next command is optional
shell> cp support-files/mysql.server /etc/init.d/mysql.server

mysql指令找不到
# which mysql
which: no mysql in (/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/vendor_perl:/usr/bin/core_perl)
解法1:
將/usr/local/mysql/bin/mysql 用ln -fs 到/usr/local/bin 去
# cd /usr/local/bin
# ln -fs /usr/local/mysql/bin/mysql
# ln -fs /usr/local/mysql/bin/mysqldump
# ln -fs /usr/local/mysql/bin/mysqladmin
解法2:
設定環境變數(未測試)

安裝後用mysql -u root -p 登錄出現錯誤:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
解法:
指定登錄位置
mysql -u root -p -h 127.0.0.1

啟用mysql 服務
# /usr/local/mysql/bin/mysqld_safe &
查mysql啟動時的錯誤
# tail -f /usr/local/mysql/data/your_pc_name.err
出現錯誤:
[ERROR] Fatal error: Can't open and lock privilege tables: Table 'mysql.user' doesn't exist
解法:
(中間下過這些指令,不確定要不要做:
# chmod 777 /usr/local/mysql/support-files/mysql.server
# chown -R mysql:mysql /usr/local/mysql/
)
# /usr/local/mysql/scripts/mysql_install_db --user=mysql
可能當初在裝mysql時,沒有停用原本的MariaDB再裝,造成這句沒有執行成功,執行成功的畫面:
OK

To start mysqld at boot time you have to copy
support-files/mysql.server to the right place for your system

PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !
To do so, start the server, then issue the following commands:

  ./bin/mysqladmin -u root password 'new-password'
  ./bin/mysqladmin -u root -h lmannb password 'new-password'

Alternatively you can run:

  ./bin/mysql_secure_installation

which will also give you the option of removing the test
databases and anonymous user created by default.  This is
strongly recommended for production servers.

See the manual for more instructions.

You can start the MySQL daemon with:

  cd . ; ./bin/mysqld_safe &

You can test the MySQL daemon with mysql-test-run.pl

  cd mysql-test ; perl mysql-test-run.pl

Please report any problems at http://bugs.mysql.com/

The latest information about MySQL is available on the web at

  http://www.mysql.com

Support MySQL by buying support/licenses at http://shop.mysql.com

WARNING: Found existing config file ./my.cnf on the system.
Because this file might be in use, it was not replaced,
but was used in bootstrap (unless you used --defaults-file)
and when you later start the server.
The new default config file was created as ./my-new.cnf,
please compare it with your file and take the changes you need.  

在此之前試過 # ./mysql_upgrade -u root -p => 無效

檢查mysql有沒有跑起來:
# ps aux | grep mysql
mysql     4649  3.5  5.6 967604 456952 pts/3   Sl   19:58   0:00 /usr/local/mysql/bin/mysqld --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --plugin-dir=/usr/local/mysql/lib/plugin --user=mysql --log-error=/usr/local/mysql/data/lmannb.err --pid-file=/usr/local/mysql/data/lmannb.pid

安裝schema sync[未解決]

目標:
在測試環境的測試資料庫欄位有所更動後,例:新增刪除欄位,修改欄位屬性...etc。需要將該更動同步到正式環境上且不把測試資料放到正式資料庫中。如MSSQL的DTS,只轉schema

資料庫:MySQL

檢查:
http://stackoverflow.com/questions/6679399/compare-two-mysql-databases-on-command-line-with-a-free-tool
只比較table:
$ mysql -u whatever -e "describe table" database1 > file1.txt
$ mysql -u whatever -e "describe table" database2 > file2.txt
$ diff file1.txt file2.txt

其他檢查方法:
http://stackoverflow.com/questions/225772/compare-two-mysql-databases
這邊有列出一些工具,如 Toad ,但看起來是windows電腦才能用,我手上的電腦灌linux

Schema Sync系統需求:
Python 2.4, 2.5, or 2.6
MySQL, version 5.0 or higher
MySQLdb, version 1.2.1p2 or higher
SchemaObject 0.5.3 or higher (Auto installed with Schema Sync)

安裝Schema Sync:
http://schemasync.org/
下載 SchemaSync-0.9.2 檔後解壓縮
$ tar xvzf SchemaSync-0.9.2.tar.gz
$ cd SchemaSync-0.9.2
$ sudo python2 setup.py install

注意:因為Schema Sync 需求的環境是 python 2.4~2.6,因為我的arch linux有裝python2和python3( python -> python3,預設python3 ),把python指到python2或直接用python2安裝
參考連結: http://stackoverflow.com/questions/15400985/how-to-completely-replace-python-3-with-python-2-in-arch-linux
MySQLdb 一樣去下載檔案解壓縮後用這個指令安裝
$ sudo python2 setup.py install

用法:
$ schemasync mysql://user:pass@dev-host:3306/dev_db mysql://user:pass@prod-host:3306/production_db
出現錯誤:
Schema Sync requires MySQL version 5.0+ (source is v10.0.12-MariaDB-log)
原因:
因為Arch Linux的pacman安裝的資料庫是MariaDB( MySQL的一個開源分支 )
登錄後資料庫介面是
MariaDB [mysql]>

接著手動安裝MySQL

2014年10月26日 星期日

使用Markdown在github上排版README.md

只針對github專案上README.md顯示有效

參考資源:
http://markdown.tw/
https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet

主標題
==========
副標題
--------------

#your word =>H1大小的your word
...
######your word =>H6大小的your word

有序的list => "1. " 數字+點+空白
1. ordered list one
2. ordered list two
...

無順序的list => "* "星號+空白
* list
* list

巢狀list => 用兩個空白縮排,可用有序或無序的list
1. ordered list one
  * nested list
  * nested list
2. ordered list two

斜體 => 一個*星號包住字
*斜體字*

粗體 => 兩個**星號包住字
**粗體字**

粗體斜體混合使用
**粗體字_粗體和斜體字_**

引言
> 一層引言 ("> "一個大於+空白)
> > 兩層引言("> "兩個大於+空白)

分隔線 => 三個*星號
***

超連結 => 直接打網址
http://tw.yahoo.com

刪除線 => 兩個~~引號包住字
~~文字上會有刪除線~~

寫程式碼 => 三個"`"(esc下面那個鍵) 包起來
```perl
use Data::Dumper;
print Dumper $bear;
```

表格 => 直接寫HTML的table(我常試過github table的寫法,但預覽時一直無效)
<table>
    <tr>
        <th>TO_BASE64('abc')</th>
        <th>FROM_BASE64(TO_BASE64('abc'))</th>
    </tr>
    <tr>
        <td>YWJj</td>
        <td>abc</td>
    </tr>
</table>


圖片連結
[Imgur](http://i.imgur.com/your_image.jpg)
註:imgur.com上傳圖片後可以直接選Markdown的圖片語法

2014年10月23日 星期四

在blogger中加入表格

blogger( google blog )編輯器預設無法加入表格,網路上有查到一些方法。如嵌入google試算表的iframe(太麻煩),開HTML寫table編輯(太遮疼),在word或WPS上寫好再貼上來(樣式有bug,原始碼有一堆無用的code)

所以我是在google雲端硬碟開一個試算表再貼上來,
要再同一個表格內換行就在sublime上寫好再貼上去
ex.
"1. aaa
2. bbb"
前後要加雙引號才能換行

例:

避免切換回撰寫模式時的提示

如果用以上方法新增表格,在【HTML檢視】切回【撰寫模式】會出現以下彈窗
原因是表格的 colgroup 這段代碼造成的
把 colgroup 那段去掉,欄寬寫到第一個tr的td裡面即可
這樣來回切換時就不會有提示了








sublime 常見問題

在前端開發嘗試過許多編輯器,現在打算用sublime來開發前端,在這邊順便寫下我摸過的編輯器的優缺點
優點缺點
aptana1. 我最熟悉
2. bug較少
1. jQuery只支援到1.6版
2. 擴展麻煩(css3, snippet, AngularJS)
3. 肥大(雖然我不在意)
eclipse-PDT1. 套件多
2. jQuery支援版本較新
1. bug多
2. 設定繁雜、版本太多
3. 肥大
webstorm1. 功能強大、套件完整
2. jQuery支援版本較新
1. 需付費
2. 設定繁雜、熱鍵需重新熟悉
3. 肥大
sublime1. 較輕量
2. 列模式
3. 有AngularJS、jQuery擴展
1. 熱鍵、介面不熟悉
2. Install Package有時候連不上
其他:
vim - 太遮疼,手太殘
Netbeans, Atom, notepad++ - 研究不深

修正註解script tag的bug
sublime在 <script src="jquery.js"></script> 使用ctrl+ / 註解時會變成
// <script src="jquery.js"></script>
要如何把他變成
<!-- <script src="jquery.js"></script> -->
http://wesbos.com/fix-sublime-text-toggle-comment/
1. 找HTML.tmLanguage, preferences → browse packages → HTML,
2. 編輯HTML.tmLanguage:
在286行附近將
<string>(?:^\s+)?(&lt;)((?i:script))\b(?![^&gt;]*/&gt;)</string>
取代成
<string>(?:^\s+)?(&lt;)((?i:script))\b(?![^&gt;]*/&gt;)(?!.*&lt;/script&gt;)</string>
注意:
arch linux安裝sublime 3 ,用browse packages會開啟目錄
/home/bear/.config/sublime-text-3/Packages/
但HTML.tmLanguage位置在
/home/bear/.config/sublime-text-2/Packages/HTML/HTML.tmLanguage
用sublime修改sublime-text-2下的HTML.tmLanguage,然後存檔後就能修正這個bug
仍然有bug:
<script src="jquery.js"></script> 必須在貼近文件的最左邊(不能有縮排),才能正常註解。所以要先把<script>最前面的縮排先刪掉=> ctrl+/註解掉 => 再用自動縮排(HTML-CSS-JS Prettify)縮回來
HTML.tmLanguage位置在
/opt/sublime_text_3/Packages/HTML.sublime-package 這個壓縮檔裡面
將HTML.sublime-package複製成zip檔再用unzip解開,照上面方法修改HTML.tmLanguage後再用zip壓回放回原位置。重開sublime即可修復此bug
注意:
sublime的syntax設成handlebars時,仍然會有bug。要設回html
Windows 7 安裝版 ( 修正註解script tag的bug )
一樣找 HTML.sublime-package (位置在 C:\Program Files (x86)\Sublime Text 3\Packages )
方法同上,改成zip解開後改裡面的HTML.tmLanguage 再壓回去改回原本檔案名稱
參考資料:
http://stackoverflow.com/questions/19790062/where-to-put-tmlanguage-in-sublime-text-3


推薦的HTML縮排工具
http://stackoverflow.com/questions/8839753/how-do-i-reformat-html-code-using-sublime-text-2
套件我用HTML-CSS-JS Prettify
JS部份我用 jsFormat 縮排

修改tag的名字
"Rename Tag" action: Ctrl + Shift + '

PHP縮排美化工具
php.fmt (用package control裝就好)
https://github.com/phpfmt/sublime-phpfmt
設定檔( Preferences -> Package Settings -> phpfmt -> Setting - User ):
{
"php_bin":"C:/xampp/php/php.exe", // 注意:因為我沒裝php,要設xampp的php,不能設cygwin的php(可能是因為cygwin的php是基於linux的php)
"format_on_save":false,
"indent_with_space": 4,
"version": 1
}
熱鍵: ctrl+shfit+p 後搜尋 phpfmt

sublime text 3 phpfmt:format 出錯
解法:
http://windows.php.net/download/
下載 Non Thread Safe 的版本zip檔
解壓縮到C:/PHP7
Preferences -> Package Settings -> phpfmt -> Setting - User
"php_bin": "C:/PHP7/php.exe",

CodeFormatter (用package control裝就好)
https://github.com/akalongman/sublimetext-codeformatter
設定檔( Preferences -> Package Settings -> CodeFormatter -> Setting - User ):
{
"codeformatter_php_path": "C:/xampp/php/php.exe"  // 理由同上
}

按一次tab,出現兩次tab
http://stackoverflow.com/questions/24356939/sublime-text-3-double-tab-issue
重開sublime即可

tab中文出現亂碼
https://github.com/seanliang/ConvertToUTF8/issues/28
如圖:
解法:
Preferences => Settings => 新增 "dpi_scale": 1, =>重啟Sublime

F12 goto definition不作用
左下角顯示 unable to find xxx
解法:
Preferences => Key Bindings => 打開來後關掉
這時候ctrl + ` 的 sublime console會顯示錯誤:
Unable to open /D/bear/Sublime/Data/Packages/Default/Default (Windows).sublime-keymap
Traceback (most recent call last):
  File "D:\bear\Sublime\sublime_plugin.py", line 462, in run_callback
    expr()
  File "D:\bear\Sublime\sublime_plugin.py", line 603, in <lambda>
    run_callback('on_activated', callback, lambda: callback.on_activated(v))
  File "D:\bear\Sublime\Data\Installed Packages\TrailingSpaces.sublime-package\trailing_spaces.py", line 419, in on_activated
    self.freeze_last_version(view)
  File "D:\bear\Sublime\Data\Installed Packages\TrailingSpaces.sublime-package\trailing_spaces.py", line 440, in freeze_last_version
    on_disk = codecs.open(file_name, "r", "utf-8").read().splitlines()
  File "./python3.3/codecs.py", line 896, in open
FileNotFoundError: [Errno 2] No such file or directory: 'D:\\bear\\Sublime\\Data\\Packages\\Default\\Default (Windows).sublime-keymap'
Could not import subprocess32 module, falling back to subprocess module
...
WINDOW COMMAND ENABLED False
然後這問題就解決了... F12可以用了

在Project => Quick Switch Project和Open Recent移除專案
https://forum.sublimetext.com/t/how-do-i-remove-a-project-from-the-switch-project-window/3725
關閉Sublime,使用其他編輯器,修改Sublime Data\Local目錄下的 Session.sublime_session 中的 "workspaces" => "recent_workspaces": ,直接刪除不要的Project,重啟Sublime

使用Alignment對齊你的Code(縮排)
http://kevintsengtw.blogspot.com/2012/03/sublime-text-2-part5-alignmentcode.html
快速鍵「Ctrl + Alt + a」

使用Alignment 對齊 php 靜態陣列:
    public static $status = [
        self::STATUS_RECEIVED   =>  '未支付',
        self::STATUS_SUCCESS    =>  '支付成功',
        self::STATUS_FAIL       =>  '支付失败',
        self::STATUS_SELECT_FAILED =>  '海选失败',
        self::STATUS_EXCEPTION  =>  '支付异常订单',
        self::STATUS_CLOSED     =>  '订单关闭',
        self::STATUS_DISPUTE     =>  '争议中'
    ];
以上陣列直接用Alignment對齊是不作用的,
https://github.com/wbond/sublime_alignment/issues/33
niquedegraaff: I can confirm. Alignment is not working at all in PHP for me. (Windows 7 64 bit)
解法:
複製黃色區塊到新的sublime 文件上 => 列模式刪除 self:: 改成$ => Aligment 熱鍵對齊 => 列模式將$改回 self:: => 貼回原本文件位置


git diff時換行出現^M,且不換行
https://stackoverflow.com/questions/11899843/fixing-sublime-text-2-line-endings
場景:某個加密文件貼回明文後報錯
看來原加密文件是格式Windows 1252。因為
http://violin-tao.blogspot.com/2016/05/crlflf-bug.html
CRLF 就是 \r\n 是只有在 windows 系統在用的形式
所有的 UNIX 系統都是用 \n
CR是carriage return的意思,也就是\r
LF是line feed的意思,也就是\n
這就是為什麼有些檔案從unix系統拿去windows上面看 會變成全部都在同一行
因為只有LF 他不知道是換行
windows只吃CRLF
除了一些比較聰明的文字編輯器會分的出來
解法:

使用sublime 打開該文件。View => Line Endings => 選Unix => 保存
這樣就能使該文件的結尾是\n,在Linux 上git diff 就不會出現^M了
ps.
我沒採用 git config --global core.autocrlf true 這種或類似對.gitconfig [core]增加配置的方法
https://stackoverflow.com/questions/1889559/git-diff-to-ignore-m

避免git diff -w 時出現 warning: CRLF will be replaced by LF in xxx 錯誤
如下:
$ git status
#       modified:   public/css/hipay.css
$ git diff -w
warning: CRLF will be replaced by LF in public/css/hipay.css.
The file will have its original line endings in your working directory.
https://stackoverflow.com/questions/17628305/windows-git-warning-lf-will-be-replaced-by-crlf-is-that-warning-tail-backwar/17628353
$ git config --global core.autocrlf false
reset 到最前面的的commit再pull
$ git reset --hard commit_id
$ git pull
$ git status
# On branch master
nothing to commit, working directory clean

installer重裝sublime 3 到同一個位置後忽然無法用package control 安裝package
sublime console報錯:
Package Control: Skipping automatic upgrade, last run at 2019-04-09 21:03:51, next run at 2019-04-09 22:03:51 or after
Traceback (most recent call last):
  File "C:\Users\48\AppData\Roaming\Sublime Text 3\Installed Packages\Package Control.sublime-package\package_control/package_installer.py", line 154, in on_done
  File "C:\Users\48\AppData\Roaming\Sublime Text 3\Installed Packages\Package Control.sublime-package\package_control/package_disabler.py", line 76, in disable_packages
ImportError: No module named 'package_control'
https://www.rrosetta.com/computers-programming/sublime-text-3-importerror-no-module-named-package_control#comment-13388
Preferences => Settings => 移除ignored_packages 的 "0_package_control_loader"







2014年10月20日 星期一

使用mplayer播放影片

安裝mplayer
使用pacman -S mplayer安裝mplayer時遇到錯誤:
error: failed retrieving file 'lirc-utils-1:0.9.1.a-3-x86_64.pkg.tar.xz' from mirrors.ustc.edu.cn : The requested URL returned error: 404 Not Found
解法:
上 http://ftp.seblu.net/archlinux/arm/packages/l/libx264/ 下載tar.xz檔然後手動安裝
# pacman -U lirc-utils-1:0.9.1.a-3-x86_64.pkg.tar.xz
再安裝mplayer
又出現錯誤:
error: failed retrieving file 'libx264-1:142.20140826-1-x86_64.pkg.tar.xz' from mirrors.ustc.edu.cn : The requested URL returned error: 404 Not Found
同理,一樣上網下載package檔手動安裝,直到使用pacman -S mplayer安裝mplayer成功為止

使用API在web server 播放影片
web server 連結自己的螢幕,使用者透過網頁想要用ajax去播web server 的影片在server的螢幕上
出現錯誤:
...
Terminal type `unknown' is not defined. Playing /srv/http/codeigniter/videos/3.mp4.
...
PHP:
system('bash play_muti.sh');

play_muti.sh:
#!/bin/bash
mplayer -vo xv -noborder -zoom -ontop -x 512 -y 384 -geometry 0:0 mf://\/srv/http/codeigniter/videos/Koala.jpg -loop 0 & 
mplayer -vo xv -noborder -zoom -ontop -x 512 -y 384 -geometry 512:0 /srv/http/codeigniter/videos/1.mp4 &

註:
在console中,登錄桌面,執行play_muti.sh( # bash play_muti.sh )可以正常播放
原因:
因為點瀏覽器的api,主機上是用apache執行,所以要讓apache能以桌面登錄的使用者(ex. bear)播放影片
解法:
1. 編輯 /etc/suders
加入這行:
http ALL=(ALL) NOPASSWD: ALL #讓apache可以以別人帳號執行命令
2. 修改play_muit.sh,在前面加上sudo -u <username>:( http://stackoverflow.com/questions/6243327/how-to-run-mplayer-with-audio-speaker-output-from-php-web-script-on-linux )
#!/bin/bash
sudo -u bear mplayer -vo xv -noborder -zoom -ontop -x 512 -y 384 -geometry 0:0 mf://\/srv/http/codeigniter/videos/Koala.jpg -loop 0 & # 前面加上 sudo -u bear ,以bear執行mplayer
sudo -u bear mplayer -vo xv -noborder -zoom -ontop -x 512 -y 384 -geometry 512:0 /srv/http/codeigniter/videos/1.mp4 &

3. php在system()前面加入 putenv("DISPLAY=:0.0"); ( http://unix.stackexchange.com/questions/14408/running-mplayer-through-a-php-script )

執行api (ex. http://domain/play.php )即可在web server播放影片和圖片(注意:不是播在使用者的瀏覽器上)

播放完後影片不要關掉
mplayer參數加上-idle -fixed-vo

使用quiet和slave模式
$ mplayer -quiet -slave 3.mp4
MPlayer SVN-r37224 (C) 2000-2014 MPlayer Team
...
pause/stop (可在終端上輸入pause暫停影片、stop關掉影片)
get_time_pos (抓取現在播到第幾秒,可以判斷是否播完)
ANS_TIME_POSITION=5.2

用Makefile+fifo做:
$ mkfifo fifofile
$ mkfifo fifofile2
Makefile:
BIN=mplayer
SCR=:0
MOV=4.mp4
MOV2=3.mp4
FIFO=/your_vidoes_path/videos/fifofile
FIFO2=/your_videos_path/videos/fifofile2

all:
    nohup $(BIN) -noborder -zoom -ontop -x 512 -y 384 -geometry 0:0 -slave -input file=$(FIFO) $(MOV) 2>&1 1>player.log &
    nohup $(BIN) -noborder -zoom -ontop -x 512 -y 384 -geometry 512:0 -slave -input file=$(FIFO2) $(MOV2) 2>&1 1>player.log &

pause:
    echo "pause" > $(FIFO) &
    echo "pause" > $(FIFO2) &

clear:
    killall $(BIN)

播影片:
$ make
暫停:
$ make pause
結束:
$ make clear

不建議在shell script使用killall mplayer殺掉mplayer程式再跑後面的mplayer,因為後面的mplayer有機會開不起來,請使用:
$ ps aux | grep mplayer | awk '{print $2}' | xargs kill

循環播放影片
http://go2linux.garron.me/mplayer-command-line-music-video-player
-loop 0 1.mp4 2.mp4 3.mp4 ...

取得影片長度
http://superuser.com/questions/650291/how-to-get-video-duration-in-seconds
$ ffmpeg -i file.flv 2>&1 | grep "Duration"| cut -d ' ' -f 4 | sed s/,// | sed 's@\..*@@g' | awk '{ split($1, A, ":"); split(A[3], B, "."); print 3600*A[1] + 60*A[2] + B[1] }' 2383

相關文章:
http://carlislebear.blogspot.tw/2014/11/arch-slim-failed-to-execute-login-command.html

2014年10月14日 星期二

用php透過usb和rs232串連控制MPU電路板

設備:
電路板+電源
MPU晶片
板子上rs232的線
rs232轉usb接頭線

需求:
web server透過rs232送一串hex code給MPU晶片,MPU晶片會輸出hex code給web server,讓使用者透過網頁介面操控板子上的功能

尋找裝置:
透過dmesg得知插入板子的usb線後是 /dev/ttyUSB0 這個裝置

設定stty:
# stty -F /dev/ttyUSB0 raw speed 9600 -crtscts cs8 -parenb -cstopb #設定,指定device,注意:重新開機後要重新設定stty 不然收到的output會有錯誤(空白或斷掉)
# stty -F /dev/ttyUSB0 -a  # 檢查,注意:要指定device

簡單的測試:
cat /dev/ttyUSB0 > rs232.log  # 因為板子傳hex編碼回來,把他倒到log檔再用sublime以hexadecimal開啟
# echo -en '\x01\x01\xCA\x60\x00\x03\xA9' > /dev/ttyUSB0 #送指令到板子上,output輸出到rs232.log

使用minicom監控:
安裝minicom後
# minicom -s
選Serial port setup(會依你使用者的設定檔而出現不同語言的介面),設定Serial Device和Bps/Par/Bits成9600 8N1(依你板子通訊協議而異),然後Save setup as dfl => Exit
因為板子要送指令才會有output,在另一個視窗送指令到板子,這邊才會顯示output,但因板子送回來的是hex code,這邊顯示是亂碼,故不使用minicom監控
minicom的操作方式
ctrl+a - z 顯示說明
ctrl+a - x 離開minicom
因操作指令和screen衝突且在我的screen設定下minicom介面會跑板,所以不在screen下操作

用php讀取hex code的檔案:
$handle = @fopen("rs232.log", "r");
if ($handle) {
    while (!feof($handle)) {
        $hex = bin2hex(fread ($handle , 4 ));
        print $hex."\n";
    }
    fclose($handle);

}

使用PHP-Serial控制:
https://github.com/Xowap/PHP-Serial
以examples/dummy.php為例:
include 'PhpSerial.php';

// Let's start the class
$serial = new PhpSerial;

// First we must specify the device. This works on both linux and windows (if
// your linux serial device is /dev/ttyS0 for COM1, etc)
$serial->deviceSet("/dev/ttyUSB0"); #改為你device的位置

// We can change the baud rate, parity, length, stop bits, flow control
$serial->confBaudRate(9600); # 改頻率
$serial->confParity("none"); # 8N1的N
$serial->confCharacterLength(8); # 8N1的8
$serial->confStopBits(1); # 8N1的1
$serial->confFlowControl("none");

// Then we need to open it
$serial->deviceOpen();

// To write into
$serial->sendMessage("\x01\x02\xCA\x60\x00\x03\x01\x03\x02\xAA"); # PHP的 "\x01" 直接是16進制字串,要使用\x01的字串要跳脫"\\x01",可從vim的highlight看出來。device直接吃hex code,所以這邊這樣寫。

// Or to read from
$read = $serial->readPort();

$hex = bin2hex($read); #將output從binary轉成hex顯示到螢幕
echo "$hex\n";

// If you want to change the configuration, the device must be closed
$serial->deviceClose();

// We can change the baud rate
$serial->confBaudRate(9600); #改成你device的頻率

不能打開device:
錯誤訊息:
PHP Warning:  Unable to open the device in php_serial.class.php on line 159
...
PHP Warning:  Device must be opened to read it in php_serial.class.php on line 476
解法:
php.ini設定open_basedir 加入 /dev/

當兩個script同時去讀寫device時,output會發生互相影響的錯誤:
解法: 使用flock()
在PhpSerial.php
$this->_dHandle = @fopen($this->_device, $mode); #在後面加入:
if (flock($this->_dHandle, LOCK_EX|LOCK_NB)) {
    $this->_lock = true;
    print "\nNo problems, I got the lock, now I'm going to sit on it.";
} else {
    $this->_lock = false;
    print "\nDidn't quite get the lock. Quitting now. Good night.";
}
把sendMessage改成:
if($this->_lock){
    $this->_buffer .= $str;

    if ($this->autoflush === true) $this->flush();

    usleep((int) ($waitForReply * 1000000));
}
Class新增屬性:
var $_lock = false;

將"00" 轉成hex code "\x00":
pack('H*',"00"); // hex code

使用C存取:
read.c:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>  
#include <string.h>

int main() {
        unsigned char byte;
        char ctl[] = "\x01\x01\xCA\x60\x00\x03\xA9";
        //  for(int i=0;i<strlen(ctl);i++)
        //      printf("%x",ctl[i]);
        int fd = open("/dev/ttyUSB0", O_RDWR);
        printf("fd=%d\n",fd);
        write(fd, ctl, 8);
        puts("Writed");
        int i;
        for(i =0;i<10;i++){
            int size = (int)read(fd, &byte, 1);
            if(size<1)break;
            printf("Read %d bytes hex=%X c=%c\n",(int)size,byte,byte);
        }
    return 0;
}

# make read
# ./read
output:
fd=3
Writed
Read 1 bytes hex=1 c=
Read 1 bytes hex=1 c=
Read 1 bytes hex=CA c=�
Read 1 bytes hex=60 c=`
Read 1 bytes hex=0 c=
Read 1 bytes hex=3 c=
Read 1 bytes hex=81 c=�
Read 1 bytes hex=0 c=
Read 1 bytes hex=2 c=
Read 1 bytes hex=2A c=*

網頁無法執行PhpSerial,但能在console執行
ex.
# php dummy.php
0102ca600003aa

http://domain/dummy.php
Fatal error: No stty availible, unable to run.
(把PhpSerial _exec()裡面的$out印出來的錯誤是:
Array ( [0] => [1] => stty: standard input: Inappropriate ioctl for device ) )
方法1. 指定stty絕對位置
結果:失敗,/bin/stty 和 /usr/bin/stty都出現一樣錯誤
方法2.  加一下 system(' ls /dev/ttyUSB0  -l');
PHP:
system('which stty');
echo "<br />";
system(' ls /dev/ttyUSB0  -l');
output:
/usr/sbin/stty
crw-rw---- 1 http http 188, 0 Oct 20 11:07 /dev/ttyUSB0
看起來正常
方法3. 修改PhpSerial.php
在PhpSerial()中
- if ($this->_exec("stty") === 0) {
+if ($this->_exec("stty -F /dev/ttyUSB0") === 0) { #將這段拿掉或指定-F /dev/ttyUSB0
    register_shutdown_function(array($this, "deviceClose"));
} else {
    trigger_error(
        "No stty availible, unable to run.",
        E_USER_ERROR
    );
}
結論:apache找不到stty設定(http@xxx $ stty ,出來是空白的),要指定設備才行
相關問題:
http://forum.arduino.cc/index.php?topic=38818.0;wap2
added the apache user (www-data) to the dialout group and it now works OK!! (但是我測試機是Arch Linux,沒有dialout,無法驗證。)

使用apache(httpd)執行command line:
修改/etc/passwd
http:x:33:33:http:/srv/http:/bin/false => http:x:33:33:http:/srv/http:/bin/bash
$ sudo su http #就能切換成http執行指令了

把http使用者增加到root群組:
# gpasswd -a http root
Adding user http to group root



2014年10月9日 星期四

long polling時,網頁開完後重新整理不出來

在使用 https://github.com/panique/php-long-polling 實做long polling遇到的狀況:
將client/index.html 複製成 client.php並開啟
http://your_domain.com/php-long-polling/client/client.php (注意:client/client.js 的 ajax網址要設成你的domain或 /php-long-polling/server/server.php )
第一次client.php開得出來,但按ctrl+r重新整理頁面後,網頁會轉不出來 ( client/index.html 不會有此問題 )

Blue解法:
通常這樣狀況 表示 你程式 找不到資料 又沒有寫 timeout 變成連線卡住,從前端處理,固定時間取消掉ajax request後重送 ( 不採用 )

但放到我朋友的主機上面卻沒這問題,比較兩個頁面的http標頭發現有以下的差異:
Cookie PHPSESSID=rc65gi80fdvpgoakur3quj04l3

差異:
發現我主機的php.ini設定:
session.auto_start = 1 => 要把他改成零 session.auto_start = 0,重啟apache就可以重刷了

另外的解法: 假如系統php.ini不能更動,且session.auto_start = 1時,把php.ini的值設到.htaccess
http://davidwalsh.name/php-values-htaccess
編輯網站根目錄的.htaccess,加入這行:
php_value  session.auto_start  0
#格式是:  php_value setting_name setting_value

原因:
http://stackoverflow.com/questions/13213396/no-reply-when-using-flush-session-cookies-and-long-execution-time
大意是說是說 因為第一個session還開著(開300秒),因為不確定之後session的變數會不會改變,所以要等第一個結束才能叫第二個,使用session_write_close()後之後session的變數就會變的可以存取。通常使用session_write_close()在長時間執行的script上。
所以在long polling 的server.php那邊要加 session_write_close()  就可以了.

另外:
使用session_commit() 也可以
http://blog.chacuo.net/168.html

檢查:
root@localhost:/var/lib/php5# ls
modules                          sess_tbdko1s1d8l8anhsjfurnq7ob4 sess_es3qrrebadlckj80gsjnv5hh27  sess_tbdko1s1d8l8anhsjfurnq7ob4
sess_14qeiqp5n44ba5nvdr4jdrfcp4
root@localhost:/var/lib/php5# lsof sess_tbdko1s1d8l8anhsjfurnq7ob4
COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF  NODE NAME
apache2 30364 www-data   16uW  REG  202,0        0 43458 sess_tbdko1s1d8l8anhsjfurnq7ob4
apache2 30367 www-data   16u   REG  202,0        0 43458 sess_tbdko1s1d8l8anhsjfurnq7ob4
apache2 30368 www-data   16u   REG  202,0        0 43458 sess_tbdko1s1d8l8anhsjfurnq7ob4
apache2 30375 www-data   16u   REG  202,0        0 43458 sess_tbdko1s1d8l8anhsjfurnq7ob4
apache2 30377 www-data   16u   REG  202,0        0 43458 sess_tbdko1s1d8l8anhsjfurnq7ob4
apache2 30378 www-data   16u   REG  202,0        0 43458 sess_tbdko1s1d8l8anhsjfurnq7ob4
apache2 30382 www-data   16u   REG  202,0        0 43458 sess_tbdko1s1d8l8anhsjfurnq7ob4
測試後 跟推測一樣,每執行一次就被卡住一次process