Saturday 6 June 2015

TE-SEM6_PL-03 (Programming Laboratory III)

  TE-SEM6_PL-03
(Programming Laboratory III)
------------------------------
Practicals List:
-----------------------------
Assignments Group A (Mandatory)
1]. Develop an application using Beeglebone Black/ ARM Cortex A5 development board to simulate the operations of LIFT.
2]. Develop an application using Beeglebone Black/ ARM Cortex A5 development board to simulate the working of signal lights.
3]. Implement an calculator (64 bit Binary Multiplication) application using concurrent lisp
4]. Apply the Following Software Engineering to all assignments(No 1,2,3 of Group A and B). Mathematical Modeling must result into UML Requirements.
Apply Assignment No 4a to 4d for all Group A and Group B assignments of Embedded Operating system and Concurrent and Distributed Programming. Use tools Open source tools like ArgoUML, UMLLet, StarUML or equivalent tools for UML models) Or Use Agile or Scrum-Agile methodologies and Tools.Use of Possitive and Negative Testing.
5]. Create Project plan, SRS, Design document and Test Plan for one group-C assignment from embedded operating system or Concurrent and Distributed Programming
6]. Write an application to parse input text file concurrently and compare the result of concurrent parsing with serial parsing ( Use concurrent YACC parser)
Assignments Group B (Any Six Assignments, All assignments to be covered in the Batch)
1]. Write an application to and demonstrate the change in BeagleBoard/ ARM Cortex A5 /Microprocessor /CPU frequency or square wave of programmable frequency.
2]. Implement a Parallel Quick Sort algorithm using NVIDIA GPU or equivalent ARM board.
3]. Vedic Mathematics method to find square of 2-digit number is used in a distributed programming. Use shared memory and distributed (multi-CPU) programming to complete the task.
4]. Implement a Parallel ODD-Even Sort algorithm using GPU or ARM equivalent.
5]. Implement n-ary search algorithm using OPENMP
6]. Implement concurrent prims algorithm using OPENMP
7]. Implement nxn matrix parallel multiplication using CUDA/OpenCL GPU, use shared memory.
8]. Develop a network based application by setting IP address on BeagleBoard/ ARM Cortex A5.
9]. Implement a Multi-threading application for echo server using socket programming in JAVA
10]. Implement Reader-Writer problem using OPENMP
11]. Implement a dinning philosophers problem using OpenCL wherein each philosopher is a distributed computer memory in a cluster.
12]. A text file is stored in a distributed manner on three hard disks on three machines such that consecutive lines, one per hard disk are stored in cyclic manner. Write a program using OpenCL to read/Write/Modify the file.
13]. A file holds a data structure that is written and modified by number of users in a distributed manner. Multiple users on multiple computers use Read-Modify-Write cycle provided resource is available else use use modify once before exit. Write necessary Program using OpenCL.
14]. Perform Assignment No 4 of Group A for Assignment No 12 of Group-B using UMLLet
15]. Perform Assignment No 4 of Group A for Assignment No 13 of Group-B usung concurrent UML.
Assignment Group C: Advance Technology Assignments (Any One)
1]. Develop Robotics(stepper motor) Application using Beagle Board.
2]. Develop bus arbitration logic using VME/PCI bus for cluster of CPU boards for high performance computing (BIG DATA)
3]. Implement a Distributed matrix multiplication using CUDA / OpenMPI
// ASSIGNMENT NO.:A_ 01
/* TITLE   :1 Develop an application using Beeglebone Black/ ARM Cortex A5 development board
to simulate the operations of LIFT.
'''
#!/usr/bin/python
###########################################
# * Python code for  LIFT Simulation using
# * Beaglebone Black running Debian 7 Linux distribution
###########################################

import sys
import time
import select
from liftpins import *
from gpio import *

def liftLEDExit (gpio):
   gpioSetVal(gpio, val="0")
   gpioUnexport(gpio)
   return
  
def liftLEDInit (gpio):
   gpioExport(gpio)
   gpioSetDir(gpio, flag="out")
   gpioSetVal(gpio, val="0")
   return
  
def liftLEDOn (gpio):
   gpioSetVal(gpio, val="1")
   return
  
def liftLEDOff (gpio):
   gpioSetVal(gpio, val="0")
   return
def liftButtonExit (gpio):
   gpioUnexport(gpio)
   return
  
def liftButtonInit (gpio):
   gpioExport(gpio)
   gpioSetDir(gpio, flag="in")
   gpioSetEdge(gpio, flag="falling")
   return

def liftInitAll():
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDInit(str(dir_leds[i]))
         
   for i in range(0, NO_OF_FLOORS):
       liftLEDInit(str(pos_leds[i]))
       liftLEDInit(str(lift_leds[i]))
       liftButtonInit(str(lift_buttons[i]))
   return

def liftExitAll():
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDExit(str(dir_leds[i]))
         
   for i in range(0, NO_OF_FLOORS):
       liftLEDExit(str(pos_leds[i]))
       liftLEDExit(str(lift_leds[i]))
       liftButtonExit(str(lift_buttons[i]))
   print "\n=== Demonstration END ===\n"
   return

def liftDefaultPos():
   liftLEDOn(str(pos_leds[DEFAULT_LIFT_POS]))
   return

def liftDirUp():
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDOn(str(dir_leds[i]))
       time.sleep(0.5)
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDOff(str(dir_leds[i]))
   return

def liftDirDown():
   for i in range(NO_OF_DIR_LEDS, 0, -1):
       liftLEDOn(str(dir_leds[i-1]))
       time.sleep(0.5)
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDOff(str(dir_leds[i]))
   return



def GetButtonVal():
   try:     
       fo0 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_0) + "/value" ,"r") 
       fo0.read(2)
       floor_set[0]["fd"] = fo0
      
       fo1 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_1) + "/value" ,"r") 
       fo1.read(2)
       floor_set[1]["fd"] = fo1
      
       fo2 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_2) + "/value" ,"r") 
       fo2.read(2)
       floor_set[2]["fd"] = fo2
      
       fo3 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_3) + "/value" ,"r") 
       fo3.read(2)
       floor_set[3]["fd"] = fo3
      
       print "\nWaiting for button press ..."
       r, w, ex = select.select([], [], [fo0, fo1, fo2, fo3])
      
       for i in range(len(floor_set)):
          if floor_set[i]["fd"] in ex:
              print "LIFT button is pressed for floor # %d" % i
              liftLEDOn(str(floor_set[i] ["led"]))
              time.sleep(1)
              but = i
              fo = floor_set[i]["fd"]   
              fo.seek(0, 0);
              str1 = fo.read(1)
              #print "Button Pressed ! Value = ", str1
       fo0.close()
       fo1.close()
       fo2.close()
       fo3.close()
       return but
  
   except IOError:
                return


try:
   print "\nLift Operation Simulation using Python\n"
   print  "-----------------------------------------------\n"
   liftInitAll()
   liftDefaultPos()

   cur_flr = DEFAULT_LIFT_POS
  
   while True:
       new_flr = GetButtonVal()
       if new_flr > cur_flr:
          tmp = cur_flr
          print "LIFT going UP to floor #%d" %new_flr
          while (tmp != new_flr):
              liftDirUp()
              time.sleep(0.01)
              liftLEDOff(str(pos_leds[tmp]))
              tmp += 1
              liftLEDOn(str(pos_leds[tmp]))
              time.sleep(0.5)
       elif new_flr < cur_flr:
          tmp = cur_flr
          print "LIFT going DOWN to floor #%d" %new_flr
          while (tmp != new_flr):
              liftDirDown()
              time.sleep(0.01)
              liftLEDOff(str(pos_leds[tmp]))
              tmp -= 1
              liftLEDOn(str(pos_leds[tmp]))
              time.sleep(0.5)
      
       cur_flr = new_flr
       liftLEDOff(str(lift_leds[new_flr]))  
       time.sleep(1)
        
   liftExitAll()
   exit()
except KeyboardInterrupt:
   liftExitAll()
   print "Program Exit due to CTRL-C"
   exit()
       sys.exit(0)

###########################################
# * Python GPIO Functions for LIFT Simulation
# * using Baglebone Black running Debian 7 Linux distribution
###########################################
import sys
import os

SYSFS_GPIO_DIR = "/sys/class/gpio"

def gpioUnexport (gpio):
   try:
       fo = open(SYSFS_GPIO_DIR + "/unexport","w") 
       fo.write(gpio)
       fo.close()
       return
   except IOError:
       return
            

def gpioExport (gpio):
   try:
       fo = open(SYSFS_GPIO_DIR + "/export","w") 
       fo.write(gpio)
       fo.close()
       return
   except IOError:
                return

def gpioSetDir (gpio, flag):
   try:
      fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w") 
      fo.write(flag)
      fo.close()
      return
   except IOError:
                return

def gpioSetVal (gpio, val):
   try:
       fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w") 
       fo.write(val)
       fo.close()
       return
   except IOError:
                return
def gpioSetEdge (gpio, flag):
   try:
       fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/edge" ,"w") 
       fo.write(flag)
       fo.close()
       return
   except IOError:
                return

####################################################
# * Python File for Lift Operation Simulation Add-on Card
# * for GPIO PIN Configurations and Other Definitions
####################################################
LED_1       =       (0 * 32) + 3                
LED_2       =       (0 * 32) + 23              
LED_3       =       (0 * 32) + 2                
LED_4       =       (0 * 32) + 26              
LED_5       =       (1 * 32) + 17              
LED_6       =       (1 * 32) + 15              
LED_7       =       (0 * 32) + 15              
LED_8       =       (1 * 32) + 14              
LED_9       =       (0 * 32) + 30
LED_10     =       (2 * 32) + 2
LED_11     =       (1 * 32) + 28
LED_12     =       (2 * 32) + 3
LED_13     =       (0 * 32) + 31
LED_14     =       (2 * 32) + 5
LED_15     =       (1 * 32) + 18
SW_1        =       (0 * 32) + 14              
SW_2        =       (0 * 32) + 27              
SW_3        =       (0 * 32) + 22              
SW_4        =       (2 * 32) + 1       
# DIRECTIN LEDS: to represent lift direction (up or down)
LIFT_DIR_1   =    LED_9
LIFT_DIR_2   =    LED_10
LIFT_DIR_3   =    LED_11
LIFT_DIR_4   =    LED_12
LIFT_DIR_5   =    LED_13
LIFT_DIR_6   =    LED_14
LIFT_DIR_7   =    LED_15
# POSITION LEDS: LEDs to indicate the current position of Lift
LIFT_POS_0   =    LED_5
LIFT_POS_1   =    LED_6
LIFT_POS_2   =    LED_7
LIFT_POS_3   =    LED_8
# LIFT BUTTONS: corresponding to each floor of the Lift
LIFT_BUTTON_0   =    SW_1
LIFT_BUTTON_1   =    SW_2
LIFT_BUTTON_2   =    SW_3
LIFT_BUTTON_3   =    SW_4
# LIFT LEDS: indication for BUTTON Press on each floor
LIFT_LED_0   =    LED_1
LIFT_LED_1   =    LED_2
LIFT_LED_2   =    LED_3
LIFT_LED_3   =    LED_4
# An array of DIRECTIN LEDS
dir_leds = [       LIFT_DIR_1,
                   LIFT_DIR_2,
                   LIFT_DIR_3,
                   LIFT_DIR_4,
                   LIFT_DIR_5,
                   LIFT_DIR_6,
                   LIFT_DIR_7
             ]    
# An array of POSITION LEDS
pos_leds = [
                   LIFT_POS_0,
                   LIFT_POS_1,
                   LIFT_POS_2,
                   LIFT_POS_3
             ]
lift_leds = [
                   LIFT_LED_0,
                   LIFT_LED_1,
                   LIFT_LED_2,
                   LIFT_LED_3
             ]
lift_buttons = [
                    LIFT_BUTTON_0,
                    LIFT_BUTTON_1,
                    LIFT_BUTTON_2,
                    LIFT_BUTTON_3
             ]
NO_OF_FLOORS        =     4
NO_OF_DIR_LEDS     =     7
DEFAULT_LIFT_POS =      0
floor_set = [
                   {"fd":-1, "button":LIFT_BUTTON_0, "led":LIFT_LED_0},
                   {"fd":-1, "button":LIFT_BUTTON_1, "led":LIFT_LED_1},
                   {"fd":-1, "button":LIFT_BUTTON_2, "led":LIFT_LED_2},                        
                   {"fd":-1, "button":LIFT_BUTTON_3, "led":LIFT_LED_3}       
             ]

'''OUTPUT
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
40:69:fa:bb:3f:36:81:62:b7:a3:92:7d:d7:08:30:94.
Please contact your system administrator.
Add correct host key in /home/sl171/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /home/sl171/.ssh/known_hosts:1
  remove with: ssh-keygen -f "/home/sl171/.ssh/known_hosts" -R 192.168.7.2
ECDSA host key for 192.168.7.2 has changed and you have requested strict checking.
Host key verification failed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$  ssh-keygen -f "/home/sl171/.ssh/known_hosts" -R 192.168.7.2
# Host 192.168.7.2 found: line 1 type ECDSA
/home/sl171/.ssh/known_hosts updated.
Original contents retained as /home/sl171/.ssh/known_hosts.old
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
The authenticity of host '192.168.7.2 (192.168.7.2)' can't be established.
ECDSA key fingerprint is 40:69:fa:bb:3f:36:81:62:b7:a3:92:7d:d7:08:30:94.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.7.2' (ECDSA) to the list of known hosts.
Debian GNU/Linux 7

BeagleBoard.org Debian Image 2015-03-01

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian

default username:password is [debian:temppwd]

Last login: Sun Mar  1 20:48:06 2015 from sl243-hp-compaq-4000-pro-sff-pc.local
root@beaglebone:~# ls
a.out  ad.c  s.py  v.py
root@beaglebone:~# cd ..
root@beaglebone:/# ls
bin  boot  dev etc  export  home  lib     lost+found  media  mnt opt  proc  root  run  sbin  selinux  srv  sys  tmp  usr  var
root@beaglebone:/#  cd media
root@beaglebone:/media# ls
BEAGLEBONE  BEAGLEBONE_
root@beaglebone:/media# cd BEAGLEBONE_
root@beaglebone:/media/BEAGLEBONE_# ls
01elevator_cpp         02traffic_python  Docs     ID.txt    README.htm  START.htm    nfs-uEnv.txt
01elevator_python  App                     Drivers  LICENSE.txt  README.md   autorun.inf  scripts
root@beaglebone:/media/BEAGLEBONE_# cd 01elevator_python
root@beaglebone:/media/BEAGLEBONE_/01elevator_python# ls
elevator.py  gpio.py  gpio.pyc       liftpins.py  liftpins.pyc
root@beaglebone:/media/BEAGLEBONE_/01elevator_python# python elevator.py

Lift Operation Simulation using Python

-----------------------------------------------


Waiting for button press ...
LIFT button is pressed for floor # 0


Press any LIFT button...
LIFT button is pressed for floor #1
LIFT going UP to floor #1 

Press any LIFT button...
LIFT button is pressed for floor #3
LIFT going UP to floor #3

Press any LIFT button...
LIFT button is pressed for floor #2
LIFT going DOWN to floor #2

Press any LIFT button...
LIFT button is pressed for floor #0
LIFT going DOWN to floor #0

Press any LIFT button...
LIFT button is pressed for floor #1
LIFT going UP to floor #1

Press any LIFT button...
LIFT button is pressed for floor #0
LIFT going DOWN to floor #0

Press any LIFT button...
LIFT button is pressed for floor #3
LIFT going UP to floor #3

Waiting for button press ...
^C
=== Demonstration END ===

Program Exit due to CTRL-C
root@beaglebone:/media/BEAGLEBONE_/01elevator_python#
Broadcast message from root@beaglebone (Sun Mar  1 20:53:24 2015):

Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$

'''


// ASSIGNMENT NO.:A_ 02
/* TITLE   : 2 Develop an application using Beeglebone Black/ ARM Cortex A5 development board
to simulate the working of signal lights.
'''
#!/usr/bin/python
##########################################################
# * Python code for Traffic Signal Simulation using
# * Beaglebone Black running Debian 7 Linux distribution
##########################################################


import sys
import time
from gpio import *
from ledpins import *

def lightExit (gpio):
      gpioSetVal(gpio, val="0")
      gpioUnexport(gpio)
      return
     
def lightInit (gpio):
      gpioExport(gpio)
      gpioSetDir(gpio, flag="out")
      gpioSetVal(gpio, val="0")
      return
     
def lightOn (gpio):
      gpioSetVal(gpio, val="1")
      return
     
def lightOff (gpio):
      gpioSetVal(gpio, val="0")
      return
     
     
def trafficInitAll():
      lightInit(str(NORTH_GREEN))
      lightInit(str(NORTH_YELLOW))
      lightInit(str(NORTH_RED))
      lightInit(str(EAST_GREEN))
      lightInit(str(EAST_YELLOW))
      lightInit(str(EAST_RED))
      lightInit(str(SOUTH_GREEN))
      lightInit(str(SOUTH_YELLOW))
      lightInit(str(SOUTH_RED))
      lightInit(str(WEST_GREEN))
      lightInit(str(WEST_YELLOW))
      lightInit(str(WEST_RED))
      return     

def trafficExitAll():
      lightExit(str(NORTH_GREEN))
      lightExit(str(NORTH_YELLOW))
      lightExit(str(NORTH_RED))
      lightExit(str(EAST_GREEN))
      lightExit(str(EAST_YELLOW))
      lightExit(str(EAST_RED))
      lightExit(str(SOUTH_GREEN))
      lightExit(str(SOUTH_YELLOW))
      lightExit(str(SOUTH_RED))
      lightExit(str(WEST_GREEN))
      lightExit(str(WEST_YELLOW))
      lightExit(str(WEST_RED))
      return     

def northSouthOn():
      lightOff(str(EAST_YELLOW))
      lightOff(str(WEST_YELLOW))
      lightOff(str(NORTH_RED))
      lightOff(str(SOUTH_RED))

      lightOn(str(EAST_RED))
      lightOn(str(WEST_RED))

      lightOn(str(NORTH_GREEN))
      lightOn(str(SOUTH_GREEN))

      time.sleep(10)

      lightOff(str(NORTH_GREEN))
      lightOff(str(SOUTH_GREEN))

      lightOn(str(NORTH_YELLOW))
      lightOn(str(SOUTH_YELLOW))
      time.sleep(1)
      return


def eastWestOn():
      lightOff(str(NORTH_YELLOW))
      lightOff(str(SOUTH_YELLOW))
      lightOff(str(EAST_RED))
      lightOff(str(WEST_RED))

      lightOn(str(NORTH_RED))
      lightOn(str(SOUTH_RED))

      lightOn(str(EAST_GREEN))
      lightOn(str(WEST_GREEN))

      time.sleep(10)

      lightOff(str(EAST_GREEN))
      lightOff(str(WEST_GREEN))

      lightOn(str(EAST_YELLOW))
      lightOn(str(WEST_YELLOW))
      time.sleep(1)
      return
     
     
try:       
      print "\nTraffic Signal Light Simulation using Python"
      print "-----------------------------------------------"
      trafficExitAll()
      trafficInitAll()
      for x in range(0, 10):
            print "\nNORTH-SOUTH    --> [GO]"
            print "EAST-WEST --> [STOP]\n"
            northSouthOn()
            time.sleep(1)
            print "\nEAST-WEST      --> [GO]"
            print "NORTH-SOUTH      --> [STOP]\n"
            eastWestOn()
            time.sleep(1)

      trafficExitAll() 
      print "done"
      exit()
except KeyboardInterrupt:
      trafficExitAll() 
      print "Program Exit due to CTRL-C"
      exit()
      sys.exit(0)
##########################################################
# * Python GPIO Functions for Traffic Signal Simulation
# * using Baglebone Black running Debian 7 Linux distribution
##########################################################


import sys
import os

SYSFS_GPIO_DIR = "/sys/class/gpio"


def gpioUnexport (gpio):
      try:
            fo = open(SYSFS_GPIO_DIR + "/unexport","w") 
            fo.write(gpio)
            fo.close()
            return
      except IOError:
            return
                 

def gpioExport (gpio):
      try:
            fo = open(SYSFS_GPIO_DIR + "/export","w") 
            fo.write(gpio)
            fo.close()
            return
      except IOError:
                return


def gpioSetDir (gpio, flag):
      try:
            fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w") 
            fo.write(flag)
            fo.close()
            return
      except IOError:
                return


def gpioSetVal (gpio, val):
      try:
            fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w") 
            fo.write(val)
            fo.close()
            return
      except IOError:
                return
##########################################################
# * Python File for Traffic Signal Simulation Add-on Card
# * for GPIO PIN Configurations and Other Definitions
##########################################################

LED_1 =     (0 * 32) + 3           
LED_2 =     (0 * 32) + 23          
LED_3 =     (0 * 32) + 2           
LED_4 =     (0 * 32) + 26          

LED_5 =     (1 * 32) + 17          
LED_6 =     (1 * 32) + 15          
LED_7 =     (0 * 32) + 15          
LED_8 =     (1 * 32) + 14          

LED_9 =     (0 * 32) + 14          
LED_10=     (0 * 32) + 27          
LED_11=     (0 * 32) + 22          
LED_12=     (2 * 32) + 1     



NORTH_GREEN       =     LED_1
NORTH_YELLOW      =     LED_5
NORTH_RED         =     LED_9

EAST_GREEN        =     LED_2
EAST_YELLOW       =     LED_6
EAST_RED          =     LED_10

SOUTH_GREEN       =     LED_3
SOUTH_YELLOW            =     LED_7
SOUTH_RED         =     LED_11

WEST_GREEN        =     LED_4
WEST_YELLOW       =     LED_8
WEST_RED          =     LED_12
'''  Output
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
Debian GNU/Linux 7
BeagleBoard.org Debian Image 2015-03-01

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian

default username:password is [debian:temppwd]

Last login: Sun Mar  1 20:51:37 2015 from sl243-hp-compaq-4000-pro-sff-pc-2.local
root@beaglebone:~# ls               
Desktop  a.cpp     a.out  bs.cpp  cpu.py  cpu2.py cpu3.py  ps.cpp  r.cpp
root@beaglebone:~# cd ..
root@beaglebone:/# ls
agg  bios.c    boot  etc   gpio.py   home     ledpins.py   lib             media  opt   root  sbin         srv     tmp     traffic2.py  var
bin  bios.c.1  dev   gpio  gpio.pyc  ledpins  ledpins.pyc  lost+found  mnt    proc  run   selinux  sys    traffic1  usr
root@beaglebone:/# python traffic2.py

Traffic Signal Light Simulation using Python
-----------------------------------------------

NORTH-SOUTH    --> [GO]
EAST-WEST         --> [STOP]

EAST-WEST         --> [GO]
NORTH-SOUTH    --> [STOP]

NORTH-SOUTH    --> [GO]
EAST-WEST         --> [STOP]

EAST-WEST         --> [GO]
NORTH-SOUTH    --> [STOP]

NORTH-SOUTH    --> [GO]
EAST-WEST         --> [STOP]

^CProgram Exit due to CTRL-C
root@beaglebone:/#
Broadcast message from root@beaglebone (Sun Mar  1 20:55:53 2015):

Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$
'''



// ASSIGNMENT NO.: 03
/* TITLE   : Implement an calculator (64 bit Binary Multiplication) application using                     concurrent lisp
//=================================================================
(defvar a)
(defvar b)
(defvar c)
(defvar d)    


(write-line " Enter two numbers in decimal : ")

 
    (setf a(read))
    (setf b(read))

    (sb-thread:make-thread(lambda()
                (progn
                (sleep 0)
                (setf c(+ a b))
                (print "ADDITION in binary: ")
                (format t " ~b" c )
                (print "ADDITION in decimal: ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(- a b))
                (print "SUBTRACTION in binary: ")
                (format t " ~b" c )
                (print "SUBTRACTION in decimal: ")
                (print c))))

     (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* a b))
                (print "MULTIPLICATION in binary: ")
                (format t " ~b" c )
                (print "MULTIPLICATION IN DECIMAL: ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* a a))
                (print "SQUARE in binary: ")
                (format t " ~b" c )
                (print "SQUARE OF 1st NUMBER  : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* b b b))
                (print "CUBE OF 2ND NUMBER : ")
                (print c)))) 


    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(sin a))
                (print "SINE OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(tan a))
                (print "TAN OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(cos a))
                (print "COSINE OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(acos a))
                (print "SEC OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(asin a))
                (print "COSEC OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(atan a))
                (print "COT OF 1ST NUMBER : ")
                (print c))))



    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(min a b))
                (print "MINIMUM NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(max a b))
                (print "MAXIMUM NUMBER : ")
                (print c))))

    

(exit)



*************output*********************

This is SBCL 1.1.14.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")
 Enter two numbers in decimal :
90
0

"ADDITION in binary: "  1011010
"ADDITION in decimal: "
90
"SUBTRACTION in binary: "  1011010
"SUBTRACTION in decimal: "
90
"MULTIPLICATION in binary: "  0
"MULTIPLICATION IN DECIMAL: "
0
"SQUARE in binary: "  1111110100100
"SQUARE OF 1st NUMBER  : "
8100
"CUBE OF 2ND NUMBER : "
0
"SINE OF 1ST NUMBER : "
0.89399666
"TAN OF 1ST NUMBER : "
-1.9952004
"COSINE OF 1ST NUMBER : "
-0.44807363
"SEC OF 1ST NUMBER : "
#C(0.0 5.192926)
"COSEC OF 1ST NUMBER : "
#C(1.5707964 -5.192926)
"COT OF 1ST NUMBER : "
1.5596857
"MINIMUM NUMBER : "
0
"MAXIMUM NUMBER : "

90

 
**************************************************
 Grp-A 5].
**************************************************


ASSIGNMENT NO.:-

Aim: - Assignment to Create Project plan, SRS, Design document and Test Plan for one group-C assignment(Stepper Motor) from embedded operating system or Concurrent and Distributed Programming.

Objective: To create the project plan, SRS, design document and test plan.
PROJECT PLAN:-
Project planning is a discipline for stating how to complete a project within a certain timeframe, usually with defined stages, and with designated resources. A project plan, according to the Project Management Body of Knowledge, is: "...a formal, approved document used to guide both project execution and project control. The primary uses of the project plan are to document planning assumptions and decisions, facilitate communication among stakeholders, and document approved scope, cost, and schedule baselines. A project plan may be summarized or detailed. The objective of a project plan is to define the approach to be used by the Project team to deliver the intended project management scope of the project.
At a minimum, a project plan answers basic questions about the project:
·                  Why? - What is the problem or value proposition addressed by the project? Why is it being sponsored?
·                  What? - What is the work that will be performed on the project? What are the major products/deliverables?
·                  Who? - Who will be involved and what will be their responsibilities within the project? How will they be organized?
·                  When? - What is the project timeline and when will particularly meaningful points, referred to as milestones, be complete?
Project plan for Stepper Motor is as follows:
Table:
Category
Recommended Action Item
Time span
1.               Planning and gathering requirement
·                  Make algorithm for project
·                  Requirement include Beagle Bone and System with required software
2. System
·                  Start to create the project.
·                  Generate the code.
4 hrs
3. Beagle Bone Black
·                  Create a connection between system & beagle board.
·                  Check whether the beagle board successfully installed or not?


2 hrs
4. Stepper Motor
·                  Create a connection between beagle board and stepper motor.

15 min.
5. Testing of Project
·                  Testing of connection with Beagle bone and Stepper motor
·                  Testing Results
20 Min
SRS(Software Requirements Specifications):-

Software Requirements Specification (SRS) is a perfect detailed description of the behavior of the system to be developed. That is SRS document is an agreement between the developer and the customer covering the functional and non functional requirements of the software to be developed. SRS is considered as a contract between the customer and the developer. This SRS document will be  used for verifying whether all the functional and non functional requirements specified in the SRS are implemented in the product.  The complete description of the functions to be performed by the software specified in the SRS will assist the potential users to determine if the software specified meets their needs or how the software must be modified to meet their needs. 
1.                Flexibility:
Flexibility is the first software requirement specification for any project. The flexibility of the stepper motor depends on frequency of the stepper motor. If the frequency is increased rotation of the stepper motor is increased. And the frequency is decreased then the rotation of the stepper motor is also decreased.

2.                Performance:
Performance of the system is depends on the working of all the hardware and software components of the system which are used in project developments. As well as performance of the system also depends on code, which is used for developing the project. The code should be more flexible, scalable, and easy to implement.

3.                Design constraints imposed on an implementation:
a.                Hardware Requirements:
1. PC(x86 Architecture)
2. Beagle Bone Black
3. Stepper Motor Board
4. Power supply cable 5v and 12v
b) Software Requirements:
1.                Beagle Bone Drives
2.                Power Supply
3.                Operating System
4.                gcc compiler on target for direct compilation of source.

General Technical Specifications:
1) Hardware:
Supply, installation, commissioning and maintenance of all necessary hardware and networking equipments and its connectivity as specified in the detailed specification. As a part of the project, the vendor should procure the required hardware and build the infrastructure as detailed in the Specifications. The vendor shall take the responsibility to install the servers, switches, routers, backup and tape devices, Workstation PCs, and other necessary hardware/software at the sites defined in the bid proposal sheet.


2) Networking:
The scope of work covers supply, installation, commissioning and maintenance of LAN at datacenter, Customer care centers, Sub division, division, Circle, Head Quarter and any other office of the utility as per their requirement along with creation of VPN/ MPLS based WAN solution. The vendor shall also provide the necessary drawings and plan for installation, sizing, cabling and connectivity and the bill of material for the networking
of all the locations specified herein.

3) GIS System Software and maps:
Supply, installation, commissioning and maintenance of GIS software and latest satellites imagery maps for GIS based customer indexing and asset mapping in the specified town. The successful bidder shall provide the maps along with the certificate and rights in favor of owner from the source that these are the latest as on date of purchase which should be later to award date.

DESIGN DOCUMENTS:-

The following documents (one set each) will be required for smooth functioning of the system at
data center and DR center:
The successful vendor will provide ongoing product information for referential purposes and facilitating self-education by Utility personnel.
Key aspects that the vendor will be evaluated on but not limited to include:
What documentation is included in the standard license fee, for example:
·                  User manuals;
·                  Technical manuals;
·                  Installation guides;
·                  Business process guides;
·                  Program flow descriptions;
·                  Data model descriptions;
·                  Sample reports;
·                  Screen formats;
·                  Toolkit guides;
·                  Troubleshooting guides;
·                  Frequently asked question (FAQ) guides.

Introduction of Stepper Motor Basics:
Working of stopper motor:
·                  Stepper motor consists of main parts called rotor and stator. A rotor is permanent magnetic rotating shaft in the middle and stator is the electromagnets positioned at specified location surrounding the rotor.

·                  Fig. Shows the arrangement of stator and rotor:



·                  The middle motor align itself with the magnetic field created as the effect of polarization
of each stator. Once a stator is electrocuted i.e. provided with a high voltage, it is magnetized and creates north and south poles of its own. As a result of this the middle rotor i.e. permanent magnet gets attracted towards the magnetized stator.
·                  The motor rotates 90, in each step. Such scenario is known as full step mode of operation.
Table: Working off step motor
D
C
B
A
0
0
0
1
0
0
1
0
0
1
0
0
1
0
0
0
1:Stator is magnetized
0: Stator in the normal state
Interfacing with Beagle Bone:-
We are using pin configuration to interface beagle board with stepper motor:
BBB P9 slot has been used for interfacing with stepper motor.
Stepper motor is connected on a PCB board with 4 stators connected to FRC26 connector pins in the format ‘A’ stator from stepper motor to pin no. 19 on FRC, similarly ‘B’ on 20,’C’ on 21,’D’ on 22.
Pins 11,12,13,14 from BBB P9 are connected to FRC pins on PCB board.
This configuration is shown in table
Connector slot no.
BBB PIN no.
PIN Description
PIN connects to stepper motor connected FRC
Function
P9
1,2
GND
GND
GND
P9
5
VCC[5V]
VCC
VCC
P9
11
GPIO[30]
FRC-21 pin
OUT
P9
12
GPIO[28]
FRC-22 pin
OUT
P9
13
GPIO[31]
FRC-19 pin
OUT
P9
14
GPIO[18]
FRC-20 pin
OUT

Each BBB pin GPIO number associated with it referred as GPIOX_Y.
Once BBB pins are selected for connection, calculate the GPIO pin number using BBB architecture and formula ((X*32)+Y).
This GPIO number will be used in program using value parameter. All the stators will be activated by setting its pin value to high i.e. 1.
Once the connection is done we are ready to write our program and performing GPIO setting (activation and direction) on Beagle Bone.

TEST PLAN:-

Test plans are prepared for each phase of testing. The initial test plan is created during the Project Planning phase. The initial test plan describes who performs which type of testing and when. Ideally master test plan covers all types of test i.e. from unit testing to production testing. The Lead Partner along with consortium partners is expected to submit the test plans to Utility for approval. Any changes made to the test plan during the project life cycle should be communicated to UTILITY for approval.


Test plans contains following items:
_ Roles and responsibilities of test team
o Approach to testing
o Function testing
o Security testing
o User Interface and reports testing
o Concurrency testing
o Performance and Load testing
_ Test Scenarios along with entry and exit criteria
_ Test specifications
_ Suspension and resumption criteria


Sr No.
Test Case Name
Steps/Action
Expected Result
Actual Result
Remark
1
Checking connections between system and Beagle bone
Whether GPIO is assign or not
Beagle bone should be connected successfully.
Beagle bone was connected successfully.
Pass
2
Checking connection between Beagle bone and Stepper motor
Whether stepper motor working according to beagle bone or not
Stepper motor should be connected successfully
Stepper motor was connected successfully
Pass
3
Checking code
Whether code working right or not
Code should be correct
Code was correct
Pass
4
Checking Result
Whether result is generated or not
Result should be correct
Result was correct
Pass



Testing and Assurance:-

Testing and quality assurance in software development is more rigorous since each component has to be more reliable, if it is to be reused. A system is tested at various stages of development and deployment. For example, each component is tested as a unit for checking the correctness of its own code. Further, the component is tested with its dependent components. After final release of the entire set of components, system is tested for the correctness of system functionality. Finally the components are further tested in simulated production load for performance and load analysis. The Lead Partner along with consortium partners shall be responsible for the testing processes such as planning (includes preparing test plans and defining roles and their responsibilities), preparation (consists of preparing test specification, test environment and test data) and execution (includes testing at various levels like unit level, integration level, system level and production).


CONCLUSION: - Hence, we have successfully developed the Project plan, SRS, Design document and Test Plan for one group-C assignment from embedded operating system or Concurrent and Distributed Programming.
 


 
**************************************************
 Grp-A 6].
**************************************************

/*================================================================ 
Assignment No. A-6 
Title : Write an application to parse input text file concurrently and       compare the result of concurrent parsing with serial parsing (       Use concurrent YACC parser) 
Batch : 
Roll no :  
=============================================================*/ 



