Posts

JDBC Connectivity using Eclipse

 import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.*;   public class mysqlconn { public static void main(String args[]){   try{   Class.forName("com.mysql.cj.jdbc.Driver");   Connection con=DriverManager.getConnection(   "jdbc:mysql://localhost:3306/demo","root","root");   Statement stmt=con.createStatement();   ResultSet rs=stmt.executeQuery("select * from emp");   while(rs.next())   System.out.println(rs.getInt(1)+"  "+rs.getString(2));  int i=17; String name1="smita"; int did=4; int credit =2000; InputStreamReader r1=new InputStreamReader(System.in);     BufferedReader br1=new BufferedReader(r1);             System.out.println("Enter your id");     try { name1=br1.readLine();  }catch(Exception E) {} i=Integer.pa...

Unit Test questions

Unit I 1)Explain Role of Lexical Analyzer in Compiler 2)  Explain use of yyleng, yytext, yylval, yywrap in yacc.. Unit II 1)Construct LR(0) item-set for following grammar. E E + E | E * E | id where + , * , id are terminals. 2) Explain left factoring with example. Unit III 1)Generate Quadruple for a = b + (c * d) / f 2) Explain  Intermediate code generation of declaration statement. Unit IV 1)Explain Parameter passing methods along with suitable example [8] b) Explain Function Call and Return with suitable example Unit V 1)Explain Simple Code Generator Algorithms along with suitable example. [8] 2) What is DAG? Explain the role of DAG in Code Generation Unit VI 1)What is loop transformations? What are its types 2)Explain Following Data Flow Properties Available Expressions, Reaching Definitions

Unit Wise Assignments

Unit Wise Assignments  Unit I 1)Explain  LEX features and specification. 2)Write regular expression for comment,operators,datatype,identifier ,keywords. Unit II 1) Expalin automatic construction of parsers using YACC. (Explain for calculator with lex and yacc specifications) 2) Explain Need of semantic analysis. Unit III 1)Explain with exampleThree-Address codes: Quadruples, Triples and Indirect Triples 2)Explain S and L attributed grammar Unit iv 1)Explain Activation Record, 2)Explain display mechanism Unit V 1)Explain Issues in code generation. 2)Explain Register allocation and Assignment, Unit VI 1) Explain common sub-expression elimination, variable propagation, code movement, strength reduction, dead code elimination. 2)Explain Data flow equations and iterative data flow analysis.

instruction scheduling with topological sorting of a DAG

// A C++ program to print topological sorting of a DAG #include<iostream> #include <list> #include <stack> using namespace std; // Class to represent a graph class Graph { int V; // No. of vertices' // Pointer to an array containing adjacency listsList list<int> *adj; // A function used by topologicalSort void topologicalSortUtil(int v, bool visited[], stack<int> &Stack); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // prints a Topological Sort of the complete graph void topologicalSort(); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v̢۪s list. } // A recursive function used by topologicalSort void Graph::topologicalSortUtil(int v, bool visited[], stack<int> &Stack) { // Mark the current node as visited. visited[v] = true;...

A Register Allocation algorithm that translates the given code into one with a fixed number of registers.

//C code for  A Register Allocation algorithm that translates the given code into one with a fixed number of registers. #include<stdlib.h> #include<stdio.h> /* We will implement DAG as Strictly Binary Tree where each node has zero or two children */ struct bin_tree { char data; int label; struct bin_tree *right, *left; }; typedef struct bin_tree node; /* R is stack for storing registers */ int R[10]; int top; /* op will be used for opcode name w.r.t. arithmetic operator e.g. ADD for + */ char *op; /* insertnode() and insert() functions are for adding nodes to tree(DAG) */void insertnode(node **tree,char val) { node *temp = NULL; if(!(*tree)) { temp = (node *)malloc(sizeof(node)); temp->left = temp->right = NULL; temp->data = val; temp->label=-1; *tree = temp; } } void insert(node **tree,char val) { char l,r; int numofchildren; insertnode(tree, val); printf("\nEnter number of children of %c:",val); scanf("%d...

