2014年11月19日 星期三

JavaScript 去除空格與換行

記錄用

去除換行
str.replace(/\r\n|\n/g,"");
去除空格
str.replace(/\s+/g, "");

Nginx 1.9以上 configure

 記錄用

sudo ./configure --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/var/run/nginx.pid --lock-path=/var/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --with-http_perl_module --with-mail --with-mail_ssl_module --with-pcre --with-google_perftools_module --with-debug --with-http_stub_status_module  --with-stream --with-http_perl_module --add-module=/home/ec2-user/nginx-upstream-fair  --with-ipv6 --with-ld-opt=-Wl,-E

sudo ./configure --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/var/run/nginx.pid --lock-path=/var/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_image_filter_module --with-http_geoip_module --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_stub_status_module --with-http_perl_module --with-mail --with-mail_ssl_module --with-pcre --with-google_perftools_module --with-debug --with-http_stub_status_module  --with-stream --with-http_perl_module  --with-ipv6 --with-ld-opt=-Wl,-E

ec2

yum install gcc pcre-devel openssl-devel libxml2-devel libxslt-devel gd-devel perl-devel perl-ExtUtils-Embed geoip geoip-devel google-perftools google-perftools-devel


sudo make
sudo make install



vim src/http/ngx_http_upstream.h
struct ngx_http_upstream_srv_conf_s {

    ngx_array_t                     *values;
    ngx_array_t                     *lengths;
    ngx_uint_t                       retries;