----------program---------- 
-----lex_pgm.j ------
%{ 
#include&lt;stdio.h&gt; 
%} 
letter [a-zA-Z] 
digit [0-9] 
under [_] 
%% 
void | 
int | 
char | 
include | 
main | 
printf | 
if | 
for | 
break | 
while {printf("\n %s is a keyword\n",yytext);} 
"+" | 
"-" | 
"*" | 
"/" {printf("\n %s is a binary operator",yytext);} 
{digit}+ {printf("\n%s is an integer constant\n",yytext);} 
{letter}({letter}|{digit}|{under})* {printf("\n %s is an identifier\n",yytext);} 
\"[a-zA-Z0-9\(\)\% ]*\" {printf("\n%s is a literal\n",yytext);} 
%% 
int main(int argc, char **argv) 

FILE *fp; 
fp=fopen(argv[1],"r");//argv[1] is string array has data taken //from file  
yyin=fp; 
yylex(); 
return 1; 

yywrap() 
{}


-------openmp.c ----------- 
#include&lt;stdio.h&gt; 
#include&lt;omp.h&gt; 
#include&lt;string.h&gt; 
int main(int argc, char **argv) 

#pragma omp parallel 

int tid=omp_get_thread_num(); 
char inst[100]; 
strcpy(inst,"./yacc_file "); 
strcat(inst,argv[tid+1]); 
system(inst); 


