***********************PYTHON PROGRAM********************
//IMPLEMENTATION OF 8 PUZZLE PROBLEM
import sys;
import re;
import math;
import time;
import collections;
def GOAL_STATE(): return [1,2,3,8,0,4,7,6,5] # The constant goal state
usedStates={}; # List of states already visited by algorithm.
[State => (parent, direction from parent, depth encountered)]
knownHeuristics={}; # List of heuristics computed for various states.
[State => heuristic]
spaceComplexity = 0; # Parameter used to judge space and time complexity.
timeComplexity = 0; # Actual semantic will depend on the algorithm
# Representing enums
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named);
reverse = dict((value, key) for key, value in enums.iteritems());
enums['reverse_mapping'] = reverse;
return type('Enum', (), enums);
# Representing setting for various program runtime parameters
DIRECTIONS = enum(UP=-3, DOWN=3, RIGHT=1, LEFT=-1); # Direction flipped from one state to next
QUEUEING = enum(STACK=1, QUEUE=2); # Different queueing between BFS and DFS
UI_ALGORITHM = enum(DFS=1, BFS=2, DLS=3, IDS=4); # List of uninformed search algorithms
IN_ALGORITHM = enum(GBF=5, AST=6, IDA=7); # List of informed search algorithms
HEURISTICS = enum(BOOLEAN=1, MANHATTAN=2); # Two heuristic used in informed search
# Check inversion number for input state
def getInversionNumber(nodeState):
return len([(x,y) for x in range(len(nodeState)-1) for y in range(x+1,9)
if nodeState[x]>nodeState[y] and (not (nodeState[x]==0 or nodeState[y]==0))]);
# Parse input arguments to get algo and initial state
def parseInputArgs():
statePattern = re.compile('^([^ ]+) \((([0-8] ){8}[0-8])\)( [h0-9]+){0,1}$');
patternMatch = statePattern.match(' '.join(sys.argv[1:]));
if patternMatch is None:
print "Invalid state pattern";
exit(1);
algoName = patternMatch.group(1).upper(); # Set algorithm to a defined enum
if algoName=='DFS':
algoName=UI_ALGORITHM.DFS;
elif algoName=='BFS':
algoName = UI_ALGORITHM.BFS;
elif algoName=='DLS':
algoName = UI_ALGORITHM.DLS;
elif algoName=='IDS':
algoName = UI_ALGORITHM.IDS;
elif algoName=='GREEDY':
algoName = IN_ALGORITHM.GBF;
elif algoName=='A-STAR':
algoName = IN_ALGORITHM.AST;
elif algoName=='IDA-STAR':
algoName = IN_ALGORITHM.IDA;
else:
print "Unrecognized algorithm: "+algoName;
exit(1);
initialState = patternMatch.group(2); # Read initial state string from input args
initialState = [int(x) for x in initialState if x.isdigit()]; # Initialize initial state to list
if not (getInversionNumber(initialState)%2 == getInversionNumber(GOAL_STATE())%2): # Compare inversion numbers for goal and initial state
print "No path exists from initial state "+str(initialState)+" to goal state "+str(GOAL_STATE());
exit(1);
if algoName<5: # If uninformed search, 3rd parameter is max search depth
if patternMatch.group(4) is None: # Read max search depth parameter from input (optional)
maxSearchDepth = 0;
else:
maxSearchDepth = int(patternMatch.group(4));
return [algoName, initialState, maxSearchDepth];
else: # If informed search, 3rd parameter is heuristic (required)
if patternMatch.group(4) is None:
print "Heuristic required for informed search. \'h1\' (for tiles out of place) or \'h2\' for Manhattan distance";
exit(1);
else:
heuristicName = patternMatch.group(4).strip().upper();
print "Heuristic: "+heuristicName;
if heuristicName == 'H1':
heuristicName = HEURISTICS.BOOLEAN;
elif heuristicName == 'H2':
heuristicName = HEURISTICS.MANHATTAN;
else:
print "Unrecognized value for heuristic. Should be \'h1\' (for tiles out of place) or \'h2\' for Manhattan distance"
exit(1);
return [algoName, initialState, heuristicName];
# Calculate heuristic value for a given state as number of tiles out of place
def getBooleanDistance(nodeState):
heuristicValue = 0;
for i in range(len(nodeState)):
if nodeState[i]==0: # Discount the blank tile
continue;
if GOAL_STATE()[i] != nodeState[i]: # Compare value at index between nodeState and goalState
heuristicValue+=1;
return heuristicValue;
# Calculate heuristic value for a given state as Manhattan distance of the tiles
def getManhattanDistance(nodeState):
heuristicValue = 0;
for i in range(1,len(nodeState)):
intendedIndex = GOAL_STATE().index(i);
actualIndex = nodeState.index(i);
xMovement = math.fabs(actualIndex-intendedIndex)%3;
yMovement = int(math.fabs(actualIndex-intendedIndex)/3);
heuristicValue += (xMovement+yMovement);
return int(heuristicValue);
# Calculate actual node cost as (heuristic + node depth)
# Heuristic function could be boolean or Manhattan distance
def getTotalCost(nodeState, heuristicFunction):
return heuristicFunction(nodeState)+usedStates[str(nodeState)][2];
# Get valid child states from a given state. Does not include states in `usedStates`
def getChildStates(currentState):
global usedStates;
zeroIndex = currentState.index(0);
xIndex = zeroIndex%3; # x-Index of '0' in the 3x3 box
yIndex = zeroIndex/3; # y-Index of '0' in the 3x3 box
validDirections = [x for x in [1, -1] if ((xIndex%3)+x) in [0,1,2]]; # Get directions movable in X-direction
validDirections.extend([y*3 for y in [-1, 1] if ((yIndex%3)+y) in [0,1,2]]); # Get directions movable in Y-direction
childStates = collections.deque(); # Deques used to optimize front-side inserts
for validDirection in validDirections: # Move '0' in the corresponding direction and check for loop
tempState = currentState[:];
(tempState[zeroIndex],tempState[zeroIndex+validDirection]) = (tempState[zeroIndex+validDirection],tempState[zeroIndex]);
if str(tempState) not in usedStates: # Child state is valid only if first encounter
childStates.append(tempState);
currentDepth = usedStates[str(currentState)][2]; # Depth of the parent node
usedStates[str(tempState)]=(currentState,validDirection, currentDepth+1);
return childStates;
def addChildrenToList(nodeList, childStates, queueingMethod):
if queueingMethod==QUEUEING.STACK: # Queueing for DFS
nodeList.extendleft(childStates);
elif queueingMethod==QUEUEING.QUEUE: # Queueing for BFS
nodeList.extend(childStates); # Prepend child states to queue. If childStates is empty, the sibling of current node will be taken next
return nodeList;
# Actual implementation of an uninformed search. Based on parameters passed for queueing mechanism and search depth,
# runs BFS, DFS or a variant
def runUninformedSearch(initialState, queueingMethod, maxSearchDepth=0):
global usedStates; # Reset usedStates to default before starting search.
usedStates={};
usedStates[str(initialState)] = (None, None, 1);
global timeComplexity;
global spaceComplexity;
nodeList = collections.deque(); # Stores list of colored nodes not yet expanded
nodeList.append(initialState);
allNodesVisited=True;
while(len(nodeList)>0):
currentState = nodeList.popleft(); # Remove element to extend all its children
currentDepth = usedStates[str(currentState)][2];
timeComplexity=timeComplexity+1;
if currentState==GOAL_STATE(): # If current node is goal, end search
return currentState;
if maxSearchDepth<=0 or currentDepth<maxSearchDepth: # Expand to children only if depth limit hasn't been reached
childStates = getChildStates(currentState); # Retrieve child states for node
nodeList = addChildrenToList(nodeList, childStates, queueingMethod); # Add children to list according to algorithm
else:
allNodesVisited=False;
if len(nodeList)>spaceComplexity:
spaceComplexity = len(nodeList);
return allNodesVisited;
# Based on algorithm and max depth, define parameters to run uninformed search
def setupUninformedSearch(algoName, initialState, maxSearchDepth=0):
global timeComplexity;
timeComplexity=0;
global spaceComplexity;
spaceComplexity = 1;
if algoName==UI_ALGORITHM.DFS or algoName==UI_ALGORITHM.DLS: # Run DFS algorithm for DFS and DLS (maxSearchDepth will determine which one)
return runUninformedSearch(initialState, QUEUEING.STACK, maxSearchDepth);
elif algoName==UI_ALGORITHM.BFS: # Run BFS algorithm
return runUninformedSearch(initialState, QUEUEING.QUEUE, maxSearchDepth);
elif algoName==UI_ALGORITHM.IDS: # Run IDS algorithm
currentDepthLimit=0; # Current depth IDS is limited to
searchResult = None; # Decides if the DLS can run any deeper
while searchResult is not True and type(searchResult) is not list:
currentDepthLimit=currentDepthLimit+1; # Run DLS while incrementing max depth each time
searchResult = runUninformedSearch(initialState, QUEUEING.STACK, currentDepthLimit);
return searchResult;
# Actual implementation of an informed search. Based on cost function,
# runs Greedy Best-First or A-*
def runInformedSearch(initialState, costFunction):
global timeComplexity;
timeComplexity=0;
global spaceComplexity;
spaceComplexity = 1;
nodeList = list();
nodeList.append(initialState);
global knownHeuristics;
knownHeuristics[str(initialState)] = costFunction(initialState);
while(len(nodeList)>0):
currentState = nodeList.pop(0);
timeComplexity +=1;
if currentState == GOAL_STATE():
return currentState;
childStates = getChildStates(currentState);
for childState in childStates:
childHeuristic = knownHeuristics[str(childState)] = costFunction(childState);
insertPosition=0;
for nodeState in nodeList:
if knownHeuristics[str(nodeState)] > childHeuristic:
break;
else:
insertPosition+=1;
nodeList.insert(insertPosition, childState);
if spaceComplexity < len(nodeList):
spaceComplexity = len(nodeList);
# DFS Contour for IDA-*
def DFSContour(currentNode, fLimit, costFunction, recursionDepth=0):
global spaceComplexity;
if spaceComplexity < recursionDepth:
spaceComplexity = recursionDepth;
global timeComplexity;
if str(currentNode) in knownHeuristics:
pathCost = knownHeuristics[str(currentNode)];
else:
pathCost = costFunction(currentNode);
knownHeuristics[str(currentNode)] = pathCost;
if pathCost>fLimit:
return (None, pathCost);
if currentNode == GOAL_STATE():
return (currentNode, fLimit);
minF = sys.maxint;
childStates = getChildStates(currentNode);
for childState in childStates:
timeComplexity = timeComplexity+1;
(searchResult, childF) = DFSContour(childState, fLimit, costFunction, recursionDepth+1);
if searchResult is not None:
return (searchResult, fLimit);
else:
minF = min(minF, childF);
return (None, minF);
# Implementation of ID-A*
def runIDAStar(initialState, costFunction):
fLimit = costFunction(initialState);
global knownHeuristics;
global usedStates;
global timeComplexity;
timeComplexity = 1;
while(True):
knownHeuristics = {};
knownHeuristics[str(initialState)] = fLimit;
usedStates = {};
usedStates[str(initialState)] = (None, None, 1);
(searchResult, fLimit) = DFSContour(initialState, fLimit, costFunction);
if searchResult is not None:
return searchResult;
if fLimit==sys.maxint:
return None;
# Based on algorithm and heuristic, define parameters to run informed search
def setupInformedSearch(algoName, initialState, heuristicName):
if heuristicName == HEURISTICS.BOOLEAN:
heuristicFunction = getBooleanDistance;
elif heuristicName == HEURISTICS.MANHATTAN:
heuristicFunction = getManhattanDistance;
if algoName==IN_ALGORITHM.GBF:
return runInformedSearch(initialState, lambda nodeState:heuristicFunction(nodeState));
elif algoName==IN_ALGORITHM.AST:
return runInformedSearch(initialState, lambda nodeState:getTotalCost(nodeState, heuristicFunction));
elif algoName==IN_ALGORITHM.IDA:
return runIDAStar(initialState, lambda nodeState:getTotalCost(nodeState, heuristicFunction));
# Follow direction that algorithm took from root node to goal
def followRootToGoal(currentNode):
movementList = collections.deque();
while(currentNode is not None):
nextDirection = usedStates[str(currentNode)][1];
if nextDirection is not None:
movementList.appendleft(DIRECTIONS.reverse_mapping[nextDirection]);
currentNode = usedStates[str(currentNode)][0];
return movementList;
# Program main routine. Expects initial state as argument
if __name__=="__main__":
searchParams = parseInputArgs(); # Check if input is a valid initial state and return run parameters
print str(searchParams);
# Recursion in DFS Contour can exceed default recursion limit
sys.setrecursionlimit(10000);
initialState = searchParams[1];
usedStates[str(initialState)] = (None, None, 1); # Root node
startTime = time.time();
if searchParams[0] < 5: # Algorithm is uninformed
goalNode = setupUninformedSearch(searchParams[0], initialState, searchParams[2]); # Run uninformed search algorithm
else: # Algorithm is informed
goalNode = setupInformedSearch(searchParams[0], initialState, searchParams[2]); # Run informed search algorithm
elapsedTime = time.time() - startTime;
if type(goalNode) is not list:
print "Goal not found. Nodes visited: "+str(timeComplexity);
exit(0);
startToGoal = followRootToGoal(goalNode); # Follow nodes from root to goal (in opposite order)
print "\nSolution:\n----------";
if len(startToGoal)<=50:
print list(startToGoal),'\n';
print "Solution takes "+str(len(startToGoal))+" movements to get to the goal";
if searchParams[0] != IN_ALGORITHM.IDA:
# Logging program time and search depth
print "\nNodes visited: ",str(timeComplexity);
print "Maximum length of node list: ",str(spaceComplexity);
print "Search run-time: ",str(elapsedTime),"seconds\n";
else:
print "\nNodes visited: ",str(timeComplexity);
print "Maximum recursion depth: ",str(spaceComplexity);
print "Search run-time: ",str(elapsedTime),"seconds\n";
PROGRAM 2 : NAIVE BAYES CLASSIFIER FOR TENNIS DATASET
********************************JAVA PROGRAM ****************************
//AIM : IMPLEMENTATION OF NAÏVE BAYES CLASSIFIER
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.*;
public class readxml {
public static void main(String argv[]) {
try {
File fXmlFile = new File("/home/pccoe/Desktop/BECOB261/SampleDB.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
//doc.getDocumentElement().normalize();
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Rootent :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("row");
float totalsamples=nList.getLength();
System.out.println("TOTALles"+totalsamples);
float play=0,noplay=0;
float ol=0,t=0,h=0,w=0;
float on=0,t1=0,h1=0,w1=0;
float pp,np;
System.out.println("Enteroutlook: ");
String s = b.readLine();
System.out.println("Entertemperature: ");
String s1 = b.readLine();
System.out.println("Enterhumidity: ");
String s2 = b.readLine();
System.out.println("Enterwindy: ");
String s3 = b.readLine();
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
//System.out.println("\nCurrentent :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String class1=eElement.getElementsByTagName("class").item(0).getTextContent();
String outlook=eElement.getElementsByTagName("outlook").item(0).getTextContent();
String temp1=eElement.getElementsByTagName("temp").item(0).getTextContent();
String humidity=eElement.getElementsByTagName("humidity").item(0).getTextContent();
String windy=eElement.getElementsByTagName("windy").item(0).getTextContent();
if(class1.equals("p"))
play++;
else noplay++;
if(outlook.equals(s) && class1.equals("p"))
ol++;
else if(outlook.equals(s) && class1.equals("n"))
on++;
if(temp1.equals(s1) && class1.equals("p"))
t++;
else if(temp1.equals(s1) && class1.equals("n"))
t1++;
if(humidity.equals(s2) && class1.equals("p"))
h++;
else if(humidity.equals(s2) && class1.equals("n"))
h1++;
if(windy.equals(s3) && class1.equals("p"))
w++;
else if(windy.equals(s3) && class1.equals("n"))
w1++;
}
}
System.out.println("playlay);
System.out.println("can'tnoplay);
System.out.println("outlookl);
System.out.println("temp);
System.out.println("humidity);
System.out.println("windy);
pp = (ol/play)*(t/play)*(h/play)*(w/play)*(play/totalsamples);
np = (on/noplay)*(t1/noplay)*(h1/noplay)*(w1/noplay)*(noplay/totalsamples);
if(pp>np)
{
System.out.println(" you can play: ");
}
else
System.out.println("yout play: ");
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
* Root element :TENNIS
TOTAL Samples11.0
Enter the outlook:
sunny
Enter the temperature:
hot
Enter the humidity:
high
Enter the windy:
true
play: 6.0
can't play: 5.0
outlook: 2.0
temp: 1.0
humidity: 3.0
windy: 4.0
you can't play:
------------------------
Root element :TENNIS
TOTAL Samples11.0
Enter the outlook:
rain
Enter the temperature:
mild
Enter the humidity:
high
Enter the windy:
false
play: 6.0
can't play: 5.0
outlook: 3.0
temp: 4.0
humidity: 3.0
windy: 2.0
you can play:
*
*/
//-------- Sample DB FOR NAIVE BAYES XML FILE-----------
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<TENNIS>
<row id="1">
<outlook>sunny</outlook>
<temp>hot</temp>
<humidity>high</humidity>
<windy>true</windy>
<class>n</class>
</row>
<row id="2">
<outlook>rain</outlook>
<temp>hot</temp>
<humidity>normal</humidity>
<windy>false</windy>
<class>n</class>
</row>
<row id="3">
<outlook>sunny</outlook>
<temp>cool</temp>
<humidity>normal</humidity>
<windy>true</windy>
<class>p</class>
</row>
<row id="4">
<outlook>sunny</outlook>
<temp>mild</temp>
<humidity>normal</humidity>
<windy>true</windy>
<class>p</class>
</row>
<row id="5">
<outlook>rain</outlook>
<temp>mild</temp>
<humidity>high</humidity>
<windy>false</windy>
<class>p</class>
</row>
<row id="6">
<outlook>overcast</outlook>
<temp>mild</temp>
<humidity>high</humidity>
<windy>false</windy>
<class>p</class>
</row>
<row id="7">
<outlook>overcast</outlook>
<temp>cool</temp>
<humidity>high</humidity>
<windy>false</windy>
<class>n</class>
</row>
<row id="8">
<outlook>overcast</outlook>
<temp>cool</temp>
<humidity>high</humidity>
<windy>false</windy>
<class>n</class>
</row>
<row id="9">
<outlook>rain</outlook>
<temp>hot</temp>
<humidity>normal</humidity>
<windy>true</windy>
<class>p</class>
</row>
<row id="10">
<outlook>sunny</outlook>
<temp>cool</temp>
<humidity>normal</humidity>
<windy>true</windy>
<class>n</class>
</row>
<row id="11">
<outlook>rain</outlook>
<temp>mild</temp>
<humidity>high</humidity>
<windy>true</windy>
<class>p</class>
</row>
</TENNIS>
*****************************PYTHON PROGRAM **************************
//IMPLEMENTATION OF TIC-TAC-TOE
from Tkinter import Frame, Canvas, Label, Button, LEFT,RIGHT, ALL, Tk
from random import randint
class main:
def __init__(self,master):
#master frame
self.frame = Frame(master)
self.frame.pack(fill="bothpand=True)
#canvas where the game is played on
self.canvas = Canvas(self.frame, width=300, height=300)
self.canvas.pack(fill="bothpand=True)
#Shows status of game
self.label=Label(self.frame, text='Tic Tac Toe Game', height=6, bg='black', fg='blue')
self.label.pack(fill="bothpand=True)
#frame to contain the buttons
self.frameb=Frame(self.frame)
self.frameb.pack(fill="bothpand=True)
#Buttons to initiate the game
self.Start1=Button(self.frameb, text='Click here to start\ndouble player', height=4, command=self.start1,bg='white', fg='purple')
self.Start1.pack(fill="both", expand=True, side=RIGHT)
self.Start2=Button(self.frameb, text='Click here to start\nsingle player', height=4, command=self.start2,bg='purple', fg='white')
self.Start2.pack(fill="both", expand=True, side=LEFT)
#canvas board drawing function call
self._board()
def start1(self):
#Starts double player
#refresh canvas
self.canvas.delete(ALL)
self.label['text']=('Tic Tac Toe Game')
#function call on click
self.canvas.bind("<ButtonPress-1.sgplayer)
self._board()
#Starts the matrix to do calculations
#of the positions of circles and crosses.
self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
#counter of turns
self.i=0
#trigger to end game
self.j=False
def start2(self):
#Starts single player
self.canvas.delete(ALL)
self.label['text']=('Tic Tac Toe Game')
self.canvas.bind("<ButtonPress-1.dgplayer)
self._board()
self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
self.i=0
self.j=False
#Trigger to check the validity of the move
self.trigger=False
def end(self):
#Ends the game
self.canvas.unbind("<ButtonPress-1>")
self.j=True
def _board(self):
#Creates the board
self.canvas.create_rectangle(0,0,300,300, outline="black")
self.canvas.create_rectangle(100,300,200,0, outline="black")
self.canvas.create_rectangle(0,100,300,200, outline="black")
def sgplayer(self,event):
#Double player game loop
for k in range(0,300,100):
for j in range(0,300,100):
#checks if the mouse input is in a bounding box
if event.x in range(k,k+100) and event.y in range(j,j+100):
#checks if there is nothing in the bounding box
if self.canvas.find_enclosed(k,j,k+100,j+100)==():
#Player plays first
if self.i%2==0:
#draws circle
X=(2*k+100)/2
Y=(2*j+100)/2
X1=int(k/100)
Y1=int(j/100)
self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
self.TTT[Y1][X1]+=1
self.i+=1
else:
#creates the cross.
X=(2*k+100)/2
Y=(2*j+100)/2
X1=int(k/100)
Y1=int(j/100)
self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
self.TTT[Y1][X1]+=9
self.i+=1
#After everything, remember to check for wins/losts/draws
self.check()
def dgplayer(self,event):
for k in range(0,300,100):
for j in range(0,300,100):
if self.i%2==0:
if event.x in range(k,k+100) and event.y in range(j,j+100):
if self.canvas.find_enclosed(k,j,k+100,j+100)==():
X=(2*k+100)/2
Y=(2*j+100)/2
X1=int(k/100)
Y1=int(j/100)
self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
self.TTT[Y1][X1]+=1
self.i+=1
self.check()
self.trigger=False
else:
print(self.i)
#check for wins/losts/draws first
#before allowing the computer to make its turn
self.check()
#Game AI code
self.AIcheck()
#refresh validity of move
self.trigger=False
def check(self):
#horizontal check
for i in range(0,3):
if sum(self.TTT[i])==27:
self.label['text']=('2nd player wins!')
self.end()
if sum(self.TTT[i])==3:
self.label['text']=('1st player wins!')
self.end()
#vertical check
self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
for i in range(0,3):
if sum(self.ttt[i])==27:
self.label['text']=('2nd player wins!')
self.end()
if sum(self.ttt[i])==3:
self.label['text']=('1st player wins!')
self.end()
#check for diagonal wins
if self.TTT[1][1]==9:
if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
self.label['text']=('2nd player wins!')
self.end()
if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
self.label['text']=('2nd player wins!')
self.end()
if self.TTT[1][1]==1:
if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
self.label['text']=('1st player wins!')
self.end()
if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
self.label['text']=('1st player wins!')
self.end()
#check for draws
if self.j==False:
a=0
for i in range(0,3):
a+= sum(self.TTT[i])
#As the player starts with a circle(value=1),
#There will be a total of 5(1) and 4(9)=41
if a==41:
self.label['text']=("It's a pass!")
self.end()
def AIcheck(self):
#Offense should come before defense so that the AI will try to win if possible
#This is built on the self.check function
self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
#OFFENSE
#this is the vertical checklist
for h in range(0,3):
k=0
j=0
if sum(self.TTT[h])==18:
while k <3:
if k==h:
while j <3:
if self.trigger==False:
if self.TTT[k][j]==0:
self.cross(j,k)
break
j+=1
k+=1
#this is the horizontal checklist
for h in range(0,3):
k=0
j=0
if sum(self.ttt[h])==18:
while k <3:
if k==h:
while j <3:
if self.trigger==False:
if self.ttt[k][j]==0:
self.cross(k,j)
break
j+=1
k+=1
#this is the diagonal checklist
if self.TTT[1][1]==9:
if self.TTT[0][0]==9:
if self.trigger==False:
if self.TTT[2][2]==0:
self.cross(2,2)
if self.TTT[0][2]==9:
if self.trigger==False:
if self.TTT[2][0]==0:
self.cross(0,2)
if self.TTT[2][0]==9:
if self.trigger==False:
if self.TTT[0][2]==0:
self.cross(2,0)
if self.TTT[2][2]==9:
if self.trigger==False:
if self.TTT[0][0]==0:
self.cross(0,0)
#DEFENSE
#this is the horizontal checklist
for h in range(0,3):
k=0
j=0
if sum(self.TTT[h])==2:
while k <3:
if k==h:
while j <3:
if self.trigger==False:
if self.TTT[k][j]==0:
self.cross(j,k)
break
j+=1
k+=1
#this is the vertical checklist
for h in range(0,3):
k=0
j=0
if sum(self.ttt[h])==2:
while k <3:
if k==h:
while j <3:
if self.trigger==False:
if self.ttt[k][j]==0:
self.cross(k,j)
break
j+=1
k+=1
#this is the diagonal checklist
if self.TTT[1][1]==1:
if self.TTT[0][0]==1:
if self.trigger==False:
if self.TTT[2][2]==0:
self.cross(2,2)
if self.TTT[0][2]==1:
if self.trigger==False:
if self.TTT[2][0]==0:
self.cross(0,2)
if self.TTT[2][0]==1:
if self.trigger==False:
if self.TTT[0][2]==0:
self.cross(2,0)
if self.TTT[2][2]==1:
if self.trigger==False:
if self.TTT[0][0]==0:
self.cross(0,0)
#NEUTRAL
if self.TTT[1][1]==0:
if self.trigger==False:
self.cross(1,1)
self.trigger=True
else:
if self.trigger==False:
self.randmove()
def cross(self, k, j):
# k is the x coords
# j is the y coords
X=(200*k+100)/2
Y=(200*j+100)/2
X1=int(k)
Y1=int(j)
self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
self.TTT[Y1][X1]+=9
self.check()
self.i+=1
self.trigger=True
def randmove(self):
# In case there's nothing for the computer to do
while True:
k=(randint(0,2))
j=(randint(0,2))
if self.TTT[j][k]==0:
self.cross(k,j)
break
else:
k=(randint(0,2))*100
j=(randint(0,2))*100
#initiate the class
root=Tk()
app=main(root)
root.mainloop()
*******************************JAVA PROGRAM **************************
//IMPLEMENTATION OF FEEDFORWARD NEURAL NETOWRK
import java.io.*;
import java.lang.*;
import java.util.*;
import java.text.DecimalFormat;
public class neural
{
public static void main(String args[])
{
neural n_ob=new neural();
int a[][]=new int[4][2];
a[0][0]=1;
a[0][1]=1;
a[1][0]=0;
a[1][1]=1;
a[2][0]=0;
a[2][1]=0;
a[3][0]=1;
a[3][1]=0;
double e1,e2,e3,e4,mean_e,w1,w2,c1,c2,nw1,nw2;
int a_op[]=new int[4];
a_op[0]=1;
a_op[1]=0;
a_op[2]=0;
a_op[3]=0;
int j=0;
int ip1=0,ip2=0;
double learn_rate=n_ob.Random_gen();
System.out.println("\nLearning= "+learn_rate);
w1=n_ob.Random_gen();
w2=n_ob.Random_gen();
double mean;
System.out.println("\nInput_1\tInput_2\tActual_Output\tExpected_Output\tr");
System.out.println("----------------------------------------------------------\n
do{
mean=0;
for(int i=0;i<=3;i++)
{
ip1=a[i][0];
ip2=a[i][1];
double op=w1*ip1+w2*ip2;
e1=a_op[i]-op;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print(ip1+"\t"+ip2+"\tp)+"\t\t "+a_op[i]+"\t\t"+df.format(e1)+"\n");
mean+=e1*e1;
c1=learn_rate*ip1*e1;
c2=learn_rate*ip2*e1;
nw1=w1+c1;
nw2=w1+c2;
w1=nw1;
w2=nw2;
}
j++;
System.out.println("Numberpoch(s) : "+j);
}while(j<=5);
//}while(mean>0.01);
}
double Random_gen()
{
Random r_no=new Random();
double r_num=r_no.nextFloat();
return r_num;
}
}
**********ANDROID PROGRAM DEVELOPED USING ADT BUNDLE *********
// BOOK RECOMMENDER SYSTEM
*********************Code AndroidManifest.xml*****************
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bookrecommender"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Holo.Light" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AddNewBookActivity"
android:label="@string/title_activity_add_new_book" >
</activity>
<activity
android:name=".BookRatingActivity"
android:label="@string/title_activity_book_rating" >
</activity>
</application>
</manifest>
**********************************************************************
Various Layout Files :
**********************Activity_main.xml********************
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.bookrecommender.MainActivity" >
<Spinner
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
**********************************************************************
************************Activity_add_new_book.xml************************
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin"
tools:context="com.example.bookrecommender.AddNewBookActivity" >
<EditText
android:id="@+id/editTextBookName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Book Name" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editTextAuther"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Auther name" />
<Spinner
android:id="@+id/categories"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/buttonAddNew"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF0040"
android:text="Add Book" />
</LinearLayout>
**********************************************************************
*************************activity_book_rating.xml******************
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.bookrecommender.BookRatingActivity" >
<ListView
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</RelativeLayout>
**********************************************************************
********************List_item_book_rating_layout.xml*******************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#E0E0E0"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin" >
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textSize="16sp"
android:textStyle="bold" />
<RatingBar
android:id="@+id/ratingBar"
style="?android:attr/ratingBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
/>
</LinearLayout>
**********************************************************************
**********************List_item_book_layout.xml********************
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:padding="@dimen/activity_horizontal_margin"
android:orientation="vertical" >
<TextView
android:id="@+id/textViewBookName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textStyle="bold"
android:textColor="@android:color/black"
android:textSize="16dp" />
<TextView
android:id="@+id/textViewReleaseDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="@android:color/black"
android:textSize="16dp" />
<TextView
android:id="@+id/textViewRating"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textColor="@android:color/black"
android:textSize="16dp" />
</LinearLayout>
**********************************************************************
**************************Various menu files*********************
****************Main.xml******************
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.bookrecommender.MainActivity" >
<item
android:id="@+id/action_add_book"
android:orderInCategory="100"
android:title="Add Book"
android:showAsAction="always"/>
<item
android:id="@+id/action_rate_book"
android:orderInCategory="100"
android:title="rate Book"
android:showAsAction="always"/>
</menu>
**********************************************************************
************************Add_new_book.xml*********************
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.bookrecommender.AddNewBookActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:showAsAction="never"/>
</menu>
**********************************************************************
***********************Book_rating.xml*****************
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.bookrecommender.BookRatingActivity" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
android:showAsAction="never"/>
</menu>
**********************************************************************
***************************Various Java Files***************
*****************************AddNewBookActivity.java******************
package com.example.bookrecommender;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class AddNewBookActivity extends Activity implements OnClickListener,
OnItemSelectedListener {
private EditText editTextBookName, editTextAuther;
private Spinner spinnerCategories;
private Button buttonAddNew;
private DatabaseHelper databaseHelper;
private ArrayAdapter<String> categoriesAdapter;
private String bookname;
private String author;
private String categories;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_book);
databaseHelper = new DatabaseHelper(getApplicationContext());
editTextBookName = (EditText) findViewById(R.id.editTextBookName);
editTextAuther = (EditText) findViewById(R.id.editTextAuther);
spinnerCategories = (Spinner) findViewById(R.id.categories);
buttonAddNew = (Button) findViewById(R.id.buttonAddNew);
categoriesAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getResources()
.getStringArray(R.array.book_types));
spinnerCategories.setAdapter(categoriesAdapter);
//set Listeners
buttonAddNew.setOnClickListener(this);
spinnerCategories.setOnItemSelectedListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.add_new_book, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
if (!editTextBookName.getText().toString().equals("")
|| !editTextAuther.getText().toString().equals("")) {
bookname = editTextBookName.getText().toString();
author = editTextAuther.getText().toString();
databaseHelper.addNewBook(bookname, categories, author);
onBackPressed();
} else {
Toast.makeText(getApplicationContext(), "Enter All Fileds",
Toast.LENGTH_SHORT).show();
}
}
@Override
public void onItemSelected(AdapterView<?> listAdapter, View view,
int position, long id) {
categories = listAdapter.getAdapter().getItem(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onBackPressed() {
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
finish();
}
}
**********************************************************************
***********************BookBean.java*********************
package com.example.bookrecommender;
public class BookBean {
private int id;
private String bookname,author,categories,releaseDate;
private float rating=0;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getAuther() {
return author;
}
public void setAuther(String author) {
this.author = author;
}
public String getCategories() {
return categories;
}
public void setCategories(String categories) {
this.categories = categories;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public String getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(String releaseDate) {
this.releaseDate = releaseDate;
}
}
**********************************************************************
****************************BookListAdapter.java******************
package com.example.bookrecommender;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class BookListAdapter extends BaseAdapter {
private ArrayList<BookBean> list;
private LayoutInflater inflater;
DatabaseHelper databaseHelper;
BookListAdapter(Context context,ArrayList<BookBean> list){
this.list=list;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
databaseHelper = new DatabaseHelper(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public BookBean getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView=inflater.inflate(R.layout.list_item_book_rlayout, null);
TextView textViewBookName=(TextView)convertView.findViewById(R.id.textViewBookName);
TextView textViewReleaseDate=(TextView)convertView.findViewById(R.id.textViewReleaseDate);
TextView textViewRating=(TextView)convertView.findViewById(R.id.textViewRating);
//Set Data
final BookBean dataBean=list.get(position);
textViewBookName.setText( dataBean.getBookname());
textViewReleaseDate.setText("Release Date : " + dataBean.getReleaseDate());
textViewRating.setText("Rating : "+dataBean.getRating());
return convertView;
}
}
**********************************************************************
******************BookRatingActivity.java******************
package com.example.bookrecommender;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
public class BookRatingActivity extends Activity {
private BookRatingAdapter bookAdapter;
private ListView listView;
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book_rating);
//Initialize views
listView = (ListView) findViewById(R.id.list);
//Initialize database
databaseHelper = new DatabaseHelper(getApplicationContext());
//get List from dataBase
ArrayList<BookBean> list = databaseHelper
.getBookList(getString(R.string.newrelease));
//Initialize adapter
bookAdapter = new BookRatingAdapter(getApplicationContext(), list);
//set adapter
listView.setAdapter(bookAdapter);
}
@Override
public void onBackPressed() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
**********************************************************************
***********************BookRatingAdapter.java*******************
package com.example.bookrecommender;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
public class BookRatingAdapter extends BaseAdapter {
private ArrayList<BookBean> list;
private LayoutInflater inflater;
private DatabaseHelper databaseHelper;
BookRatingAdapter(Context context,ArrayList<BookBean> list){
this.list=list;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
databaseHelper = new DatabaseHelper(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public BookBean getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
/*create views(List item)*/
convertView=inflater.inflate(R.layout.list_item_book_rating_layout, null);
TextView textView=(TextView)convertView.findViewById(R.id.textView);
RatingBar ratingBar=(RatingBar)convertView.findViewById(R.id.ratingBar);
//LayerDrawable stars = (LayerDrawable) ratingBar.getProgressDrawable();
//set Data
final BookBean dataBean=list.get(position);
ratingBar.setRating(dataBean.getRating());
textView.setText(dataBean.getBookname());
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
databaseHelper.rateBook(dataBean.getId(), rating);
} });
return convertView;
}
}
**********************************************************************
*************************DatabaseHelper.java***************************
package com.example.bookrecommender;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = DatabaseHelper.class.getName();
public static final String DATABASE_NAME = "BOOKSYSTEM";
private static final int DATABASE_VERSION = 1;
rivate static final String TABLE_QUERY =
"CREATE TABLE BOOKSYSTEM( ID INTEGER PRIMARY KEY AUTOINCREMENT, BOOKNAME TEXT
NOT NULL, AUTHOR TEXT NOT NULL, RATING REAL,RELEASEDATE TEXT,
DESC TEXT,CATEGORY TEXT)";
private static DatabaseHelper sDbInstance = null;
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_QUERY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public static DatabaseHelper getInstance(Context context) {
if (sDbInstance == null) {
sDbInstance = new DatabaseHelper(context);
}
return sDbInstance;
}
/**
* Method to execute SQL Query
*
* @param s
* SQL Query
* @return cursor of returned results
*/
public synchronized Cursor ExecuteRawSql(String s) {// Select Query
try {
SQLiteDatabase sqLiteDb = getReadableDatabase();
Cursor cursor = sqLiteDb.rawQuery(s, null);
return cursor;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Method to execute SQL Query
*
* @param s
* SQL Query
* @return true if query was successfully executed.
*/
public synchronized boolean ExecuteSql(String s) {// Update Query
try {
Log.d(TAG, "Actual Query--->>" + s);
SQLiteDatabase sqLiteDb = getWritableDatabase();
sqLiteDb.execSQL(s);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean saveData(String startTime, String stopTime, int stepCount) {
String qry = "INSERT INTO PEDODATA (STARTTIME,STOPTIME,STEPS) VALUES('"
+ startTime + "','" + stopTime + "','" + stepCount + "');";
return ExecuteSql(qry);
}
public ArrayList<String> getData() {
ArrayList<String> list = new ArrayList<String>();
String qry = "SELECT STARTTIME,STOPTIME,STEPS FROM PEDODATA ORDER BY ID DESC";
Cursor cursor = ExecuteRawSql(qry);
if (cursor != null && cursor.moveToFirst()) {
do {
String startTime = cursor.getString(0);
String stopTime = cursor.getString(1);
int stepCount = cursor.getInt(2);
String time = "From : " + startTime + " \nTo : " + stopTime;
String steps = " \nSteps : " + stepCount;
list.add(time + steps);
} while (cursor.moveToNext());
}
return list;
}
public boolean addNewBook(String name, String category, String AUTHOR) {
String qry = "INSERT INTO BOOKSYSTEM
(BOOKNAME,CATEGORY,AUTHOR ,RELEASEDATE) VALUES('"
+ name + "','" + category + "','" + AUTHOR + "','"+getDateTime()+"');";
return ExecuteSql(qry);
}
public boolean rateBook(int bookId, float rating) {
String qry = "UPDATE BOOKSYSTEM SET RATING=" + rating + " WHERE id="
+ bookId + "";
return ExecuteSql(qry);
}
public ArrayList<BookBean> getBookList(String category) {
ArrayList<BookBean> list = new ArrayList<BookBean>();
String qry;
if (category.equals(context.getString(R.string.toprated))) {
qry = "SELECT ID,BOOKNAME,AUTHOR,RELEASEDATE,RATING,CATEGORY FROM BOOKSYSTEM ORDER BY RATING DESC";
} else {
qry = "SELECT ID,BOOKNAME,AUTHOR,RELEASEDATE,RATING,CATEGORY
FROM BOOKSYSTEM ORDER BY RELEASEDATE DESC";
}
Cursor cursor = ExecuteRawSql(qry);
if (cursor != null && cursor.moveToFirst()) {
do {
BookBean bookName = new BookBean();
bookName.setId(cursor.getInt(0));
bookName.setBookname(cursor.getString(1));
bookName.setAuther(cursor.getString(2));
bookName.setReleaseDate(cursor.getString(3));
bookName.setRating(cursor.getFloat(4));
bookName.setCategories(cursor.getString(5));
list.add(bookName);
} while (cursor.moveToNext());
}
return list;
}
public String getDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy",
Locale.US);
String formattedDate = formatter.format(c.getTime());
String s = formattedDate;
return s;
}
}
**********************************************************************
**********************MainActivity.java***********************
package com.example.bookrecommender;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
public class MainActivity extends Activity {
private Spinner searchView;
private ArrayAdapter<String> searchAdapter;
private ListView listView;
private DatabaseHelper databaseHelper;
private BookListAdapter bookListAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize UI components
searchView = (Spinner) findViewById(R.id.searchView);
listView = (ListView) findViewById(R.id.list);
searchAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.searchCategory));
searchView.setAdapter(searchAdapter);
databaseHelper = new DatabaseHelper(getApplicationContext());
ArrayList<BookBean> list = databaseHelper.getBookList(searchView.getSelectedItem().toString());
bookListAdapter = new BookListAdapter(getApplicationContext(), list);
listView.setAdapter(bookListAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add_book) {
Intent intent=new Intent(this,AddNewBookActivity.class);
startActivity(intent);
finish();
}else if(id == R.id.action_rate_book){
Intent intent=new Intent(this,BookRatingActivity.class);
startActivity(intent);
finish();
}
return super.onOptionsItemSelected(item);
}
/**
* Find book as per search text
*
* @param bookType
*/
/* private void findBookList(String bookType) {
String[] booklist = getBooklistfromResources(bookType);
listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, booklist);
listView.setAdapter(listAdapter);
}*/
/**
* get list of books from resources
*
* @param bookType
* @return
*/
/* private String[] getBooklistfromResources(String bookType) {
String[] booklist = null;
if (bookType.equals(getString(R.string.novel))) {
booklist = getResources().getStringArray(R.array.novel);
} else if (bookType.equals(getString(R.string.fantasy))) {
booklist = getResources().getStringArray(R.array.fantasy);
} else if (bookType.equals(getString(R.string.literature))) {
booklist = getResources().getStringArray(R.array.literature);
} else if (bookType.equals(getString(R.string.scienceFiction))) {
booklist = getResources().getStringArray(R.array.scienceFiction);
} else if (bookType.equals(getString(R.string.java))) {
booklist = getResources().getStringArray(R.array.java);
}
return booklist;
}*/
*******************Program for Pizza Shop Management******************
*******************Index.html*******************
<html>
<head>
var arr = new Array();
for(i=0;i
<title>Online food ordering</title>
</head>
<body bgcolor="silver" onload="slide()">
<table align="center">
<tr>
<td><img id="image1" height="500px" width="500px" border="5"/>
</td></tr>
</table>
<form method="post" action="login.jsp">
<h1 align="center">Login</h1>
<table align="center" border=1>
<tr>
<td><b>User ID:</b></td>
<td><input type="text" name="uid"></td>
</tr>
<tr>
<td><b>Password:</b></td>
<td><input type="password" name="pass"></td>
</tr>
<tr>
<td><input type="submit" value="OK"></td>
<td><input type="reset" value="Clear"></td>
</tr>
</table>
</form><br>
<p align="center">New user click <a href="register.html">here.</a>
</body>
</html>
*******************Login.jsp*******************
<body bgcolor='silver'>
<h2 align="center" color="red">Select your category</h2>
<%@ page import="java.sql.*"%>
<%!
private Connection con;
private PreparedStatement ps;
private ResultSet rs;
%>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:system/l&t@localhost:1521:XE");
String uid=null,pass=null;
if(session.getAttribute("uid")==null){
uid = request.getParameter("uid");
pass = request.getParameter("pass");
session.setAttribute("uid", uid);
session.setAttribute("pass", pass);
}
else{
uid = session.getAttribute("uid").toString();
pass = session.getAttribute("pass").toString();
}
ps = con.prepareStatement("SELECT * FROM Users WHERE UserID=? AND Password=?");
ps.setString(1, uid);
ps.setString(2, pass);
rs = ps.executeQuery();
if(rs.next()){
ps = con.prepareStatement("SELECT * FROM Category");
rs = ps.executeQuery();
out.print("<table align='center' border=1>");
while(rs.next()){
%>
<tr>
<td><img width="500px" height="500px" src='<%="category"+rs.getInt(1)+".jpg"%>'/></td>
<td><a href='<%="prodlist.jsp?cid="+rs.getInt(1)%>'><%=rs.getString(2)%></a></td>
</tr>
<%
}
out.println("</table>");
}
else{
%>
Login failed.<br>
<a href="index.html">Home</a>
<%
}
%>
</body>
*******************Register.jsp*******************
<%@ page import="java.sql.*"%>
<%!
private Connection con;
private PreparedStatement ps;
%>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:system/l&t@localhost:1521:XE");
String uid = request.getParameter("uid");
String pass = request.getParameter("pass");
String un = request.getParameter("uname");
String addr = request.getParameter("addr");
String bdate = request.getParameter("bdate");
String pno = request.getParameter("phno");
String email = request.getParameter("email");
String gender = request.getParameter("gender");
ps = con.prepareStatement("INSERT INTO Users VALUES(?,?,?,?,to_date(?,'dd/mm/yyyy'),?,?,?)");
ps.setString(1, uid);
ps.setString(2, pass);
ps.setString(3, un);
ps.setString(4, addr);
ps.setString(5, bdate);
ps.setString(6, pno);
ps.setString(7, email);
ps.setString(8, gender);
ps.executeUpdate();
%>
User ID <b><%=uid%></b> is registered successfully.<br>
Click <a href="index.html">here</a> to login.
*******************Order.jsp*******************
<%@ page import="java.sql.*,java.util.*"%>
<%!
private Connection con;
private PreparedStatement ps;
private Statement s;
private ResultSet rs;
%>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:system/l&t@localhost:1521:XE");
s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = s.executeQuery("SELECT * FROM OrderHeader");
int ono = 1;
if(rs.last())
ono = rs.getRow()+1;
java.util.Date d = new java.util.Date();
String odate = d.getDate()+"/"+(d.getMonth()+1)+"/"+(d.getYear()+1900);
String uid = session.getAttribute("uid").toString();
float tot = Float.parseFloat(session.getAttribute("tot").toString());
ps = con.prepareStatement("INSERT INTO OrderHeader VALUES(?,to_date(?,'dd/mm/yyyy'),?,?)");
ps.setInt(1, ono);
ps.setString(2, odate);
ps.setString(3, uid);
ps.setFloat(4, tot);
ps.executeUpdate();
ps = con.prepareStatement("INSERT INTO OrderDetails VALUES(?,?,?)");
Vector v = (Vector)session.getAttribute("prodlist");
for(int i=0;i<v.size();i++){
String s = v.get(i).toString();
int k = s.indexOf(' ');
int pid = Integer.parseInt(s.substring(0,k));
k = s.lastIndexOf(' ');
int qty = Integer.parseInt(s.substring(k+1));
ps.setInt(1, ono);
ps.setInt(2, pid);
ps.setInt(3, qty);
ps.executeUpdate();
}
%>
<p align="center">Your order is placed successfully!!!Enjoy your meal.<br>
<p align="center">Order ID:<b><%=ono%></b><br>
<table border=1 align="center">
<tr>
<td><a href='continue.jsp'>Continue Shopping</a></td>
<td><a href='logout.jsp'>Logout</a></td>
</tr>
</table>
*******************Database Connection Statement*******************
CREATE TABLE Users(
UserID varchar(30) primary key,
Password varchar(20) not null,
UserName varchar(30) not null,
Address varchar(60),
BirthDate date,
PhoneNo varchar(10),
EmailID varchar(30),
Gender char(1));
CREATE TABLE Category(
CatID integer primary key,
CatDesc varchar(30) not null);
CREATE TABLE Products(
ProdID integer primary key,
ProdDesc varchar(30) not null,
Rate float,
CatID integer references Category(CatID));
INSERT INTO Category VALUES(1,'Starters');
INSERT INTO Category VALUES(2,'Main Course');
INSERT INTO Category VALUES(3,'Soups');
INSERT INTO Category VALUES(4,'Desserts');
INSERT INTO Category VALUES(5,'Beverages');
INSERT INTO Products VALUES(1,'Masala Papad',10,1);
INSERT INTO Products VALUES(2,'Veg Manchurian',100,1);
INSERT INTO Products VALUES(3,'Chicken Manchurian',150,1);
INSERT INTO Products VALUES(4,'Paneer Chilly',90,1);
INSERT INTO Products VALUES(5,'Chicken Lollypop',200,1);
INSERT INTO Products VALUES(6,'Nan',20,2);
INSERT INTO Products VALUES(7,'Plain Roti',10,2);
INSERT INTO Products VALUES(8,'Butter Roti',15,2);
INSERT INTO Products VALUES(9,'Paneer Hyderabadi',180,2);
INSERT INTO Products VALUES(10,'Paneer Tika Masal',190,2);
INSERT INTO Products VALUES(11,'Veg Tikka',190,2);
INSERT INTO Products VALUES(12,'Veg Kolhapuri',180,2);
INSERT INTO Products VALUES(13,'Veg Biryani',100,2);
INSERT INTO Products VALUES(14,'Tomato Soup',80,3);
INSERT INTO Products VALUES(15,'Hot and Sour',100,3);
INSERT INTO Products VALUES(16,'Veg clear',10,3);
INSERT INTO Products VALUES(17,'Ice cream',70,4);
INSERT INTO Products VALUES(18,'Fruit cream',100,4);
INSERT INTO Products VALUES(19,'Gulab Jamun',80,4);
INSERT INTO Products VALUES(20,'Rabadi',75,4);
INSERT INTO Products VALUES(21,'Gulab Jamun with Ice cream',120,4);
INSERT INTO Products VALUES(22,'Gajar Halwa',65,4);
INSERT INTO Products VALUES(23,'Ras malai',70,4);
INSERT INTO Products VALUES(24,'Milk shake',55,5);
INSERT INTO Products VALUES(25,'Fruit Juice',60,5);
INSERT INTO Products VALUES(26,'Cold coffee',40,5);
INSERT INTO Products VALUES(27,'Ice tea',30,5);
INSERT INTO Products VALUES(28,'Mastani',100,5);
CREATE TABLE OrderHeader(
OrderNo integer primary key,
OrderDate date,
UserID references Users(UserID),
Total float);
CREATE TABLE OrderDetails(
OrderNo integer references OrderHeader(OrderNo),
ProdID integer references Products(ProdID),
Qty integer,
primary key(OrderNo,ProdID));
**********Google MAP API CODE for Source and Destination with Distance **********
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" value="Bandra, Mumbai, India" style="width: 200px" />
Destination:
<input type="text" id="txtDestination" value="Andheri, Mumbai, India" style="width: 200px" />
<br />
<input type="button" value="Get Route" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
</tr>
</table>
http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places
var source, destination;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
google.maps.event.addDomListener(window, 'load', function () {
new google.maps.places.SearchBox(document.getElementById('txtSource
new google.maps.places.SearchBox(document.getElementById('txtDestination
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var mumbai = new google.maps.LatLng(18.9750, 72.8258);
var mapOptions = {
zoom: 7,
center: mumbai
};
map = new google.maps.Map(document.getElementById('dvMapmapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('dvPanel'));
//*********DIRECTIONS AND ROUTE**********************//
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = {
origin: source,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//*********DISTANCE AND DURATION**********************//
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: ,
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text;
var duration = response.rows[0].elements[0].duration.text;
var dvDistance = document.getElementById("dvDistance");
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "
";
dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
************************************C PROGRAM********************************
//C Program to implement Unification Algorithm
#include<stdio.h>
int no_of_pred;
int no_of_arg[10];
int i,j;
char nouse;
char predicate[10];
char argument[10][10];
void unify();
void display();
void chk_arg_pred();
void main()
{
char ch;
do{
// clrscr();
printf("\t=========PROGRAM FOR UNIFICATION=========\n");
printf("\nEnter Number of Predicates:- [ ]\b\b");
scanf("%d",&no_of_pred);
for(i=0;i<no_of_pred;i++)
{
scanf("%c",&nouse); //to accept "Enter" as a character
printf("\nEnter Predicate %d:-[ ]\b\b",i+1);
scanf("%c",&predicate[i]);
printf("\n\tEnter No.of Arguments for Predicate %c:-[ ]\b\b",predicate[i]);
scanf("%d",&no_of_arg[i]);
for(j=0;j<no_of_arg[i];j++)
{
scanf("%c",&nouse);
printf("\n\tEnter argument %d:( )\b\b",j+1);
scanf("%c",&argument[i][j]);
}
}
display();
chk_arg_pred();
// getch();
// flushall();
printf("Do you want to continue(y/n): ");
scanf("%c",&ch);
}while(ch=='y');
}
void display()
{
printf("\n\t=======PREDICATES ARE======");
for(i=0;i<no_of_pred;i++)
{
printf("\n\t%c(",predicate[i]);
for(j=0;j<no_of_arg[i];j++)
{
printf("%c",argument[i][j]);
if(j!=no_of_arg[i]-1)
printf(",");
}
printf(")");
}
}
void chk_arg_pred()
{
int pred_flag=0;
int arg_flag=0;
/*======Checking Prediactes========*/
for(i=0;i<no_of_pred-1;i++)
{
if(predicate[i]!=predicate[i+1])
{
printf("\nPredicates not same..");
printf("\nUnification cannot progress!");
pred_flag=1;
break;
}
}
/*=====Chking No of Arguments====*/
if(pred_flag!=1)
{
for(i=0;i<no_of_arg[i]-1;i++)
{
if(no_of_arg[i]!=no_of_arg[i+1])
{
printf("\nArguments Not Same..!");
arg_flag=1;
break;
}
}
}
if(arg_flag==0&&pred_flag!=1)
unify();
}
/*==========UNIFY FUNCTION=========*/
void unify()
{
int flag=0;
for(i=0;i<no_of_pred-1;i++)
{
for(j=0;j<no_of_arg[i];j++)
{
if(argument[i][j]!=argument[i+1][j])
{
if(flag==0)
printf("\n\t======SUBSTITUTION IS======");
printf("\n\t%c/%c",argument[i+1][j],argument[i][j]);
flag++;
}
}
}
if(flag==0)
{ printf("\nArguments are Identical...");
printf("\nNo need of Substitution\n");
}
}
***************************JAVA PROGRAM********************
//JAVA PROGRAM TO IMPLEMENT K-MEANS CLUSTERING ALGORITHM
//Aim:To implement Kmeans clustering algorithm.
import java.util.*;
class KMeans
{
static int count1,count2,count3;
static int d[];
static int k[][];
static int tempk[][];
static double m[];
static double diff[];
static int n,p;
static int cal_diff(int a) // This method will determine the cluster in which an element go at a particular step.
{
int temp1=0;
for(int i=0;i<p;++i)
{
if(a>m[i])
diff[i]=a-m[i];
else
diff[i]=m[i]-a;
}
int val=0;
double temp=diff[0];
for(int i=0;i<p;++i)
{
if(diff[i]<temp)
{
temp=diff[i];
val=i;
}
}//end of for loop
return val;
}
static void cal_mean() // This method will determine intermediate mean values
{
for(int i=0;i<p;++i)
m[i]=0; // initializing means to 0
int cnt=0;
for(int i=0;i<p;++i)
{
cnt=0;
for(int j=0;j<n-1;++j)
{
if(k[i][j]!=-1)
{
m[i]+=k[i][j];
++cnt;
}}
m[i]=m[i]/cnt;
}
}
static int check1() // This checks if previous k ie. tempk and current k are same.Used as terminating case.
{
for(int i=0;i<p;++i)
for(int j=0;j<n;++j)
if(tempk[i][j]!=k[i][j])
{
return 0;
}
return 1;
}
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
/* Accepting number of elements */
System.out.println("Enternumber of elements ");
n=scr.nextInt();
d=new int[n];
/* Accepting elements */
System.out.println("Enter" elements: ");
for(int i=0;i<n;++i)
d[i]=scr.nextInt();
/* Accepting num of clusters */
System.out.println("Enternumber of clusters: ");
p=scr.nextInt();
/* Initialising arrays */
k=new int[p][n];
tempk=new int[p][n];
m=new double[p];
diff=new double[p];
/* Initializing m */
for(int i=0;i<p;++i)
m[i]=d[i];
int temp=0;
int flag=0;
do
{
for(int i=0;i<p;++i)
for(int j=0;j<n;++j)
{
k[i][j]=-1;
}
for(int i=0;i<n;++i) // for loop will cal cal_diff(int) for every element.
{
temp=cal_diff(d[i]);
if(temp==0)
k[temp][count1++]=d[i];
else
if(temp==1)
k[temp][count2++]=d[i];
else
if(temp==2)
k[temp][count3++]=d[i];
}
cal_mean(); // call to method which will calculate mean at this step.
flag=check1(); // check if terminating condition is satisfied.
if(flag!=1)
/*Take backup of k in tempk so that you can check for equivalence in next step*/
for(int i=0;i<p;++i)
for(int j=0;j<n;++j)
tempk[i][j]=k[i][j];
System.out.println("\n\nAt step");
System.out.println("\nValuelusters");
for(int i=0;i<p;++i)
{
System.out.print("K"+(i+1or(int j=0;k[i][j]!=-1 && j<n-1;++j)
System.out.print(k[i][j]+" ");
System.out.println("}");
}//end of for loop
System.out.println("\nValue ");
for(int i=0;i<p;++i)
System.out.print("m"+(i+1)+"="+m;count2=0;count3=0;
}
while(flag==0);
System.out.println("\n\n\nThel Clusters By Kmeans are as follows: ");
for(int i=0;i<p;++i)
{
System.out.print("K"+(i+1or(int j=0;k[i][j]!=-1 && j<n-1;++j)
System.out.print(k[i][j]+" ");
System.out.println("}");
}
}
}
/*
OUTPUT
C:\Users\Aman\Desktop\Aman>javac k_means.java
C:\Users\Aman\Desktop\Aman>java k_means
Enter the number of elements
8
Enter 8 elements:
2 3 6 8 12 15 18 22
Enter the number of clusters:
3
At this step
Value of clusters
K1{ 2 }
K2{ 3 }
K3{ 6 8 12 15 18 22 }
Value of m
m1=2.0 m2=3.0 m3=13.5
At this step
Value of clusters
K1{ 2 }
K2{ 3 6 8 }
K3{ 12 15 18 22 }
Value of m
m1=2.0 m2=5.666666666666667 m3=16.75
At this step
Value of clusters
K1{ 2 3 }
K2{ 6 8 }
K3{ 12 15 18 22 }
Value of m
m1=2.5 m2=7.0 m3=16.75
At this step
Value of clusters
K1{ 2 3 }
K2{ 6 8 }
K3{ 12 15 18 22 }
Value of m
m1=2.5 m2=7.0 m3=16.75
The Final Clusters By Kmeans are as follows:
K1{ 2 3 }
K2{ 6 8 }
K3{ 12 15 18 22 } */
No comments:
Post a Comment