Monday, 20 February 2017

Connecting Mysql with Node.js

We know  that NodeJS is becoming popular due to its fast prototype development and implemention with more performance than Python or any other programming language.
Lets start by creating a package.json file.

To create package.json file . Goto directory where you want to setup files,then run command
npm init.
Make sure that you have installed version of Node and NPM.

Now lets install mysql.
You can run 
                  npm install mysql

//create a file named database.js for database related options

const mysql = require('mysql'); //export required module

//create connection object 
const connection = mysql.createConnection({
    'host': 'localhost',
    'port': 3306,
    'user': 'username',
    'password': 'password',
    'database': 'databasename'
});

//test connection 
connection.connect(function(error) {
    if (error) {
        console.log('error code is ' + error.code);
    } else {
        console.log('connection successfull');
    }
});

//check for error in connection
connection.on('error', (error) => {
    console.log(`error code is ${error.code}`);
});

//export the module to use with other files
module.exports = connection;  



Now enter touch index.js to create a new file.

open index.js in editor and write

const connection = require('./database.js');
//make a query
connection.query('show databases, (error, result) => {
    if (error) {
        console.log('error in processing query');
    } else {
        console.log(JSON.stringify(result));
    }
});


Thanks for reading.Please Mention your comment if you have any questions regarding this.


Friday, 10 February 2017

Common operations in Binary Search Tree


In This Post,I would like to explain the simple structure on how to 
create binary search tree using python classes.In binary search tree,
left child is always smaller than parent and right child is 
greater than parent.This property makes it easy for operations like 
addition,search,deletion of node.In Real world,you may have seen of phone 
directory in which we search by getting common string numbers.
 


class Node:

    #initialize node structure   
    def __init__(self,data):
      self.data = data
      self.left = None      
      self.right = None

   #get minimum node from tree starting from this node   
    def get_min_Node(self):
      current = self      
      while current.left is not None:
         current = current.left
      return current.data

    #get maximum node from tree starting from this node   
     def get_max_Node(self):
      current = self      
      while current.right is not None:
         current = current.right
      return current.data

#insert node in binary tree
def insert(self,data):
      current = self
      if current is None:
         current = Node(data)
      if current.left is None and current.data>data:
         current.left = Node(data)
      elif current.right is None and current.data < data:
         current.right = Node(data)
      elif current.data >data:
         insert(self.left,data)
      else:
         insert(self.right,data)
#delete node from binary tree
def delete_Node(self,data):

   #check for none type    
    if self is None:
        return self
    #if data is greater than node data
    elif data>self.data:
        self.right = delete_Node(self.right,data)
    #if data is less than node
    elif self.data>data:
        self.left = delete_Node(self.left,data)
    else:
        if self.left is None:
            tmp = self.right
            self = None            
            return tmp
        elif self.right is None:
            tmp = self.left
            self = None            
            return tmp
        #get minimal node from right subtree
        tmp = self.right.get_min_Node()
        #put data into self
        self.data  = tmp.data
        #delete the minimal subtree from right
        self.right = delete_Node(self.right,tmp.data)
    return self
#print inorder traversal of binary tree
def inorder(self):
   if self is None:
      return   
   inorder(self.left)
   print(self.data)
   inorder(self.right) 

#print preorder traversal of binary tree
def preorder(self):
   if self is None:
      return   
   print(self.data)
   inorder(self.left)
   inorder(self.right)

#print postorder traversal of binary tree
def postorder(self):
   #if node is null or None 
   if self is None:
      return   

   #if node is not none
   inorder(self.left)
   inorder(self.right)
   print(self.data)

#get height of tree
def height(self):
   if self is None:
      return 0   
   else:
      lheight = height(self.left)
      rheight = height(self.right)

      if lheight > rheight:
         return lheight + 1      
      else:
         return rheight + 1
#level order traversal of tree
def level_order(self):
   #get height of tree
   h = height(self)
   for i in range(1,h+1):
      print_level(self,i)

def print_level(self,level):

   if self is None:
      return   
   if level == 1:
      print(self.data)
   else:
      if level > 1:
         print_level(self.left,level-1)
         print_level(self.right,level-1)

a = Node(30)
insert(a,22)
insert(a,1)
insert(a,36)
#print preorder traversal of binary tree
preorder(a)
root = delete_Node(a,36)
#print tree
preorder(a)