------------------ INPUT FILES -----------------
------------- Pl1.txt ---------- 
main() 

printf("jshdjfash dsfasdf sa"); 

------------- Pl2.txt ---------- 
main() 

int x, y; 

-------------pl3.txt---------- 
int abc; 
char yx; 
fun(); 
-------------pl4.txt---------- 
main() 

while() 
switch() 




----------OUTPUT---------- 
op:yacc 
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ lex lex_pgm.l 
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ cc lex.yy.c -o yacc_file 
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ gcc openmp.c -fopenmp 
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ ./a.out p1.c p2.c p3.c p4.c 
 main is a keyword 
() 

 while is a keyword 
() 
 switch is an identifier 
() 

 main is a keyword 
() 
 main is a keyword 
() 


 int is a keyword 
  
 x is an identifier 
,  
 printf is a keyword 

"jshdjfash dsfasdf sa" is a literal 
); 

 y is an identifier 


 int is a keyword 
  
 abc is an identifier 

 char is a keyword 
  
 yx is an identifier 

 fun is an identifier 
(); 
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$



 
**************************************************
 Grp-B 1].
**************************************************


#================================================================
#
#
#================================================================
#!/usr/bin/python 
#================================================================ 
import sys
import time
#================================================================
SYSFS_GPIO_DIR = "/sys/class/gpio"
#================================================================
def gpioUnexport (gpio):
    try: 
           fo = open(SYSFS_GPIO_DIR + "/unexport","w")  
           fo.write(gpio)
           fo.close()
           return
       except IOError:
         return
