2014年12月24日 星期三

Arch 開機自動登錄開啟全屏firefox

系統:Arch Linux
桌面:enlightenment
註:enlightenment 關閉程式熱鍵是ctrl+alt+x 不是alt+f4

需求:
開機自動登錄,然後開啟全屏firefox

開機自動登錄(無須輸入密碼):
https://wiki.archlinux.org/index.php/SLiM_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)
修改 /etc/slim.conf:
# default_user simone => default_user username
取消该行的注释,然后将“simone”改为需要自动登录的用户名。
# auto_login no
取消该行的注释,然后将‘no’改为‘yes’
自动登录功能就被启用了。

登錄後自動開啟firefox:
$ cp /etc/skel/.xinitrc ~
編輯.xinitrc:
firefox -new-window localhost/welcome/exhibition(你要打開的網址) &
exec enlightenment_start
這邊似乎可以用 openbox做 https://wiki.archlinux.org/index.php/openbox ,沒試過
https://wiki.archlinux.org/index.php/Xinitrc
注意:
確保取消註釋只有一行exec,因為這將是.xinitrc script的最後一個運行命令; 以下所有命令只會被忽略。
如果只執行exec firefox ,不登錄桌面。會有解析度問題

Firefox打開全屏:
安裝 Real Kiosk 套件 https://addons.mozilla.org/zh-tw/firefox/addon/r-kiosk/

2014年12月19日 星期五

LINUX 插入USB執行某個script

系統:
Arch linux

需求:
重開機後/dev/ttyUSB[0-9] 的設定會跑掉,我的板子頻率要跑9600 8n1 才能溝通

手動設定指令:
# stty -F /dev/ttyUSB1 raw speed 9600 -crtscts cs8 -parenb -cstopb

重開機自動設定:
原本在這篇 arch 開機執行程式 想要用rc.local做,但是stty在rc.local我一直無法設定,印出來的內容是空的,所以改從udev的rules下手
新增檔案 /etc/udev/rules.d/usb.rules ,內容為:
ACTION=="add", KERNEL=="ttyUSB*", RUN+="/usr/bin/bash /your_script_path/set_stty.sh"
功用為:
在/dev/ttyUSBx插入時,會跑set_stty.sh這個程式。

根據 Arch 官方文件 https://wiki.archlinux.org/index.php/udev ,必須命名 .rules 的檔案,而/etc/udev/rules.d/ 和 /usr/lib/udev/rules.d/ (由其他packages自動產生的rules)有同樣名字的rules時,以 /etc/udev/ 下的優先

set_stty.sh內容:
#!/bin/sh
LOGFILE=/tmp/set_stty.log
exec 3>> $LOGFILE && exec >& 3 && exec 2>&1
echo $SEQNUM $SUBSYSTEM $ACTION $DEVNAME
if [ "$SUBSYSTEM" = "tty" -a "$ACTION" = "add" ]
then
    echo ""
    echo "=============================="
    date "+%G-%m-%dT%H:%M:%S %z"
    echo "$SUBSYSTEM $ACTION"
    stty -F $DEVNAME raw speed 9600 -crtscts cs8 -parenb -cstopb
fi
exit $?  # 結束這個 script 並把當時的執行結果傳回(return)給呼叫這個 script 的任何程式。想要省略掉的話,也沒什麼問題,然而我們必須平時就養成撰寫程式的正確習慣,在 UNIX 系統上,任何程式、函式都必須要有傳回值,就算是不知道有誰會去用它。我們不希望看到那一天,當有人突然去用它的時候,就必須面對噩運。這看似小事一件,然而缺乏持續性對小節的正確習慣或態度。 by 翔

$SEQNUM $SUBSYSTEM $ACTION $DEVNAME 這些是uevents ,可以幫助我們在script裡面判斷
例如插入一次接板子的usb,在log中可以看到set_stty.sh跑了兩次
ex.
echo $SEQNUM $SUBSYSTEM $ACTION $DEVNAME 這行印到/tmp/set_stty.log的內容:
2355 usb-serial add "(空)"
2356 tty add /dev/ttyUSB1

實測:
重開機後,呼叫串口的web api ,有正常返回值

參考資料:
http://king70327.blogspot.jp/2011/12/linux-centosusbscript.html

javascript去檢測(類似ping)區網有無這個ip

http://stackoverflow.com/questions/4282151/is-it-possible-to-ping-a-server-from-javascript
修改後:
ping = function(ip, callback) {
 if (!this.inUse) {
  this.status = 'unchecked';
  this.inUse = true;
  this.callback = callback;
  this.ip = ip;
  var _that = this;
  this.img = new Image();
  this.img.onload = function() {
   _that.inUse = false;
   _that.callback('responded');

  };
  this.img.onerror = function(e) {
   if (_that.inUse) {
    _that.inUse = false;
    _that.callback('responded', e);
   }

  };
  this.start = new Date().getTime();
  this.img.src = "http://" + ip;
  this.timer = setTimeout(function() {
   if (_that.inUse) {
    _that.inUse = false;
    _that.callback('timeout');
   }
  }, 1500);
 }
};

//使用:
new ping('192.168.0.88', function(status, e) {
 console.log(status);
});

有這個ip,在控制台會顯示 responded,沒有則會顯示timeout

PHP CLI筆記

$ php -m #列出所有modules
$ php -r "code" #類似perl -e 執行代碼
$ php -n # 不使用php.ini設定,用前面加time 可以看跑多快

arch 開機執行程式

前言:
每次重開機後,主機與serial port的stty設定都會跑掉,所以想在開機時去設定(重新插拔USB接口設定不會跑掉)

https://raymii.org/s/tutorials/rc.local_support_on_Arch_Linux_and_systemd.html
1. 編輯 /etc/rc.local (如果沒有就自己建一個)
2. 把 /etc/rc.local 權限設成 755,注意:因為是bash,最前面要寫 #!/usr/bin/bash,例:
#!/usr/bin/bash
touch /tmp/1
stty -F /dev/ttyUSB1 raw speed 9600 -crtscts cs8 -parenb -cstopb

3. 編輯 /usr/lib/systemd/system/rc-local.service:
[Unit]
Description=/etc/rc.local compatibility

[Service]
Type=oneshot
ExecStart=/etc/rc.local
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target

4. 執行 下面這個指令,他會產生一個symlink 到 /etc/systemd/system/multi-user.target.wants/ 下面
# systemctl enable rc-local.service
Created symlink from /etc/systemd/system/multi-user.target.wants/rc-local.service to /usr/lib/systemd/system/rc-local.service.

5. 手動檢測:
# systemctl start rc-local.service

