What are Kalman filters ?

Why to use Kalman filter ?

The sensor measurements are not generally accurate, they usually have unpredictable, random and uncertain error/variation in their measurements. What does that mean ? Consider a thermometer which reads/measures room temperature, In a room with steady/constant temperature the sensor outputs a varying temperature measurement within a given range, the readings will be scattered around the actual room temperature, this is because the sensors generally have a degree of uncertainty in their measurement.

In the image below the marked X’s demonstrates the sensor readings over a period of time. You can see the though the actual temperature of the room is constant, the readings are distributed over a range of values around the actual temperature.

Screen Shot 2017-12-04 at 8.08.28 AM


If sensor measurements return uncertain measurements, how do we know the actual room temperature ?

We’ll, that’s where Kalman filters comes to your rescue. Kalman filter is an iterative mathematical approach which is used to quickly (with less number of actual readings and iterations) converge to a better estimation of the actual value (better than the sensor measurement itself). In this case using Kalman filter will quickly help us estimate the actual room temperature using the uncertain measurements. In the above you can see how Kalman filter technique helps to quickly approximate the actual room temperature by converging close to the actual value by making use of the uncertain sensor measurements.

The application of Kalman filters are wide, For example Similar issues too are found when Lidar or Radar measurements are used to object tracking in self driving cars, the right estimate of other vehicle on the road is critical for safe driving, Kalman filter are used here too for estimation the actual position and velocity of other vehicles on the road.

Http/2 and implementation in GoLang-1: Http/2 Frameheaders and parsing HTTP/2 Frameheaders in Golang

Http/2 is around the corner and its specifications look really interesting ! The complete specification of Http/2 can be seen at this following link https://http2.github.io/http2-spec/ .

In this post ill be discussing about Http/2 FrameHeader and lets figure out the binary math done to parse it in GoLang .
The complete Http/2 implementation of Golang is available at https://github.com/bradfitz/http2 .

Now Lets Look at the structure of HTTP Frameheader from its spec

| Length (24) |
| Type (8) | Flags (8) |
|R| Stream Identifier (31) |
| Frame Payload (0…) …

The fields of the frame header are defined as:

The length of the frame payload expressed as an unsigned 24-bit integer. Values greater than 214 (16,384) MUST NOT be sent unless the receiver has set a larger value for SETTINGS_MAX_FRAME_SIZE.

The 9 octets of the frame header are not included in this value.

The 8-bit type of the frame. The frame type determines the format and semantics of the frame. Implementations MUST ignore and discard any frame that has a type that is unknown.

An 8-bit field reserved for frame-type specific boolean flags.

Flags are assigned semantics specific to the indicated frame type. Flags that have no defined semantics for a particular frame type MUST be ignored, and MUST be left unset (0x0) when sending.

A reserved 1-bit field. The semantics of this bit are undefined and the bit MUST remain unset (0x0) when sending and MUST be ignored when receiving.

Stream Identifier:
A stream identifier expressed as an unsigned 31-bit integer. The value 0x0 is reserved for frames that are associated with the connection as a whole as opposed to an individual stream.

Now let us look at the implementation of Parsing Http/2 FrameHeader in GoLang
Let us look at the function readFrameHeader https://github.com/bradfitz/http2/blob/master/frame.go . Here is the code