#================================================================
def gpioExport (gpio): 
    try:
           fo = open(SYSFS_GPIO_DIR + "/export","w")  
           fo.write(gpio)
           fo.close()
           return
       except IOError:
                return
#================================================================
def gpioSetDir (gpio, flag):
    try: 
           fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w")  
           fo.write(flag)
           fo.close()
           return
     except IOError:
                return
#================================================================
def gpioSetVal (gpio, val):
    try: 
        fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w")  
        fo.write(val)
        fo.close()
        return
    except IOError:
                return
#================================================================
def lightExit (gpio):
    gpioSetVal(gpio, val="0")
    gpioUnexport(gpio)
    return 
#================================================================    
def lightInit (gpio):
    gpioExport(gpio)
    gpioSetDir(gpio, flag="out")
     gpioSetVal(gpio, val="0")
     return
#================================================================     
def lightOn (gpio):
    gpioSetVal(gpio, val="1")
    return 
#================================================================    
def lightOff (gpio):
    gpioSetVal(gpio, val="0")
    return 
#================================================================    
try:    
    lightInit(str(23))    
    for i in range(0,3):
        lightOn(str(23))
        time.sleep(1)
        lightOff(str(23))
        time.sleep(1)
    lightExit(str(23))
except KeyboardInterrupt:
    exit()
        sys.exit(0)
**************************************************
 Grp-B 7].
**************************************************
#include<cuda.h>
#include<cuda_runtime.h>
#include <iostream>
using namespace std;
#define BLOCK_SIZE 2
__global__ void gpuMM(float *A, float *B, float *C, int N)
{
    // Matrix multiplication for NxN matrices C=A*B
    // Each thread computes a single element of C
    int row = blockIdx.y*blockDim.y + threadIdx.y;
    int col = blockIdx.x*blockDim.x + threadIdx.x;
    float sum = 0.f;
    for (int n = 0; n < N; ++n)
        sum += A[row*N+n]*B[n*N+col];
    C[row*N+col] = sum;
}
int main(int argc, char *argv[])
{
    // Perform matrix multiplication C = A*B
    // where A, B and C are NxN matrices
    // Restricted to matrices where N = K*BLOCK_SIZE;
    int N,K;
    K = 2;
    N = K*BLOCK_SIZE;
    cout << "Executing Matrix Multiplcation" << endl;
    cout << "Matrix size: " << N << "x" << N << endl;
    // Allocate memory on the host
    float *hA,*hB,*hC;
    hA = new float[N*N];
    hB = new float[N*N];
    hC = new float[N*N];
    // Initialize matrices on the host
    cout<<"\n\t Enter matrix a : \n";
    for (int j=0; j<N; j++){
        for (int i=0; i<N; i++){
            //hA[j*N+i] = 2.f*(j+i);
            //hB[j*N+i] = 1.f*(j-i);
            cin>>hA[j*N+i];
        }
    }
    cout<<"\n\t Enter matrix B: \n";
    for (int j=0; j<N; j++){
            for (int i=0; i<N; i++){
                //hA[j*N+i] = 2.f*(j+i);
                //hB[j*N+i] = 1.f*(j-i);
                cin>>hB[j*N+i];
            }
        }
    // Allocate memory on the device
    int size = N*N*sizeof(float);    // Size of the memory in bytes
    float *dA,*dB,*dC;
    cudaMalloc(&dA,size);
    cudaMalloc(&dB,size);
    cudaMalloc(&dC,size);
    dim3 threadBlock(BLOCK_SIZE,BLOCK_SIZE);
    dim3 grid(K,K);
    // Copy matrices from the host to device
    cudaMemcpy(dA,hA,size,cudaMemcpyHostToDevice);
    cudaMemcpy(dB,hB,size,cudaMemcpyHostToDevice);
    //Execute the matrix multiplication kernel
    gpuMM<<<grid,threadBlock>>>(dA,dB,dC,N);
    // Now do the matrix multiplication on the CPU
    float c;
    for (int i=0; i<N; i++){
        for (int j=0; j<N; j++){
            c = 0.f;
            for (int k=0; k<N; k++){
                c=c+ hA[i*N+k]*hB[N*j+k];
            }
            hC[i*N+j] = c;
        }
    }
    // Allocate memory to store the GPU answer on the host
    float *C;
    C = new float[N*N];
    // Now copy the GPU result back to CPU
    cudaMemcpy(C,dC,size,cudaMemcpyDeviceToHost);
    cout<<"\nAnswer matrix...\n";
        for (int j=0; j<N; j++){
                for (int i=0; i<N; i++){
                    cout<<"\n"<<C[j*N+i];
                }
            }
    int flag=0;
    // Check the result and make sure it is correct
    for (int row=0; row<N; row++){
        for (int col=0; col<N; col++){
            if ( C[row*N+col] != hC[row*N+col] ){
                flag=0;
                cout<<"\n\n\t Wrong answer.........";
                row = col = N;
            }
            else
            {
                flag=1;
            }
        }
    }
    if(flag==1)
    {
        cout<<"\n\n\t Correct answer.......";
    }
    else
    {
        cout<<"\n\n\t Wrong answer.........";
    }


    cout << "Finished." << endl;
}
/*output
Executing Matrix Multiplcation
Matrix size: 4x4
     Enter matrix a : 
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
     Enter matrix B: 
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
Answer matrix...
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
4
     Correct answer.......Finished.
*/

**************************************************
 Grp-B 8].
**************************************************
//=================================================================== 
//Assignment No :B(8) 
//Title : Develop a network based application by setting IP address on  BeagleBoard/ARM Cortex A5. 
//Roll No : 
//Batch :  
//=================================================================== 
#!/usr/bin/python  
import socket, struct, fcntl 
import ftplib 
IP_ADDR          = "192.168.2.180"  
SIOCSIFADDR     = 0x8916 
SIOCGIFADDR     = 0x8915 
  
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
#================================================================  
def setIpAddr(iface, ip): 
     bin_ip = socket.inet_aton(ip) 
     ifreq = struct.pack('16sH2s4s8s', iface, socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8) 
     fcntl.ioctl(sock, SIOCSIFADDR, ifreq) 
     return 
#=================================================================      
def getIpAddr(iface = 'eth0'): 
     ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14) 
     try: 
         res = fcntl.ioctl(sock, SIOCGIFADDR, ifreq) 
     except: 
         return None    
     ip = struct.unpack('16sH2x4s8x', res)[2] 
     return socket.inet_ntoa(ip) 
#=================================================================== 
print "Current IP Address: %s" % getIpAddr('eth0') 
print "Setting IP to: %s" % IP_ADDR    
setIpAddr('eth0', IP_ADDR) 
print "New IP Address: %s" % getIpAddr('eth0') 
Output 
root@beaglebone:/home/debian/Desktop# ifconfig  
eth0      Link encap:Ethernet  HWaddr 6c:ec:eb:5c:3d:27    
          inet addr:192.168.0.125  Bcast:192.168.0.255  Mask:255.255.255.0  
          UP BROADCAST MULTICAST  MTU:1500  Metric:1  
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0  
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0  
          collisions:0 txqueuelen:1000  
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)  
          Interrupt:40  
lo        Link encap:Local Loopback    
          inet addr:127.0.0.1  Mask:255.0.0.0  
          inet6 addr: ::1/128 Scope:Host  
          UP LOOPBACK RUNNING  MTU:65536  Metric:1  
          RX packets:5 errors:0 dropped:0 overruns:0 frame:0  
          TX packets:5 errors:0 dropped:0 overruns:0 carrier:0  
          collisions:0 txqueuelen:0  
          RX bytes:460 (460.0 B)  TX bytes:460 (460.0 B)  
usb0      Link encap:Ethernet  HWaddr 1e:42:cc:e3:d9:72    
          inet addr:192.168.7.2  Bcast:192.168.7.3  Mask:255.255.255.252  
          inet6 addr: fe80::1c42:ccff:fee3:d972/64 Scope:Link  
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1  
          RX packets:711 errors:0 dropped:0 overruns:0 frame:0  
          TX packets:515 errors:0 dropped:0 overruns:0 carrier:0  
          collisions:0 txqueuelen:1000  
          RX bytes:75258 (73.4 KiB)  TX bytes:94898 (92.6 KiB)  
root@beaglebone:/home/debian/Desktop# python B08_setIPnFTP.py  
Current IP Address: 192.168.0.125  
Setting IP to: 192.168.2.180  
New IP Address: 192.168.2.180  
root@beaglebone:/home/debian/Desktop# ifconfig  
eth0      Link encap:Ethernet  HWaddr 6c:ec:eb:5c:3d:27    
          inet addr:192.168.2.180  Bcast:192.168.2.255  Mask:255.255.255.0  
          UP BROADCAST MULTICAST  MTU:1500  Metric:1  
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0  
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0  
          collisions:0 txqueuelen:1000  
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)  
          Interrupt:40  
lo        Link encap:Local Loopback    
          inet addr:127.0.0.1  Mask:255.0.0.0  
          inet6 addr: ::1/128 Scope:Host  
          UP LOOPBACK RUNNING  MTU:65536  Metric:1  
          RX packets:5 errors:0 dropped:0 overruns:0 frame:0  
          TX packets:5 errors:0 dropped:0 overruns:0 carrier:0  
          collisions:0 txqueuelen:0  
          RX bytes:460 (460.0 B)  TX bytes:460 (460.0 B)  
usb0      Link encap:Ethernet  HWaddr 1e:42:cc:e3:d9:72    
          inet addr:192.168.7.2  Bcast:192.168.7.3  Mask:255.255.255.252  
          inet6 addr: fe80::1c42:ccff:fee3:d972/64 Scope:Link  
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1  

#Assignment No         : 1 
#Title                : Develop Robotics(stepper motor) Application using  Beagle Board. 
import sys 
import os 
import time 
#===============================================================================LED_9    =    (0 * 32) + 30        #GPIO0_30 
LED_10    =    (2 * 32) + 2        #GPIO2_2 
LED_11    =    (1 * 32) + 28        #GPIO1_28 
LED_12    =    (2 * 32) + 3        #GPIO2_3 
STEPPER_1   =    LED_9 
STEPPER_2   =    LED_10 
STEPPER_3   =    LED_11 
STEPPER_4   =    LED_12 
#===============================================================================SYSFS_GPIO_DIR = "/sys/class/gpio" 
#===============================================================================def gpioUnexport (gpio): 
    try:  
           fo = open(SYSFS_GPIO_DIR + "/unexport","w")   
           fo.write(gpio) 
           fo.close() 
           return 
       except IOError: 
         return 
#===============================================================================def gpioExport (gpio):  
    try: 
           fo = open(SYSFS_GPIO_DIR + "/export","w")   
           fo.write(gpio) 
           fo.close() 
           return 
       except IOError: 
                return 
#===============================================================================def gpioSetDir (gpio, flag): 
    try:  
           fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w")   
           fo.write(flag) 
           fo.close() 
           return 
     except IOError: 
                return 
