HTML or File call in Node.js


Before to Start please read the 3_Http_Request Doc. This is use to read a html file which is in our disk. push in to browser according to client request.

var http = require("http");
// Import File system module to read the file
var file = require("fs");

console.log("Starting");

var host = "127.1.1.1";
var port = 1337;

/* Creating a callback which fired every single request that contain the url from client request and response is similar as request*/
var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);

//After we receive the file then we have to read the file from the request URL
file.readFile("." + request.url,
function(error,data){
/* Here we have error object and Data Object in function. So error and data can be return to that specific variables. Therefore If we have error we have to respond to user with predefined String else we have to return the file*/
if(error){
//404 is the status code for not found
response.writeHead(404,{"Content-type":"text/plain"}); response.end("Sorry the page was not found");
}else{

//here our file system is Html so the content type is html
response.writeHead(200,{"Content-type":"text/Html"});
response.end(data);
}
});
});

server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);

After the code completes,
1) Go to project directory using terminal
2) command : node fileName.js
3) If the server starts Go to web browser and  type http://127.0.0.1:1337/name.html
4) you will get the result as html page or error message depend on the request in browser.


HTTP Request In Node.js


Here we are request a server with defined host and port to get a response from server. This is basically created by callback function (non-blocking). Also here I mentioned some modules. The modules can be explained in coming posts.

// Importing the HTTP module from node_module
var http = require("http");

// Print some text to check the start
console.log("Starting");

// Host and Port Address
var host = "127.1.1.1";
var port = 1337;

/* Creating a callback function which fired every single request that contain the url from client request and response is similar as request. here we are importing the createServer class from http module(http.createServer)*/
var server = http.createServer(
function(request,response){
console.log("Received request: " + request.url);
response.writeHead(200,{"Content-type":"text/plain"});
response.end("Hello");
}
);

//Server Listening
server.listen(port,host,
function(){
console.log("listening " + host + ":" + port);
}
);

After completing this code ,
1) Go to project directory using terminal
2) command : node fileName.js
3) If the server starts Go to web browser and  type http://127.0.0.1:1003
4) you will get the “Hello” in browser.

Node.js Installation



To install node.js we need to install dependencies
-----------------------------------------------------------------
apt-get update
sudo apt-get install libssl-dev
sudo apt-get install g++ curl libssl-dev apache2-utils
sudo apt-get install git-core
Check the python version as well

Note: There has some possibility to have an error  when we try to install the node Because of the Dependencies .So Please recheck the dependencies

Install from the downloaded version of node from node site
----------------------------------------------------------------------------------
tar -zxf node-v0.6.18.tar.gz #Download this from nodejs.org
cd node-v0.6.18
./configure && make && sudo make install


Clone node.js from github and installation process
----------------------------------------------------------------------
git clone git://github.com/ry/node.git
cd node
./configure
make
sudo make install


Test the version and conformation of installtion
------------------------------------------------------------------
node --version //This will print the version of the node.js


Node as a real time console
--------------------------------------
Here we can check the single code or any command with node command prompt. For that in terminal text “node” Then automatically the command prompt redirect to node.js console for real . To print some line “hello node.js” in command prompt.

Example:
dhanushanth@ubuntu:~/node$ node
> console.log('hello Node.js')
hello Node.js


Run external .js files using node
--------------------------------------------
Say If the Java script file name is helloPrint.js then,
To run using terminal:
node helloPrint.js

If any issue with installation feel free to mail : dhanu.chrish@gmail.com

Why Node.js