實測結果:
重開機後
touch /tmp/1 會正常執行(執行身份是root),但stty 把他印到/tmp/1 (  stty >> /tmp/1 )則是一片空白,這可能要看開機message... 這挺複雜的....
這位網友遇到同樣的問題: http://www.gobsd.org/viewtopic.php?f=4&t=3239
最後暫時用每次呼叫web api時都設定stty,這會讓使用者每次多等0.3s
之後可以嘗試用cronjob看看

參考資料:
http://stackoverflow.com/questions/18903512/set-up-serial-on-start-up-raspberry-pi # Raspberry Pi 在rc.local設定stty的答案被採納

2014年12月17日 星期三

減少PHP-Serial的I/O等待時間

繼前篇 用php透過usb和rs232串連控制MPU電路板
dummy.php:
echo "\ntime 0:".round(microtime(true) * 1000);
include 'PhpSerial.php';

echo "\ntime 1:".round(microtime(true) * 1000);
`stty -F /dev/ttyUSB0 raw speed 9600 -crtscts cs8 -parenb -cstopb`;
echo "\ntime 2:".round(microtime(true) * 1000);
// Let's start the class
$serial = new PhpSerial();
echo "\ntime 3:".round(microtime(true) * 1000);
// 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");
echo "\ntime 4:".round(microtime(true) * 1000);
// We can change the baud rate, parity, length, stop bits, flow control
$serial->confBaudRate(9600);
echo "\ntime 5:".round(microtime(true) * 1000);
$serial->confParity("none");
echo "\ntime 6:".round(microtime(true) * 1000);
$serial->confCharacterLength(8);
echo "\ntime 7:".round(microtime(true) * 1000);
$serial->confStopBits(1);
echo "\ntime 8:".round(microtime(true) * 1000);
$serial->confFlowControl("none");
echo "\ntime 9:".round(microtime(true) * 1000);
// Then we need to open it
$serial->deviceOpen();

// To write into
echo "\ntime A:".round(microtime(true) * 1000);
$serial->sendMessage("O(00,02,1)E");

測試:
$ time sudo php -n dummy.php ( -n 是不走php.ini的設定,因為我之前browscap.ini設定太肥會delay)

time 0:1418786501622
time 1:1418786501623
time 2:1418786501890
time 3:1418786501890
time 4:1418786501890
time 5:1418786502156
time 6:1418786502423
time 7:1418786502690
time 8:1418786502956
time 9:1418786503223
time A:1418786503223
time B:1418786504957 # 後面sleep了一秒,讓燈關掉
real    0m3.373s
user    0m0.007s
sys     0m0.003s

在 PHP-Serial API的底層,每叫一次function ( new PhpSerial()、$serial->deviceSet、$serial->confBaudRate )都會用stty去檢查一次,每次stty檢查都會在IO上delay 0.3秒,所以我們現在假設你的裝置都連結配置好,將多餘的設定和stty檢查拿掉

更改PhpSerial.php:
+++ b/PhpSerial.php
@@ -32,22 +32,27 @@ class PhpSerial
      * @var bool
      */
     public $autoFlush = true;
+    public $_check_stty = true;
 
     /**
      * Constructor. Perform some checks about the OS and setserial
      *
      * @return PhpSerial
      */