#===============================================================================def gpioSetVal (gpio, val): 
    try:  
        fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w")   
        fo.write(val) 
        fo.close() 
        return 
    except IOError: 
                return 
#===============================================================================
def stepperExit (gpio): 
    gpioSetVal(gpio, val="0") 
    gpioUnexport(gpio) 
    return  
#===============================================================================def stepperInit (gpio): 
    gpioExport(gpio) 
    gpioSetDir(gpio, flag="out") 
     gpioSetVal(gpio, val="0") 
     return 
#===============================================================================def stepperOn (gpio): 
    gpioSetVal(gpio, val="1") 
    return  
#===============================================================================def stepperOff (gpio): 
    gpioSetVal(gpio, val="0") 
    return  
#===============================================================================def stepperInitAll(): 
    stepperInit(str(STEPPER_1)) 
    stepperInit(str(STEPPER_2)) 
    stepperInit(str(STEPPER_3)) 
    stepperInit(str(STEPPER_4)) 
#===============================================================================def stepperExitAll(): 
    stepperExit(str(STEPPER_1)) 
    stepperExit(str(STEPPER_2)) 
    stepperExit(str(STEPPER_3)) 
    stepperExit(str(STEPPER_4)) 
    print "\n=== Demonstration END ===\n" 
    return    
#==============================================================================
def stepperSeq5(): 
    stepperOn(str(STEPPER_1)) 
    time.sleep(0.0001) 
    stepperOff(str(STEPPER_2)) 
    time.sleep(0.0001) 
    stepperOn(str(STEPPER_3)) 
    time.sleep(0.0001) 
    stepperOff(str(STEPPER_4)) 
    time.sleep(0.0001) 
    return  
#===============================================================================
def stepperSeq9(): 
    stepperOn(str(STEPPER_1)) 
    time.sleep(0.0001) 
    stepperOff(str(STEPPER_2)) 
    time.sleep(0.0001) 
    stepperOff(str(STEPPER_3)) 
    time.sleep(0.0001) 
    stepperOn(str(STEPPER_4)) 
    time.sleep(0.0001) 
    return  
#===============================================================================
def stepperSeq10(): 
    stepperOff(str(STEPPER_1)) 
    time.sleep(0.0001) 
    stepperOn(str(STEPPER_2)) 
    time.sleep(0.0001) 
    stepperOff(str(STEPPER_3)) 
    time.sleep(0.0001) 
    stepperOn(str(STEPPER_4)) 
    time.sleep(0.0001) 
    return  
#===============================================================================
def stepperSeq6(): 
    stepperOff(str(STEPPER_1)) 
    time.sleep(0.0001) 
    stepperOn(str(STEPPER_2)) 
    time.sleep(0.0001) 
    stepperOn(str(STEPPER_3)) 
    time.sleep(0.0001) 
    stepperOff(str(STEPPER_4)) 
    time.sleep(0.0001) 
    return  
#===============================================================================
def stepperDirLeft(): 
    stepperSeq5() 
    time.sleep(0.01) 
    stepperSeq9() 
    time.sleep(0.01) 
    stepperSeq10() 
    time.sleep(0.01) 
    stepperSeq6() 
    time.sleep(0.01) 
    return 
#===============================================================================
def stepperDirRight(): 
    stepperSeq6() 
    time.sleep(0.01) 
    stepperSeq10() 
    time.sleep(0.01) 
    stepperSeq9() 
    time.sleep(0.01) 
    stepperSeq5() 
    time.sleep(0.01) 
    return 
#============================================================================================= 
try: 
    print "\nStepper Motor Driver using Python\n" 
    print  "-----------------------------------------------\n"     
    stepperInitAll() 
    while True: 
        for i in range(0, 12): 
            stepperDirLeft() 
        time.sleep(3) 
        for i in range(0, 12): 
            stepperDirRight() 
        time.sleep(3) 
        
    stepperExitAll 
    exit() 
except KeyboardInterrupt: 
    stepperExitAll()    
    print "Program Exit due to CTRL-C" 
    exit() 
        sys.exit(0)

************
output
************


 
**************************************************
 Grp-C 3].
**************************************************
#include <iostream>
using namespace std;
#define BLOCK_SIZE 16
__global__ void gpuMM(float *A, float *B, float *C, int N)
{
    // Matrix multiplication for NxN matrices C=A*B
    // Each thread computes a single element of C
    int row = blockIdx.y*blockDim.y + threadIdx.y;
    int col = blockIdx.x*blockDim.x + threadIdx.x;
    float sum = 0.f;
    for (int n = 0; n < N; ++n)
        sum += A[row*N+n]*B[n*N+col];
    C[row*N+col] = sum;
}
void matmul(int a[10][10],int b[10][10])
{
    int c,d,k,m,q,p;
    int ans[10][10];
    int sum=0;
    for (c = 0; c < 10; c++) {
          for (d = 0; d < 10; d++) {
            for (k = 0; k < 10; k++) {
              sum = sum + a[c][k]*b[k][d];
            }
            ans[c][d] = sum;
            sum = 0;
          }
        }
        cout<<"Product of entered matrices:-\n";
        for (c = 0; c < 10; c++) {
          for (d = 0; d < 10; d++)
            cout<<ans[c][d]<<"\t";
          //cout<<"\n");
        }}
int main(int argc, char *argv[])
{
    // Perform matrix multiplication C = A*B
    // where A, B and C are NxN matrices
    // Restricted to matrices where N = K*BLOCK_SIZE;
    int N,K;
    K = 100;
    N = K*BLOCK_SIZE;
    cout << "Executing Matrix Multiplcation" << endl;
    cout << "Matrix size: " << N << "x" << N << endl;
    // Allocate memory on the host
    float *hA,*hB,*hC;
    hA = new float[N*N];
    hB = new float[N*N];
    hC = new float[N*N];
    // Initialize matrices on the host
    for (int j=0; j<N; j++){
        for (int i=0; i<N; i++){
            hA[j*N+i] = 2.f*(j+i);
            hB[j*N+i] = 1.f*(j-i);
        }
    }
    // Allocate memory on the device
    int size = N*N*sizeof(float);    // Size of the memory in bytes
    float *dA,*dB,*dC;
    cudaMalloc(&dA,size);
    cudaMalloc(&dB,size);
    cudaMalloc(&dC,size);
    dim3 threadBlock(BLOCK_SIZE,BLOCK_SIZE);
    dim3 grid(K,K);
    // Copy matrices from the host to device
    cudaMemcpy(dA,hA,size,cudaMemcpyHostToDevice);
    cudaMemcpy(dB,hB,size,cudaMemcpyHostToDevice);
    //cpu array
    int a[10][10],b[10][10],c[10][10];
    for(int i=0;i<10;i++)
    {
        for(int j=0;j<10;j++)
        {
                a[i][j]=b[i][j]=j+i+2;
                c[i][j]=0;
        }
    }
    //Execute the matrix multiplication kernel
    gpuMM<<<grid,threadBlock>>>(dA,dB,dC,N);
    matmul(a,b);
    // Now do the matrix multiplication on the CPU
    float sum;
    for (int row=0; row<N; row++){
        for (int col=0; col<N; col++){
            sum = 0.f;
            for (int n=0; n<N; n++){
                sum += hA[row*N+n]*hB[n*N+col];
            }
            hC[row*N+col] = sum;
        }
    }
    // Allocate memory to store the GPU answer on the host
    float *C;
    C = new float[N*N];
    // Now copy the GPU result back to CPU
    cudaMemcpy(C,dC,size,cudaMemcpyDeviceToHost);
    // Check the result and make sure it is correct
    for (int row=0; row<N; row++){
        for (int col=0; col<N; col++){
            if ( C[row*N+col] != hC[row*N+col] ){
                cout << "Wrong answer!" << endl;
                row = col = N;
            }
        }
    }
    cout << "Finished." << endl;
}
PL-3 ALL PRACTICALS