Why Node .js?
This is basically focused on performance. Node performs the best for client’s response for servers. Say we have 100 concurrent clients and 1 megabyte of response. According that the node will have 833 Req/sec. This is comparably very fast response rather than ngins and thin. For this kind of thing we have some option call Sync and un-Sync options. We can see that later in this progress Document.
Code Comparison between Node and PHP.
For a Request,
Query in PHP.
result =query('select * from T')
The above single line of query may blocks the entire process somewhere or implies multiple execution stacks Until it get the response of the DB. Because the query is accessing the disk for an information. But when is come to the Ram and L1, L2 caches those are non-blocking processes. So we can increase our performance when we keep the application request in that level.
So the solutions for the above blocking issue are,
Option 1: Multitasking
Option 2: Other threads of execution can run while waiting
Through the event looping we can process the query efficiently.
query('select..',function(result){
        //use result
});
The above line allows the program to return to the event loop immediately using the callback function. Here No machinery required
The beauty of this event looping and callback is we can use this according to our needs (block or un-block),
For example:
We need to stop the process until we read any specific config file or specific name for the process. So for that we have to do some waiting event.
>In cultural Base
puts("Enter your name ");
var name = gets();
puts("Name : " + name);
The above sample code is asking for a user name. Until it receives the using name the other lines will not process. But again we have another problem if we have 1000 users online. And those 1000 users waiting to enter their names like this then think about the server load as that time. So here the callback plays the role to execute other line until is wait for some specific functions.
Using callback function,
puts ('Enter your name');
gets(function (name){
puts("Name :" + name);
});
But again the rejection is so complicated. Then why everyone using event loops? Because single threaded event loops require I/O to be non-blocking. We can access the disk without blocking. ruby python are event based programming languages. But the according to the user increases we need some expert knowledge of event loops. The JavaScript designed specifically to be used with an event loop and amazing thing
-Anonymous function, closures
-Only one callback at a time
-I/O through DOM event callbacks
The node.js project is to provide a purely evented non-blocking infrastructure to script highly concurrent programs.
Node JS Design goals
No function should directly perform I/O
To receive info from disk, network, or another process there must be a callbacks.
The Node is process based on Stack
ev_loop()->socket_readable(1)->http_parse(1)->load("index.html") So node sends request to the thread pool to load "index.html" and the request is send to disk In the mean time it will call the socket_readable(2) until the socket_readable(1) response. If the socket_readable(1)response then it will return file_loaded() in stack as bellow ev_loop -> file_loaded() ->http_respond(1) it means is respond to first request
Reference:
Nodes Conference 2012 - Click
Ryan Dahl (Creator of Node.js) Introduction speech - Click
Bruno Terkaly of Microsoft workshop - Click

Logic Gates In Artificial Neural Network and mesh Ploting using Matlab

In this part, you are required to demonstrate the capability of a single-layer perceptron to model the following logic gates:
AND , OR , NOT , XOR
Generate the output curves/surfaces for these perceptron-models as the input/s vary continuously from 0.0 to 1.0 (hint: mesh function can come in handy)

And Gate

%input perseptrons
p=[0 0 1 1;0 1 0 1];
%Output Perseptrons
t=[0 0 0 1];
%creation of new pereceptron
net=newp([0 1;0 1],1)
%plot input/outpur
plotpv(p,t);
grid on;
%train the perceptron at 100 iterations
net.trainParam.passes=100;
%assign perceptron to net value
[net,a,e]=train(net,p,t);
%Border Line of the Active function
plotpc(net.iw{1,1},net.b{1})
%To plot the mesh Surface
y = ones(11,11);
input = 0:0.1:1;
for i = 0:10
for j = 0:10
y(i + 1,j + 1) = sim(net,[i/10;j/10]);
end
end
mesh(input,input,y)
colormap([1 0 0; 0 1 1])







Or Gate

%input perseptrons
p=[0 0 1 1;0 1 0 1];
%Output Perseptrons
t=[0 1 1 1];
%creation of new pereceptron
net=newp([0 1;0 1],1)
%plot input/outpur
plotpv(p,t);
grid on;
%train the perceptron at 100 iterations
net.trainParam.passes=100;
%assign perceptron to net value
[net,a,e]=train(net,p,t);
%Border Line of the Active function
plotpc(net.iw{1,1},net.b{1})
a=sim(net,[1;1])
%To plot the mesh Surface
y = ones(11,11);
input = 0:0.1:1;
for i = 0:10
for j = 0:10
y(i + 1,j + 1) = sim(net,[i/10;j/10]);
end
end
mesh(input,input,y)
colormap([1 0 0; 0 1 1])



Not Gate