-    public function PhpSerial()
+    public function PhpSerial($param)
     {
+        $this->_check_stty = (isset($param['check_stty']))? $param['check_stty'] : $this->_check
         setlocale(LC_ALL, "en_US");
 
         $sysName = php_uname();
         if (substr($sysName, 0, 5) === "Linux") {
             $this->_os = "linux";
+            if (!$this->_check_stty) {
+                register_shutdown_function(array($this, "deviceClose"));
+                return false;
+            }
@@ -86,9 +91,12 @@ class PhpSerial
      */
     public function deviceSet($device)
     {
+        if (!$this->_check_stty) {
+            $this->_device = $device;
+            $this->_dState = SERIAL_DEVICE_SET;
+            return false;
+        }

修改dummy.php
echo "\ntime 0:".round(microtime(true) * 1000);
include 'PhpSerial.php';

echo "\ntime 1:".round(microtime(true) * 1000);
echo "\ntime 2:".round(microtime(true) * 1000);
$serial = new PhpSerial(array('check_stty'=> false));
echo "\ntime 3:".round(microtime(true) * 1000);
$serial->deviceSet("/dev/ttyUSB0");
echo "\ntime 4:".round(microtime(true) * 1000);
$serial->deviceOpen();

echo "\ntime A:".round(microtime(true) * 1000);
$serial->sendMessage("O(00,02,1)E");

測試:
$ time sudo php -n dummy.php

time 0:1418787683165
time 1:1418787683165
time 2:1418787683165
time 3:1418787683165
time 4:1418787683165
time A:1418787683166
time B:1418787684896 # 後面sleep了一秒,讓燈關掉
real    0m1.774s
user    0m0.000s
sys     0m0.007s



2014年12月8日 星期一

列出sublime裝了哪些套件

在Packages Controll中
ctrl+shift+p 輸入list packages

在設定檔中
Preferences -> Browse Packages -> 搜尋檔案 Package Control.sublime-settings
用sublime打開
(Win 7 免安裝版)
C:\Users\bear\Desktop\Sublime Text 2.0.2\Data\Packages\User\Package Control.sublime-settings
我Win7的sublime裝的套件:
{
"installed_packages":
[
"AngularJS",
"CSS Extended Completions",
"CSS Snippets",
"Emmet",
"HTML Snippets",
"HTML-CSS-JS Prettify",
"HTMLAttributes",
"HTMLEntity Snippets",
"jQuery",
"ModernPerl",
"Package Control",
"SFTP"
]
}

Arch:
{
"installed_packages":
[
"AngularJS",
"CakePHP (Native)",
"Codecs33",
"CodeIgniter Snippets",
"CodeIgniter Utilities",
"ConvertToUTF8",
"DocBlockr",
"Emmet",
"GoSublime",
"Handlebars",
"HTML Snippets",
"HTML-CSS-JS Prettify",
"HTMLAttributes",
"jQuery",
"Seti_UI",
"SFTP",
"SideBarEnhancements",
"SublimeCodeIntel",
"Tag",
"Text Pastry",
"TrailingSpaces"
]
}

Debian:
{
    "installed_packages":
    [
        "AngularJS",
        "CakePHP (Native)",
        "CodeIgniter Snippets",
        "ConvertToUTF8",
        "CSS Completions",
        "CSS3",
        "DocBlockr",
        "Emmet",
        "Handlebars",
        "HTML Snippets",
        "HTML-CSS-JS Prettify",
        "HTML5",
        "HTMLAttributes",
        "InputHelper",
        "JavaScript & NodeJS Snippets",
        "jQuery",
        "jQuery Mobile Snippets",
        "jQueryDocs",
        "PHP Completions Kit",
        "PhpDoc",
        "Sass",
        "SFTP",
        "SideBarEnhancements",
        "SublimeLinter"
    ]
}

Windows 7 Sublime 3
"installed_packages":
[
    "Alignment",
    "AngularJS",
    "CodeFormatter",
    "ConvertToUTF8",
    "DocBlockr",
    "Emmet",
    "Handlebars",
    "HTML Snippets",
    "HTML-CSS-JS Prettify",
    "HTMLAttributes",
    "JavaScript Snippets",
    "jQuery",
    "JsFormat",
    "JSLint",
    "Package Control",
    "phpfmt",
    "SFTP",
    "SideBarEnhancements",
    "Smarty",
    "SqlBeautifier",
    "SublimeCodeIntel",
    "Text Pastry",
    "TrailingSpaces",
    "Xdebug Client"
]

ThinkPad 20170722
{
"bootstrapped": true,
"in_process_packages":
[
],
"installed_packages":
[
"Alignment",
"CodeFormatter",
"ConvertToUTF8",
"DocBlockr",
"Emmet",
"HTML Snippets",
"HTML Underscore Syntax",
"HTML-CSS-JS Prettify",
"HTMLAttributes",
"JavaScript Snippets",
"jQuery",
"JsFormat",
  "Minifier",
"Package Control",
"SFTP",
"SideBarEnhancements",
"SqlBeautifier",
"SublimeCodeIntel",
"Text Pastry",
"TrailingSpaces",
"Underscorejs snippets",
"Xdebug Client"
]
}
跳板機 20190630 - latest  之後轉phpstorm
{
"bootstrapped": true,
"in_process_packages":
[
],
"installed_packages":
[
"Alignment",
"Blade Snippets",
"Case Conversion",
"CodeFormatter",
"ConvertToUTF8",
"Diffy",
"DocBlockr",
"Emmet",
"HTML Snippets",
"HTML Underscore Syntax",
"HTML-CSS-JS Prettify",
"HTMLAttributes",
"JavaScript Snippets",
"jQuery",
"JsFormat",
"Laravel 5 Snippets",
"Laravel Blade Highlighter",
"Laravel Migrations Snippets",
"Minifier",
"Package Control",
"PHP Completions Kit",
"SFTP",
"SideBarEnhancements",
"SqlBeautifier",
"SublimeCodeIntel",
"Text Pastry",
"TrailingSpaces",
"Underscorejs snippets"
]
}

20220316 ThinkPad
{
"bootstrapped": true,
"in_process_packages":
[
],
"installed_packages":
[
"Alignment",
"Case Conversion",
"CodeFormatter",
"ConvertToUTF8",
"Diffy",
"Dockerfile Syntax Highlighting",
"Generic Config",
"Hosts",
"jQuery",
"Log Highlight",
"MoveTab",
"nginx",
"Package Control",
"SideBarEnhancements",
"SqlBeautifier",
"SublimeCodeIntel",
"Text Pastry",
"TrailingSpaces",
"Vue Syntax Highlight",
],
}



ThinkPad 20170722 )Key Bindings: 
[
{ "keys": ["ctrl+k", "s"], "command": "set_mark" },
// XDebug
{ "keys": ["ctrl+k", "alt+s"], "command": "xdebug_watch" },
{ "keys": ["ctrl+k", "alt+c"], "command": "xdebug_watch", "args": {"clear": true} },
{ "keys": ["ctrl+k", "alt+e"], "command": "xdebug_evaluate" },
{ "keys": ["ctrl+k", "alt+1"], "command": "xdebug_clear_all_breakpoints" },
{ "keys": ["ctrl+k", "alt+2"], "command": "xdebug_conditional_breakpoint" },
{ "keys": ["ctrl+k", "alt+3"], "command": "xdebug_session_start", "args": {"launch_browser": true} },
]

ThinkPad 20170722 )Settings:
{
"font_size": 12,
"ignored_packages":
[
"Vintage"
],
"word_wrap": false
}

( NII-48 20190528 ) Preferences.sublime-settings
{
    "color_scheme": "Monokai.sublime-color-scheme",
    "detect_indentation": false,
    "font_face": "Consolas",
    "font_size": 12,
    "ignored_packages":
    [
        "Vintage"
    ],
    "tab_size": 4,
    "theme": "Default.sublime-theme",
    "translate_tabs_to_spaces": true,
    "update_check": false,
    "word_wrap": false,
    "default_line_ending": "unix"  // 避免CRLF錯誤
}

20200411 新增installed_packages: Dockerfile Syntax Highlighting
20220316 新增installed_packages: MoveTab
20220828 新增:Compare Side-By-Side  。棄用:Diffy


參考資料:
http://stackoverflow.com/questions/16412678/exporting-sublime-text-configuration-and-installed-packages

2014年12月4日 星期四

JMDM-COM10MR繼電器使用心得

上淘寶買了 10路繼電器輸出模塊 負載220V25A 串口通訊 串口控制器(JMDM-COM10MR,深圳市精敏数字机器有限公司)
内含:
JMDM-COM10MR 繼電器
12V電源適配器(可選24V) - 紅接1 黑接3
RS232 傳輸線 ( 要接USB需另買RS232轉USB傳輸線 )

共有10路輸出:
背面
側面(紅色數字為第幾號開關)
側面 (紅色數字為第幾號開關)
Linux控制方式:
事前設定:( /dev/ttyUSB0非唯一,依你繼電器插入後linux所抓到的device,可能是/dev/ttyUSBx )
# stty -F /dev/ttyUSB0 raw speed 9600 -crtscts cs8 -parenb -cstopb
# chmod 777 /dev/ttyUSB0
接收:
# cat /dev/ttyUSB0

查詢:
# echo -en 'O(00,40,1)E' > /dev/ttyUSB0 # 命令控制器返回第 1 路~第 10 路数据
OA(00,0000000000)E  # cat /dev/ttyUSB0收到的結果

控制:控制成功繼電器會發出開關的聲音,可用萬用表測有沒有迴路,中間和左邊兩個有通為0關閉,中間和右邊兩個有通為1打開)
# echo -en 'O(00,00,1)E' > /dev/ttyUSB0 # 所有继电器输出全開
OA(00,1111111111)E  # 用'O(00,40,1)E'查詢,在cat /dev/ttyUSB0收到的結果
# echo -en 'O(00,00,0)E' > /dev/ttyUSB0 # 所有继电器输出全關
OA(00,0000000000)E  # 用'O(00,40,1)E'查詢,在cat /dev/ttyUSB0收到的結果
# echo -en 'O(00,01,1)E' > /dev/ttyUSB0 # 第 1路继电器输出"开启"
OA(00,1000000000)E  # 用'O(00,40,1)E'查詢,在cat /dev/ttyUSB0收到的結果
# echo -en 'O(00,01,0)E' > /dev/ttyUSB0 # 第 1路继电器输出"關閉"
OA(00,0000000000)E  # 用'O(00,40,1)E'查詢,在cat /dev/ttyUSB0收到的結果
# echo -en 'O(00,02,1)E' > /dev/ttyUSB0 # 第 2路继电器输出"开启"
OA(00,0100000000)E  # 用'O(00,40,1)E'查詢,在cat /dev/ttyUSB0收到的結果
# echo -en 'O(00,02,0)E' > /dev/ttyUSB0 # 第 2路继电器输出"關閉"
OA(00,0100000000)E  # 用'O(00,40,1)E'查詢,在cat /dev/ttyUSB0收到的結果