// ASSIGNMENT NO.:A_ 01
/* TITLE   :1 Develop an application using Beeglebone Black/ ARM Cortex A5 development board
to simulate the operations of LIFT.
'''
#!/usr/bin/python
###########################################
# * Python code for  LIFT Simulation using
# * Beaglebone Black running Debian 7 Linux distribution
###########################################

import sys
import time
import select
from liftpins import *
from gpio import *

def liftLEDExit (gpio):
   gpioSetVal(gpio, val="0")
   gpioUnexport(gpio)
   return
  
def liftLEDInit (gpio):
   gpioExport(gpio)
   gpioSetDir(gpio, flag="out")
   gpioSetVal(gpio, val="0")
   return
  
def liftLEDOn (gpio):
   gpioSetVal(gpio, val="1")
   return
  
def liftLEDOff (gpio):
   gpioSetVal(gpio, val="0")
   return
def liftButtonExit (gpio):
   gpioUnexport(gpio)
   return
  
def liftButtonInit (gpio):
   gpioExport(gpio)
   gpioSetDir(gpio, flag="in")
   gpioSetEdge(gpio, flag="falling")
   return

def liftInitAll():
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDInit(str(dir_leds[i]))
         
   for i in range(0, NO_OF_FLOORS):
       liftLEDInit(str(pos_leds[i]))
       liftLEDInit(str(lift_leds[i]))
       liftButtonInit(str(lift_buttons[i]))
   return

def liftExitAll():
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDExit(str(dir_leds[i]))
         
   for i in range(0, NO_OF_FLOORS):
       liftLEDExit(str(pos_leds[i]))
       liftLEDExit(str(lift_leds[i]))
       liftButtonExit(str(lift_buttons[i]))
   print "\n=== Demonstration END ===\n"
   return

def liftDefaultPos():
   liftLEDOn(str(pos_leds[DEFAULT_LIFT_POS]))
   return

def liftDirUp():
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDOn(str(dir_leds[i]))
       time.sleep(0.5)
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDOff(str(dir_leds[i]))
   return

def liftDirDown():
   for i in range(NO_OF_DIR_LEDS, 0, -1):
       liftLEDOn(str(dir_leds[i-1]))
       time.sleep(0.5)
   for i in range(0, NO_OF_DIR_LEDS):
       liftLEDOff(str(dir_leds[i]))
   return



def GetButtonVal():
   try:     
       fo0 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_0) + "/value" ,"r") 
       fo0.read(2)
       floor_set[0]["fd"] = fo0
      
       fo1 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_1) + "/value" ,"r") 
       fo1.read(2)
       floor_set[1]["fd"] = fo1
      
       fo2 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_2) + "/value" ,"r") 
       fo2.read(2)
       floor_set[2]["fd"] = fo2
      
       fo3 = open(SYSFS_GPIO_DIR + "/gpio" + str(LIFT_BUTTON_3) + "/value" ,"r") 
       fo3.read(2)
       floor_set[3]["fd"] = fo3
      
       print "\nWaiting for button press ..."
       r, w, ex = select.select([], [], [fo0, fo1, fo2, fo3])
      
       for i in range(len(floor_set)):
          if floor_set[i]["fd"] in ex:
              print "LIFT button is pressed for floor # %d" % i
              liftLEDOn(str(floor_set[i] ["led"]))
              time.sleep(1)
              but = i
              fo = floor_set[i]["fd"]   
              fo.seek(0, 0);
              str1 = fo.read(1)
              #print "Button Pressed ! Value = ", str1
       fo0.close()
       fo1.close()
       fo2.close()
       fo3.close()
       return but
  
   except IOError:
                return


try:
   print "\nLift Operation Simulation using Python\n"
   print  "-----------------------------------------------\n"
   liftInitAll()
   liftDefaultPos()

   cur_flr = DEFAULT_LIFT_POS
  
   while True:
       new_flr = GetButtonVal()
       if new_flr > cur_flr:
          tmp = cur_flr
          print "LIFT going UP to floor #%d" %new_flr
          while (tmp != new_flr):
              liftDirUp()
              time.sleep(0.01)
              liftLEDOff(str(pos_leds[tmp]))
              tmp += 1
              liftLEDOn(str(pos_leds[tmp]))
              time.sleep(0.5)
       elif new_flr < cur_flr:
          tmp = cur_flr
          print "LIFT going DOWN to floor #%d" %new_flr
          while (tmp != new_flr):
              liftDirDown()
              time.sleep(0.01)
              liftLEDOff(str(pos_leds[tmp]))
              tmp -= 1
              liftLEDOn(str(pos_leds[tmp]))
              time.sleep(0.5)
      
       cur_flr = new_flr
       liftLEDOff(str(lift_leds[new_flr]))  
       time.sleep(1)
        
   liftExitAll()
   exit()
except KeyboardInterrupt:
   liftExitAll()
   print "Program Exit due to CTRL-C"
   exit()
       sys.exit(0)

###########################################
# * Python GPIO Functions for LIFT Simulation
# * using Baglebone Black running Debian 7 Linux distribution
###########################################
import sys
import os

SYSFS_GPIO_DIR = "/sys/class/gpio"

def gpioUnexport (gpio):
   try:
       fo = open(SYSFS_GPIO_DIR + "/unexport","w") 
       fo.write(gpio)
       fo.close()
       return
   except IOError:
       return
            

def gpioExport (gpio):
   try:
       fo = open(SYSFS_GPIO_DIR + "/export","w") 
       fo.write(gpio)
       fo.close()
       return
   except IOError:
                return

def gpioSetDir (gpio, flag):
   try:
      fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/direction" ,"w") 
      fo.write(flag)
      fo.close()
      return
   except IOError:
                return

def gpioSetVal (gpio, val):
   try:
       fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/value" ,"w") 
       fo.write(val)
       fo.close()
       return
   except IOError:
                return
def gpioSetEdge (gpio, flag):
   try:
       fo = open(SYSFS_GPIO_DIR + "/gpio" + gpio + "/edge" ,"w") 
       fo.write(flag)
       fo.close()
       return
   except IOError:
                return

####################################################
# * Python File for Lift Operation Simulation Add-on Card
# * for GPIO PIN Configurations and Other Definitions
####################################################
LED_1       =       (0 * 32) + 3                
LED_2       =       (0 * 32) + 23              
LED_3       =       (0 * 32) + 2                
LED_4       =       (0 * 32) + 26              
LED_5       =       (1 * 32) + 17              
LED_6       =       (1 * 32) + 15              
LED_7       =       (0 * 32) + 15              
LED_8       =       (1 * 32) + 14              
LED_9       =       (0 * 32) + 30
LED_10     =       (2 * 32) + 2
LED_11     =       (1 * 32) + 28
LED_12     =       (2 * 32) + 3
LED_13     =       (0 * 32) + 31
LED_14     =       (2 * 32) + 5
LED_15     =       (1 * 32) + 18
SW_1        =       (0 * 32) + 14              
SW_2        =       (0 * 32) + 27              
SW_3        =       (0 * 32) + 22              
SW_4        =       (2 * 32) + 1       
# DIRECTIN LEDS: to represent lift direction (up or down)
LIFT_DIR_1   =    LED_9
LIFT_DIR_2   =    LED_10
LIFT_DIR_3   =    LED_11
LIFT_DIR_4   =    LED_12
LIFT_DIR_5   =    LED_13
LIFT_DIR_6   =    LED_14
LIFT_DIR_7   =    LED_15
# POSITION LEDS: LEDs to indicate the current position of Lift
LIFT_POS_0   =    LED_5
LIFT_POS_1   =    LED_6
LIFT_POS_2   =    LED_7
LIFT_POS_3   =    LED_8
# LIFT BUTTONS: corresponding to each floor of the Lift
LIFT_BUTTON_0   =    SW_1
LIFT_BUTTON_1   =    SW_2
LIFT_BUTTON_2   =    SW_3
LIFT_BUTTON_3   =    SW_4
# LIFT LEDS: indication for BUTTON Press on each floor
LIFT_LED_0   =    LED_1
LIFT_LED_1   =    LED_2
LIFT_LED_2   =    LED_3
LIFT_LED_3   =    LED_4
# An array of DIRECTIN LEDS
dir_leds = [       LIFT_DIR_1,
                   LIFT_DIR_2,
                   LIFT_DIR_3,
                   LIFT_DIR_4,
                   LIFT_DIR_5,
                   LIFT_DIR_6,
                   LIFT_DIR_7
             ]    
# An array of POSITION LEDS
pos_leds = [
                   LIFT_POS_0,
                   LIFT_POS_1,
                   LIFT_POS_2,
                   LIFT_POS_3
             ]
lift_leds = [
                   LIFT_LED_0,
                   LIFT_LED_1,
                   LIFT_LED_2,
                   LIFT_LED_3
             ]
lift_buttons = [
                    LIFT_BUTTON_0,
                    LIFT_BUTTON_1,
                    LIFT_BUTTON_2,
                    LIFT_BUTTON_3
             ]
NO_OF_FLOORS        =     4
NO_OF_DIR_LEDS     =     7
DEFAULT_LIFT_POS =      0
floor_set = [
                   {"fd":-1, "button":LIFT_BUTTON_0, "led":LIFT_LED_0},
                   {"fd":-1, "button":LIFT_BUTTON_1, "led":LIFT_LED_1},
                   {"fd":-1, "button":LIFT_BUTTON_2, "led":LIFT_LED_2},                        
                   {"fd":-1, "button":LIFT_BUTTON_3, "led":LIFT_LED_3}       
             ]

'''OUTPUT
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that a host key has just been changed.
The fingerprint for the ECDSA key sent by the remote host is
40:69:fa:bb:3f:36:81:62:b7:a3:92:7d:d7:08:30:94.
Please contact your system administrator.
Add correct host key in /home/sl171/.ssh/known_hosts to get rid of this message.
Offending ECDSA key in /home/sl171/.ssh/known_hosts:1
  remove with: ssh-keygen -f "/home/sl171/.ssh/known_hosts" -R 192.168.7.2
ECDSA host key for 192.168.7.2 has changed and you have requested strict checking.
Host key verification failed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$  ssh-keygen -f "/home/sl171/.ssh/known_hosts" -R 192.168.7.2
# Host 192.168.7.2 found: line 1 type ECDSA
/home/sl171/.ssh/known_hosts updated.
Original contents retained as /home/sl171/.ssh/known_hosts.old
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
The authenticity of host '192.168.7.2 (192.168.7.2)' can't be established.
ECDSA key fingerprint is 40:69:fa:bb:3f:36:81:62:b7:a3:92:7d:d7:08:30:94.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.7.2' (ECDSA) to the list of known hosts.
Debian GNU/Linux 7

BeagleBoard.org Debian Image 2015-03-01

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian

default username:password is [debian:temppwd]

Last login: Sun Mar  1 20:48:06 2015 from sl243-hp-compaq-4000-pro-sff-pc.local
root@beaglebone:~# ls
a.out  ad.c  s.py  v.py
root@beaglebone:~# cd ..
root@beaglebone:/# ls
bin  boot  dev etc  export  home  lib     lost+found  media  mnt opt  proc  root  run  sbin  selinux  srv  sys  tmp  usr  var
root@beaglebone:/#  cd media
root@beaglebone:/media# ls
BEAGLEBONE  BEAGLEBONE_
root@beaglebone:/media# cd BEAGLEBONE_
root@beaglebone:/media/BEAGLEBONE_# ls
01elevator_cpp         02traffic_python  Docs     ID.txt    README.htm  START.htm    nfs-uEnv.txt
01elevator_python  App                     Drivers  LICENSE.txt  README.md   autorun.inf  scripts
root@beaglebone:/media/BEAGLEBONE_# cd 01elevator_python
root@beaglebone:/media/BEAGLEBONE_/01elevator_python# ls
elevator.py  gpio.py  gpio.pyc       liftpins.py  liftpins.pyc
root@beaglebone:/media/BEAGLEBONE_/01elevator_python# python elevator.py

Lift Operation Simulation using Python

-----------------------------------------------


Waiting for button press ...
LIFT button is pressed for floor # 0


Press any LIFT button...
LIFT button is pressed for floor #1
LIFT going UP to floor #1 

Press any LIFT button...
LIFT button is pressed for floor #3
LIFT going UP to floor #3

Press any LIFT button...
LIFT button is pressed for floor #2
LIFT going DOWN to floor #2

Press any LIFT button...
LIFT button is pressed for floor #0
LIFT going DOWN to floor #0

Press any LIFT button...
LIFT button is pressed for floor #1
LIFT going UP to floor #1

Press any LIFT button...
LIFT button is pressed for floor #0
LIFT going DOWN to floor #0

Press any LIFT button...
LIFT button is pressed for floor #3
LIFT going UP to floor #3

Waiting for button press ...
^C
=== Demonstration END ===

Program Exit due to CTRL-C
root@beaglebone:/media/BEAGLEBONE_/01elevator_python#
Broadcast message from root@beaglebone (Sun Mar  1 20:53:24 2015):

Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$

'''
// ASSIGNMENT NO.:A_ 02
/* TITLE   : 2 Develop an application using Beeglebone Black/ ARM Cortex A5 development board
to simulate the working of signal lights.
'''
#!/usr/bin/python
##########################################################
# * Python code for Traffic Signal Simulation using
# * Beaglebone Black running Debian 7 Linux distribution
##########################################################


import sys
import time
from gpio import *
from ledpins import *

def lightExit (gpio):
      gpioSetVal(gpio, val="0")
      gpioUnexport(gpio)
      return
     
def lightInit (gpio):
      gpioExport(gpio)
      gpioSetDir(gpio, flag="out")
      gpioSetVal(gpio, val="0")
      return
     
def lightOn (gpio):
      gpioSetVal(gpio, val="1")
      return
     
def lightOff (gpio):
      gpioSetVal(gpio, val="0")
      return
     
     
def trafficInitAll():
      lightInit(str(NORTH_GREEN))
      lightInit(str(NORTH_YELLOW))
      lightInit(str(NORTH_RED))
      lightInit(str(EAST_GREEN))
      lightInit(str(EAST_YELLOW))
      lightInit(str(EAST_RED))
      lightInit(str(SOUTH_GREEN))
      lightInit(str(SOUTH_YELLOW))
      lightInit(str(SOUTH_RED))
      lightInit(str(WEST_GREEN))
      lightInit(str(WEST_YELLOW))
      lightInit(str(WEST_RED))
      return     

def trafficExitAll():
      lightExit(str(NORTH_GREEN))
      lightExit(str(NORTH_YELLOW))
      lightExit(str(NORTH_RED))
      lightExit(str(EAST_GREEN))
      lightExit(str(EAST_YELLOW))
      lightExit(str(EAST_RED))
      lightExit(str(SOUTH_GREEN))
      lightExit(str(SOUTH_YELLOW))
      lightExit(str(SOUTH_RED))
      lightExit(str(WEST_GREEN))
      lightExit(str(WEST_YELLOW))
      lightExit(str(WEST_RED))
      return     

def northSouthOn():
      lightOff(str(EAST_YELLOW))
      lightOff(str(WEST_YELLOW))
      lightOff(str(NORTH_RED))
      lightOff(str(SOUTH_RED))

      lightOn(str(EAST_RED))
      lightOn(str(WEST_RED))

      lightOn(str(NORTH_GREEN))
      lightOn(str(SOUTH_GREEN))

      time.sleep(10)

      lightOff(str(NORTH_GREEN))
      lightOff(str(SOUTH_GREEN))

      lightOn(str(NORTH_YELLOW))
      lightOn(str(SOUTH_YELLOW))
      time.sleep(1)
      return


def eastWestOn():
      lightOff(str(NORTH_YELLOW))
      lightOff(str(SOUTH_YELLOW))
      lightOff(str(EAST_RED))
      lightOff(str(WEST_RED))

      lightOn(str(NORTH_RED))
      lightOn(str(SOUTH_RED))

      lightOn(str(EAST_GREEN))
      lightOn(str(WEST_GREEN))

      time.sleep(10)

      lightOff(str(EAST_GREEN))
      lightOff(str(WEST_GREEN))

      lightOn(str(EAST_YELLOW))
      lightOn(str(WEST_YELLOW))
      time.sleep(1)
      return
     
     
try:       
      print "\nTraffic Signal Light Simulation using Python"
      print "-----------------------------------------------"
      trafficExitAll()
      trafficInitAll()
      for x in range(0, 10):
            print "\nNORTH-SOUTH    --> [GO]"
            print "EAST-WEST --> [STOP]\n"
            northSouthOn()
            time.sleep(1)
            print "\nEAST-WEST      --> [GO]"
            print "NORTH-SOUTH      --> [STOP]\n"
            eastWestOn()
            time.sleep(1)

      trafficExitAll() 
      print "done"
      exit()
except KeyboardInterrupt:
      trafficExitAll() 
      print "Program Exit due to CTRL-C"
      exit()
      sys.exit(0)
##########################################################
##########################################################
# * Python File for Traffic Signal Simulation Add-on Card
# * for GPIO PIN Configurations and Other Definitions
##########################################################

LED_1 =     (0 * 32) + 3           
LED_2 =     (0 * 32) + 23          
LED_3 =     (0 * 32) + 2           
LED_4 =     (0 * 32) + 26          

LED_5 =     (1 * 32) + 17          
LED_6 =     (1 * 32) + 15          
LED_7 =     (0 * 32) + 15          
LED_8 =     (1 * 32) + 14          

LED_9 =     (0 * 32) + 14          
LED_10=     (0 * 32) + 27          
LED_11=     (0 * 32) + 22          
LED_12=     (2 * 32) + 1     



NORTH_GREEN       =     LED_1
NORTH_YELLOW      =     LED_5
NORTH_RED         =     LED_9

EAST_GREEN        =     LED_2
EAST_YELLOW       =     LED_6
EAST_RED          =     LED_10

SOUTH_GREEN       =     LED_3
SOUTH_YELLOW            =     LED_7
SOUTH_RED         =     LED_11

WEST_GREEN        =     LED_4
WEST_YELLOW       =     LED_8
WEST_RED          =     LED_12
'''  Output
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
Debian GNU/Linux 7
BeagleBoard.org Debian Image 2015-03-01

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian

default username:password is [debian:temppwd]

Last login: Sun Mar  1 20:51:37 2015 from sl243-hp-compaq-4000-pro-sff-pc-2.local
root@beaglebone:~# ls               
Desktop  a.cpp     a.out  bs.cpp  cpu.py  cpu2.py cpu3.py  ps.cpp  r.cpp
root@beaglebone:~# cd ..
root@beaglebone:/# ls
agg  bios.c    boot  etc   gpio.py   home     ledpins.py   lib             media  opt   root  sbin         srv     tmp     traffic2.py  var
bin  bios.c.1  dev   gpio  gpio.pyc  ledpins  ledpins.pyc  lost+found  mnt    proc  run   selinux  sys    traffic1  usr
root@beaglebone:/# python traffic2.py

Traffic Signal Light Simulation using Python
-----------------------------------------------

NORTH-SOUTH    --> [GO]
EAST-WEST         --> [STOP]

EAST-WEST         --> [GO]
NORTH-SOUTH    --> [STOP]

NORTH-SOUTH    --> [GO]
EAST-WEST         --> [STOP]

EAST-WEST         --> [GO]
NORTH-SOUTH    --> [STOP]

NORTH-SOUTH    --> [GO]
EAST-WEST         --> [STOP]

^CProgram Exit due to CTRL-C
root@beaglebone:/#
Broadcast message from root@beaglebone (Sun Mar  1 20:55:53 2015):

Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$
'''

// ASSIGNMENT NO.: 03
/* TITLE   : Implement an calculator (64 bit Binary Multiplication) application using                     concurrent lisp
//=================================================================
(defvar a)
(defvar b)
(defvar c)
(defvar d)    


(write-line " Enter two numbers in decimal : ")

 
    (setf a(read))
    (setf b(read))

    (sb-thread:make-thread(lambda()
                (progn
                (sleep 0)
                (setf c(+ a b))
                (print "ADDITION in binary: ")
                (format t " ~b" c )
                (print "ADDITION in decimal: ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(- a b))
                (print "SUBTRACTION in binary: ")
                (format t " ~b" c )
                (print "SUBTRACTION in decimal: ")
                (print c))))

     (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* a b))
                (print "MULTIPLICATION in binary: ")
                (format t " ~b" c )
                (print "MULTIPLICATION IN DECIMAL: ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* a a))
                (print "SQUARE in binary: ")
                (format t " ~b" c )
                (print "SQUARE OF 1st NUMBER  : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(* b b b))
                (print "CUBE OF 2ND NUMBER : ")
                (print c)))) 


    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(sin a))
                (print "SINE OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(tan a))
                (print "TAN OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(cos a))
                (print "COSINE OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(acos a))
                (print "SEC OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(asin a))
                (print "COSEC OF 1ST NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(atan a))
                (print "COT OF 1ST NUMBER : ")
                (print c))))



    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(min a b))
                (print "MINIMUM NUMBER : ")
                (print c))))

    (sb-thread:make-thread(lambda()(progn(sleep 0)
                (setf c(max a b))
                (print "MAXIMUM NUMBER : ")
                (print c))))

    

(exit)



*************output*********************

This is SBCL 1.1.14.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")
 Enter two numbers in decimal :
90
0

"ADDITION in binary: "  1011010
"ADDITION in decimal: "
90
"SUBTRACTION in binary: "  1011010
"SUBTRACTION in decimal: "
90
"MULTIPLICATION in binary: "  0
"MULTIPLICATION IN DECIMAL: "
0
"SQUARE in binary: "  1111110100100
"SQUARE OF 1st NUMBER  : "
8100
"CUBE OF 2ND NUMBER : "
0
"SINE OF 1ST NUMBER : "
0.89399666
"TAN OF 1ST NUMBER : "
-1.9952004
"COSINE OF 1ST NUMBER : "
-0.44807363
"SEC OF 1ST NUMBER : "
#C(0.0 5.192926)
"COSEC OF 1ST NUMBER : "
#C(1.5707964 -5.192926)
"COT OF 1ST NUMBER : "
1.5596857
"MINIMUM NUMBER : "
0
"MAXIMUM NUMBER : "
90
GroupB
//=======================================================
// ROLL NO     : 09
// CLASS       : TE(COMPUTER)
// BATCH       :T1
// ASSIGNMENT NO.: 02
/* TITLE   :2 Implement a Parallel Quick Sort algorithm using NVIDIA GPU or equivalent ARM board.*/
//=======================================================