%input perseptrons
p=[0 1];
%Output Perseptrons
t=[1 0];
%creation of new pereceptron
net=newp([0 1],1)
%plot input/outpur
plotpv(p,t);
grid on;
%train the perceptron at 100 iterations
net.trainParam.passes=100;
%assign perceptron to net value
[net,a,e]=train(net,p,t);
%Border Line of the Active function
plotpc(net.iw{1,1},net.b{1})
a=sim(net,1)




Neural Model for Random Data

%in/Out values
%------------------
%| In1  | In2  |Out|
%|------|------|---|
%| 100  | 200  | 0 |
%| 0.15 | 0.23 | 0 |
%| 0.33 | 0.46 | 0 |
%| 0.42 | 0.57 | 1 |
%------------------

input=[ 100 0.15 0.33 0.42;150 0.23 0.46 0.57];

%here we can use the output value as 0 and 1.
%Because we are using hardlimit threshold function.
%The values are 0 or 1
target=[0 0 0 1];
%creation of new pereceptron
net=newp([0 1;0 1],1);
%plot input/outpur
plotpv(input,target);
grid on;
%train the perceptron at 100 iterations
net.trainParam.passes=100;
%assign perceptron to net value
[net,a,e]=train(net,input,target);
%Active border line
plotpc(net.iw{1,1},net.b{1})
hold on
%second Inputs
p2=[0.20 0.6 0.1;0.20 0.9 0.4];
t2=sim(net,p2)
plotpv(p2,t2);
[net, a, e]= train(net,p2,t2);
plotpc(net.iw{1,1},net.b{1});
hold off




Daemon Service for Graphite

A daemon is a program running in the background, usually providing some sort of service.” enabling other work in the “foreground,” and is independent of control from a terminal. Typical daemons that provide e-mail, printing, telnet, FTP, and web access.

Daemons can either be started by a process, such as a system startup script, where there is no controlling terminal, or by a user at a terminal without “tying up” that terminal
Here we used this technic in Graphite to automate the servers of the Graphite. So we plan to start carbon and graphite server automatically using daemon.

The daemons referenced in /etc/init.d are configured to be run as Linux services. Services are programs that are started and stopped through the init scripts in the /etc/init.d directory. Many of these services are launched when the system is booted. The /sbin/service utility provides a consistent interface to executing the init scripts. The init scripts provide a consistent interface to managing a service by providing options that start, stop, restart, query status.

For Code Breakers


Here's a short collection of quotes from Clean Code, with my comments added after each quote.

"Later equals never."
In our youth we always said, "I'll clean up the code later", but of course we never did. "Later equals never" is known as LeBlanc's Law.


"The only way to make the deadline -- the only way to go fast -- is to keep the code as clean as possible at all times."
The only thing I'd change in that quote is to say, "the only way to constantly go fast". You can go fast in the short term by taking shortcuts, but not in the long term.


"Clean code always looks like it was written by someone who cares."
This was written by Michael Feathers. This quote reflects something I stress during training and mentoring sessions. Programmers need to think of themselves as craftsmen, and take pride in their work. Maybe customers can't see your work, but other developers certainly can, and you should take pride in writing crisp, clear code that other programmers can easily read and comprehend.


"Leave the campground cleaner than the way you found it."
This is similar to the previous quote. I didn't know it, but this is a Boy Scouts of America rule/slogan. In Alaska they have the exact same statement about using the Public Use Cabins here, leave it in better shape than the way you found it.


"The ratio of time spent reading (code) versus writing is well over 10 to 1 ... (therefore) making it easy to read makes it easier to write."
This was something I never really thought about before, but Uncle Bob Martin makes a very convincing case that when we're working on software projects with other developers, we're constantly trying to understand existing code when writing new code, to see how our new code should work and fit into the system.


"You know you are working on clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem."
That quote comes from Ward Cunningham (inventor of the Wiki, inventor of Fit, co-inventor of eXtreme Programming, and much more), who seems to be one of the greatest programmers of our time. I haven't met him yet, but whenever I read his writing, he blows me away. That statement alone sold me on this book.
Make your code read like a story


"The LOGO language used the keyword 'TO' in the same way that Ruby and Python use 'def'."
I never worked with LOGO, but the author begins describing how code should read like sentences in a book. Later he adds:


