จัด repository ใหม่

googlecode แม่มเลิก support แล้ว เลยต้องย้ายไป github

ยังดีว่า กดปุ่ม เดียวไปได้เลย แต่ต้องมาเสียเวลาเขียน README เพิ่มเข้าไป

แถมใน github แม่ม หน้าเวปโชว์ไฟล์ได้แค่ 1000 ไฟล์

git_1000_files

ของ googlecode แสดงทีละ 1000 ไฟล์

แต่ก็ไม่ค่อยได้กดเข้าไปดูหรอก มันเข้าลึกไปน่ะ

googlecode

ก็ได้โอกาสมาจัดเรียง folder ใหม่ สวยงามแล้วน้ะแจ๊ะ ตอนนี้

Advertisements

Gulp 101

ตอนแรกเลือกระหว่าง Gulp หรือ Grunt
หาๆดู มีคนบอกว่า Gulp จะเป็น code, Grunt จะเป็น config
เลยบ้ายบาย Grunt เพราะว่าเข็ดจาก config ของ จาวา
เขียนผิดทีไม่รู้ไปเจ๊งตรงไหน

ตอนแรกเขาบอกว่าเป็นโปรแกรมทำ task
ก็นึกว่า เป็นโปรแกรมทำ task โง่ๆ
ทำไมต้องใช้ ในเมื่อมี shell script หรือ python หรือ snippet code ภาษาอะไรก็ได้ ก็ทำได้

พอไปดู plugin ค่อนข้างน่าสนใจ
เช่น minifyHTML,
minifyCSS,
minifyJS,
optimizeImage,
concat js file,

glob : Match files using the patterns the shell uses, like stars and stuff

penthouse : tool to generate criticalCSS. For more understanding, try this.

clean-css : fast and efficient CSS optimizer

ซึ่งอิ javascript minify นี่เคยลองหาตั้งแต่ปี 2006 แต่ก็ไม่ค่อยมีเจ้าไหนทำ

Installation
Global scope

sudo npm install -g gulp

or Installation to project dependency

sudo npm install --save-dev gulp

Hello World
gulpfile.js

var gulp = require('gulp');

gulp.task('dsintask', function() {
    console.log('Hello');
});

run

gulp dsintask

Default task
Run multiple task at once
gulpfile.js

gulp.task('default', ['taskName1', 'taskName2', 'taskName3'], function() {
// do nothing
});

run

gulp

Watch
if file change, process task

gulp.task('default', ['imageOptimizeTask'], function() {
    gulp.watch("src/images/*.JPG", ['imageOptimizeTask']);
});

Node.js module pattern

PATTERN 1: DEFINE A GLOBAL

// foo.js
foo = function () {
  console.log('foo!');
}
// app.js
require('./foo.js');
foo();

PATTERN 2: EXPORT AN ANONYMOUS FUNCTION

// bar.js
    module.exports = function () {
      console.log('bar!');
}
// app.js
    var bar = require('./bar.js');
    bar();

PATTERN 3: EXPORT A NAMED FUNCTION

// fiz.js
    exports.fiz = function () {
      console.log('fiz!');
}
// app.js
    var fiz = require('./fiz.js').fiz;
    fiz();

PATTERN 4: EXPORT AN ANONYMOUS OBJECT

// buz.js
    var Buz = function () {};

    Buz.prototype.log = function () {
      console.log('buz!');
    };

    module.exports = new Buz();

PATTERN 5: EXPORT A NAMED OBJECT

  // baz.js
    var Baz = function () {};

    Baz.prototype.log = function () {
      console.log('baz!');
    };

    exports.Baz = new Baz();
 // app.js
    var baz = require('./baz.js').Baz;
    baz.log(); 

PATTERN 6: EXPORT AN ANONYMOUS PROTOTYPE

// doo.js
    var Doo = function () {};

    Doo.prototype.log = function () {
        console.log('doo!');
    }

    module.exports = Doo;