//parallel quick sort

#include "stdlib.h"
#include "stdio.h"
#include "omp.h"

// parallel partition
int ParPartition(int *a, int p, int r) {
    int b[r-p];
    int key = *(a+r); // use the last element in the array as the pivot
    int lt[r-p]; // mark 1 at the position where its element is smaller than the key, else 0
    int gt[r-p]; // mark 1 at the position where its element is bigger than the key, else 0
    int cnt_lt = 0; // count 1 in the lt array
    int cnt_gt = 0; // count 1 in the gt array
    int j=p;
    int k = 0; // the position of the pivot
    // deal with gt and lt array
    #pragma omp parallel for
    for ( j=p; j<r; ++j) {
        b[j-p] = *(a+j);
        if (*(a+j) < key) {
            lt[j-p] = 1;
            gt[j-p] = 0;
        } else {
            lt[j-p] = 0;
            gt[j-p] = 1;
        }
    }
    // calculate the new position of the elements
    for ( j=0; j<(r-p); ++j) {
        if (lt[j]) {
            ++cnt_lt;
            lt[j] = cnt_lt;
        } else
            lt[j] = cnt_lt;
        if (gt[j]) {
            ++cnt_gt;
            gt[j] = cnt_gt;
        } else
            gt[j] = cnt_gt;
    }
    // move the pivot
    k = lt[r-p-1];
    *(a+p+k) = key;
    // move elements to their new positon
    #pragma omp parallel for
    for ( j=p; j<r; ++j) {
        if (b[j-p] < key)
            *(a+p+lt[j-p]-1) = b[j-p];
        else if (b[j-p] > key)
            *(a+k+gt[j-p]) = b[j-p];
    }
    return (k+p);
}

void ParQuickSort(int *a, int p, int r) {
    int q;
    if (p<r) {
        q = ParPartition(a, p, r);
        #pragma omp parallel sections
        {
        #pragma omp section
        ParQuickSort(a, p, q-1);
        #pragma omp section
        ParQuickSort(a, q+1, r);
        }
    }
}

int main() {
    int a[10] = {5, 3, 8, 4, 0, 9, 2, 1, 7, 6};
    ParQuickSort(a, 0, 9);
    int i=0;
    for (; i!=10; ++i)
        printf("%d\t", a[i]);
    printf("\n");
    return 0;
}



/*OUTPUT
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
Debian GNU/Linux 7

BeagleBoard.org Debian Image 2015-03-01

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian

default username:password is [debian:temppwd]

Last login: Sun Mar  1 20:55:35 2015 from sl243-hp-compaq-4000-pro-sff-pc-2.local
root@beaglebone:~# cd ..
root@beaglebone:/# vi b4.c
root@beaglebone:/# gcc b4.c
root@beaglebone:/# ./a.out
0      9      9      2      2      2      6      7      7      7     
root@beaglebone:/#
Broadcast message from root@beaglebone (Sun Mar  1 22:00:43 2015):

Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$

*/






GroupB
//=======================================================
// ROLL NO     : 09
// CLASS       : TE(COMPUTER)
// BATCH       :T1
// ASSIGNMENT NO.: 04
/* TITLE   :4 Implement a Parallel ODD-Even Sort algorithm using GPU or ARM equivalent.*/
//=======================================================

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

#define NO_OF_THREADS 2
#define A_size 7
#define DIVIDER 10000

int num_arr[A_size];

int print_sorted_array(int *a)
{
        int i;
        printf("\n Sorted Array is:");

        for(i=0;i<A_size;i++)
        {
                if(i+1==A_size)
                        break;
                printf("%d\t",a[i]);
        }
        printf("%d\n",a[i]);
}

void get_random_arr(void)
{
        int i;
        printf("\n Elements to sort are:[");
        for(i=0;i<A_size;i++)
        {
                num_arr[i]=rand()%DIVIDER;
                if(i+1==A_size)
                        break;
                printf("%d\t",num_arr[i]);
        }
        printf("%d]\n",num_arr[i]);
}

void odd_even_sort(int *a,int n)
{
        int phase,i,temp;
        for(phase=0;phase<n;++phase)
        {
                if(phase%2==0)
                {
                        #pragma omp parallel for num_threads(NO_OF_THREADS) default(none) shared(a,n)private(i,temp)
                for(i=1;i<n;i+=2)
                        if(a[i-1]>a[i])
                        {
                                temp=a[i];
                                a[i]=a[i-1];
                                a[i-1]=temp;
                        }
                }
                else
                {
                        #pragma omp parallel for num_threads(NO_OF_THREADS) default(none) shared(a,n)private(i,temp)
                for(i=1;i<n-1;i+=2)
                        if(a[i]>a[i+1])
                        {
                                temp=a[i];
                                a[i]=a[i+1];
                                a[i+1]=temp;
                        }
                }
        }
}

int main(void)
{
        int i;
        int* arr1;
        double start_time_omp,end_time_omp,elapsed_time_omp;

        printf("\n parallel odd-even sort using openmp");
        printf("\n....................................");

        printf("\n Data array");
        printf("\n..........");
        get_random_arr();

        arr1=(int*)malloc(sizeof(int)*A_size);

        memcpy(arr1,num_arr,sizeof(int)*A_size);

        printf("\n openmp method");
        printf("...............");
        printf("\n sorting data parallelly with openmp");

        start_time_omp=omp_get_wtime();
        odd_even_sort(arr1,A_size);
        end_time_omp=omp_get_wtime();
        elapsed_time_omp=end_time_omp-start_time_omp;
        printf("[done]\n");

        printf("\n Result of openmp");
        printf("\n.......");
        print_sorted_array(arr1);

        printf("\n Time info");
        printf("\n.........");
        printf("\n Time taken to run algorithm\t:%lf(s)\n",elapsed_time_omp);
        free(arr1);

return 0;
}

/*output

sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
Debian GNU/Linux 7

BeagleBoard.org Debian Image 2015-03-01

Support/FAQ: http://elinux.org/Beagleboard:BeagleBoneBlack_Debian

default username:password is [debian:temppwd]

Last login: Sun Mar  1 20:51:27 2015 from sl243-hp-compaq-4000-pro-sff-pc-2.local
root@beaglebone:~# vi b4.c
root@beaglebone:~# gcc -fopenmp b4.c
b4.c: In function 'main':
b4.c:85:2: warning: incompatible implicit declaration of built-in function 'memcpy' [enabled by default]
root@beaglebone:~# ./a.out

 parallel odd-even sort using openmp
....................................
 Data array
..........
 Elements to sort are:[9383     886   2777 6915 7793 8335 5386]

 openmp method...............
 sorting data parallelly with openmp[done]

 Result of openmp
.......
 Sorted Array is:886 2777 5386 6915 7793 8335 9383

 Time info
.........
 Time taken to run algorithm   :0.001530(s)
root@beaglebone:~#
Broadcast message from root@beaglebone (Sun Mar  1 21:05:32 2015):

Power button pressed
The system is going down for system halt NOW!
Connection to 192.168.7.2 closed by remote host.
Connection to 192.168.7.2 closed.
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$
*/
GroupB
//=======================================================
// ROLL NO     : 09
// CLASS       : TE(COMPUTER)
// BATCH       :T1
// ASSIGNMENT NO.: 05
// TITLE   :5  Implement n-ary search algorithm using OPENMP
//=======================================================