注意:
1. 勿傳送hex,傳送的是字符(ASCII)
2. 淘宝和pdf文档里 关闭指令:O ( 00,N,0)E 开启指令:O ( 00,N,1)E
O ( 00,N,1)E => "(" 前後多了空白 所以没反应... 要把空白去掉,继电器吃到错误的代码不会报错回来

同時先關再開某個output(同時送兩個指令)到繼電器:
# echo -en 'O(00,00,0)E O(00,01,1)E' > /dev/ttyUSB1 #中間以一個空格隔開,就能同時關閉所有電燈再開某個電燈,而不會為了等serial port而慢一秒亮燈。

Windows(Win7)控制方式:
賣家會提供windows的執行檔(免安裝和安裝板)
安裝板裝好後要另外把他們提供的dll檔放到該目錄下
更新Win 7 的Prolific USB-to-Serial Comm Port 的驅動程式(電腦需連上網路)
( 開始 -> 設備和打印機 -> "未指定"中的Prolific USB-to-Serial Comm Port 右鍵 -> 屬性 -> 硬件 -> 屬性 -> 驅動程序 -> 更新驅動程序 )
設定COM port
開始 -> 設備和打印機 -> "未指定"中的Prolific USB-to-Serial Comm Port 右鍵 -> 屬性 -> 硬件 -> 屬性 -> 端口設置 -> 高級 -> COM端口號選"COM2"
廠商提供的應用程式 通信串口選擇:串口一 ( 注意必須在打開程式時預設選擇串口一,不然報錯後依然跑不動,串口設錯請設定串口後關閉程式重開,勿點擊按鈕讓程式自動關閉 )



2014年12月1日 星期一

linux .d資料夾的意思

linux中常看到許多.d的資料夾,如
/etc/php/conf.d/
/etc/init.d/

Generally when you see that *.d convention, it means "this is a directory holding a bunch of configuration fragments which will be merged together into configuration for some service."
翻譯:一般來說,當你看到*.d的常規,它的意思是"這是一個目錄拿著一群將被合併為設定一些服務設定的片段。"

例如,
init.d 中存放的就是一系列系统服务的管理(启动与停止)脚本。
当系统升级有新的 *.conf 时,只需简单的替换原来的,因为用户和其他程序添加的配置都以单独文件的形式存放在 .d 文件夹中,不会受到影响。


參考資料:
http://unix.stackexchange.com/questions/4029/what-does-the-d-stand-for-in-directory-names
http://zhidao.baidu.com/question/297983472.html

2014年11月27日 星期四

PHP 偵測瀏覽器是否為手機

原理:

使用$_SERVER['HTTP_USER_AGENT']

前言:

忘了從哪邊看到的,HTTP Header的User-Agent是可以更改的,所以最好是在前端判斷(?)。不過我想用php來判斷應該可以應付大部分情況,而且今天都在遮疼php的解決方案,就把他記錄下來。

一、使用get_browser()

http://php.net/get_browser
get_browser()預設不能直接使用,須先做設定
安裝:
1. 到 http://browscap.org/ 下載PHP版本的full_php_browscap.ini
2. 然後設定php.ini 裡面[browscap]的
browscap = /your_browscap_ini_path/full_php_browscap.ini
3. 重啟apache
用法:
$browser = get_browser(null, true);
echo "is mobile:".$browser['ismobiledevice'];
報錯:
PHP:  syntax error, unexpected $end, expecting ']' in /etc/php/conf.d/full_php_browscap.ini on line 78
解法:
$ sed 's/;/\\\;/g' original_browscap.ini > browscap.ini
如果original_browscap.ini放在/etc/php/conf.d/ 下記得把original_browscap.ini移除,不然仍會報錯

因為使用browscap.ini ( 23MB ),刷頁面有呼叫get_browser()時會多800ms(不呼叫沒事),又ini_set無法在script時去設定browscap.ini
http://stackoverflow.com/questions/2545910/php-using-browscap-ini-on-shared-host-ini-set-failing
'browscap' is changeable only in the system php.ini and/or httpd.conf. You cannot set it at the script level.
且在cli時如果不加 -n 也會延遲,所以不建議使用這方法

參考資料:
https://github.com/browscap/browscap/issues/119

二、使用Mobile-Detect類

https://github.com/serbanghita/Mobile-Detect
require "Mobile-Detect/Mobile_Detect.php";
$detect = new Mobile_Detect;
echo "\$detect->isMobile():".$detect->isMobile();

可以在php.ini裡面設定include_path去呼叫該類別。或是把該類別放到/usr/share/pear下
我的php.ini設定:
include_path = ".:/usr/share/pear"
更多Mobile-Detect的使用方法:
https://github.com/serbanghita/Mobile-Detect/wiki/Code-examples

三、使用phpbrowscap類別

https://github.com/GaretJax/phpbrowscap
安裝方法使用composer:
https://github.com/GaretJax/phpbrowscap/wiki/QuickStart
1. 在專案根目錄新增composer.json
{
    "require": {
        "garetjax/phpbrowscap": "~2.0"
    }
}
2.
$ wget http://getcomposer.org/composer.phar
$ php composer.phar install
如果這步有報錯
PHP Fatal error:  Class 'Phar' not found in /xxx/composer.phar on line xx
請將php.ini的
extension=phar.so 註解拿掉
安裝完成後目錄裡面會多出一個vendor的資料夾
新增一個test.php檔案:
<?php
require 'vendor/autoload.php'; //要用composer的類必須加入這行
use phpbrowscap\Browscap;
$bc = new Browscap('path/to/the/cache/dir'); //
$current_browser = $bc->getBrowser();
echo '<pre>'; // some formatting issues ;)
print_r($current_browser);
echo '</pre>';