// app.js
    var Doo = require('./doo.js');
    var doo = new Doo();
    doo.log();

PATTERN 7: EXPORT A NAMED PROTOTYPE

// qux.js
    var Qux = function () {};

    Qux.prototype.log = function () {
      console.log('baz!');
    };

    exports.Qux = Qux;
// app.js
    var Qux = require('./qux.js').Qux;
    var qux = new Qux();
    qux.log();

ref : https://darrenderidder.github.io/talks/ModulePatterns

Express GET and POST variable

GET params

app.get('/:name', function(req, res, next){
   var name = req.params.name;
   var getvar = req.query.getvar1;
});

TIPS: iterate over req.query to get all GET variables

POST params

app.use(express.bodyParser());
function errorHandler(err, req, res, next){
   console.error(err.message);
   console.error(err.stack);
   res.status(500);
   res.render('error_template', {error: err});
}
app.use(errorHandler);

app.post('/', function(req, res, next){
    var favourite = req.body.fruit;
    if(typeof favourite == 'undefined'){
         next(Error('Please choose a fruit!'));
    } else {
         // success 
    }
});

[ ubuntu ] MongoDB

Introduction
– schemaless
– not support join beteen collections
– not support transaction beteen collections
– Limitation : collection could not exceed the 16MB document limit

Installation.X

NOTE : This only supports 64 bit machine

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

For ubuntu 12.04

echo "deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

 

sudo apt-get update

Install latest stable

sudo apt-get install -y mongodb-org

or specific released

sudo apt-get install -y mongodb-org=3.0.7 mongodb-org-server=3.0.7 mongodb-org-shell=3.0.7 mongodb-org-mongos=3.0.7 mongodb-org-tools=3.0.7

Service

sudo service mongodb start
sudo service mongodb stop
sudo service mongodb restart

problem : Couldn’t connect to server 127.0.0.1:27017
Solution

Step 1: Remove lock file.

sudo rm /var/lib/mongodb/mongod.lock

Step 2: Repair mongodb.

sudo mongod --repair

Step3 : start mongodb again

sudo service mongodb start

ref : http://stackoverflow.com/questions/12831939/couldnt-connect-to-server-127-0-0-127017

Installation

create /data/db

start server

sudo ./mongod

Console

mongo

Connect mongo on different host

mongo localhost:10001

Execute list of mongo command

mongo localhost:27017 jsfilename

Help

help

Show databases

show dbs

Use database

use <db_name>

Show collecions

show collections

Insert

db.<collectionName>.save(<data in json format>)

or

db.<collectionName>.insert(<data in json format>)

Moreover, we can make use of javascript environment

for(var i=0;i<=10;i++){
db.&amp;lt;collectionName&amp;gt;.insert(<data in json format>)
}

Query

db.users.find({name: 'dsin'})

or indent in pretty way

db.users.find({name: 'dsin'}).pretty()

TIPS : type ‘it’ for more, and it will return `no cursor` if it is end

> DBQuery.shellBatchSize = 1
1
> db.playerids.find({})
{ "_id" : "123456789" }
Type "it" for more
> it
{ "_id" : "234567890" }
Type "it" for more
> it
{ "_id" : "345678901" }
> it
no cursor

 

var j = db.users.findOne({name: 'dsin'}); j.colname = xxx; db.users.save(j);

Check if the attribute exists

db.records.find( { attribute: { $exists: true } } )
Query by id

{
"_id":ObjectId("538fb6a48ead0e08140041a7")
}

Nested Query

{
"user.name": "joe",
"point.lat":{
"$gt":40.038599
}
}

Regex

{
"name": /joe/i
}

or

{
"name": {
"$regex":"joe",
"$options":"i"
}
}

OR

{
"$or": [
{
"name": /joe/
},
{
"age": {
"$gt": 20
}
}
]
}

