Showing posts with label PL 3. Show all posts
Showing posts with label PL 3. Show all posts

Thursday, 20 April 2017

PL 3 A4 Simple LEX and YACC

Simple Calculator program using LEX and YACC:


calc.l:

%{
//declarations for c code
#include<stdio.h>
#include"y.tab.h"
//extern because it is declared in yacc file and used here   
extern int yylval;

%}

//regular expressions and corresponding actions for input streams read
%%
[0-9]+ {
    yylval=atoi(yytext);
    return NUMBER;
    }   
    //If any number is encountered yylval stores its value and we are returning token number which shows yylval's type ie int

[\t];    //we are ignoring white spaces
[\n] return 0; 
. return yytext[0];  //return all the other characters as it is
%%

int yywrap()   //returns 1 when end of file is reached otherwise its value is 0
{
return 1;
}


calc.y :

//for c declarations
%{
#include<stdio.h>
 #include<time.h>
int flag=0;
extern FILE* yyin;    //file pointer by default points to terminal
%}

//for declarations in yacc
%token NUMBER        //declaring token NUMBER
%left '+''-'        //to maintain associativity
%left '*''/''%'
%left '('')'

//context free grammar rules and corresponding action
%%
ArithematicExpression:E{
    printf("\n Result=%d\n",$$);
    return 0;
    }

E:E'+'E{$$=$1+$3;}    //$$ refers to non-terminal on left side, $1 to first E on right and so on
|E'-'E{$$=$1-$3;}    //Pseudo varibles in {} describe action to be performed for given grammar rule
|E'*'E{$$=$1*$3;}
|E'/'E{$$=$1/$3;}
|E'%'E{$$=$1%$3;}
|'('E')'{$$=$2;}
|NUMBER{$$=$1;}
;
%%

void main()
{
clock_t starttime;
clock_t endtime;
double timeinterval;
int i;
FILE* fp=fopen("expressions.txt","r");        //file contains expression to be evaluated
yyin=fp;

starttime=clock();
yyparse();     //yyparse() in turn calls yylex()

endtime=clock();
timeinterval=(double)(endtime-starttime)/CLOCKS_PER_SEC;
printf("Time required for execution=%lf Seconds.\n",timeinterval);

if(flag==0)
{
printf("\n ENTERED ARETHEMATIC EXPRESSION IS VALID \n\n");
}

}

void yyerror()
{
printf("\n ENTERED ARETHEMATIC EXPRESSION IS INVALID \n\n");
flag=1;
}


OUTPUT: 


PL 3 LEX and YACC installation in Ubuntu

LEX and YACC is very simple to install on Ubuntu. Just follow the three commands:

1)sudo apt-get update
2)sudo apt-get install flex       //flex package required for lex
3)sudo apt-get install bison    //bison package required for yacc

Screenshots for the same are attached below:

1)


2)


3)

Monday, 27 February 2017

Write an application to parse input text file concurrently and compare the result of concurrent parsing with serial parsing ( Use concurrent YACC parser)


CODE(assign.l):

%{
#include<stdio.h>
#include "y.tab.h"

#define YYSTYPE int    //to avoid global var coz multiple instances
%}
%option reentrant bison-bridge

%%
[0-9]+ {
          *yylval=atoi(yytext);    //to refer to address of yylval
          return NUMBER;
       }
[\t] ;
[\n] return 0;
. return yytext[0];
%%
int yywrap(yyscan_t yyscanner)  //parser object in bracket
{
return 1;
}


CODE(assign.y):


 %{
    #include<stdio.h>
    #include<stdlib.h>
    #include<omp.h>
   
    #define YYSTYPE int

    int numofthreads,expsperthread;
    char inputfilename[30];
%}
%token NUMBER

%left '+' '-'
%left '*' '/' '%'
%left '(' ')'

%pure-parser
%lex-param {void * scanner}
%parse-param {void * scanner}

%%

ArithmeticExpression: E{
         
         //printf("\nResult=%d\n",$$);
     
         return $$;
        }
E:E'+'E {$$=$1+$3;}
 |E'-'E {$$=$1-$3;}
 |E'*'E {$$=$1*$3;}
 |E'/'E {$$=$1/$3;}
 |E'%'E {$$=$1%$3;}
 |'('E')' {$$=$2;}
 | NUMBER {$$=$1;}
;

%%