    in_port_t                        default_port;



nginx 升級
http://zhangge.net/4856.html


EC2 掛載 S3 空間作為備份磁區


須安裝 s3fs


s3fs -o use_cache=/media/xxxx/tmp_cache backup /mnt/s3-backup

C++ boolean to string

備份用
libjingle on android  印 Log



inline const char * const BooleanToString(bool b)
{
  return b ? "true" : "false";

 __android_log_print(ANDROID_LOG_ERROR, "Tag: ", "Text: %s", BooleanToString(a));

2013年8月23日 星期五

jQuery 檢測綁定事件列表

一切都是龜毛惹的禍

需要偵測是否有重複綁定事件

$._data($('body').get(0), "events").keydown.length

如此可列出 keydown 事件綁定了幾次

進階一些可以再綁定事件時
加入 namespace
以利在多人協作開發時, 正確判斷出自己綁定的事件

$._data( $('body').get(0), 'events').keydown

    1. 0:{
      1. dataundefined
      2. guid6
      3. handlerfunction (e) {
      4. namespace""
      5. needsContextundefined
      6. origType"keydown"
      7. selectorundefined
      8. type"keydown"
      9. }
  1.     }
  2. delegateCount0
  3. length2

2013年7月19日 星期五

Heroku On Linux 安裝

Heroku 是提供雲端運算的平台
方便讓不想自行架設伺服器或是管理server的人

國內大多的空間都提供 PHP + MySQL
對於目前想找 Ruby or Python 甚至是當紅的 Node.js
是不太好找到合適的空間來放

老牌的 Heroku 支持 Ruby, Node.js, Clojure, Java, Python, and Scala.
這篇是基礎的安裝教學

要使用 Heroku 一定要預先安裝 Heroku Toolbelt
才可以開始使用他的服務


Linux Mint:

首先連結至 https://toolbelt.heroku.com/debian

wget -qO- https://toolbelt.heroku.com/install-ubuntu.sh | sh

這段 script 將會新增 heroku 的 repository 以及 key 至您的 apt 來源,並安裝 heroku 以及 foreman 套件。 heroku client 將會被安裝至 /usr/local/heroku 並將 /usr/local/heroku/bin 新增至您的 PATH 環境變數內

Linux Fedora 17

https://toolbelt.heroku.com/standalone

wget -qO- https://toolbelt.heroku.com/install.sh | sh
echo "$ echo 'PATH=\"/usr/local/heroku/bin:\$PATH\"' >> ~/.bashrc"


第一行的安裝 script 將會下載 heroku client 的 tarball 檔 並將他安裝至 /usr/local/heroku
第二行則是將 heroku 的路徑加入至 PATH 環境變數中


在 Terminal 裡面輸入上面的指令

這是什麼呢?
  • Heroku client - 建立或管理 Heroku apps 的 CLI tool
  • Foreman - 簡易快速在 Local 端運行你的 apps
  • Git -版本控制及更新至 Heroko

開始動手玩

安裝完畢後, 你可以在 Terminal 中輸入 heroku 指令, 登入使用你在 Heroku 建立帳號時所使用的 email 及 密碼.
(中途會問您是否要建立 SSH 的 public key , 這是要)

$ heroku login
Enter your Heroku credentials.
Email: adam@example.com
Password:
Could not find an existing public key.
Would you like to generate one? [Yn]
Generating new SSH public key.
Uploading ssh public key /Users/adam/.ssh/id_rsa.pub

現在可以開始建立 Heroku app 囉

$ cd ~/myapp
$ heroku create
Creating stark-fog-398... done, stack is cedar
http://stark-fog-398.herokuapp.com/ | git@heroku.com:stark-fog-398.git
Git remote heroku added

2013年7月18日 星期四

Express.js: Session for Production

Express.js Production Mode 啟動後會收到以下訊息
Warning: connection.session() MemoryStore is not designed for a production environment, as it will leak memory, and obviously only work within a single process.
避免造成 Memory Leak 方案如下
  1. no sessions - fast (438 req/sec)
  2. cookieSession: requires no external service, minor speed impact (311 req/sec) - fastest, sessions will expire with the cookie (customised by maxAge)
  3. connect-redis: requires redis server, large speed impact (4 req/sec with redis2go and redisgreen) - faster than mongo, sessions will be deleted after a while (customised by ttl)
  4. connect-mongo - requires mongodb server, large speed impact (2 req/sec with mongohq) - slower than redis, also has no way to remove sessions with no maxAge, requires manual clear_interval to be set to cleanup sessions

這邊我選用了 MongoDB 來作為解決方案

使用 connect-mongo 

INSTALL

  
$ npm install connect-mongo
  
mongoStore = require('connect-mongo')(express);
app.configure(function(){
    ...
    app.use(express.session({
        secret: "@#$TYHBVGHJIY^TWEYKJHNBGFDWGHJKUYTWE#$%^&*&^%$#",
        store: new mongoStore({
            host: setting.mongo.host,
            port: setting.mongo.port,
            db: 'examOnlineSessions',
            collection: 'sessions'
        })
    }));
    ...
})
With connect:
var connect = require('connect');
var MongoStore = require('connect-mongo')(connect);

2013年7月17日 星期三

那年不怕死的冒險


離開了服務近三年的公司
要說沒有不捨是騙人的
從 App 開發一路到了系統, 甚至是 server side 開發
以及最後整套考試系統的規劃與開發
兩年多來成長了不少

但攻略迷宮
總有走完的一天
沒走透也許可惜
但新的地圖還是會出現在眼前
展開新的冒險吧


今天也是與小天使第一次約會的紀念日
我會記得承諾
讓妳在天上也看的見的

不管外人如何數落抹黑
作自己就對了

2013年7月3日 星期三

Nginx 設定檔相關說明

Setting

主要設定檔位置: /etc/nginx/nginx.conf
引入設定檔路徑: include /etc/nginx/conf.d/*.conf
伺服器設定檔: /etc/nginx/conf.d/default.conf

nginx.conf 設定檔內容

user              nginx;
worker_processes  8;
worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
worker_rlimit_nofile 1048576;

error_log  /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /run/nginx.pid;

events {
    use   epoll;
    worker_connections  1048576;
}

http {
    include       /etc/nginx/mime.types;

    default_type  application/octet-stream;


    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip on;
    gzip_comp_level 6;
    gzip_vary on;
    gzip_min_length 1000;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_buffers 16 8k;

    include /etc/nginx/conf.d/*.conf;

    upstream node_server {
        server 192.168.1.1:3000 weight=2;
        server 192.168.1.1:3001 weight=1;
    }
}

設定說明:

>>> user        nginx;
nginx 為使用者名稱
>>> worker_processes  8;
需要開啟的 worker 數量,盡量以核心數為設定標準
>>> worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
綁定每個 worker process 給 CPU 核心
>>> worker_rlimit_nofile 1048576;
要和系统單一 process 的 open file 數量一致
Note
The Linux kernel has a hard upper limit of 1024*1024
>>> error_log  /var/log/nginx/error.log;
錯誤紀錄檔 參考
>>> pid        /run/nginx.pid;
Pid文件位置

event 區塊

>>> use epoll;
epoll 是 I/O Multiplexing 中的一種方式, 用於linux kernel 2.6以上,可提高nginx的效能
>>> worker_connections  1048576;
每個 worker 的大連接數,理論上每台 nginx 伺服器的最大連接數為 worker_processes * worker_connections

http 區塊

>>> include       /etc/nginx/mime.types;
設定MIME, 由mime.type 檔案來定義
>>> default_type  application/octet-stream;
設定預設的MIME类型
>>> log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    '$status $body_bytes_sent "$http_referer" '
    '"$http_user_agent" "$http_x_forwarded_for"';
設定紀錄檔的格式
>>> access_log  /var/log/nginx/access.log  main;
設定 access 紀錄檔
>>> sendfile        on;
開啟 sendfile(), 指定Nginx 使用 kernel 的 sendfile 函數來提高 web 傳輸文件的效率,一般設為 on,如果用來進行下載等應用 磁碟IO 重負載的應用,可設為 off,以平衡磁碟與網路 I/O 處理速度,降低系統的負載。 P.S.如果圖片顯示不正常把這個改成off
>>> tcp_nopush      on;
開啟 TcpNopush(TCP_CORK), 採用 Nagle 算法較小的 packet 存入緩衝區直到蓄足一個 frame 後一起發送,這樣可以最小化所發送的 message 的數量來提高應用程序的效率,用以縮減網路傳輸過程中的封包數量,並減輕網絡擁塞問題。 可參考 TcpNopush
>>> keepalive_timeout 65 5;
第一個參數指定 Client 端連接保持活動的限制時間,在這個時間之後,Server 會關掉連接,第二個參數是可選的,它指定了消息頭保持活動的有效時間,即響應中的 timeout=time,它可以告訴某些瀏覽器關閉連接,因此服務器就不必關閉連接了,如果沒有這個參數,Nginx不會發送Keep-Alive頭。
>>> gzip  on;
開啟gzip壓縮 參考資料: GzipModule
>>> include /etc/nginx/conf.d/*.conf;
讀取來自於 /etc/nginx/conf.d 資料夾的 config 檔案, 預設的 Server 設定在 conf.d/default.conf
>>> upstream node_server {
        server 192.168.1.146:3000 weight=2;
        server 192.168.1.146:3001 weight=1;
    }
開啟負載平衡, weight 是用來設定 server 分配權重

Nginx 安裝

Nginx

輕量級的web server, reverse proxy server 與apahce & IIS 角色相同
epoll 非同步non-blocking I/O
下面為Linux下的安裝方式

Install

Fedora 17
yum install nginx
CentOS 6
vim /etc/yum.repos.d/nginx.repo
nginx.repo >
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

NodeJS Production Depoly (1)

最近公司的專案要開始Depoly
從原本的測試環境改為production 

目前用到以下技術:
Nginx: 負責Loadblance
NodeJS: 撰寫後端應用
MongoDB: 儲存Session與服務的資料

NodeJS 用到的Module:
connect-mongo: 存session資料
expressjs: 網站Framework
i18n: 多國語系
moment: 處理日期時間
mongoskin: 連結mongoDB
underscore: 前後端都好用的JS Library (針對Flow Control也有用到)

因應多核心主機使用了 cluster


整體架構圖

2013年2月4日 星期一

Chromium 啟動全螢幕

on Linux FC17 chromium --kiosk http://127.0.0.1:3000

ExpressJS 印出JSON範例

 
msg = JSON.stringify(json);
res.writeHead(200, {
    "Content-Type": "application/json;",
    "Content-Length": msg.length
});
res.end(msg);

2012年10月3日 星期三

Nginx 反向代理與Rewite

以下為筆記 :p
延續上次的設定

反向代理 

利用proxy_pass來設定欲導向的服務
修改/etc/nginx/conf.d 底下的設定檔
我在此新增一個localnginx.conf的設定檔
server {
    listen       80;
    server_name  localnginx1;
    
    charset utf-8;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
    }
}

listen跟server_name請看上篇
重點在於 location / 的部份
 / 代表根目錄
也就是在網址輸入 http://localnginx1/ 的時候
要處理的動作
這裡我使用 proxy_pass 把 client 端發出的 Request
轉發到 3000 port 的 service

Url Rewrite 
rewrite 可以接兩個參數
第一個參數設下條件
第二個參數則設定目標
server {
    listen       80;
    server_name  localnginx2;
    
    charset utf-8;

    location / {
        rewrite  ^(.*) http://127.0.0.1:3000;
    }
    
    location /google {
        rewrite ^ http://www.google.com.tw;
    }
}

按照上面的方式設定
輸入 http://localnginx2/ 時
會導向 http://127.0.0.1:3000; 並改變網址

輸入 http://localnginx2/google 時
會導向 google 台灣首頁


Nginx Virtual Host 設定

最近開始碰Nginx 紀錄一下設定的部份 環境為FC17 kernel: 3.5.3-1.fc17.i686.PAE 安裝好Nginx後 先設定為開機啟動 在Terminal上輸入
systemctl enable nginx.service
成功之後 輸入啟動指令
systemctl start nginx.service

完成後輸入在瀏覽器網址列上輸入localhost應該就能看到Nginx的歡迎頁面了


接下來為了測試方便 我們使用修改 hostname 的方式來模擬 sub domain 的部份 先編輯 /etc/hosts

如上圖所示, 在127.0.0.1那行加上 localnginx ~ localnginx2 三個name來測試 設定完畢就開始進入Nginx的設定了 Nginx的conf檔置於 /etc/nginx/conf.d/底下 只要在此目錄下的.conf檔案都會在Nginx啟動時載入 新增一個設定檔
vim /etc/conf.d/localnginx.conf

server {
    listen       80;
    server_name  localnginx;

    charset utf-8;

    location / {
        root   /home/sean/nginx/;
        index  index.html index.htm;
    }
}
此設定檔設定偵聽 80 port 並在遇到server name為localnginx時 使用此設定檔 粗體的部份就是設定此server的初始目錄在哪 存檔完畢後輸入重新啟動nginx
systemctl reload nginx.service
在對應的目錄底下放入index.html後 如此一來在瀏覽器上就能看到結果囉



2012年8月22日 星期三

正規表示法筆記

此區純粹筆記用 :p

只能輸入中英文與數字:
rule ='^[0-9a-zA-Z\u4e00-\u9fa5]+$'
str = '只能輸入中文與English123345';
var regexp = new RegExp(rule);   
console.log(regexp.test( str ));

2012年8月15日 星期三

MongoDB 指令筆記

開啟Mongo: mongod

顯示所有DB: show dbs

切換DB: use 資料庫名稱

顯示所有collection(資料表): show collections

顯示collection內容: db.collection名稱.find()




2012年8月13日 星期一

用 JavaScript 做中文驗證

利用正規輸入法來判斷


  function isChinese ( str ) {
      var regx = /[^\u4e00-\u9fa5]/;
      if ( regx.test( str ) ){
        return false;
      } else {
        return true;
      }
  }
  alert(isChinese("中文"));

範例網址: http://jsfiddle.net/dNVDV/5/

2012年8月8日 星期三

改善Google Blog 顯示程式碼的簡單方案 Google Code Prettify + CSS


今天明明是巴巴節,
我卻很不孝的跑去參加Node.js Taiwan Party 13
沒想到現場來的還是不少人呀XDD

離題了...
話說今天很害羞的被看到年久失修的網誌
實在忙到寫一堆草稿都沒發
後來Louis 問了我怎麼讓程式碼在blog裡顯示出來的時候
小弟真是慚愧
其實之前很刻苦的用區塊在自己加上css在美化的 囧!

今晚一回家趕快找估狗大神幫忙
好在找到一篇
在 Blogger 文章中利用 CSS Block 及 Google Code Prettify 顯示程式碼

文章使用了Google Code Prettify 這個語法上色工具
並利用css來修改美化整個區塊

咱們就來嘗試看看

首先要在網誌的範本區塊修改HTML

並在head標籤內貼上下方語法


<link href="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css" rel="stylesheet" type="text/css"></link>
<script src="http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js" type="text/javascript">
</script>

這邊是載入google code prettify的svn來使用
為了要使它運作
必須要body標籤內插入


onload='prettyPrint();'


最後在需要顯示為程式碼的地方用 pre 標籤包起來並賦予class

<pre class="prettyprint code">
   輸入想顯示的程式碼
</pre>

就能夠讓程式碼變顏色囉
最後我們可以利用修改css來增加框線及背景色
以下是我自己在用的css

.post .code { 
  display: block; 
  font-family: Courier New; 
  font-size: 10pt; 
  overflow:auto; 
  background: #f3f3f3;
  border: 1px solid #ddd;
  padding: 10px 10px 10px 21px;
  line-height: 1.2;
  border-radius:3px;
}

2012年6月14日 星期四

Android SDK on Windows 7 x64 安裝疑難雜症

最近入手了One-X 就是為了著手進行開發的娛樂XD


既然手機來了, 電腦也該裝上開發工具了!
不過怎麼開始還是個大問題
以下純屬個人筆記


- 建置開發環境 - 


需安裝三樣套件
  1. JDK( Java SE Development Kit)    (筆記時使用的版本為 Java SE 7u5)
  2. Eclipse Classic  (筆記時使用的版本為 3.7.2 )
  3. Andorid SDK  ( 筆記時使用的版本為 installer_r18-windows.exe)
安裝 JDK應該不會有什麼大問題

不過在Eclipse的部分
會因為找不到JDK的javaw.exe而出錯
A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations:C:\eclipse\jre\bin\javaw.exejavaw.exe in your current PATH
(此處將eclipse解壓至 C槽底下)

這時候需到系統內容來設定環境變數


將安裝路徑補在變數值後方
;C:\Program Files\Java\jdk1.7.0_05\bin
(上述路徑為Java SE 7u5預設的路徑)
注意前方須加上分號以作為區隔

這樣就能解決找不到SDK的問題

而在Andorid SDK的部分
如果出現以下訊息

則一樣需到系統內容去設定環境變數
設定如下

如此一來就不會發生安裝程式傻傻找不到java的問題囉