func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
	_, err := io.ReadFull(r, buf[:frameHeaderLen])
	if err != nil {
		return FrameHeader{}, err
	return FrameHeader{
		Length:   (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
		Type:     FrameType(buf[3]),
		Flags:    Flags(buf[4]),
		StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
		valid:    true,
	}, nil

Looks like Greek isn’t it 😛 Lets do some binary math to understanding the parsing of the buffer containing the HTTP/2 Frame .
From the structure of the HTTP/2 Frameheader the first 24 bytes contains the Length of the payload , but since the Http Frame along with its data is obtained in the form of a byte Array ([]byte) , the header now has to be parsed from the same .Since each element in an byte array is a byte, it can only hold 8 bit of data . So now the 24 bit Payload length is spread across 3 consecutive members of the byte array ranging from buf[0] to buf[2] .

Now the challenge is to parse these 3 elements of the array into one integer number . But first lets see how in the first place a 24 bit integer is made to fit into a byte array

Let do a small exercise to understand this .
Let take an random integer , hmm, lets consider the integer 99999 and convert this to binary and present it in 24 bit

99999 = 00000001 10000110 10011111

Here is its binary representation again and how it is stuffed as bytes inside byte array

00000001 10000110 10011111
| | |
| | |
buf[0] buf[1] buf[2]

Oh now i know how in first place how this 24 bit integer is stuffed inside byte array , but do i now parse it back into an integer

Very Simple , Here is how an 0 valued 32 bit integer looks like

00000000 00000000 00000000 00000000

First take buf[0] and place it at the 3rd byte from left of the 32 bit integer and make it look like this

00000000 00000001 00000000 00000000

How to do that ???

Simple …. First convert buf[0] into a 32 bit int


After this the 32 bit integer look like this

00000000 00000000 00000000 000000001

Thhhhhh…!! But content of buf[0] is supposed to be in 3rd byte position but its now 1 byte position !

Okay , now just left shift the integer by two bytes (16 bits) , after this the content of buf[0] will be moved to the 3rd byte position .


Now in the same fashion , you gotto generate a 32 bit integer with the content of buf[1] in the 2nd byte position . This is the done by now left shifting the integer by a byte (8 bits) .


and at the end just convert buf[2] into a 32 bit integer .

Now just perform a logical OR (|) on these 3 integers which will fetch one integer representing the 24 bit Frame Payload Length parsed .

After first 24 bits in the Http Frameheader the next 8 bits correspond to the FrameType . This can be easy retrieved by converting buf[3] into an integer



The next 8 bits correspond to the Flags . This can be easy retrieved by converting buf[3] into an integer



As you can see in the FrameHeader image the next 1 bit is a Reserved bit and 31 bit following it is the Stream ID .

Now the Last 31 bit has to be parsed from the buffer to be able to obtain the stream ID . To be able to do it first fast last 32 bits a 32 bit int

uint32(buf[5])<<24| ]uint32(buf[5]) <<16 | ]uint32(buf[5]) << 8| ]uint32(buf[5])


or there is an equivalent function from the package binary, which does the above functionality


The following link explains more about binary.BigEndian.Uint32 , http://stackoverflow.com/questions/7380158/how-to-convert-4uint8-into-uint32-in-go

Now the challenge is to turn the 32nd bit to 0 so that the 31 bit Stream ID is retrieved .

But how to achieve it ??
Well , easy . Take a number which in binary is equivalent to 0 followed by 31 1’s and then perform a logical AND (&) operation with the number on which you want to strip out or set the 32nd bit of the number to be zero .

First generate an integer which in binary representation is equivalent to 0 followed by 31 1’s

(1<<31 - 1)


This is how at the end last 31 bit representing the Stream ID is obtained

binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1)


Here is the source from https://github.com/bradfitz/http2 , The GoLang Http2 implementation which corresponds to parsing of HTTP2 FrameHeader and i hope after all the explanation the source should make some sense 😛