Implementation of Code optimization

//c code for illustrating Code optimization #include<stdio.h> #include<stdlib.h> #include<string.h> #include<ctype.h> struct TAC { char res[5]; char op[2]; char arg1[5]; char arg2[5]; }quad[10]; struct ref { char * id; int label; struct node *ptr; }ref[10]; int cnt=0; int n; typedef struct node { struct node *left; struct node *right; char * val; char arg1[10]; char arg2[10]; char lable1; char label2; }node; struct node *nptr; struct node *ptr; void printtree(); node * mknode(node *left,node *right,char *val,char *arg1,char *arg2,char l1,char l2); int search(char*); void main() { int i,sres; printf("Enter how many TAC"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter res"); scanf("%s",quad[i].res); printf("Enter op"); scanf("%s",quad[i].op); printf("Enter arg1"); scanf("%s",quad[i].arg1); printf("Enter arg2...

Implementation of Three address code generation

Contents of tac.l file  %{ #include "y.tab.h" #include <string.h> char * split(char* s,char* delimeter); %} relop >=|<=|>|<|==|!= number [0-9]+ %% [\n\t ]+ {;} "if" {return IF;} "while" {return WHILE;} "for" {return FOR;} "else" {return ELSE;} "int"|"string"|"char"|"double" { return TYPE;} [a-z]([a-z]|[0-9])* { yylval.tuple.result = strdup(yytext); return identifier; } [0-9]+  {yylval.tuple.num= atoi(yytext); return number;} {relop} { yylval.tuple.arg1 =strdup(yytext); return RELOP;}  [-+*=/;] {return yytext[0];} [(){}]               {return yytext[0];} %% int yywrap(void) { return 1; } Contents of tac.y file  %{     int yylex();     void yyerror(char* s);     #include <stdio.h>     #include <stdlib.h>     #include <string.h>     char* symbols[1000];     int symbol...

Implementation of Semantic analysis (Type checking)

Contents of type1.l file  %{ #include<stdio.h> #include<string.h> #include"y.tab.h" %} %% [a-zA-Z]+[a-zA-Z0-9]*"(" {strcpy(yylval.DataType,yytext);return function;} int|float|char {strcpy(yylval.DataType,yytext); return Type;} [a-zA-Z]+[a-zA-Z0-9]*"," {strcpy(yylval.DataType,yytext);return parameter;} [a-zA-Z]+[a-zA-Z0-9]*"){}" {strcpy(yylval.DataType,yytext);return functionbody; } ");" {strcpy(yylval.DataType,yytext);return functioncall;} [a-zA-Z]+[a-zA-Z0-9]* {strcpy(yylval.ID,yytext); return Name;} [0-9]+ {strcpy(yylval.DataType,"int"); return Type;} [0-9]+.[0-9]+ {strcpy(yylval.DataType,"float"); return Type;} "'"[a-zA-Z]+"'" {strcpy(yylval.DataType,"char"); return Type;} ";" return SC; "=" return EQ; "," return C; "\n" {} %% Contents of type1.y file  %{ #include<stdio.h> #include...

Implementation of Symbol Table using Lex

File name sym.l %{ #include<stdio.h> #include<string.h> typedef struct node {     char ID[10],DataType[10];     struct node * next; } node_t; node_t *head = NULL,*temp=NULL,*current=NULL; %} %% int|float|char {if(head==NULL){head = (node_t*)malloc(sizeof(node_t)); strcpy(head->DataType,yytext);}else{strcpy(temp->DataType,yytext);}} [a-zA-Z]+[a-zA-Z0-9]* {if(head->next==NULL){strcpy(head->ID,yytext);head->next=NULL;}else{strcpy(temp->ID,yytext);temp->next=NULL;}} ";"  {if(temp==NULL){temp=(struct node*)malloc(sizeof(struct node));head->next=temp;}else{temp->next=(struct node*)malloc(sizeof(struct node));temp=(node_t*)temp->next;}} "\n" {node_t *current = head;     while (current != NULL) {         printf("%s\t%s\n", current->ID,current->DataType);         current = current->next;     }             ...

Implementation of Calculator using lex and yacc

file name Cal.l  %{ #include<stdio.h> #include "y.tab.h" //extern int yylval; %} %% [0-9]+ { yylval=atoi(yytext); return NUMBER; } [\n] return 0; . return yytext[0]; %% int yywrap() { return 1; } file name  cal.y %{ #include<stdio.h> int flag=0; %} %token NUMBER %left '+' '-' %left '*' '/' '%' %left '(' ')' %% ArithmeticExpression: E{          printf("\nResult=%d\n",$$);          return 0;         }; 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;} ; %% int main() {   yyparse();   if(flag==0)    printf("\nEntered arithmetic expression is Valid\n\n");   return 0; } int yyerror() {    printf("\nEntered arithmetic expression is Invalid\n\n");    flag=1;    re...

Implementation of Lexical Analyzer

%{ int lc=0; %} %% printf printf("\nPrintf found at line no. %d",lc); scanf  printf("\nScanf found at line no. %d",lc); if | else | while | do | switch | case | for | return printf("\n%s Keyword found at line no. %d ",yytext,lc); "void main" printf("\n%s Keyword found at line no. %d ",yytext,lc); \"[^"]*\" printf("\nQuoted string found at line no. %d",lc); #include | #include<stdio.h> printf("\nHeader found at line no. %d",lc); int | float | char | double | long printf("\n%s Datatype found at line no. %d",yytext,lc); ";" | "," | ":" | "{" | "}" | "(" | ")" | "." printf("\n%s Punctuation Symbol found at line no. %d",yytext,lc); [a-z]+[a-z,0-9]* printf("\n %s Variable found at line no. %d\n",yytext,lc); [0-9]+ printf("\n%s Number found at l...

List of assignments for LP IV

1. Implement a Lexical Analyzer using LEX for a subset of C.  2. Implement a parser for an expression grammar using YACC and LEX for the subset of C. Cross check your output with Stanford LEX and YACC. 3. Generate and populate appropriate Symbol Table. 4. Implementation of Semantic Analysis Operations (like type checking, verification of function parameters, variable declarations and coercions) possibly using an Attributed Translation Grammar. 5. Implement the front end of a compiler that generates the three address code for a simple language. 6. A Register Allocation algorithm that translates the given code into one with a fixed number of regsters. 7. Implementation of Instruction Scheduling Algorithm. 8. Implement Local and Global Code Optimizations such as Common Sub-expression Elimination, Copy Propagation, Dead-Code Elimination, Loop and Basic-Block Optimizations.  9. Mini-Pr...

MongoDB code for Mapreduce,Aggregation and Index

[student@localhost ~]$ su Password: su: Authentication failure [student@localhost ~]$ su Password: [root@localhost student]# systemctl start mongod [root@localhost student]# ./mongo bash: ./mongo: No such file or directory [root@localhost student]# mongo MongoDB shell version: 2.4.6 connecting to: test > use spp switched to db spp > db.createCollection("fruits"); { "ok" : 1 } > db.fruits.insert({"name":"Apple","cost":200}) > db.fruits.insert({"name":"Apple","cost":200}) > db.fruits.insert({"name":"Apple","cost":300}) > db.fruits.mapReduce(function(){emit(this.name,this.price);}function(key,values){return Array.sum(values)},{out:"MapReduce_F"}).find(); Thu Jan  1 14:51:33.905 SyntaxError: Unexpected token function > db.fruits.mapReduce(function(){emit(this.name,this.cost);}function(key,values){return Array.sum(values)},{out:...

Java MongoDB Connectivity -code snippet for Insert,Update,Search,Delete operations

Insert Save a document (data) into a collection (table) named “user”. DBCollection table = db . getCollection ( "user" ) ; BasicDBObject document = new BasicDBObject ( ) ; document . put ( "name" , "mkyong" ) ; document . put ( "age" , 30 ) ; document . put ( "createdDate" , new Date ( ) ) ; table . insert ( document ) ;      Update Update a document where “name=mkyong”. DBCollection table = db . getCollection ( "user" ) ; BasicDBObject query = new BasicDBObject ( ) ; query . put ( "name" , "mkyong" ) ; BasicDBObject newDocument = new BasicDBObject ( ) ; newDocument . put ( "name" , "mkyong-updated" ) ; BasicDBObject updateObj = new BasicDBObject ( ) ; updateObj . put ( "$set" , newDocument ) ; table . update ( query , updateObj ) ; Search Find document where “name=mkyong”, and display it with DBCursor DBCol...

Java MongoDB connectivity Code

package mongoconn; ////import com.mongodb.client.MongoDatabase; import java.net.UnknownHostException; import java.sql.Date; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.DB; import com.mongodb.DBCollection; //import com.mongodb.MongoCredential;  public class myconn{       public static void main( String args[] ) throws UnknownHostException {              // Creating a Mongo client       MongoClient mongo = new MongoClient("localhost" , 27017 );          System.out.println("Connected to the database successfully");                DB db = mongo.getDB("SP");       DBCollection table = db.getCollection("user");                BasicDBOb...

MongoDB queries for CRUD operation

root@localhost student1]# systemctl start mongod [root@localhost student1]# mongo MongoDB shell version: 2.4.6 connecting to: test > show dbs TE     0.203125GB company      0.203125GB local 0.078125GB tecomp       0.203125GB > use shubhangi switched to db shubhangi > show collections > db.createCollection("information") { "ok" : 1 } > db.information.insert({"rollno":101,"name":"shubhangi","marks":85}); > db.information.insert({"rollno":102,"name":"Itisha","marks":90}); > db.information.insert({"rollno":103,"name":"ram","marks":88}); > db.iformation.find() > db.information.find() { "_id" : ObjectId("59b8ba5dc1991a8ea9ff1dea"), "rollno" : 101, "name" : "shubhangi", "marks" : 85 } { "_id" : ObjectId("59b8bacbc1991a8ea9ff1deb...

Java Mysql Connectivity Code

import java.sql.DriverManager; import java.sql.ResultSet; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.mysql.jdbc.Statement; public class jdbcConn {     private static Connection connect = null;     private static Statement statement = null;     private PreparedStatement preparedStatement = null;     private static ResultSet resultSet = null;     public static void main(String[] args) throws Exception     { try {         // This will load the MySQL driver, each DB has its own driver         Class.forName("com.mysql.jdbc.Driver");         // Setup the connection with the DB         connect = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/emp?"+"user=root");     ...

Example of Cursor in Mysql

DELIMITER //   CREATE PROCEDURE myone()   BEGIN                 declare myno   int(3);      DECLARE done INT DEFAULT FALSE;                 declare mycursor CURSOR for   select roll_no from fine;          DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;          open mycursor;       Label1 : LOOP                                 fetch mycursor into   myno;                           ...

Integrity Constraints

Integrity Constraints There are  1.  domain integrity 2. entity integrity, 3. referential integrity  4. Enterprise  integrity constraints. Domain Integrity Domain integrity means the definition of a valid set of values for an attribute. You define  - data type,  - lenght or size - is null value allowed - is the value unique or not for an attribute. You may also define the default value, the range (values in between) and/or specific values for the attribute. Some DBMS allow you to define the output format and/or input mask for the attribute. These definitions ensure that a specific attribute will have a right and proper value in the database. Entity Integrity Constraint The entity integrity constraint states that primary keys can't be null. There must be a proper value in the primary key field. This is because the primary key value is used to identify individual rows in a table. If there were null values for primary...