因為刷http://localhost/test.php會刷很久刷不出來,所以放棄用第三個方式做

在FB的討論:
https://www.facebook.com/groups/199493136812961/permalink/713514665410803/
其他方法:
http://detectmobilebrowsers.com/mobile
http://www.useragentstring.com/pages/api.php #不建議使用,因為要去呼叫api
https://github.com/ventoviro/windwalker-environment #未測試
結論:
行動裝置太多樣了 幾個大牌子能正確偵測到已經夠了

2014年11月24日 星期一

linux安裝megatools和megacmd

在linux上能用指令下載mega檔案的工具有:
megatools
megacmd

系統:Debian 7

安裝megacmd

安裝megacmd難度比較低
1. 在github上下載megacmd-master.zip後解壓縮
2. 在解壓縮的資料夾下
$ make
$ cp megacmd /usr/local/bin
即安裝完成

使用megacmd
下載(需開一個帳號,然後將你要下載的檔案import到你的帳號裡面再下載,沒看到可以直接下載https連結的方法)
$ megacmd -force get mega:/testing/megacmd /tmp/
報錯:
ERROR: Downloading mega:/xxx.jpg failed (Object (typically, node or user) not found)
用wget檢查:
$ wget https://mega.xxx/
錯誤: “mega.xxx” 的证书不可信。
錯誤: “mega.xxx” 的证书颁发者未知。
... 無解,只好改用megatools

安裝megatools

方法一
把source.list改成unstable
deb http://ftp.cn.debian.org/debian unstable main contrib non-free
然後用apt-get安裝。但是我實在不想讓我的debian炸掉... 所以沒用這方法安裝
方法二
安裝所需的套件
# aptitude install libglib2.0-dev libcurl4-openssl-dev libssl-dev
不然./configure時會報錯
...
configure: error: Package requirements (gio-2.0 >= 2.32.0 libcurl openssl) were not met:
...
下載megatools的linux原始碼Archive(megatools-1.9.93.tar.gz),並解壓縮後到該資料夾下
$ ./configure
$ make
# make install
安裝完後就能使用megadl等相關mega指令了

下載
$ megadl 'https://mega.co.nz/#!xxx...'
報錯:
megadl: error while loading shared libraries: libmega.so.0: cannot open shared object file: No such file or directory
需要使用root執行一次ldconfig後才能正常下載
# ldconfig


參考資料:
http://blog.hbautista.com/linux/megatools-en-debian-jessie/ (西班牙文blog...請搭配google翻譯使用)

2014年11月23日 星期日

linux桌面安裝dropbox

OS: Debian 7

新申請的dropbox帳號後導會到安裝頁面:https://www.dropbox.com/install?os=lnx

推薦使用指令安裝,下載的deb檔我裝失敗(自動裝成64位元的,啟動不了)

請注意你系統是32bits還是64bits

官網寫的 cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86" | tar xzf - 我執行會報錯,所以我把他分段執行...
$ cd ~
$ wget -O dropbox.tar.gz "https://www.dropbox.com/download?plat=lnx.x86"
$ tar zxvf dropbox.tar.gz

下載 CLI 指令碼(dropbox.py) 放到/usr/local/bin/下,記得把權限改成777

啟動dropbox(在有GFW干擾情況下,記得先設定proxychains)
$ proxychains ~/.dropbox-dist/dropboxd
查dropbox狀態
$ dropbox.py status



git同時push到兩個repo

情境:
以github和gitlab為例,假設他們各自有不同的內容要整合在一起

模擬環境
分別在github和gitlab建立新專案(ex 專案名稱mp),gitlab為master的pull
master 更新檔案 pull從gitlab
master 上傳檔案push到 gitlab和github(github純備份用,因為gitlab上是和其他人共同開發)

(分別在github和gitlab的mp.git新增不同的內容,我們之後要整合在一起)

拉下gitlab檔案
$ git clone git@xxx.tw:bear/mp.git gitlab_mp #用ssh要在gitlab設定keys,用https不用,但要輸入gitlab的帳號密碼
新增remote
$ git remote add github git@github.com:bear/mp.git
更新remote(remote branch會多remotes/github/master,用git branch -a 查詢)
$ git remote update

更新特定的remote

$ git remote update github

(這邊假設github和gitlab裡面各自有不同內容要整合,如果備份的repo為新開的repo可以略過a.b.c這三步)
a. 開github的branch
$ git checkout -b github remotes/github/master
b. 切回master
$ git checkout master
c. 將github整合進gitlab
$ git rebase github


git pull(做這步之後才能push,中間有conflict就手動改)
$ git pull #這步會多一個git merge的 commit
設定origin remote的url
$ git remote set-url origin --push --add git@xxx.tw:bear/mp2.git
$ git remote set-url origin --push --add git@github.com:bear/mp.git
檢查remote 會push到哪裡
$ git remote -v
github  git@github.com:bear/mp.git (fetch)
github  git@github.com:bear/mp.git (push)
origin  git@xxx.tw:bear/mp2.git (fetch)  # 因為git push預設是git push origin master,所以master會抓自架gitlab的repo
origin  git@xxx.tw:bear/mp2.git (push) # master會push到 gitlab
origin  git@github.com:bear/mp.git (push) # master也會push到 github
最後git push就能同時推到兩個不同的repo去了
$ git push

刷新gitlab和github頁面檢查

要更改預設master pull的repo
修改 .git/config 的
[remote "origin"]
    url = git@xxx.tw:bear/mp2.git #改成你要pull的repo

參考資料:
http://stackoverflow.com/questions/849308/pull-push-from-multiple-remote-locations 採用Malvineous的答案

關於刪除branch
移除gitlab上多餘的branch
$ git push origin --delete alt(多餘的branch名字)
本地的branch要分開刪,沒辦法一起刪
$ git branch -D alt
把本地remote的branch( git branch -a )也刪
# git branch --delete --remotes origin/alt

push新的branch到remote repository
$ git push origin exhibition:exhibition3
這樣遠端倉庫就會新建exhibition3分支,內容是本地端exhibition的內容,另外origin是你remote的名字

將遠端master branch拉到本地端exhibition branch
$ git pull origin master:exhibition
語法:
git pull <remote_name> <remote_branch>:<local_branch>

將本地端exhibition branch推到遠端master branch
$ git push origin exhibition:master
語法:
git push <remote_name> <local_branch>:<remote_branch>







2014年11月19日 星期三

debian gnome桌面顯示捷徑

系統:Debian 7 (wheezy)
桌面:gnome

開啟Advanced Settings
$ gnome-tweak-tool