#include<stdio.h>
#include<math.h>
#include<omp.h>

void main()
{
 int sep[20],array[20],key,i,j,n,left,right,size,interval,index,break_value=0,tid;
 printf("Enter the size of array\n");
 scanf("%d",&size);
 printf("Enter the elements of array in ascending order\n");
 for(i=0;i<size;i++)
  {
   scanf("%d",&array[i]);
  }
 printf("Enter the key to be searched\n");
 scanf("%d",&key);
 printf("Enter the value of n for n-ary search algorithm\n");
 scanf("%d",&n);

 left=0;
 right=size-1;

 if(key>=array[left] && key<=array[right])
  {
   while(left!=right)
   {
     // (start) code to find seperators
     printf("left=%d, right=%d, size=%d\n",left,right,size);
     if(size<=n)
      {
       #pragma omp parallel for num_threads(size)
       for(i=0;i<size;i++)
        {
         sep[i]=left+i;
         tid=omp_get_thread_num();
         printf("Thread %d allocated sep[%d]=%d\n",tid,i,sep[i]);
        }
      }

     else
      {
       sep[0]=left;
       interval=ceil((float)size/(float)n);
    
       #pragma omp parallel for num_threads(n-1)
       for(i=1;i<=n-1;i++)
        {
         sep[i]=left+interval*i-1;
         tid=omp_get_thread_num();
         printf("Thread %d allocated sep[%d]=%d\n",tid,i,sep[i]);
        }

        sep[n]=right;
       }
      // (end) Code to find seperators

      // (start) Code for comparison

      for(i=0;i<=n;i++)
       {
         if(key==array[sep[i]])
          {
            index=sep[i];
            printf("Element found at position %d\n",index+1);
            break_value=1;
            break;
          }
         if(key<array[sep[i]])
          {
            right=sep[i];
            if(i!=0)
              left=1+sep[i-1];
            size=right-left+1;
            break;
          }
       }

      // (end) Code for comparison

      if(break_value==1)
        break;
   } //End of 'while' loop
  } //End of 'if'

if(left==right || !(key>=array[left] && key<=array[right]))
  printf("Element does not present in the list\n");

} //End of main()

/*Output
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ gcc -fopenmp b_5.c -lm
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ ./a.out
Enter the size of array
5
Enter the elements of array in ascending order
5
9
12
16
32
Enter the key to be searched
12
Enter the value of n for n-ary search algorithm
2
left=0, right=4, size=5
Thread 0 allocated sep[1]=2
Element found at position 3
*/

  GroupB
//===================================================
// ROLL NO     : 09
// CLASS       : TE(COMPUTER)
// BATCH       :T1
// ASSIGNMENT NO.: 09
/* TITLE   : 9  Implement a Multi-threading application for echo server using socket programming in  JAVA*/
//===================================================
//server.java
import java.io.*;
import java.net.*;

public class server {
    public static void main(String args[]) {
int port = 6789;
server server = new server( port );
server.startServer();
    }

    // declare a server socket and a client socket for the server;
    // declare the number of connections

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int numConnections = 0;
    int port;
    public server( int port ) {
this.port = port;
    }

    public void stopServer() {
System.out.println( "Server cleaning up." );
System.exit(0);
    }

    public void startServer() {
// Try to open a server socket on the given port
// Note that we can't choose a port less than 1024 if we are not
// privileged users (root)
        try {
    echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
    System.out.println(e);
        } 
System.out.println( "Server is started and is waiting for connections." );
System.out.println( "With multi-threading, multiple connections are allowed." );
System.out.println( "Any client can send -1 to stop the server." );

// Whenever a connection is received, start a new thread to process the connection
// and wait for the next connection.
while ( true ) {
    try {
clientSocket = echoServer.accept();
numConnections ++;
serverConnection oneconnection = new serverConnection(clientSocket, numConnections, this);
new Thread(oneconnection).start();
    } 
    catch (IOException e) {
System.out.println(e);
    }
}
    }
}
class serverConnection implements Runnable {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    int id;
    server server;
    public serverConnection(Socket clientSocket, int id, server server) {
this.clientSocket = clientSocket;
this.id = id;
this.server = server;
System.out.println( "Connection " + id + " established with: " + clientSocket );
try {
    is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
    os = new PrintStream(clientSocket.getOutputStream());
} catch (IOException e) {
    System.out.println(e);
}
    }
    public void run() {
        String line;
try {
    boolean serverStop = false;

            while (true) {
                line = is.readLine();
System.out.println( "Received " + line + " from Connection " + id + "." );
                int n = Integer.parseInt(line);
if ( n == -1 ) {
    serverStop = true;
    break;
}
if ( n == 0 ) break;
                os.println("" + n*n );
            }
    System.out.println( "Connection " + id + " closed." );
            is.close();
            os.close();
            clientSocket.close();
    if ( serverStop ) server.stopServer();
} catch (IOException e) {
    System.out.println(e);
}
    }
}



 //client.java

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

public class client {
    public static void main(String[] args) {
String hostname = "localhost";
int port = 6789;

// declaration section:
// clientSocket: our client socket
// os: output stream
// is: input stream
        Socket clientSocket = null; 
        DataOutputStream os = null;
        BufferedReader is = null;
// Initialization section:
// Try to open a socket on the given port
// Try to open input and output streams
        try {
            clientSocket = new Socket(hostname, port);
            os = new DataOutputStream(clientSocket.getOutputStream());
            is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + hostname);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " + hostname);
        }
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on the given port
if (clientSocket == null || os == null || is == null) {
    System.err.println( "Something is wrong. One variable is null." );
    return;
}

try {
    while ( true ) {
System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String keyboardInput = br.readLine();
os.writeBytes( keyboardInput + "\n" );

int n = Integer.parseInt( keyboardInput );
if ( n == 0 || n == -1 ) {
    break;
}
String responseLine = is.readLine();
System.out.println("Server returns its square as: " + responseLine);
    }
   
    // clean up:
    // close the output stream
    // close the input stream
    // close the socket
    os.close();
    is.close();
    clientSocket.close(); 
} catch (UnknownHostException e) {
    System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
    System.err.println("IOException:  " + e);
}
    }         
}

/*
Server output:
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ javac server.java
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ java server
Server is started and is waiting for connections.
With multi-threading, multiple connections are allowed.
Any client can send -1 to stop the server.
Connection 1 established with: Socket[addr=/127.0.0.1,port=58777,localport=6789]
Received 890 from Connection 1.
Received 67 from Connection 1.
Received -1 from Connection 1.
Connection 1 closed.
Server cleaning up.

Received 0 from Connection 1.
Connection 1 closed.

Client Output::
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ javac client.java
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ java client
Enter an integer (0 to stop connection, -1 to stop server): 890
Server returns its square as: 792100
Enter an integer (0 to stop connection, -1 to stop server): 67
Server returns its square as: 4489
Enter an integer (0 to stop connection, -1 to stop server): -1


Enter an integer (0 to stop connection, -1 to stop server): 0

GroupB
//=======================================================
// ROLL NO     : 09
// CLASS       : TE(COMPUTER)
// BATCH       :T1
// ASSIGNMENT NO.: 10
// TITLE   :10   Implement Reader-Writer problem using OPENMP
//=======================================================
#include<omp.h>
#include<stdio.h>
void main()
{
int s=0;
FILE *fptr;
char ch;
    char name[20];

    int age;

    float salary;
char filename[15];
char fname1[20],fname2[20];
//pragma omp parallel num_threads(2)
{
int tid=omp_get_thread_num();
int x;
while(1)
{
if(tid==0)
printf("tid ==> %d\t%d)read\t%d)write\n",tid,2*tid,2*tid+1);

if(tid==1)
printf("\t\t\t\t\t\ttid ==> %d\t%d)read\t%d)write\n",tid,2*tid,2*tid+1);

scanf("%d",&x);

switch(x)
{
case 0:while(s==1)
   printf("Shared memory is in used\n");

 printf("Thread 0 is reading\n");
 printf("Enter the filename to be opened \n");

    scanf("%s", filename);

    /*  open the file for reading */

    fptr = fopen(filename, "r");

    if (fptr == NULL)

    {

        printf("Cannot open file \n");

        //return 0;

    }

    ch = fgetc(fptr);

    while (ch != EOF)

    {

        printf ("%c", ch);

        ch = fgetc(fptr);

    }

    fclose(fptr);

   //sleep(5);
   printf("Thread 0 complete reading\n");
   break;
case 1:while(s==1)
   printf("Shared memory is in used\n");
   s=1;

 printf("Enter the filename to be opened \n");

    scanf("%s", filename);

    /*  open the file for reading */

    fptr = fopen(filename, "w");

        if (fptr == NULL)

    {

        printf("File does not exists \n");

        return;

    }

    printf("Enter the name \n");

    scanf("%s", name);

    fprintf(fptr, "Name    = %s\n", name);

    printf("Enter the age\n");

    scanf("%d", &age);

    fprintf(fptr, "Age     = %d\n", age);

    printf("Enter the salary\n");

    scanf("%f", &salary);

    fprintf(fptr, "Salary  = %.2f\n", salary);

    fclose(fptr);

   printf("Thread 0 is writing\n");
   sleep(5);
   printf("Thread 0 complete writing\n");
   s=0;
   break;
case 2:while(s==1)
   printf("Shared memory is in used\n");
   printf("\t\t\t\t\t\tThread 1 is reading\n");
   sleep(5);
   printf("\t\t\t\t\t\tThread 1 complete reading\n");
   break;
case 3:while(s==1)
   printf("Shared memory is in used\n");
   s=1;
   printf("\t\t\t\t\t\tThread 1 is writing\n");

/*p = fopen("one.txt", "w");
 printf("Enter data");
 while( (ch = getchar()) != 5) {
    putc(ch,fp);
}
fclose(fp);*/
   sleep(5);
   printf("\t\t\t\t\t\tThread 1 complete writing\n");
   s=0;
   break;
}
}
}
}

/*OUTPUT
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ gcc -fopenmp b_10.c -lm
^[[Asl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ ./a.out
tid ==> 0 0)read     1)write
0
Thread 0 is reading
Enter the filename to be opened
b10
Thread 0 complete reading
tid ==> 0 0)read     1)write
1
Enter the filename to be opened
b10
Enter the name
Aman
Enter the age
21
Enter the salary
20000
Thread 0 is writing
Thread 0 complete writing
tid ==> 0 0)read     1)write
0
Thread 0 is reading
Enter the filename to be opened
b10
Name    = Aman
Age     = 21
Salary  = 20000.00
Thread 0 complete reading
tid ==> 0 0)read     1)write
^C
sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$
*/

#Group             : C 
#!/usr/bin/python  
/* OUTPUT

sl171@sl243-HP-Compaq-4000-Pro-SFF-PC:~$ ssh root@192.168.7.2
Debian GNU/Linux 7

BeagleBoard.org BeagleBone Debian Image 2014-04-23

Last login: Wed Apr 23 20:20:41 2014 from administrator-optiplex-390.local
root@beaglebone:~# cd /home/debian/Desktop/
root@beaglebone:/home/debian/Desktop# ls
16 a.out elevator hello.c liftpins.py te22
stepper.py abc.cpp elevator.cpp hello123 liftpins.pyc te24
Te25 asd elevator.py kkk.py main te25
a e1.py gpio.py lift main.c
a.c ele gpio.pyc lift.cpp prasad
root@beaglebone:/home/debian/Desktop# python stepper.py

Stepper Motor Driver using Python

-----------------------------------------------


^C
[1]+ Stopped python stepper.py
root@beaglebone:/home/debian/Desktop#

*/


No comments :

Post a Comment