GT

{
"age": {
"$gt": 20
}
}

ref: RockMongo

check exists : https://docs.mongodb.org/manual/reference/operator/query/exists/

Update

UPDATE USERS SET AGE=18 WHERE NAME=’DSIN’

db.users.update(
{'name': 'dsin'},
{
$set: {'age': 18}
}
)

Remove Mongo Attributes

db.playerids.update({'_id': '123456789'}, {$unset: {'pruned': ''}})

Remove

db.users.remove({name: 'SomeName'}, {justOne: true})

optional justOne : true

Mongo script

NOTE : this is Synchronous

Script.js

var result = db.things.findOne();
printjson(result);

 

mongo script.js

Example in node.js

NOTE : this is Asynchronous

var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  if(err) throw err;
  // find one document in our collection
  db.collection("things").findOne({}, function(err, result) {
    // print the result
    console.dir(result);

    db.close();
  });
});

 

var mongoclient = new MongoClient(new Server('localhost', 27017, {'native_parser': true}));

ver db = mongoclient.db('things');

app.get('/', function(req, res){
   db.collection('things').findOne(funciton(err,doc)){
       console.log(doc);
 });
});

mongoclient.open(function(err, mongoclient){
    app.listen(8080);
    console.log("Express server connected at 8080");
});

Start mongodb

mongod --dbpath=/data/db

Restore database

mongorestore dump

Data Type

NumberInt(1)
NumberLong(1)
new Date()
ISODate("2012-10-21T17:41:58.389Z")

Auto generated _id
current time + machine id + process id

Manipulate user

use dbname
db.adduser('username', 'password')
db.auth('username', 'password') // login
db.removeUser('username')

create/get/drop text index

db.articles.createIndex( { subject: "text" } )
db.articles.getIndexes();
db.pets.dropIndex( "catIdx" )

connect remote host

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

ref ( include uninstall procedure ) : http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

MEAN stack

0. Introduction

MEAN stack
– MongoDB
– Express : Javascript Web framework and add-ons – including Mongoose, an ORM for MongoDB
– Angular : Template
– Node : event-driven, server-side Javascript runtime – powered by the V8 engine

NPM : package manager

X. [nodejs v.s. npm] Around the bush Installation

To fix this error, we have to set the URL

Error: failed to fetch from registry:

use http://registry.npmjs.org/ instead of https://registry.npmjs.org/

$ npm config set registry http://registry.npmjs.org/

NOTE : however, in ubuntu 12.04, nodejs and npm version is conflicted.

npm ERR! error installing express@3.4.4
npm ERR! error rolling back express@3.4.4 Error: UNKNOWN, unknown error '/media/disk-1/testnewfolder/node_modules/express'

npm ERR! Unsupported
npm ERR! Not compatible with your version of node/npm: connect@2.11.0
npm ERR! Required: {"node":">= 0.8.0"}
npm ERR! Actual:   {"npm":"1.1.4","node":"0.6.12"}

1. [nodejs and npm] Real Installation

On ubuntu 12.04, the launchpad repository gives conflict of npm and nodejs ( as in section X. )

Therefore, we need to add PPA following official nodejs documentation

$ curl --silent --location https://deb.nodesource.com/setup_4.x | sudo bash -
$ sudo apt-get install --yes nodejs

2. Express installation

npm usage : command line

Example : install express

 $ npm install express

The folder node_modules/express will be created

npm usage : install all dependencies using package.json

package.json

{
"name" : "MyStaticServer",
"version" : "0.0.1",
"dependencies" : {
"express" : "3.3.x"
}
}

Then run

 $&nbsp;npm install

TIPS : install and add dependency to package.json

npm install --save socket.io

Run Express

server.js

var express = require('express'),
app = express();

app.use(express.static(__dirname + '/public'));

app.listen(8080);
 $&nbsp;node server.js

That is the file server that we can access image on, for example http://localhost:8080/my_image.png