void func()
{
void * scanner;
    yylex_init(&scanner);        /*parser object created ie scanner initialized and destroyed*/

FILE *fp;
fp=fopen(inputfilename,"r");

int i,j;

int tid;
int res;
 
tid=omp_get_thread_num();

char *s=malloc(100);
size_t n=100;

for(i=0;i<(expsperthread*tid);i++)        //to skip some lines
  {
    getline(&s,&n,fp);
  }

yyset_in(fp,scanner);

for(j=0;j<expsperthread;j++)
  {
    res=yyparse(scanner);            //invoking parser  which invokes lexer

    printf("%dth Expression=%d is given by Thread %d\n",(expsperthread*tid+j+1),res,tid);
  }

    yylex_destroy(scanner);

fclose(fp);
}

void main()
{
printf("Enter Input Text File Name\n");
scanf("%s",inputfilename);
printf("Enter Number of threads to be created\n");
scanf("%d",&numofthreads);
printf("Enter Number of Arithmetic Expressions to be evaluated by each thread\n");
scanf("%d",&expsperthread);

#pragma omp parallel num_threads(numofthreads)
  {
    func();
  }
}

int yyerror()
{
   printf("\nArithmetic expression is Invalid\n\n");
}

CODE(file.txt):

2+3
3+4
4+5
5+6
1*2
2*3
3*4
4*5
5*6
2-1
3-2
4-3
5-4
6-5
7+5
5*7
34+790
120+210
12*23
1+2

OUTPUT:

[pl3@pl3]$ lex test.l
[pl3@pl3]$ yacc -d test.y
[pl3@pl3]$ ls
a.out  lex.yy.c  file.txt  assign.l  assign.l~  assign.y  assign.y~  y.tab.c  y.tab.h
[pl3@pl3]$ gcc -fopenmp lex.yy.c y.tab.c
[pl3@pl3]$ ./a.out
Enter Input Text File Name
test1.txt
Enter Number of threads to be created
5
Enter Number of Arithmetic Expressions to be evaluated by each thread
3
7th Expression=12 is given by Thread 2
13th Expression=1 is given by Thread 4
14th Expression=1 is given by Thread 4
15th Expression=12 is given by Thread 4
4th Expression=11 is given by Thread 1
8th Expression=20 is given by Thread 2
1th Expression=5 is given by Thread 0
9th Expression=30 is given by Thread 2
10th Expression=1 is given by Thread 3
2th Expression=7 is given by Thread 0
3th Expression=9 is given by Thread 0
5th Expression=2 is given by Thread 1
11th Expression=1 is given by Thread 3
6th Expression=6 is given by Thread 1
12th Expression=1 is given by Thread 3
[cnlab@localhost 3]$ ./a.out
Enter Input Text File Name
test1.txt
Enter Number of threads to be created
3
Enter Number of Arithmetic Expressions to be evaluated by each thread
3
7th Expression=12 is given by Thread 2
8th Expression=20 is given by Thread 2
1th Expression=5 is given by Thread 0
9th Expression=30 is given by Thread 2
4th Expression=11 is given by Thread 1
5th Expression=2 is given by Thread 1
6th Expression=6 is given by Thread 1
2th Expression=7 is given by Thread 0
3th Expression=9 is given by Thread 0

Saturday, 25 February 2017

Implement an calculator (64 bit Binary Multiplication) application using concurrent lisp

The following lisp program shows implementation of a calculator:

CODE(calculator.lisp):

(write-line "Welcome to a Calculator Program using Concurrent Lisp")     

(defvar num1)     
(defvar num2)
(defvar result)

(defun square(x)
(write-line "SQUARE of first number is:")
(setf result (* x x))
(format t "~D" result ))

(defun cube(x)
(write-line "CUBE of second number is:")
(setf result (* x x x))
(format t "~D" result ))

(defun sine(x)
(write-line "SINE of first number is:")
(setf result (sin x))
(format t "~D" result ))

(defun tangent(x)
(write-line "TANGENT of first number is:")
(setf result (tan x))
(format t "~D" result ))

(defun cosine(x)
(write-line "COSINE of first number is:")
(setf result (cos x))
(format t "~D" result ))

(defun exponential(x)
(write-line "EXPONENTIAL FUNCTION of first number is:")
(setf result (exp x))
(format t "~D" result ))