Saturday, 28 January 2017

Fibonacci Series

Lets generate fibonacci series using generators in python

The Fibonacci Sequence is the series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The next number is found by adding up the two numbers before it.

  • The 2 is found by adding the two numbers before it (1+1)
  • The 3 is found by adding the two numbers before it (1+2),
  • And the 5 is (2+3),
  • and so on!


num = int(input())

#method to generate fibonacci sequence
def fibo(n):
    a,b = 0,1
    for i in range(n):
        yield a
        a,b = b,a+b
#print the numbers
for i in fibo(num):
    print(i)

Diamond Pattern


How to print diamond pattern.
For printing pattern like this,

  1. We need to take care of spaces,
  2. print the required number of spaces.

lets checkout the program in python
//take number of rows input from user
num = int(input())
for i in range(0,num):
#loop for printing the spaces as required first half of diamond
    for j in range(1,num-i):
        print(' ',end='')
    print((2*i+1)*'*')
#print other half of diamond
for i in range(1,num):
    print(' '*i,end='')
    print((2*(num-i-1)+1)*'*')



#If you have any doubt and want to do in any other language.You can simply post a comment here.


Saturday, 25 April 2015

Reverse a linked list using recursion and without recursion

#include<stdio.h>
#include<stdlib.h>

/* Link list node */
struct node
{
    int data;
    struct node* next;
};
 node * reverse1( node * ptr , node * previous) //with recursion
{
    node * temp;
    if(ptr->next == NULL) {
        ptr->next = previous;
        return ptr;
    } else {
        temp = reverse1(ptr->next, ptr);
        ptr->next = previous;
        return temp;
    }
}
/* Function to reverse the linked list */
static void reverse(struct node** head_ref)  //without recursion
{
    struct node* prev   = NULL;
    struct node* current = *head_ref;
    struct node* next;
    while (current != NULL)
    {
        next  = current->next;
        current->next = prev;  
        prev = current;
        current = next;
    }
    *head_ref = prev;
}

/* Function to push a node */
void push(struct node** head_ref, int new_data)
{
    /* allocate node */
    struct node* new_node =
            (struct node*) malloc(sizeof(struct node));
           
    /* put in the data  */
    new_node->data  = new_data;
               
    /* link the old list off the new node */
    new_node->next = (*head_ref);  
       
    /* move the head to point to the new node */
    (*head_ref)    = new_node;
}

/* Function to print linked list */
void printList(struct node *head)
{
    struct node *temp = head;
    while(temp != NULL)
    {
        printf("%d  ", temp->data);  
        temp = temp->next;
    }
}  


int main()
{
    /* Start with the empty list */
    struct node* head = NULL;
 
     push(&head, 20);
     push(&head, 4);
     push(&head, 15);
     push(&head, 85);    
   
     printList(head);  
     head=reverse1(head,NULL);                    
     printf("\n Reversed Linked list \n");
     printList(head);  
 
    return 0;
}

Thursday, 23 April 2015

Prime Number

Program to check for prime number:
Solution:
#include <stdio.h> int main() { int n, i, c = 0; printf("Enter any number n:"); scanf("%d", &n); /*logic*/ for (i = 1; i <= n; i++) { if (n % i == 0) { c++; } } if (c == 2) { printf("n is a Prime number"); } else { printf("n is not a Prime number"); } return 0; }
Prime number between two number is given by:

#include <stdio.h>
int main()
{
  int n1, n2, i, j, flag;
  printf("Enter two numbers(intevals):");
  scanf("%d %d", &n1, &n2);
  printf("Prime numbers between %d and %d are: ", n1, n2);
  for(i=n1+1; i<n2; ++i)
  {
      flag=0;
      for(j=2; j<=i/2; ++j)
      {
        if(i%j==0)
        {
          flag=1;
          break;
        }
      }
      if(flag==0)
        printf("%d ",i);
  }
  return 0;
}

To Find GCD of two number

Problem: To find GCD of two number.
Solution:

#include <iostream>

using namespace std;
int gcd_iter(int u, int v) 
{
  int t;
  while (v) 
  {
    t = u; 
    u = v; 
    v = t % v;
  }
  return u < 0 ? -u : u; 
}
int main()
{
  int n=3,m=6;
  int result=gcd_iter(n,m);
  cout<<result;
   return 0;
}