func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
	_, err := io.ReadFull(r, buf[:frameHeaderLen])
	if err != nil {
		return FrameHeader{}, err
	return FrameHeader{
		Length:   (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
		Type:     FrameType(buf[3]),
		Flags:    Flags(buf[4]),
		StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
		valid:    true,
	}, nil


ssssssssssssssss …..Thats it for now !!! I hope this helped you guys to understand the structure of parsing of Http2 . Will follow up with lots of blogs on Http2 implementation in GoLang..Till then , Happy Coding 😀

Dynamic Programming : Making change for an given amount with least number of coins

Helloooooooooo !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Its been sometime since the last blog … loads of em are struggling to come out of the drafts 😛 I’ve been working on Dynamic programming concepts for a while now , So i thought of sharing my insights on the same by taking up the problem of finding  change for the given amount using  least possible no of currencies , and in the process i would love to explain what Dynamic programming is all about . Without wasting lot of time lets get into solving the problem .

Let me take an example scenario . Lets say you gotto make change for  11 cents and you have coins of 1,2,5  cents.  Now the question is what are various ways(the last step)  to reach to 11 cents considering you have coins of 1,2 and 5 cents ??? hmmm, thats not tough!

Add a 2 cents coin after having change for   9 cents  (9 + 2 )= 11 cents |  add 1 cents after having change for  10 cents ( 10 +1)=11cents |  add 5 cents after having change for  6 cents (6 + 5)= 11 cents  . Now we have 3 ways ( 9 + 2 , 10 + 1 , 6 + 5 ) But amongst these 3 approach which one would consist of minimal number of currencies or coins to make it to 11 ?? Hmm ….

Thats tricky !!!!! Well , that inturn depends on number of coins in the change for 9 , 10 and 6 cents. we have to consider the minimum amongst the 3 cases below

case 1: No.of.coins to make it to 9 cents (x) +  one  coin of 2 ceeents

case 2: No.of.coins to make it to 10 cents(y) + one coin of 1 cents (1)

case 3: No.of.coins to make it to 6 cents (z) + one coin of 5 cents (1)

In short we have to consider min(x+1 , y+1, z+1)

Now lets set  arbitrary values for x,y,z to be {3,2,2} respectively and Lets translate this logic into code for this particular value of amount for which we are supposed to find change using coins of 1,2,5 cents

Here is the code and explanation follows it , The names of variable used reflects their purpose . If you quickly want to execute and mess around with the code here is link https://ideone.com/M9qq4f . Here is the Github link of the code

amntForWhichChangeIsToBeFound = 11

coinsWeHaveUsingwhichChangeHastoBeFound = [1,2,5]

LastcoinUsedToGetChangeArray = [0]*(amntForWhichChangeIsToBeFound+1)  

numberOfCoinsUsedForChange = [0]*(amntForWhichChangeIsToBeFound+1)

coinCount = 11
#In the worst the change will contain 11 coins with all of them ,obviously  lastCoinUsedForChange also  one being 1 cent
LastCoinUsedforChange = 1

numberOfCoinsUsedForChange[9] = 3
numberOfCoinsUsedForChange[10] = 2

numberOfCoinsUsedForChange[6] = 2 

for j in [c for c in coinsWeHaveUsingwhichChangeHastoBeFound if c<=amntForWhichChangeIsToBeFound]:
    #List comprehension in python , iterates only through values of array which satisfies if condition
    if numberOfCoinsUsedForChange[amntForWhichChangeIsToBeFound - j] + 1 < coinCount:
	    coinCount = numberOfCoinsUsedForChange[amntForWhichChangeIsToBeFound - j] + 1
	    LastCoinUsedforChange = j 
numberOfCoinsUsedForChange[amntForWhichChangeIsToBeFound] = coinCount 
LastcoinUsedToGetChangeArray[amntForWhichChangeIsToBeFound] = LastCoinUsedforChange 
print (numberOfCoinsUsedForChange)
print (LastcoinUsedToGetChangeArray)

In 5 and line 7 of the above code there is declaration and initialization to 0

LastcoinUsedToGetChangeArray = [0]*(amntForWhichChangeIsToBeFound+1)  

numberOfCoinsUsedForChange = [0]*(amntForWhichChangeIsToBeFound+1)

The array element numberOfCoinsUsedForChange[i] contains the minimum number of coins used to obtain change for i cents . Thats is , numberOfCoinsUsedForChange[1] contains the minimum number of coins used to obtain change for 1 cent , numberOfCoinsUsedForChange[6] contains the minimum number of coins used to obtain change for 6 cent and it follows . But for now i have assigned arbitrary values to numberOfCoinsUsedForChange[6] , numberOfCoinsUsedForChange[9] , numberOfCoinsUsedForChange[10] , but in practical these values are to be computed .

Also the LastcoinUsedToGetChangeArray[i] contains the last coin used to get the change for i cents . LastcoinUsedToGetChangeArray[11] contains the last coin used in the change for 11 cents .

This sounds Ok , but You have now hard coded and assigned arbitrary values for inumberOfCoinsUsedForChange[6] , numberOfCoinsUsedForChange[9] , numberOfCoinsUsedForChange[10]  , but in real how do i have to compute in runtime ,how do i compute them ??

Yes , There are two ways to compute them . It can be recursively computed using top-down approach or iteratively computed using bottom-up approach . In the complete code sample later in the article ill be using the iterative approach .So using one of these approach the values are computed and the arrays are filled .
So now in this case to compute minimum number of coins required for change of 11 cents we need minimum number of coins required for change of 10,9 and 6 cents and those values are  in turn are dependent on others(10 is dependent on 10 – [1,2,5],9 is dependent on 9 – [1,2,5] and so on …..) , so to solve this inter dependency ,one amongst either recursive or  iterative approach can be used .

That sounds cool , but Size of both the arrays used is equal to the amount for which im finding change for , LastcoinUsedToGetChangeArray = [0]*(amntForWhichChangeIsToBeFound+1) allocates and initializes array of size = (amntForWhichChangeIsToBeFound+1) , why are we wasting so much of memory ??

Yes , in the previous question above I spoke about the interdependencies , these arrays are used to store these interdependencies to avoid re-computation . These re-computations are avoided by storing these values and using them instead of recomputing them every-time . Yes , This needs more memory to be able to store these values , but this is traded off with the speed , This potentially can bring an exponentially time complexed algorithm down to polynomial and this is the core idea of Dynamic Programming . Yes the full program later First we’ll build the numberOfCoinsUsedForChange[] array from bottom-up approach . That is first we’ll compute  numberOfCoinsUsedForChange[1] , numberOfCoinsUsedForChange[2], numberOfCoinsUsedForChange[3] and so on and these stored values are used to compute the later values because these serve as dependencies and recomputation is avoided .

Now analyze the output of the above program ,

In the output LastcoinUsedToGetChangeArray[11] contains value 1 , so 1 cent is the last coin used in the change . Now we know that the last coin is 1 cent , If we could find the last coin used in change for 10 cents (11 -1 )  this gives us one more coin in the minimum change for 11 cents , and this is stored in LastcoinUsedToGetChangeArray[10] , if this process is recursively followed all the coins used in getting the change can be obtained . Using this process PrintCoin function is written which prints out the coins used .

Phewwwwwwww!! Now i believe i spoke about enough of background work required to understand the logic easily , now lets scale it up to be able work with any value .

Here is the code which finds out the number of coins used and the coins used to find change for given amount with given set of coins . Again if you quickly want to execute and hack around here is the link of the code on cloud IDE https://ideone.com/eHhAcB. If you want to fork and mess around with the code here is the link of the code on Github Github link of the code

def printCoins(amntForWhichChangeIsToBeFound,LastcoinUsedToGetChangeArray):
    coin = amntForWhichChangeIsToBeFound
    while coin > 0:
        LastCoinForCoinCent = LastcoinUsedToGetChangeArray[coin]
        coin = coin - LastCoinForCoinCent

def main():
    amntForWhichChangeIsToBeFound = 68
    #edit it for the value you want it for 
    coinsWeHaveUsingwhichChangeHastoBeFound = [1,5,10,21,25]
    LastcoinUsedToGetChangeArray = [0]*(amntForWhichChangeIsToBeFound+1)  
    numberOfCoinsUsedForChange = [0]*(amntForWhichChangeIsToBeFound+1)
    for cents in range(amntForWhichChangeIsToBeFound+1):
    	#This loop starts finding change from 1 cent, then 2,3,4..amntForWhichChangeIsToBeFound
        coinCount = cents
        LastCoinUsedforChange = 1
        for j in [c for c in coinsWeHaveUsingwhichChangeHastoBeFound if c <= cents]:
            if numberOfCoinsUsedForChange[cents - j] + 1 < coinCount:
    	        coinCount = numberOfCoinsUsedForChange[cents - j] + 1
    	        LastCoinUsedforChange = j 
        numberOfCoinsUsedForChange[cents] = coinCount 
        LastcoinUsedToGetChangeArray[cents] = LastCoinUsedforChange 
    #print (numberOfCoinsUsedForChange)
    #print (LastcoinUsedToGetChangeArray)	
    print("Number of coins used: "+ str(numberOfCoinsUsedForChange[amntForWhichChangeIsToBeFound]))
    print("Here are the coins used ")
    printCoins(amntForWhichChangeIsToBeFound, LastcoinUsedToGetChangeArray)


Finallllllllly!! I’ll following up with few more posts on Dynamic programming and Golang implementation of HTTP/2 in the further posts to come …. Till then , Happy Coding 😀

Encrypted Client-server communication using Nodejs TLS module and OpenSSL

TaDaaaaaaaaaaaaaaaaaaaaaaa !!!!!!!! After meddling with the readers mind in my attempt to get into the source of NodeJS in the last and its previous post , i decided to take it easy on the readers in this blog post 😛 So this post is on using the TLS module from the application layer . Lets see how to securely communicate using the TLS module and OPENSSL .Sounds interesting ?? We’ll , then read on 😀

“What do you mean by a secure communication ???”

In this case im talking about encrypting the message and sending it to other parties so that even if your data is captured by other parties its wont be readable .

Hmmm,Ok , then you gotto decrypt it back at the other end to be able to interpret it right ??

Thats right …. Thats obvious right ? If the data is sent encrypted from one end , it has to be decrypted at the other end to be able to read the information .

So there are 2 questions that has to be answered now ..

1.How do i Encrypt the message ??

2.How do i decrypt the message ???

drrrrrrrrrrrrrrrrrr, Now , How do you think you can achieve this ????

HMMMMMM…….. “Can i use some sort of Encryption-decryption algorithm ????”

You got it right , You use some algorithm to encrypt your message and send it across and then using the reversal of the algorithm it can be decrypted .

“But , isnt this risky? What if someone could understand my algorithm , or crack my Algorithm and decrypt my message ??”

Welllllllll ,here is a secret …………….. “This had happened during the Second World War …” shhhhhhhhhhhhhhhhhhhhhhhhh 😛

Then whats the way out ??


Here is how two parties in communication use Public Key Encryption secure the message exchanged between them .

1.How to Encrypt the message in Public Key Encryption ?

In Public key Encryption both parties have a private-key and public-key with them . Private key remains exclusive to both the parties and they dont share it with anyone . But the public key used exchanged with any other party with the communciation and information exchange takes place .
Lets say X and Y are the 2 parties who now are intending to have a secure encrypted communication using Public key encryption method .

How does X encrypt the message to send it to Y .
– For X to Encrypt a message for the purpose it to Y , X needs to use its own private key (Y too has its own private key) and Y’s public key .

Hmmm, this sounds cool , But since X sends the message encrypted , how will Y decrypt it ???
– For Y to decrypt X’s message it needs its own private key and X’s public key .

You might be wondering now , “Lol !!! Now private key and public key story sounds cool , but how to create one of these ??”


OPENSSL executable comes bundled with most of the popular Linux Distributions and it offers wide range cryptography methods . TLS module uses OPENSSL libraries under the hood . Here is the command to create Private Keys using OpenSSL

 openssl genrsa -out private-key.pem 1024

This creates a private key by name private-key.pem

Public keys are also called as certificates . They are called so because public keys will contain digital signatures which are used to identify the right peer/server.
The certificate can be self signed or it can be signed from certification authorities (As in case of HTTPS sites) . Lets see how to create a self signed public key (self signed certificate) using OPENSSL .
First you gotto create a Certificate Signing Request file using your private key:

 openssl req -new -key private-key.pem -out csr.pem

Then you can create a self-signed certificate, using your private key:

openssl x509 -req -in csr.pem -signkey private-key.pem -out public-cert.pem

“HaHaHa , The certificate Saga was pretty , but certificates are used to just encrypt the data during communication between two parties , but how can i communicate by just using the certificates ?? 😛 “
Well , thats right … Now you gotto create a server and a client which uses these certificate and communicate securely using public key encryption.
Here is the code for the TLS server

 var tls = require('tls'),
    fs = require('fs'),
    colors = require('colors'),
    msg = [
            &quot;#######  ####    ####### ######  ####### &quot;,
    &quot;##    # #     # #     # #             # #     #&quot;,
    &quot;# #   # #     # #     # #             # #&quot;,
    &quot;#  #  # #     # #     # #####         #  #####&quot;,
    &quot;#   # # #     # #     # #       #     #       #&quot;,
    &quot;#    ## #     # #     # #       #     # #     #&quot;,
    &quot;#     # ####### ######  #######  #####   #####&quot;


var options = {
  key: fs.readFileSync('private-key.pem'),
  cert: fs.readFileSync('public-cert.pem')

tls.createServer(options, function (s) {

Run the code in the folder where you have created your certificates . Here is the link .
The server writes out the message string [msg] to the client when requested , The difference here is that when the message is being transmitted it is encrypted and sent .

 node tls-server.js   

Once the server is running open another terminal

USING OPENSSL to securely communicate with the TLS server

$ openssl s_client -connect

You can now see the screen with the message array [msg] being sent to the OPENSSL client

Open ssl client
Open ssl client

“Nice story on encryption using Node and OPENSSL, but whats the proof that the data is being encrypted and sent to the client ??”

Use Wireshark and check it out for yourself . Here is the screenshot from wireshark after capturing the communciation between the TLs server and the Open SSL client

Encrypted data
Encrypted data

Wireshark clearly shows that the data transmitted is encrypted . Try writing a simple TCP client-server socket program using NodeJS and then capture the dat using wireshark and the data communicated will be directly visible in wireshark inside the captured packets .

Thats it for now !! Ufffffffffffff!!! I shall get into the more details of source of TLS module in the further posts to come . Till then , Happy coding 😀

Preparing to land on C++ core of NodeJS: Sharpening the weapons – Using C++ Templates

Ahhhhhhhhhhhhhhh!!!!!! Travelling 700Kms without music or books on Technology is so pissing off!!!!This is what i call as “Throw away your frustration blog”  😛 😛 Enough !!!!
In the last blog i started out the series on Peeking into the Source code of node.Js .And also i promised to get into the C++ core of NodeJs while i had restricted myself to the
top most layer of node , that is the Javascript layer of it , dont remember ?? :PThen take a look at this .
So you might be thinking now “Yaay, its now time to start with the C++ core of NodeJs”….But when i started out with the defination of GetCIphers() of the TLS node module inside the C++ core ,the C++ lines of code written were just mindblowing. If you check the lines between 4807-4823 in this link from source of node you’ll understand C++ sophistication that lies beneath. It was important to get back to few important C++ concepts before landing on the C++ core of Node.So this post is on Preparing to land on NodeJs C++ Core..To be precise get Ready for a glimpse on C++ Templates and meddling around with them .C++ templates are widely used within the NodeJs core , so its vital to understand them thoroughly

Being into Hardcore Javascript development from past 15 months the term “template” reminds me of ReactJs , AngularJs Templates ,Jade , EJS ,Handle bars and Underscore Templates .Like Templates in Javascript libraries are used to generate dynamic html ,templates in C++ are used to write “generic programs ” where in the same piece of code can deal with variety of datatypes .

Still confused ??? Ill illustrate an example Lets say your are building a class which provides all the functionalities of a calculator .
Here is the link for the code on github .You can execute the code with cloud C++ IDE by clicking on this link

#include <iostream>
using namespace std;
class calculator {
		int add(int x,int y);
		int multiply(int x,int y);

int calculator::add(int x,int y){
	return x+y;

int calculator::multiply(int x,int y){
	return x*y;
int main(){
    calculator instance;

So whats the issue here.
You can clearly see that the member functions Add and Multiply of the class Calculator
can work only on integer datatypes. They return int , the add take int values as
their parameters .
What if this decision on the data type to be worked upon could have made dynamic ??
What if the a same piece of code can dynamically make the same piece of code work for
various datatypes . Yes , its possible by the use of C++ class templates.
By using C++ class templates any given member function can be made flexible enought to be
able to work on various datatypes . Here is how to do it .Here is the implementation using
C++ template classes .
Here is the link of the code on Github.Click here to execute the same code using online C++ editor

template <typename Type> class calcultor{
		Type multiply(Type x,Type y);
		Type add(Type x,Type y);

template <typename Type> Type calc<Type>::add(Type x,Type y)
	return x+y;

template <typename Type> Type calc<Type>::multiply(Type x,Type y)
	return x*y;

calcultor <int> instance1;
claculator <double> instance2;

baffled ??? 😛
Here is the detailed explanation ,

template <typename Type> class calculator {}

is the declaration of the template class , here template and typename are the keywords and
this should be followed after the typename keyword , a placeholder name has to be given
to the variable datatypes that is sent during the creation of the object of the template class.
but it has to be made sure that the same placeholder name has to be used to refer to the
datatype in its member function .

Type multiply(Type x,Type y);

by using this declaration the return type and the parameters of the member functions are also
made dynamic and are ot predefined like it is in the first case .

this is the format for writing the defination for the member functions of a template class .

template <typename [namespace]> return_type parent_class<[namespace]>::member_function(parameters);

and Both the parameters and return Type can itself be dynamic template varialbles (as it is the case
the template class code example )

now while creating the new instance of the object you have the freedom to choose and set the
datatype on which the member functions process upon .

calculator <int> instance1; 

Now the ‘Type’ will be set to int , so this is equivaluent to

class calculator {
		int add(int x,int y);
		int multiply(int x,int y);


int calculator::add(int x,int y){
	return x+y;

int calculator::multiply(int x,int y){
	return x*y;

now ,

calculator <double> instace2;

this is equivalent to

class calculator {
		double add(double x,double y);
		double multiply(double x,double y);


double calculator::add(double x,double y){
	return x+y;

double calculator::multiply(double x,double y){
	return x*y;

The same analogy can be applied to create functions templates .It is illustrated in the code below .

Here is the link of the code on GitHub .Click here to execute the code online.

#include <iostream>
#include <typeinfo>
using namespace std;
template <typename Type> void test_template(Type x){
    cout << x <<endl;
    cout << typeid(Type).name() << endl;
int main()
   return 0;

More Meddling with Class templates

Using class templates as function arguments parameters

Here is a piece of code where Template classes are sent as arguments , the comments give a clear explanation on the syntax.Here is the link of the code on Github.Click here to execute the code on Cloud IDE.

#include <iostream>

template<class Type>
class Other {
    	Type x;
    	Other(Type y){
        	x = y;

    void first(const Other<int>& o) {/*One way of specifying the formal parameter*/
    	std::cout << o.x << '\n';

    template<typename T> void second(const Other<T>& o) {/*Other way of specifyin formal parameter*/
    	/*Has to be decalred as templated function*/
        std::cout << o.x << '\n';

int main(){
    Other<int> other(123);/*initializing template class constructor*/
    first(other);/*sending templated class as parameters*/

Now you know how template classes are sent as function parameters and how the actual and formal parameters are defined .
The C++ core of NodeJs contains magnificent pieces of C++ writing and its very essential to have a strong hold of C++ to be able to comprehend the lines written and this blog was an attempt at helping you guys achieve it .We are Getting closer and closer to land on the planet on NodeJs C++ core ….Its just matter of time !!!
Till then …………….As Usual , Happy Coding 😀

Cracking the Source: UnderStanding NodeJs Source Code -1

………!!!!…………!!!!!!!!……..!!!!!! Its time for some extreme engineering 😛
Welcome to the series Cracking source ..
This is the first post in the series of posts to come about understanding the source code of Node.JS .  Its been enough time since i’ve been using Node as the webserver for all my projects and its time to understand the source and making an attempt to contribute to its repo ! This blog cannot be considered as a step by step tutorials on understand the source of NodeJs , this is the place where i share my learning , experience and views in the course of journey in understanding the source code of NodeJS.

I stumbled upon this pull request on my mobile screen while i was travelling back home few days ago . The request on the this file called tls.js  from the lib folder of the nodejs source tree . This is how the i started exploring tls.js from the source

The tls module uses OpenSSL (uses the underlying OpenSSL executable installed on your system) to provide Transport Layer Security and/or Secure Socket Layer: encrypted stream communication.

So this post is about tls.js and how it works .

Here is the documentation of the TLS api http://nodejs.org/api/tls.html  . Lets get into details of the API tls.getCiphers()

Here is the code of the API tls.getCiphers() from its source

exports.getCiphers = function() {
  var names = process.binding('crypto').getSSLCiphers();
  // Drop all-caps names in favor of their lowercase aliases,
  var ctx = {};
  names.forEach(function(name) {
    if (/^[0-9A-Z\-]+$/.test(name))
        name = name.toLowerCase();
    ctx[name] = true;
  return Object.getOwnPropertyNames(ctx).sort();

process.binding() is a Javascript interface for the C++ core of Node . So process.binding(‘crypto’).getSSLCiphers will result in execution of corresponding function from the c++ core of Node , here is the link to source of getSSLCiphers() from the c++ core https://github.com/joyent/node/blob/master/src/node_crypto.cc. We shall get into the C++ core in the further posts to come .
The C++ core returns an array contains all Cipher names .
Later the array of names are iterated using forEach() method of node . Each names are tested against the Regular Expression /^[0-9A-Z\-] ,Any string that begins/ends and containing digits (0-9) and alphabets in caps (A-Z) and another character ‘-‘ are matched and set as keys in the ctx{} object . And at the end the keys of the object ctx containing the names of the Cipher are returned as an array in sorted order using the following line of code

return Object.getOwnPropertyNames(ctx).sort();

Lets use this API from the tls library , and here is the code

var tls = require('tls');
var cipher = tls.getCiphers();

Lets get into the C++ core in the posts to come in future , but thats it for now .Wait for more exciting posts to come in my journey through source of Node .
Till then happy Coding 😀