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]
        print(LastCoinForCoinCent)
        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)

main()

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 😀

Advertisements

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 ??

PUBLIC KEY ENCRYPTION

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 ??”

CREATING PRIVATE KEYS USING OPENSSL

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

CREATING PUBLIC KEYS USING OPENSSL
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;

          ].join(&quot;\n&quot;).red;

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

tls.createServer(options, function (s) {
  s.write(msg+&quot;\n&quot;);
  s.pipe(s);
}).listen(8000);

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 127.0.0.1:8000

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 {
    public:
		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;
    cout<<instance.add(1,2)<<endl;
    cout<<instance.multiply(5,2)<<endl;
}

.
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{
	public:
		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 {
	public:
		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 {
	public:
		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()
{
   
   test_template<int>(2);
   test_template<double>(3.0);
   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 {
    
    public:
    	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*/
    second(other);
}


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();
console.log(cipher);

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 😀

Installing/setting up Neo4j/Cipher-query-terminal in ubuntu

Fascinated by the world of Graphs??Ever wondered how to install/setup the popular graphDB neo4j and the local console to execute your cipher queries (The Graph DB queries) ??If so , read on 😀

Neo4j provides webconsole to execute queries at console.neo4j.org , but you need to have it installed on your local machines to test things out during development(There are drivers available to use neo4j using almost all popular languages). This is a short post describing the setting up of the popular graphDb neo4j in ubuntu
Step-1: Setup Oracle 7
Neo4j needs JVM (its java based) , setup Oracle Java 7 which is a dependency to run Neo4J ,here are the set of instructions to execute from the terminal to setup Oracle Java 7


sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
sudo apt-get install oracle-java7-set-default

Step-2: Download and extract Neo4J
Download  extract Neo4j server  from Neo4j-server-Download and extract it

Neo4j-server
Neo4j-server

Step-3:Run the Neo4j server
Go to the extracted folder nd execute the following commands to setup neo4j

cd bin
sudo ./neo4j-installer install
./neo4j start

This starts the Neo4j server on the default port 7474

step-4:Go to browser and checkout localhost:7474
Once the Neo4J server is running,Open you browser and visit localhost:7474 , here is the screenshot

Neo web interface running locally
Neo web interface running locally

Step-5:Execute the cipher queries
Now using the browser interface you can easily execute the cipher queries agianst the Neo4J server running locally

Local cipher
Local cipher

In case you want to use the command line shell to exeute cipher-queries just shell the neo4j-shell , from the /bin start the neo4j-shell

cd bin
./neo4j-shell

tadaaaaaaaaaaaa!!The cipher-query shell opens And start executing the cipher queries 🙂 Here is the screenshot

Cypher-console
Cypher-console

Welllllllll , this is th end of the post , i hope that this post helped you guys setup neo4j and cypher-query-console on your machines and get started.There will be series of posts coming up soon on using neo4j alongside NodeJs server , till then Happy coding 😀
 

Intro to AngularJS and Client Server communication using nodeJS and AngularJS:Posting data to the Node-Express server using AngularJS

Hmmmm , its time for a new post !!! After the last post on Depth First Search in python , now you have a U-turn ahead and this post is on achieving client server communication using NodeJS server in the backend and AngularJS in the front end  !!!

If your curious on achieving client-server communication using backbone.JS and nodeJS , here is the link
In case you try the same using websockets and nodeJS , here is the link for the post .

And here is the github link for the codes posted in this blog !

Lets get started with how to achieve it using Angular and NodeJS as server .This might be a very simple task for a AngularJS developer ,but the blogs are not always meant for experts 😛  Since the blog is aimed at web developers who are starting to develop web applications by using NodeJs in the backend and AngularJS in the front end , ill try to keep the post as simple and easy as possible .

So , Lets get started ……….

Before we begin here are the basics of AngularJS ,

  • AngularJS provides a set of html attributes which starts with ng , example ng-app,ng-controller,ng-view,ng-click , these attributes are used to direct and communicate with angularJS .
  • ng-app attribute tells angularJS to bootstrap or start the application , usually this is associated with the html tag of the application , example 
<html ng-app>
     <head>
     </head>
     <body>
         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
     </body>
</html>

 controllers in AngularJS

  • Using controllers you can tell AngularJS ,which of javascript variables or primitives forms the Models data which will be used the views
  • Angular by default passes this object called $scope for every Angular controller
  • By assigning the data to this $scope object you’ll
    be telling angular that the assigned data are those which are supposed to be the used by views to render HTML , this is the model data

To brief , the controllers in angularJS have three responsibilities
1.Initializing the model variables
2.Give views the access to the models data by assigning them to the $scope variable
3.It provides the code and logic to execute while users interact with the various parts of the controllers

$http is another directive passed onto a controller and can be made use of to interact with server (make GET,POST requests etc…) , we’ll be using same directive in this post to interact with the server

One of the amazing feature of Angular which makes application development really easy is the ability of Angular’s controller to bind the data of an HTML element (like a input box , text box or any widget) with the models data and it also provides event handlers/methods to propagate the changes to the model data automatically  

Here is an simple example of how controller binds the data and the views , a angular controller is binded to the application by using ng-controller attribute  within a html element , the controller will be incharge of the application within the scope of that html tag,the explanation is given after the code example  

<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>
  </head>
    <body>
      <div ng-controller="firstController">
      <!--firstController is the name of the controller function, its scope expands within this div element -->
        <input ng-model="modelData" >
       <!--
      -->
      <p>{{modelData}}</p>
    </div> 

       <script>
         function firstController($scope){ //controller function
           $scope.modelData='';
 /*This is the same variable which is used in html,now the value is variable is binded the input box data*/
           $scope.$watch('modelData',function(newVal,oldval,scope){
             console.log("New: "+newVal);/*Watch the browser console*/
           },true);
           /*$scope.$watch listens to the changes in the modelData variable ,
             The value in the modelData variable is changed when the value in the input box is changed ,
             these are automatically bound together  using <input ng-model="modelData" > */
         }
       </script>
     </body>
</html>

ng-model=”modelData”, This is like a global declaration of the variable ‘modelData’ within the controllers scope(within div element in this case) without the need to declare it anywhere .This variable now can be accessed as model data inside the html to render by using it inside the double braces {{}}, this is how you can bind the data with the views . Now lets say you have some application logic to be performed using this data , so you need to be able to access the variable within the Javascript too , the variable `modelData` can be accessed only within the controller function (inside your javascript) which is incharge the current html scope , in this case the data is accessible through the firstController() , controller function (since this is the controller function for the input elements scope,that is, the input element inside the scope of the div with ng-controller=”firstController”).Now as i had already mentioned the model’s data can be accessed using the $scope object which is passed onto the controller,so this can be accessed using $scope.modelData inside the controller function of the Javscript
ng-model=”modelData suggests that the $scope.modelData is the controller variable with which this view is associated,and this is how angular easily brings in binding of the views and data with the help of the controller.
Now lets say you have used {{modelData}} at ten different places in your html to render the view , the change to the modelData is automatically propagated to all thee places in views so that the html with new data is rendered
Here is the screenshot on with the browsers console opened

Angular MVC
Angular MVC

Phew!!!!! 😯 Lets now start with the headline of the post …How to communicate to the server from angular ,and how to handle it using NodeJs-express server
Here is the code snippet ang2.html of where angular makes a POST request to the server when user clicks the submit ,

<html ng-app>
<body>
    <form ng-controller='appController' ng-submit="send()">
      <!--send() function from the controller is called on form submission -->
        <textarea ng-model='data.textdata'></textarea>
        <pre>{{data.textdata}}</pre>
        <input type="submit" ngClick="Submit">
        <div><pre>{{response.data}}</pre>
        </div>
        <ng-form>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js">
    </script>
    <script>
        function appController($scope, $http) {
            /*$http directive is used to communicate ot the server */
            $scope.data = {}
            $scope.response = {}

            $scope.send = function () {
                /*executed when submit is clicked*/
                console.log("inside click");
                console.log($scope.data.textdata);

                var posting = $http({
                    method: 'POST',
                    /*posting to /post */
                    url: '/post',
                    data: $scope.data,

                    processData: false
                })
                posting.success(function (response) {
                    /*executed when server responds back*/
                    console.log(response);
                    $scope.response.data = response;
                });
            }
        };
    </script>
</body>

</html>

Here is the server code app.js using node.js-express to handle the POST request from the AngularJS frontend script and respond back to it .

var express = require('express')
, http = require('http'), path = require('path');

var app = express();

app.use(express.static(path.join(__dirname, 'public')));
/*JS client side files has to be placed under a folder by name 'public' */
app.use(express.bodyParser());
/*to access the posted data from client using request body*/
app.post('/post', function (req, res) {
    /* Handling the AngularJS post request*/
    console.log(req.body);
    res.setHeader('Content-Type', 'application/json');
    /*response has to be in the form of a JSON*/
    req.body.serverMessage = "NodeJS replying to angular"
        /*adding a new field to send it to the angular Client */
    res.end(JSON.stringify(req.body));
    /*Sending the respone back to the angular Client */
});

http.createServer(app).listen(3000, function () {
    console.log("Express server listening on port 3000");
});

Create a folder called public and place ang2.html inside it
, Here is the link for the codes published in this post

Here are the screenshots from server and client side ,

Angular posting data
Angular posting data

server handling client angularJS request
server handling client angularJS request

fianlly !!!!!!!!!!!!!!!!thats the end of this post , i hope you guys found this post to be helpful in understanding how to use AngularJS to communicate to the server , will catch up soon with further exciting posts , till then Happy coding 😀

Algorithms using python:Graph Algorithms-1:Depth First search

Firstly hello to all the readers !!After the last and its previous post on node.js , Here is the first post of the series of posts to come related to algorithms using python.In this post Ill be discussing about popular tree traversal algorithm Depth First Search . Using python makes the implementation of the algorithm relatively easy because of the availability of numerous built in data structures like hashes(dictionaries) ……….In this this blog post ill be using dictionaries as the main data structure for most of the operations .I’ve tried my best to enhance the degree of detailing in the post so that folks with even least acquaintance with python can understand the code . So then what are we waiting for??? Lets begin 😛

1.REPRESENTATION OF GRAPH USING DICTIONARIES IN PYTHON

A graph will represented using a JSON like structure . here is an example …

Consider the following graph

Image

Here node A is connected to nodes B,C and E and this is represented as described below

{

‘A’:{‘B’:1,’C’:1 }

}

Using the similar approach here is the representation of the complete graph

{

‘A’:{‘B’:1,’C’:1,’E’:1},

‘B’:{‘A’:1,’D’:1,’F’},

‘C’:{‘A’:1,’G’:1},

‘D’:{},

‘E’:{‘A’:1,’F’:1},

‘F’:{‘B’:1,’E’:1},

‘G’:{}

}

  • Declaration of a dictionary

Declaring an empty dictionary in python very simple , the line below illustrates it

      example_dictionary = {}             

Now lets see given tuples containing the pair of codes between which there exists an edge , how to convert them into graph

representation given above and store them in dictionaries ,Here is the tuple representation of connected nodes of the above graph

[(‘A’,’B’),(‘A’,’C’),(‘A’,’E’),(‘B’,’D’),(‘B’,’F’),(‘C’,’G’),(‘E’,’F’)]

def make_link(G,node1,node2):
	if node1 not in G:
		G[node1]= { }
	(G[node1])[node2]= 1 
	if node2 not in G:
		G[node2]= {}
	(G[node2])[node1]= 1 
	return G 
anil_akg rediff

connections = [('a','g'),('a','d'),('d','g'),('g','c')]
G = {}
for x,y in connections:make_link(G,x,y)

print G 

         

Here are the key points that could help you understand the above operations on dictionary G

G= {} #initializes the empty dictionary
G['A'] = {} #Creates a key 'A' in the dictionaries and assigns the key to a value of another empty hash
(G['A'])['B'] = 1 #Creates a Sub-Hash for key 'A' of the hash,Sub-hash is {'B':1}
print G

Here is the screen shot with the above mentioned operations , this will help you understand the process of representing a Graph similar to JSON using dictionaries .

Image

2.Concept of Depth first search

As wikipedia quotes “Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

Now let us traverse the above graph using Depth-First-Search.Lets start from node ‘A’ and then move to any of its neighbouring nodes,lets say ndoe ‘C’ , mark these nodes when you visit them for the first time , ‘C’ has only one neighbour ‘G’,so move to node ‘G’ .’G’ has no neighbours so now start backtracking,move to the previous node , that is node ‘C’,node has no more unvisited neighbours , ‘G’ has already been visited.So now backtrack to ‘A’ ,since ‘C’ has already been visited now move on to an unvisited node of ‘A’ , lets say ‘B’ , this process repeats till all the nodes of the graph are visited ,Here is the python code to achieve the some

def make_link(g,node1,node2): #function to construct the graph in JSOn like format 
	if node1 not in G:
		G[node1]={}
	(G[node1])[node2]=1
	if node2 not in G:
		G[node2]={}
	(G[node2])[node1]=1

G={} #initializing the empty grapgh
connections = [('A','B'),('A','C'),('A','E'),('B','D'),('B','F'),('C','G'),('E','F')] #tuples representing the connections

for x,y in connections:make_link(G,x,y) #constructing the graph using tuple representation 

print G

def dfs(G,node,traversed):
	traversed[node]=True #mark the traversed node 
	print "traversal:"+ node 
	for neighbour_nodes in G[node]: #take a neighbouring node 
		if neighbour_nodes not in traversed: #condition to check whether the neighbour node is already visited
			dfs(G,neighbour_nodes,traversed) #recursively traverse the neighbouring node 

def start_traversal(G):
	traversed = {} #dictionary to mark the traversed nodes 
	for node in G.keys(): #G.keys() returns a node from the graph in its iteration
		if node not in traversed: #you start traversing from the root node only if its not visited 
			dfs(G,node,traversed); #for a connected graph this is called only once 

start_traversal(G)

The comments in the code explains everything . The worst case time complexity of DFS is of order n*m , ‘n’ is the number of nodes and ‘m’ is no of edges .We’ll thats it for now,hope that this post helped you understand the implementation of D.F.S in python 😀 see you folks soon with more exciting posts,this is the link to the code from my GITHUB profile