左上角"應用程式" -> 系統工具 -> 偏好設定 -> 進階設定值

"桌面"分頁 -> 打開 "Have file manager handle the desktop"

如果還是沒有出現,打開"偏好的應用程式"GUI(左上角"應用程式"選單內我找不到,只能用指令開啟)
$ exo-preferred-applications
"公用程式"分頁 -> 檔案管理員 -> 選"Nautilus"

注意:
sublime的Preferences -> Browse Packages 預設檔案管理員要選"Thunar",不然打不開

新增捷徑:
在面板上按住alt點右鍵 -> 加入面板 -> 啟動圖示 -> 新增應用程式在面板後然後按ctrl複製拉到桌面

參考資料:
http://forums.debian.net/viewtopic.php?f=30&t=83012

linux查區網內有哪些ip

目標:
要查無線路由器內有多少機器上線,因為有時候無法開網進無線ap後台網頁看連線狀態,或者,有些無線路由器只列出dhcp的ip位址,固定ip位址沒列出來(ex. TP-Link TL-WR742N)。

google關鍵字搜尋:
linux ip scanner

工具:
arp-scan或nmap (推薦使用nmap)

安裝:(以arch linux為例)
# pacman -S arp-scan

# pacman -S nmap

使用:
arp-scan -
# arp-scan -l #我有兩張網卡(乙太網路和無線網路),只會列出乙太網路查詢的結果
# arp-scan 192.168.0.0/24 #Scans 192.168.0.0 255.255.255.0
# arp-scan 192.168.0.1-192.168.0.254 #Scans the obvious range

nmap -
# nmap -sP 192.168.199.0/24 #Scans 192.168.199.0 255.255.255.0
# nmap -sP 192.168.199.1-254 #Scans the obvious range

實測:
在檢查"極路由"路由器時(所有設備都連無線網路),arp-scan列出的結果過少,不正確
使用nmap列出的結果較多,但每次數量都不一樣。所以以列出數量那次為參考。

參考資料:
http://itswapshop.com/articles/top-3-ip-scanners-linux

arch 看syslog

什麼是syslog?
是 system log, 會紀錄誰執行了哪些東西, 有哪些 CRON 或者哪些動作正在被執行等紀錄.

在debian中看syslog:
# tail -f /var/log/syslog
在arch linux看syslog:
# journalctl -f

參考資料:
http://blog.longwin.com.tw/2011/11/linux-data-syslog-logger-2011/

2014年11月18日 星期二

rpm使用心得

前言:
在幫Jethro安裝gitlab( 很難裝 )時,要移除之前用embedded方法安裝的gitlab

RPM - 最早由Red Hat研製(CentOS基於Red Hat),rpm檔屬於原始碼包(Source)。

常用指令:
安裝:
$ rpm -ivh webmin.rpm
列出所有安裝的rpm套件:
$ rpm -qa
查某個rpm套件是否安裝:
$ rpm -qa iptables

$ rpm -qa | grep iptables
刪除rpm套件:
$ rpm -e <package name>(我打全名,ex. rpm -e gitlab-7.4.3_omnibus.5.1.0.ci-1.el6.x86_64)
列出所有套件檔案:
$ rpm -ql iptables
列出套件資訊:
$ rpm -qi iptables


參考資料:
http://webcache.googleusercontent.com/search?q=cache:kz__FWHKVHQJ:www.howtoforge.com/forums/showthread.php%3Ft%3D8+&cd=3&hl=zh-TW&ct=clnk&gl=tw
http://www.cyberciti.biz/faq/howto-list-installed-rpm-package/

2014年11月12日 星期三

eclipse luna新增view在perspective中

在kelper之後的版本,左下角新增view的按鈕不見了,要怎麼把裝好套件上的工具(view)新增到當前的視角(perspective)中呢?

Window -> Show View -> Other -> 選你要的工具

2014年11月10日 星期一

Arch fcitx無法打英文

某天升級fcitx重開機後,發現無法輸入英文,且在fcitx設定裡面也找不到英文輸入法可以加入

嘗試:
重新安裝fctix,在自動安裝fcitx-gtk2和fcitx-gtk3時會報錯
解法:
升級glib2 (但不是真正解決此問題方法)
# pacman -S glib2

查問題:
1. 關閉fctix
2. 在命令列輸入下面這指令看出什麼錯誤
$ fcitx &
...
(ERROR-1136 /build/fcitx/src/fcitx-4.2.8.5/src/lib/fcitx/ime.c:303) IM: open /usr/lib/fcitx/fcitx-keyboard.so fail libicuuc.so.54: cannot open shared object file: No such file or directory
$ locate libicuuc.so
/usr/lib/libicuuc.so
/usr/lib/libicuuc.so.53
/usr/lib/libicuuc.so.53.1
/usr/lib32/libicuuc.so
/usr/lib32/libicuuc.so.53
/usr/lib32/libicuuc.so.53.1
原來是libicuuc.so.53這檔案沒升級
解法:
升級下面這兩個套件
# pacman -S lib32-icu
# pacman -S icu

即可正常使用fcitx

後記:
做了上面的升級後firefox打不開
$ firefox &
[1] 9803
bear@lmannb:~$ XPCOMGlueLoad error for file /usr/lib/firefox/libxul.so:
libicui18n.so.53: cannot open shared object file: No such file or directory
Couldn't load XPCOM.
解法:
升級firefox
# pacman -S firefox

總結:
1. pacman -Syu是個危險的命令
2. linux is free if your time is no value

參考資料:
http://kelvinh.github.io/blog/2013/03/29/fix-fcitx-on-archlinux/ ( 非用這邊解法s )


使用正規表示式複製檔案

目標:
只將下面資料夾裡面的1.jpg 2.jpg 3.jpg 4.jpg複製到某個資料夾
$ ls
04.jpg   3.jpg     sp640x480.gif       2.jpg
1.jpg   2-bg-m.jpg       22.jpg           4.jpg
解法:
ls | egrep "^[0-9].jpg" | xargs cp -t destination_folder
例:
$ ls | egrep "^[0-9].jpg" | xargs cp -t ../images/
注意:
egrep看不懂正規式數字的\d,要用[0-9]

參考資料:
http://stackoverflow.com/questions/3185457/why-doesnt-this-pattern-work-in-egrep
http://superuser.com/questions/441422/how-do-you-use-regular-expressions-with-the-cp-command-in-linux

2014年11月7日 星期五

Firefox FoxyProxy設定

設定了shadowsocks+foxyproxy翻牆後有個問題一直很困擾我,手動設定代理伺服器後一些內網自訂的網址( ex. test.localhost 、公司內網網站 )都沒辦法同時打開