(defun exponential1(x y)
(write-line "EXPONENTIAL FORM of BASE AND POWER is:")
(setf result (expt x y))
(format t "~D" result ))

(defun logarithm(x)
(write-line "LOGARITHM of first number to base 2 is:")
(setf result (log x 2))
(format t "~D" result ))

(defun logarithm1(x)
(write-line "LOGARITHM of first number to base 10 is:")
(setf result (log x 10))
(format t "~D" result ))

(write-line "Enter two numbers:") 
(setf num1(read)) 
(setf num2(read))
 

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(+ num1 num2))
    (print "ADDITION in binary:")
    (format t "~b" result )
    (print "ADDITION in decimal:")
    (format t "~D" result ))))

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(- num1 num2))
    (print "SUBTRACTION in binary:")
    (format t "~b" result )
    (print "SUBTRACTION in decimal:")
    (format t "~D" result ))))

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(* num1 num2))
    (print "MULTIPLICATION in binary:")
    (format t "~b" result )
    (print "MULTIPLICATION in decimal:")
    (format t "~D" result ))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(/ num1 num2))
    (print "DIVISION in binary:")
    (format t "~b" result )
    (print "DIVISION in decimal:")
    (format t "~D" result ))))

(sb-thread:make-thread(lambda()(progn (sleep 0)(setf result(mod num1 num2))
    (print "MODULUS in binary:")
    (format t "~b" result )
    (print "MODULUS in decimal:")
    (format t "~D" result ))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (square num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (cube num2))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (sine num1))))