"Make the code read like a top-down set of TO paragraphs.
Eventually he takes these thoughts to this excellent conclusion:



"Master programmers think of systems as stories to be told rather than programs to be written."
For me, that's a very powerful phrase. I suspect you probably need to read his book to really understand what he's saying here, but if you read the section where he writes about the LOGO "TO" statements, he makes his point very well.


"In order to make sure our functions are doing 'one thing', we need to make sure that the statements within the function are all at the same level of abstraction."
This is another great line, and something I hadn't thought of consciously before. If code in a function is doing one thing at a high level of abstraction, another thing at a medium level, and another at a low level, it's going to be very hard to read, whether you consciously know why, or not. (This really is an excellent observation.)

Functions

"The first rule of functions is that they should be small."
As you've probably read elsewhere, a function should do one thing, and only one thing.


"Functions should do something, or answer something, but not both."
As he states, a function should change the state of an object, or return some information about that object, but not both. I've run into many functions over the years where a function was named "setSomething", and then when I looked at the source for that function, I found that it did several other things besides the "set" it claimed to do.


"Methods should have verb or phrase names."
Very true. I'm always naming methods "handleXYZ", "getXYZ", "calculateXYZ", and so on, trying to use verbs and action names.


"One way to know that a function is doing more than 'one thing' is if you can extract another function from it with a name that is not merely a restatement of its implementation."
This is another great observation that I've never thought about consciously. Many times you can look at a function and obviously know it's trying to accomplish more than one thing, but other times you look at a function and all you can tell is that it's wrong ... it doesn't seem right for some reason, but you can't put your finger on it.


Comments

"Every time you write a comment, you should grimace and feel the failure of your ability of expression."
Like many experienced programmers, the author has been burned by out of date comments, useless comments, and so on, and has come to the conclusion many others have: Most comments are not needed, and if you feel the need to write a comment, you should consider rewriting your code to make it more readable.


"It is better to extract the bodies of the try and catch blocks out info functions of their own."
This is a clever technique that can be used to make try/catch blocks as readable as they can be.
Clean Code, and the Principles of OOD


RRDTOOL for Graphing

RRDtool is the OpenSource industry standard, high performance data logging and graphing system for time series data. RRDtool can be easily integrated in shell scripts, perl, python, ruby, lua or tcl applications.



It has the similar features as Graphite graphing. This is very use full in for industrial level approaches .
Also,

  • RRDtool stores data; that makes it a back-end tool. The RRDtool command set allows the creation of graphs; that makes it a front-end tool as well. Other databases just store data and can not create graphs.
  • In case of linear databases, new data gets appended at the bottom of the database table. Thus its size keeps on increasing, whereas the size of an RRDtool database is determined at creation time. Imagine an RRDtool database as the perimeter of a circle. Data is added along the perimeter. When new data reaches the starting point, it overwrites existing data. This way, the size of an RRDtool database always remains constant. The name "Round Robin" stems from this behaviour.
  • Other databases store the values as supplied. RRDtool can be configured to calculate the rate of change from the previous to the current value and store this information instead.
  • Other databases get updated when values are supplied. The RRDtool database is structured in such a way that it needs data at predefined time intervals. If it does not get a new value during the interval, it stores an UNKNOWN value for that interval. So, when using the RRDtool database, it is imperative to use scripts that run at regular intervals to ensure a constant data flow to update the RRDtool database.


RRDtool assumes time-variable data in intervals of a certain length. This interval, usually named step, is specified upon creation of an RRD file and cannot be changed afterwards. Because data may not always be available at just the right time, RRDtool will automatically interpolate any submitted data to fit its internal time-steps.

The value for a specific step, that has been interpolated, is named a primary data point (PDP). Multiple PDPs may be consolidated according to a consolidation function (CF) to form a consolidated data point (CDP). Typical consolidation functions are average, minimum, maximum.

After the data have been consolidated, the resulting CDP is stored in a round-robin archive (RRA). A round-robin archive stores a fixed number of CDPs and specifies how many PDPs should be consolidated into one CDP and which CF to use.

Reference :
http://en.wikipedia.org/wiki/RRDtool
http://oss.oetiker.ch/rrdtool/index.en.html