要怎麼設定讓firefox同時上牆外網站(ex. facebook)和內網網站呢?

開啟FoxyProxy介面後,代理伺服器面板:
Default => "代理伺服器細節"選擇"選擇"直接連線"
新增代理伺服器( 假設命名MyProxy ) => "代理伺服器細節"選擇"手動設定代理伺服器"(設定值依你的代理伺服器設定而異)
MyProxy => 網址樣式 =>
1. 勾選"內部IP位址不使用此代理伺服器"
2. 將你要直接連線的內網網址"增加新的網址"到黑名單中
ex.
增加新的樣式:
樣式名稱:隨便打
網址樣式:*test.localhost* (我用萬用字元,要注意最後要加*號才能讓網址下所有檔案都直連)
然後下面選擇"黑名單"
新增萬用樣式:(必加,不然牆外的網站上不去)
樣式名稱:*
網址樣式:*
然後下面選擇"白名單" (黑名單的優先權會大於白名單)

回到FoxyProxy的代理伺服器面板,上方"選擇樣式"選"根據已經定義好的樣式及優先權使用代理伺服器"

然後國內哪些網站要連就要像設routing table一樣一個一個設進去,不然連線會較慢,無法作到完全的智能翻牆。

自訂routing table
使用 https://github.com/kalecgos0616/tools/tree/master/wildcard_bypass_domain 裡面的foxyProxy_bypass.json 在FoxyProxy的網址樣式中匯入
檢查:
開百度地圖看是不是鎖定在你所在的城市,如果在國外地圖會放到最小

SSLedge Chrome套件設定不走代理的網址
如同上面Firefox FoxyProxy遇到一樣的問題,有些內網網址要怎麼不走代理:
點選SSLedge套件圖示 => 點你走的代理上的設定圖示 => ByPass(繞行) 最下面加入你要直連的網址(ex. ,*test.localhost*)




Arch Linux 的Firefox使用VLC播放rtsp串流