(sb-thread:make-thread(lambda()(progn (sleep 0)
    (tangent num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (cosine num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (exponential num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (exponential1 num1 num2))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (logarithm num1))))
   
(sb-thread:make-thread(lambda()(progn (sleep 0)
    (logarithm1 num1))))
   
(print (sb-thread:list-all-threads))
(sleep 30 )      

(exit)




OUTPUT:

pl3@pl3:~$ sbcl
This is SBCL 1.3.1.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.

SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses.  See the CREDITS and COPYING files in the
distribution for more information.
* (load "calculator.lisp")   
Welcome to a Calculator Program using Concurrent Lisp
Enter two numbers:
5
3

"ADDITION in binary:" 1000
"ADDITION in decimal:" 8
"SUBTRACTION in binary:" 10
"SUBTRACTION in decimal:" 2
"MULTIPLICATION in binary:" 1111
"MULTIPLICATION in decimal:" 15
"DIVISION in binary:" 101/11
"DIVISION in decimal:" 5/3
"MODULUS in binary:" 10
"MODULUS in decimal:" 2
SQUARE of first number is:25
CUBE of second number is:27
SINE of first number is:-0.9589243
TANGENT of first number is:-3.380515
COSINE of first number is:0.2836622
EXPONENTIAL FUNCTION of first number is:148.41316
EXPONENTIAL FORM of BASE AND POWER is:125
LOGARITHM of first number to base 2 is:2.321928
LOGARITHM of first number to base 10 is:0.69897

(#<SB-THREAD:THREAD FINISHED values: NIL {1003F13763}>
#<SB-THREAD:THREAD "main thread" RUNNING {100399C4D3}>)

Thursday, 23 February 2017

Write an application to and demonstrate the change in BeagleBoard( ARM Cortex A8) /CPU frequency or square wave of programmable frequency.



Following is the code to demonstrate change in  Beagle Bone Board CPU Frequency:

#Code (assignment.py):

import os


print "Current CPU Information"
os.system("cpufreq-info")

print "\n"

#300MHz
print "Changing current frequency to: 300MHz"
os.system("cpufreq-set -f 300Mhz")
os.system("python fact.py")

print "\n"

#600MHz
print "Changing current frequency to: 600MHz"
os.system("cpufreq-set -f 600Mhz")
#os.system("cpufreq-info")
os.system("python fact.py")

print "\n"

#800MHz
print "Changing current frequency to: 800MHz"
os.system("cpufreq-set -f 800Mhz")
os.system("python fact.py")

print "\n"

#1000MHz
print "Changing current frequency to: 1000MHz"
os.system("cpufreq-set -f 1000Mhz")
os.system("python fact.py")

print "\n"

os.system("cpufreq-set -f 300Mhz")   #Restoring back original frequency



#fact.py:

import sys,time
def Factorial():
    n = 100
    fact=1
    for i in range(1,n+1):
       fact=fact*i

start_time=time.time()
Factorial()
print "Time taken in fact.py: %s seconds" % (time.time()-start_time)

#Output:

root@beaglebone:~# python assignment.py
cpufrequtils 008: cpufreq-info (C) Dominik Brodowski 2004-2009
Report errors and bugs to cpufreq@vger.kernel.org, please.
analyzing CPU 0:
  driver: generic_cpu0
  CPUs which run at the same hardware frequency: 0
  CPUs which need to have their frequency coordinated by software: 0
  maximum transition latency: 300 us.
  hardware limits: 300 MHz - 1000 MHz
  available frequency steps: 300 MHz, 600 MHz, 800 MHz, 1000 MHz
  available cpufreq governors: conservative, ondemand, userspace, powersave, performance
  current policy: frequency should be within 300 MHz and 1000 MHz.
                  The governor "userspace" may decide which speed to use
                  within this range.
  current CPU frequency is 300 MHz (asserted by call to hardware).
  cpufreq stats: 300 MHz:68.71%, 600 MHz:3.54%, 800 MHz:25.30%, 1000 MHz:2.45%  (33)

Current frequency: 300MHz
Time taken in fact.py: 0.000475883483887 seconds


Current frequency: 600MHz
Time taken in fact.py: 0.000253200531006 seconds


Current frequency: 800MHz
Time taken in fact.py: 0.000197887420654 seconds


Current frequency: 1000MHz
Time taken in fact.py: 0.000165939331055 seconds

Implement a Multi-threading application for echo server using socket programming in JAVA


The folllowing code implements a multi-threading application for echo server in java:

EchoServer.java:

import java.io.*;
import java.net.*;

public class EchoServer implements Runnable
{
    public Socket client;
 
    public EchoServer(Socket sock)
    {
      this.client = sock;
    }
   
    public EchoServer(int portnum)
    {
        try
        {
            server = new ServerSocket(portnum);    //create new socket
        }
        catch (Exception err)
        {
            System.out.println(err);
        }
    }   

    public void serve()
    {
        try
        {
            while (true)    //wait for client connection
            {               
                Socket client = server.accept();    //accept client connection               
                System.out.println("Connection accepted at :" + client);
                new Thread(new EchoServer(client)).start();   
            }
        }
        catch (Exception err)
        {
            System.err.println(err);
        }
    }
   
    public void run()
    {
        try
        {
           long threadId = Thread.currentThread().getId();                   
           BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));
           PrintWriter w = new PrintWriter(client.getOutputStream(), true);
           w.println("Welcome to the Java EchoServer.  Type 'bye' to close.");                   
           String line;
           do
           {
              line = r.readLine();
              if ( line != null )
              {
                  System.out.println("Received from Client "+ threadId +":"+line);
                  w.println("Echo in client: "+line);
              }
           }
           while ( !line.trim().equals("bye") );
           client.close();   
        }
        catch (Exception err)
        {
            System.err.println(err);
        }       
   
    }

    public static void main(String[] args)
    {
       
        EchoServer s = new EchoServer(9999);
        s.serve();       
    }

    private ServerSocket server;
}


EchoClient.java:

import java.io.*;
import java.net.*;

public class EchoClient
{
    public static void main(String[] args)
    {
        try
        {
            Socket s = new Socket("127.0.0.1", 9999);
            BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
            PrintWriter w = new PrintWriter(s.getOutputStream(), true);
            BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
            String line;
            do
            {
                line = r.readLine();
                if ( line != null )
                    System.out.println(line);
                line = con.readLine();
                w.println(line);
            }
            while ( !line.trim().equals("bye") );
        }
        catch (Exception err)
        {
            System.err.println(err);
        }
    }
}


Output: 


Saturday, 28 January 2017

An Assignment to develop an application using Beeglebone Black/ ARM Cortex A5 development board to simulate the working of signal lights.

The Interfacing of BBB(Beagle Bone Black) with switch and led are shown in figure below. However in this assignment we have interfaced only LED's with BBB(Beagle Bone Black).


The following python code helps to simulate working of signal lights using Beagle Bone Black:

import time
import Adafruit_BBIO.GPIO as a

a.setup("P8_10", a.OUT)    #red LED
a.setup("P8_12", a.OUT)    #yellow LED
a.setup("P8_14", a.OUT)    #green LED

while True:
    a.output("P8_10", a.HIGH) 
    time.sleep(5)
    a.output("P8_10", a.LOW)  
    a.output("P8_12", a.HIGH)
    time.sleep(5)
    a.output("P8_12", a.LOW)
    a.output("P8_14", a.HIGH)
    time.sleep(5)
    a.output("P8_14", a.LOW)


At some Places all the Traffic Lights start blinking at night time after normal execution throughout the day. This situation can be simulated by the following Python code using Beagle Bone Black:


import time
import Adafruit_BBIO.GPIO as a

a.setup("P8_10", a.OUT) #red LED
a.setup("P8_12", a.OUT) #yellow LED
a.setup("P8_14", a.OUT) #green LED
count=10
count_1=4

while True:
    while count>0:
        a.output("P8_10", a.HIGH)
        time.sleep(2)
        a.output("P8_10", a.LOW)   
        a.output("P8_12", a.HIGH)
        time.sleep(2)
        a.output("P8_12", a.LOW)
        a.output("P8_14", a.HIGH)
        time.sleep(2)
        a.output("P8_14", a.LOW)
        count=count-1
    count=10

    while count_1>0:
        a.output("P8_10", a.HIGH)
        a.output("P8_12", a.HIGH)
        a.output("P8_14", a.HIGH)
        time.sleep(1)       
        a.output("P8_10", a.LOW)   
        a.output("P8_12", a.LOW)
        a.output("P8_14", a.LOW)
        time.sleep(2)
        count_1=count_1-1
    count_1=4


An assignment to develop an application using Beeglebone Black/ ARM Cortex A5 development board to simulate the operations of LIFT.


The Intefacing of BBB(Beagle Bone Black) with Switch and LED is as follows:




The following python program helps to simulate operations of LIFT using Beagle Bone Black:

import Adafruit_BBIO.GPIO as g
import time

g.setup("P8_26",g.OUT)       #yellow led i.e. second floor
g.output("P8_26",g.LOW)
g.setup("P8_10",g.OUT)       #red led i.e. first floor
g.output("P8_10",g.HIGH)
g.setup("P9_15",g.OUT)         #green led i.e third floor
g.output("P9_15",g.LOW)
g.setup("P8_14",g.IN)        #switch 1 i.e. button for first floor
g.setup("P8_18",g.IN)         #switch 2 i.e. button for second floor
g.setup("P9_17",g.IN)        #switch 3 i.e. button for third floor
print "The Lift is on First Floor"
current_floor=1

while True:
        if(current_floor==1):
            if(g.input("P8_18")==1):    
                print "The Lift is moving from First to Second Floor"
                g.output("P8_26",g.HIGH)
                time.sleep(1)
                g.output("P8_10",g.LOW)  
                current_floor=2
                continue
            if(g.input("P9_17")==1): 
                print "The Lift is moving from First to Second Floor"
                g.output("P8_26",g.HIGH)
                time.sleep(1)
                print "The Lift is moving from Second to Third Floor"
                g.output("P9_15",g.HIGH)
                time.sleep(1)
                g.output("P8_10",g.LOW)
                g.output("P8_26",g.LOW)
                current_floor=3
                continue

        if(current_floor==2):
            if(g.input("P8_14")==1):           
                print "The Lift is moving from Second to First Floor"
                g.output("P8_10",g.HIGH)
                time.sleep(1)
                g.output("P8_26",g.LOW)
                current_floor=1
                continue
            if(g.input("P9_17")==1):           
                print "The Lift is moving from Second to Third Floor"
                g.output("P9_15",g.HIGH)
                time.sleep(1)
                g.output("P8_26",g.LOW)
                current_floor=3
                continue

        if(current_floor==3):
            if(g.input("P8_14")==1):
                print "The Lift is moving from Third toSecond Floor"
                g.output("P8_26",g.HIGH)
                time.sleep(1)
                print "The Lift is moving from Second to First Floor"
                g.output("P8_10",g.HIGH)
                time.sleep(1)
                g.output("P9_15",g.LOW)
                g.output("P8_26",g.LOW)
                current_floor=1
                continue
            if(g.input("P8_18")==1):
                print "The Lift is moving from Third to Second Floor"
                g.output("P8_26",g.HIGH)
                time.sleep(1)
                g.output("P9_15",g.LOW)
                current_floor=2
                continue