Another express example : response send

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
 res.send('<h1>Hello world</h1>');
});

http.listen(3000, function(){
 console.log('listening on *:3000');
});

NOTE : use app.get(‘*’, For page not found

Another : serving HTML

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

ref : https://developers.openshift.com/en/node-js-example-meanstack.html
, http://learn.mean.io/#mean-io-hosting-mean-openshift

openshift redhat rhc

1. Setup

$ rhc setup
/var/lib/gems/1.8/gems/highline-1.6.21/lib/highline/system_extensions.rb:230: warning: Insecure world writable dir /media/disk-1/eclipse_android in PATH, mode 040777
/var/lib/gems/1.8/gems/highline-1.6.21/lib/highline/system_extensions.rb:230: warning: Insecure world writable dir /media/disk-1/eclipse_android in PATH, mode 040777
OpenShift Client Tools (RHC) Setup Wizard

This wizard will help you upload your SSH keys, set your application namespace,
and check that other programs like Git are properly installed.

If you have your own OpenShift server, you can specify it now. Just hit enter to
use the server for OpenShift Online: openshift.redhat.com.
Enter the server hostname: |openshift.redhat.com|

You can add more servers later using 'rhc server'.

Using an existing token for phong.ek@gmail.com to login to openshift.redhat.com

Saving configuration to /home/dsin/.openshift/express.conf ... done

No SSH keys were found. We will generate a pair of keys for you.
/var/lib/gems/1.8/gems/rhc-1.37.1/lib/rhc/helpers.rb:578: warning: Insecure world writable dir /media/disk-1/eclipse_android in PATH, mode 040777

Created: /home/dsin/.ssh/id_rsa.pub

Your public SSH key must be uploaded to the OpenShift server to access code.
Upload now? (yes|no)
yes

default (type: ssh-rsa)
-----------------------
Fingerprint: XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
Available: true

You can enter a name for your key, or leave it blank to use the default name.
Using the same name as an existing key will overwrite the old key.

Provide a name for this key: |phongekdsinlapto| dsin-dell-linux

Uploading key 'dsin-dell-linux' ... done

Checking for git ... found git version 1.7.9.5

Checking common problems .. done

Checking for a domain ... dsin

Checking for applications ... found 1

dsin http://dsin-dsin.rhcloud.com/

You are using 1 of 3 total gears
The following gear sizes are available to you: small

Your client tools are now configured.

2. ssh

$ rhc ssh dsin
Connecting to XXXXXXXXXXXXXXXXXXXXXXXX@dsin-dsin.rhcloud.com ...

*********************************************************************

You are accessing a service that is for use only by authorized users.
If you do not have authorization, discontinue use at once.
Any use of the services is subject to the applicable terms of the
agreement which can be found at:
https://www.openshift.com/legal

*********************************************************************

Welcome to OpenShift shell

This shell will assist you in managing OpenShift applications.

!!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!
Shell access is quite powerful and it is possible for you to
accidentally damage your application. Proceed with care!
If worse comes to worst, destroy your application with "rhc app delete"
and recreate it
!!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!

Type "help" for more info.

[dsin-dsin.rhcloud.com XXXXXXXXXXXXXXXXXXXXXXXX]\&gt; ls
app-deployments app-root gear-registry git haproxy nodejs
[dsin-dsin.rhcloud.com XXXXXXXXXXXXXXXXXXXXXXXX]\&gt; 

NOTE : to view deploy log

$ cd $OPENSHIFT_LOG_DIR

NOTE : sign-in as others

rhc ssh uisp -l username_ie_whatever@gmail.com

ref : http://stackoverflow.com/questions/16046038/openshift-rhc-setup-using-multiple-accounts

3. create application ( either through website or through rhc )

4. Every OpenShift application you create has its own Git repository that only you can access.

To deploy app,

$ git push

ref : Official openshift page