維護頁面時發現該頁面<embed>使用vlc( type="application/x-vlc-plugin" )播放影片(*.avi)和串流(rtsp://)
 
or
  

s
而我的Arch Linux用firefox開出現下面這個錯誤畫面:
解法:
安裝npapi-vlc-git (需先裝vlc,pacman有套件)
$ yaourt -Ss npapi-vlc-git #注意pacman找不到npapi-vlc-git這套件
aur/npapi-vlc-git 2.1.3.100.g417d246-1 (148)
    The modern VLC Mozilla plugin
yaourt太慢的話就用proxychains4 翻牆去下載安裝
# proxychains4 yaourt -S npapi-vlc-git

裝完後重開firefox,<embed>會出現這畫面:
點擊啟用VLC Web.後就能正常看影片

VLC更進階的應用(Firefox plugin API):
http://www.videolan.org/doc/play-howto/en/ch04.html



sublime sftp使用心得

1. 在電腦上開一個資料夾
2. Sublime: Project -> Add Folder to Project
3. 在左邊slide bar的資料夾上點右鍵 -> SFTP/FTP -> Map to Remote
4. 就會在資料夾下打開sftp-config.json
注意:上層資料夾不能有sftp-config.json,不然即使資料夾開在下層,點右鍵SFTP/FTP後仍會吃到上層sftp-config.json的設定
5. 設定sftp-config.json,我有更動到的設定:
"upload_on_save": true, //儲存後就上傳到遠端
"sync_down_on_open": true, // 打開檔案時自動從伺服器同步最新檔案回來
"host": "example.com", //設定ip、帳號、密碼和遠端資料夾路徑
"user": "username",
"password": "password",
"remote_path": "/example/path/",
"ignore_regexes": [
    ...  ,
    "\\.mp4", //因為遠端的影片檔較大,不將遠端的影片檔同步回來。設定檔為json字串,所以這邊正規式要跳脫兩次
    "app/storage/",  "api/storage/",  "\\.jpg",  "\\.png", "vendor/", "lib/PHPExcel/", // 避免下載Laravel套件、log和圖片
    "[\u4e00-\u9a05]",  // 避免下載中文名檔案,因sublime sftp下載中文名字的檔案會報錯
    "ssh_key_file": "C:\/Users\/x.x.x.x-project.ppk"  // 如果主機ssh需要key登入
]
6. 同步遠端檔案回本機
資料夾上點右鍵 -> SFTP/FTP -> Download Folder
7. 直接用sublime編輯本機上同步的檔案儲存後自動上傳到server

ps.
ln -s 軟連結目錄下的檔案也會下載下來
ex.
source -> /www/wwwroot/codes/source

參考連結:http://www.barryblogs.com/sublime-text2-ftp-sftp-remotefilesync/

2014年11月4日 星期二

使用tty7( ctrl+alt+F7 )登錄桌面slim出現錯誤:failed to execute login command

環境:Arch linux
桌面:enlightenment

使用tty7( ctrl+alt+F7 )登錄桌面slim出現錯誤:
failed to execute login command
http://wiki.alpinelinux.org/wiki/SLiM
https://wiki.archlinux.org/index.php/enlightenment
解法:
編輯
~/.xinitrc
加入
exec enlightenment_start  # 這台電腦的桌面是 enlightenment
必須使用tty7登錄桌面後才能遠端或透過web api 播mplayer
不然遠端console用 DISPLAY=:0 mplayer 4.mp4 會出現錯誤:
Xlib: Invalid MIT-MAGIC-COOKIE-1 key vo: couldn't open the X11 display (:0)!

2014年11月3日 星期一

Arch linux start不能開啟桌面

狀況:電腦在外接samsung的LCD螢幕(Model: S24B370H)時無法啟動桌面

http://unix.stackexchange.com/questions/33825/startx-error-when-setting-up-x-server-on-archlinux

在startx出現類似下面的錯誤:
$ startx
...
Loading extension GLX
ile at "var/log/Xorg.0.log" for addigional information.  (EE) Server terminated with error
xinit: giving up
xinit: unable to connect to X server: Connection refused
xinit: server error

查log:
/var/log/Xorg.0.log 或 #以root執行startx
/home/user/.local/share/xorg/Xorg.0.log #以user執行startx
依錯誤提示而異
注意:
每次執行startx後Xorg.0.log是整隻檔案重寫,所以不能像apache error log用tail -f 去看他變化,只能重新打開或:edit去看新的log寫什麼

原因:沒裝主機板上顯卡驅動和設定,無須安裝samsung LCD的驅動

查主機板顯卡:
$ lspci | grep VGA
00:02.0 VGA compatible controller: Intel Corporation Xeon E3-1200 v3/4th Gen Core Processor Integrated Graphics Controller (rev 06)
得知主機板是intel的顯卡

安裝intel顯卡driver:
extra/libva-intel-driver 1.4.1-1 [installed]
    VA-API implementation for Intel G45 and HD Graphics family
# pacman -S libva-intel-driver
安裝成功後
$ ls /usr/lib/xorg/modules/drivers
會多出 intel_drv.so*這檔案。同理,安裝nvidia driver後會這邊多出nvidia_drv.so*這檔案

啟動startx出現錯誤:
(EE) No devices detected.
Fatal server error:
no screens found

解法:
設定/etc/X11/xorg.conf
Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
EndSection

Section "Device"
   Identifier  "Intel Graphics"
   Driver      "intel"
   Option      "AccelMethod"  "uxa"
EndSection
注意:
設定在 /etc/X11/xorg.conf.d/20-intel.conf ( 這個路徑是 pacman -S xf86-video-intel 裝完後給我的提示) 上無效

最後
$ startx 即可開啟桌面

調整登錄畫面的解析度
編輯 /etc/X11/xorg.conf  ,在 Section "Monitor" 裡面加入這行
Section "Monitor"
  Option      "PreferredMode" "1920x1080" #你要的解析度
EndSection



Arch linux pacman 安裝軟體出現錯誤

如這篇 使用mplayer播放影片 在安裝mplayer時發生錯誤

# pacman -S 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

解法:
# pacman -Syu mplayer #更新package清單和升級所有package然後安裝mplayer
先更新pacman的database,再安裝mplayer(使用pacman -Syu會更新所有安裝的程式)
# pacman -Sy
# pacman -S mplayer

遇到錯誤:
:: Import PGP key 2048R/, "Zuyi Hu <hzy068808@gmail.com>", created: 2014-03-31? [Y/n] Y
error: key "Zuyi Hu <hzy068808@gmail.com>" could not be imported
error: required key missing from keyring
error: failed to commit transaction (unexpected error)
Errors occurred, no packages were upgraded.
解法:
https://wiki.archlinux.org/index.php/Pacman-key#Cannot_import_keys
編輯/etc/pacman.conf
SigLevel = Never # 將SigLevel設定改成Never

注意:
這步會讓pacman安裝不可信任的packages

升級chromium ( chrome的測試板 )後無法執行
$ chromium
/usr/lib/chromium/chromium: /usr/lib/libpci.so.3: version `LIBPCI_3.3' not found (required by /usr/lib/chromium/chromium)
查原因:
$ pacman -Qo /usr/lib/libpci.so.3
/usr/lib/libpci.so.3 屬於 pciutils 3.2.1-1
# pacman -Ss pciutils
core/pciutils 3.3.0-1 (base) [installed: 3.2.1-1]
    PCI bus configuration space access library and tools
原來是pciutils 版本太舊,升級....
# pacman -S pciutils
解決,正常使用。
參考資料:
https://forum.manjaro.org/index.php?topic=19875.0

Arch Internet sharing(透過另一台電腦上網)

環境:
我的電腦有連兩個網路、內網(接有線eth0 or enp0s25)和外網(收無線網路wlan0 or wls1) 有個內網的設備想透過我電腦上外網去更新程式。 內網不能對外,外網可以。
我的電腦enp0s25和內網設備enp2s0(用ifconfig查該點腦是用哪個網路)連同一個無線ap,在同一個LAN

原本要外接usb無線網卡用wpa_supplicant(需另外安裝)連無線網路去更新,但是更新一下網卡就過熱段掉了。才改採用internet sharing的方法
# wpa_supplicant -i wlan0 -c <(wpa_passphrase your_SSID your_key)

參考:https://wiki.archlinux.org/index.php/Internet_sharing
我的電腦:
1. 設定固定IP - 這步我將mac網址寫在無線ap的設定上面去設定固定ip
2. 啟用封包轉發( Enable packet forwarding )
查packet forwarding 設定:
# sysctl -a | grep forward
暫時啟用packet forwarding:
# sysctl net.ipv4.ip_forward=1
如果保留這些設定在重開機後:
編輯/etc/sysctl.d/30-ipforward.conf:
net.ipv4.ip_forward=1
net.ipv6.conf.default.forwarding=1
net.ipv6.conf.all.forwarding=1
3. 啟用NAT
# iptables -t nat -A POSTROUTING -o internet0(能上外網的網路) -j MASQUERADE
# iptables -A FORWARD -i net0(內網的網路) -o internet0(能上外網的網路) -j ACCEPT
# iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
例:
# iptables -t nat -A POSTROUTING -o wls1 -j MASQUERADE
# iptables -A FORWARD -i enp0s25 -o wls1 -j ACCEPT
# iptables -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

設備:
1. 設定固定ip - 將mac網址寫在無線ap的設定上面去設定固定ip
2. 設定route方向
# ip route add default via 192.168.123.100 dev eth0
例:
# ip route add default via 192.168.0.101 dev enp2s0
出現錯誤:
RTNETLINK answers: File exists
解法:
重啟網路
# ifconfig enp2s0 down
# ifconfig enp2s0 up
3. 檢查ping不ping得出去
# ping 114.114.114.114
4. ping得出去後設定DNS
/etc/resolv.conf:
nameserver 114.114.114.114

內網設備即可透過我電腦去更新程式
如:
# pacman -Syu mplayer

shan:此方法適用於linux-like的系統

更快速的方法:proxychains
假設server IP(能上外網那台):192.168.92.2
client IP(只能上內網那台):192.168.92.138
[bear@192.168.92.138 proxychains]$ ssh -NfD 9050 bear@192.168.92.2
[bear@192.168.92.138 ~]proxychains4 curl http://baidu.com
註:
server無須做任何設定,9050 port是client上proxychains.conf預設走的port
socks4     127.0.0.1 9050

client透過server上的shadowsocks上牆外網站
把server(非shadowsocks的server,是internet sharing中的server)的ss跑在0.0.0.0上
然后把client的代理配置到server的IP上
server shadowsocks的config.json配置新增:
"local_address": "0.0.0.0",
client proxychains.conf配置:
socks5  192.168.92.2 8080
最後用這些指令透過ss上網
[bear@192.168.92.138 ~] proxychains4 curl http://facebook.com
[bear@192.168.92.138 ~] proxychains4 pacman -S subversion
特別改謝shell指導

2014/11/27
上述"client透過server上的shadowsocks上牆外網站"情況在使用pacman -Sy更新時會報錯:
error: failed retrieving file 'core.db' from mirrors.163.com : Resolving timed out after 10519 milliseconds
使用iptables方法則正常

參考資料:
http://heylinux.com/archives/2933.html



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