Thursday, March 10, 2016

BMI Calculator in Java



a. Java Program for the body mass index (BMI) is commonly used by health and nutrition professionals to estimate human body fat in populations.

It is computed by taking the individual's weight (mass) in kilograms and dividing it by the square of their height in meters.

Write a Java program that reads from the keyboard the wight and the height in kilograms and meters and prints on the screen the BMI of the individual plus using this table gives a verdict:

BMI category
less than 18.5 underweight
18.5 to 24.9 normal weight
25.0 to 29.9 overweight
30.0 or more obese
b. Extend the program at a. to

1. read the name of the person from the keyboard

2. give the choice of the wight to be input either in kilograms or in pounds

3. give the choice of the height to be given either in meters or in feet

Perform the conversions from lb to Kg or from feet to meters and using the table above give the verdict.

Code Solution:

import java.util.Scanner;


public class BMI {

public static void main(String[] args) {
// TODO Auto-generated method stub
final double KILOGRAMS_PER_POUND = 0.453;
    //final double METERS_PER_INCH = 0.026;
        double weight = 0.0;
        double height = 0.0;
        double bmi = 0.0;
String name;
        String weightType = null;
        String heightType =null;

System.out.println("Enter your Name: ");
Scanner readname = new Scanner(System.in);
name = readname.nextLine();

        System.out.println("Press 1 or 2 to choose Weight Type: ");
        System.out.println("1.KILOGRAMS");
        System.out.println("2.POUNDS");
        Scanner readweightType = new Scanner(System.in);
        weightType = readweightType.next().trim();
        if(weightType.equalsIgnoreCase("1"))
        System.out.println("Enter Weight in Kilograms:");
        else if(weightType.equalsIgnoreCase("2"))
        System.out.println("Enter Weight in Pounds:");
        else
        {
        System.out.println("Invalid WeightType Entry");
        System.exit(0);
        }
        Scanner getWeight = new Scanner(System.in);
        weight = getWeight.nextDouble();
     
       if(weightType.equalsIgnoreCase("2"))
        {
        weight = weight* KILOGRAMS_PER_POUND ;
        //convert pounds to KG
        }
        System.out.println("Press 1 or 2 to choose Height Type: ");
        System.out.println("1.METERS");
        System.out.println("2.FEET");
     
        Scanner readHeightType = new Scanner(System.in);
        heightType = readHeightType.next().trim();
     
        if(heightType.equalsIgnoreCase("1"))
         
        System.out.println("Enter Height in Meters:");
        else if(heightType.equalsIgnoreCase("2"))
        System.out.println("Enter Weight in Feet:");
        else
        {
        System.out.println("Invalid HeightType Entry");
        System.exit(0);
        }
     
     
        Scanner readHeight = new Scanner(System.in);
        height = readHeight.nextDouble();
           
        if(heightType.equalsIgnoreCase("2"))
        {
        height = height/3.2808;
        }
     
        bmi = Math.abs((weight)/(height * height));
     
     
System.out.print("\n \t Your Name is " +name);
        System.out.printf("\n \t The BMI is %f", bmi);
        if(bmi < 18.5)
        System.out.print(" belongs to UnderWeight");
        else if(bmi >= 18.5 && bmi < 24.9)
          System.out.print(" belongs to NormalWeight");
        else if(bmi >= 25.0 && bmi <= 29.9)
          System.out.print(" belongs to OverWeight");
        else if(bmi >= 30.0 )
          System.out.print(" belongs to Obese");
     
}

}

Wednesday, March 9, 2016

Prime Factors in Java



 Write a Java program that is reading from the keyboard a value between 100 and 700 and is printing on the screen the divisors of the number.

Your program should use a cycle for validating the input (if the value typed from the keyboard is less than 100 or bigger than 700 to print an error and ask the user to input another value).

Also the program should print the prime factors in the order from smallest to biggest.

For example,

for the value 128 the program should print 128=2*2*2*2*2*2*2

for the value 122 the program should print: 122=2*61

change the program at a. to print one time a divisor but provide the power of that divisor:

for the value 128 the program should print 128=2^7

for the value 122 the program should print: 122=2^1*61^1



Solution Code:

import java.io.*;
import java.util.*;

public class Divisors {

  /* Java Program that is reading from the keyboard a value between 100 and 700
 and is printing on the screen the prime divisors of the number.  */
 public static void main(String args[]) throws IOException
 {
 List<Integer> resultList = new ArrayList<Integer>();
 Map<Integer, Integer> resultMap = new HashMap<Integer, Integer>();
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 StringBuffer result = new StringBuffer();
 int n;
 System.out.print("Enter a Number : ");
 n=Integer.parseInt(br.readLine());
  if(n < 100 || n > 700)
  {
   System.out.println("Invalid Number!! Please enter the valid number in between 100 to 700");
  }
  else
  {
   System.out.print("The Prime Divisors of "+n+" are : ");
   int i=2;
   while(n>1)
   {
     if(n%i == 0)
     {
      resultList.add(i);
      //System.out.print(i+"*");
        n=n/i;
      }
   else
       i++;
   }  
   for(int index = 0; index < resultList.size(); index++)
   {
    if(index != resultList.size()-1)
     System.out.print(resultList.get(index)+"*");
    else 
     System.out.print(resultList.get(index));
    if(resultMap.containsKey(resultList.get(index)))
    {
     Integer value = resultMap.get(resultList.get(index));
     resultMap.put(resultList.get(index), value+1);
    }else
    {
    int initialize = 1;
    resultMap.put(resultList.get(index), initialize);
    }
   }
  System.out.println();
  Set<Integer> resultSet = resultMap.keySet();
  
  for(Integer key: resultSet)
  {
   result.append(key+"^"+resultMap.get(key)+"*");
  }
  
  result.replace(result.length()-1, result.length(), "");
  System.out.println(result);
   }
  }
}

Wednesday, March 2, 2016

Display Robot in Java




Write a small Java program that is printing on the screen a ROBOT. You can print whatever form of the robot you want.




import java.io.*;
import java.lang.*;
import java.util.*;
public class Robot
{
public static void main(String[] args)
    {
            System.out.println("Program for displaying pattern of Robot.\n");
         
System.out.print("      ------- \n");
System.out.print("       -   -  \n");
System.out.print("      ------- \n");
System.out.print("         |    \n");
System.out.print("         |    \n");
System.out.print("       / | \\ \n");
System.out.print("         |    \n");
System.out.print("        / \\  \n");
}
}

Tuesday, March 1, 2016

CLass Registartion System Stereotype Class Diagram







Class Registration System State Chart




State Chart for Class Registration system

Class Registration System Class Diagram




Class Diagram

Class Registration System UseCase Diagram




Use Case Diagram

Help Desk Support System Analysis Report



Analysis Report
Use Case Diagram:
Use case diagram for Help Desk Support System (including only Core functionalities):
Scenarios:
One possible Scenario for Use Case Login:
Help Desk Support System users (Customer, Technician and Administrator) can login to the system for Creating/updating the requests.
1.      At the login page user keys in the username and password, and then click on submit button.
2.      System verifies login info.
3.      System displays the Help Desk Support System main menu.
Possible Alternatives
A.      In case of user account is not active the system will display message “your account is not active. contact your system administrator”
B.      Invalid login message: the system shall display “Please enter a valid username and password”

One possible Scenario for Use Case Manage Requests:
Customer will add/raise a request whenever Customer needs a technician support.
1.      Customer will add a request which needs support.
2.      System displays the added request
Possible Alternatives

A.      Customer mistakenly add the wrong request

Second possible Scenario for Use Case Manage Requests:
Customers can cancel the request that they created whenever they think that the request is no more required. They may also cancel whey they find their own solution.
1.      Customer can delete the request from the list of the requests they raised.
2.      System removes the deleted requests and display the list of existing requests
Possible Alternatives

A.      Customer can mistakenly delete the wrong request.

Third possible Scenario for Use Case Manage Requests:
Customers can view status of all requests that they created to know whether their request is solved or not.
Possible Alternatives

A.      Customers may view the status of other request instead of the request they want to see by wrongly entering the wrong request number.

One possible Scenario for Use Case Update Request Status:
Technician will update the status of the request to fixed whenever they solved the request that are created by the customers.

Possible Alternatives

A.      Technician may update the status of the request wrongly.
Second possible Scenario for Use Case Update Request Status:
Technician will update the status of the request to progress when the request is being solved but not yet solved.
Possible Alternatives

A.      Technicians may forget to update the status to progress when they are busy solving the request.

One possible Scenario for Use Case Manage Users:
Administrator can add the technicians to solve the requests of the customers whenever needed.
Possible Alternatives

A.      Administrator may wrongly add the more technicians for the same request.
Second possible Scenario for Use Case Manage Users:
Administrator delete’s a technician and assign new technician to solve a particular request.
Possible Alternatives

A.      Administrator may delete the wrong technician instead of deleting the technician that they want.
Third possible Scenario for Use Case Manage Users:
Administrator will add the new Customer’s to the system
Possible Alternatives

A.      Administrator may wrongly enter the customer details.

Fourth possible Scenario for Use Case Manage Users:
Administrator will delete the customer details once they are no more their customers.
Possible Alternatives

A.      Administrator may wrongly delete the customer.

One possible Scenario for Use Case Logout:

Help Desk Support System users (Customer, Technician and Administrator) can login to the system and use the system for adding/updating the requests and will logout once work is done on the system.
1.      System has a logout button to logout from the Help Desk Support system.

Possible Alternatives
A.      When users press Logout button mistakenly.

Noun Extraction:

This system is mainly for managing customer requests for technical support from the help desk. Customers are able to request technical support for any issue. There are three types of users who are allowed to log into the system. The first type of users is a regular customer, who is allowed to view the status of all requests they have sent. The second type of users is a technician who is allowed to update the status of a certain request. The third type of users is the system Administrator, who has the ability to add and remove technician and user accounts.

From the above noun extraction we have gathered the long lived entity classes as follows:

Customer, Administrator, Technician, User





Class Diagram:








State Chart Diagram:



Help Desk Support System State Chart




State Chart

Help Desk Support System Sequence Diagrams





Sequence Diagram

Help Desk Support System Class Diagram





Class Diagram

Help Desk Support System Full Use Case Diagram




More Detailed Use Case Diagram

Help Desk Support System Use Case Diagram





Use Case Diagram

Facade Sequence Diagram











Facade Design Pattern Sample Class Diagram with Facade









Class Diagram With Facade

Facade Design Pattern with Sample Class DIagrams




Class Diagram Without Facade



Facade Design Pattern Class Diagram









LEX program that replicates the input on screen but filters out everything that is neither letter nor digit.




%{
/* a simple LEX program that replicates the input
   on screen but filters out everything that is
   neither letter nor digit.
*/
#include <stdio.h>
/* letter and digit counters */
int letters = 0, digits = 0;
%}
letter [a-zA-Z]
digit [0-9]
%%
{letter} { ECHO; letters++; }
{digit} { ECHO; digits++; }
[^{letter}{digit}] ;
%%
int main(int argc, char *argv[]) {
FILE *inFile;
if (argc == 2 && (inFile = fopen(argv[1], "r")))
yyin = inFile;
yylex();
if (inFile) fclose(inFile);
printf("\n\n        Count\nLetters %d\n Digits %d\n", letters, digits);
return 0;
}

LEX program that adds line numbers to lines of text, printing the new text to the standard output




%{
/* a LEX program that adds line numbers
   to lines of text, printing the new text
   to the standard output
*/
#include <stdio.h>
int lineno = 1;
%}
line .*\n
%%
{line} { printf("%5d %s", lineno++, yytext); }
%%
int main() { yylex(); return 0; }

LEX program that changes all numbers from decimal to hexadecimal notation, printing a summary statistic to stderr




%{
/* a LEX program that changes all numbers
   from decimal to hexadecimal notation,
   printing a summary statistic to stderr
*/
#include <stdlib.h>
#include <stdio.h>
int count = 0;
%}
digit [0-9]
number {digit}+
%%
{number} {
int n = atoi(yytext);
printf("%x", n);
if (n > 9) count++;
}
%%
main() {
yylex();
fprintf(stderr, "number of replacements = %d", count);
return 0;
}

LEX Program to Selects only lines that end or begin with the letter 'a'. Deletes everything else.




%{
/* Selects only lines that end or
   begin with the letter 'a'.
   Deletes everything else.
*/
#include <stdio.h>
%}
ends_with_a     .*a\n
begins_with_a   a.*\n
%%
{ends_with_a} ECHO;
{begins_with_a} ECHO;
.*\n ;
%%
main() { yylex(); return 0; }

LEX program to convert uppercase to lowercase except inside comments




%{
/* LEX program to convert uppercase to
   lowercase except inside comments
*/
#include <stdio.h>
#include <stdlib.h>
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
%}
%option noyywrap
%%
[A-Z] {
putchar(tolower(yytext[0]));
/* yytext[0] is the single
  uppercase char found */
}
"/*" {
char c;
int done = FALSE;
ECHO;
do {
while ((c = input()) != '*')
putchar(c);
putchar(c);
while ((c = input()) == '*')
putchar(c);
putchar(c);
if (c == '/') done = TRUE;
} while (!done);
}
%%
int main() { yylex(); return 0; }

Dead Lock and Main Memory OS Assignment


Questions From Text book : Operating Systems Concept by Abraham,Peter and Greg (9th Edition)


7.8
a. No, Deadlock cannot occur because preemption exists.
b. Yes. A process may never acquire all the resources it needs if they are continuously preempted by a series of requests such as those of process p2.
7.22
a.      
b.      

7.23
a.      
b.

c.
8.9   When memory allocated to a process is larger than the requested memory, space at the end of a partition is wasted or unused. This space which is getting wasted within the partition is called internal fragmentation. When enough total memory space exists to satisfy a request, but it is not contiguous storage is fragmented to into a large number of small holes. This wasted space not allocated to any partition is called external fragmentation. Internal Fragmentation occurs when a fixed size memory allocation technique is used. External fragmentation occurs when a dynamic memory allocation technique is used.






8.11
Best fit uses the memory efficiently and then the first fit. Worst fit must wait.
8.13
Contiguous memory allocation suffers from external fragmentation as address spaces are allocated contiguously and holes develop as old processes dies and new processes are initiated. It also does not allow processes to share code , since a processes virtual memory segment is not broken into non-contiguous fine-grained segments. 
Pure segmentation also suffers from external fragmentation as a segment of a process is laid out contiguously in physical memory and fragmentation would occur as segments of dead processes are replaced by segments of new processes. Segmentation however enables processes to share code for instance two different processes could share a code segment but have distinct data segments.
Pure Paging doesn’t not suffer from external fragmentation, but instead it suffers from internal fragmentation. Processes are allocated in page granularity and if a page is not a completely utilized, it results in internal fragmentation and a corresponding wastage of space. Paging also enables processes to share code at granularity of pages.
8.17
Paging requires more memory overhead to maintain the translation structures. Segmentation requires just two registers per segment. One to maintain the base of the segment and the other to maintain the extent of the segment. Paging on the other hand requires one entry per page, and this entry provides the physical address in which page is located.
8.25
a. 100 nanoseconds, 50 ns to access the page table and 50ns to access the word in memory.
b. Effective access time = ( 0.75*50ns) + (0.25*100ns)+2=64.5ns




9.21





9.22
a. Virtual Address to Physical address
·        0xE12C à0x312C
·         0x3A9Dà0xAA9D
·         0xA9D9à0x59D9
·         0x7001à0xF001
·         0xACA1à0x5CA1
Below is the page table updated with reference bit.
Page                                       Page Frame                                      Reference Bit
0                                                          9                                                          0
1                                                          1                                                         0
2                                                          14                                                      0
3                                                          10                                                       1
4                                                          –                                                          0
5                                                          13                                                       0
6                                                          8                                                         0
7                                                          15                                                      1
8                                                          –                                                         0
9                                                          0                                                          0
10                                                       5                                                          1
11                                                       4                                                          0
12                                                       –                                                         0
13                                                       –                                                          0
14                                                       3                                                          1
15                                                       2                                                          0

b. Pages 4,8,12 and 13 result and page fault and their logical address in hexadecimal as follows 0x4… , 0x8… ,0xC… , 0xD…
c. In the above page table which has reference bit 0 those page frames will choose page replacement. They are {9,1,14,13,8,0,4,2}



Sample questions on OS



1. When a process requests for I/O, how many process switches take place?
 Answer:
Two. In the first switch, the process to be switched is taken out and the scheduler starts executing. Then the next process is brought to execution. So there are two process switches.
2. Consider a system consisting of four resources of the same type that are shared by three processes, each of which needs at most two resources. Show that the system is deadlock free.
 Answer:
Suppose the system is deadlocked. This implies that each process is holding one resource and is waiting for one more. Since there are three processes and four resources, one process must be able to obtain two resources. This process requires no more resources and, therefore it will return its resources when done.
3. Explain the sequence of events that happens when a page-fault occurs.
Answer:
When the operating system cannot load the desired page into memory, a page-fault occurs. First, the memory reference is checked for validity. In the case of an invalid request, the program will be terminated. If the request was valid, a free frame is located. A disk operation is then scheduled to read the page into the frame just found, update the page table, restart the instruction that was interrupted because of the page fault, and use the page accordingly.

4. Explain the usefulness of a modify bit.
Answer:
A modify bit is associated with each page frame. If a frame is modified (i.e. written), the modify bit is then set. The modify bit is useful when a page is selected for replacement. If the bit is not set (the page was not modified), the page does not need to be written to disk. If the modify bit is set, the page needs to be written to disk when selected for replacement.
5. If you were creating an operating system to handle files, what would be the six basic file operations that you should implement?
Answer:
 The six basic file operations include: creating a file, writing a file, reading a file, repositioning within a file, deleting a file, and truncating a file. These operations comprise the minimal set of required file operations.


Virtual Memory OS Assignment




1. What is thrashing? Why does it occur? Explain the two approaches to prevent it from happening
Answer: A process is busy swapping pages in and out consequently it quickly faults again and again, replacing pages that it must bring back in immediately. This high paging activity is called thrashing. Thrashing occurs when a process does not have the number of frames it needs to support pages in active use, it will quickly page-fault. At this point, it must replace some page. However, since all its pages are in active use, it must replace a page that will be needed again right away.
The working-set model is based on the assumption of locality. This model uses a parameter to define the working-set window. The idea is to examine the most recent page references. The set of pages in the most recent page references is the working set. If a page is in active use, it will be in the working set. If it is no longer being used, it will drop from the working set time units after its last reference. Thus, the working set is an approximation of the program’s locality.

Page-fault frequency (PFF) takes a more direct approach. The specific problem is how to prevent thrashing. Thrashing has a high page-fault rate. Thus, we want to control the page-fault rate. When it is too high, we know that the process needs more frames. Conversely, if the page-fault rate is too low, then the process may have too many frames. We can establish upper and lower bounds on the desired page-fault rate. If the actual page-fault rate exceeds the upper limit, we allocate the process another frame. If the page-fault rate falls below the lower limit, we remove a frame from the process. Thus, we can directly measure and control the page-fault rate to prevent thrashing.

2. What is memory-mapped-file? Explain the advantage of the approach.
Answer:  Consider a sequential read of a file on disk using the standard system calls open(), read(), and write(). Each file access requires a system call and disk access. Alternatively, we can use the virtual memory techniques to treat file I/O as routine memory accesses. This approach, known as memory mapping a file, allows a part of the virtual address space to be logically associated with the file.
The advantage of this approach is I/O intensive operations can be much faster since content does need to be copied between kernel space and user space. In some cases, performance can nearly double.
3. With an average page-fault service time of 4 milliseconds and a memory access time of 200 nanoseconds, what is the effective memory access time in nanoseconds for 0.0001% page-fault rate?
Answer:

4. Consider a demand-paging system with the following time-measured utilizations:
CPUutilization 20%
Paging disk 97.7%
OtherI/Odevices 5%
For each of the following, indicate whether it will (or is likely to) improve
CPUutilization. Explain your answers.
a. Install a fasterCPU.
b. Install a bigger paging disk.
c. Increase the degree of multiprogramming.
d. Decrease the degree of multiprogramming.
e. Install more main memory.
f. Install a faster hard disk or multiple controllers with multiple hard disks.
h. Increase the page size.

Answer:

The system is spending most of its time paging, indicating over-allocation of memory. If the level of multiprogramming is reduced resident processes would page fault less frequently and the CPU utilization would improve. Another way to improve performance would be to get more physical memory or a faster paging drum.

a. Install a faster CPU-No, This will likely have no effect. The limiting factor is available memory per program

b. Install a bigger paging disk—No, This should have no effect.

c. Increase the degree of multiprogramming—No, This typically decreases CPU utilization because less memory is available to each program and the chances of page fault increase.

d. Decrease the degree of multiprogramming—Yes, this typically increase CPU utilization by keeping more of the working set of each program in memory, thereby reducing the number of page faults.

e. Install more main memory—Likely to improve CPU utilization as more pages can remain resident and not require paging to or from the disks.

f. Install a faster hard disk, or multiple controllers with multiple hard disks—Also an improvement, for as the disk bottleneck is removed by faster response and more throughput to the disks, the CPU will get more data more quickly.

h. Increase the page size—increasing the page size will result in fewer page faults if data is being accessed sequentially. If data access is more or less random, more paging action could ensue because fewer pages can be kept in memory and more data is transferred per page fault. So this change is as likely to decrease utilization as it is to increase it.


5. Answer to the textbook question “10.7. It is sometimes said …”












6. Answer to the textbook question “10.11. Suppose that a disk …”
2,069, 1,212, 2,296, 2,800, 544, 1,618, 356, 1,523, 4,965, 3681

Answer:
a. FCFS -   2150, 2,069, 1,212, 2,296, 2,800, 544, 1,618, 356, 1,523, 4,965, 3681
The total distance is 13011

b. SSTF -   2150, 2069, 2296, 2800, 3681, 4965, 1618, 1523, 1212, 544, 356. The total distance is 7586.

c. SCAN - 2150, 2296, 2800, 3681, 4965, 4999, 2069, 1618, 1523, 1212, 544, 356.  Total distance is 7492.

d. LOOK - 2150, 2296, 2800, 3681, 4965, 2069, 1618, 1523, 1212, 544, 356
Total distance is 7424.

e. C-SCAN - 2150, 2296, 2800, 3681, 4965, 4999, 0, 356, 544, 1212, 1523, 1618, 2069.   The total distance is 9917.

f. C-LOOK - 2150, 2296, 2800, 3681, 4965, 356, 544, 1212, 1523, 1618, 2069.  
Total distance is 9137.

7. Answer to the textbook question “11.12. Provide examples of …”
Answer:
Sequential: Applications that access files sequentially include word processors, music players, video players and web servers

Random: Applications that access files randomly include databases, video editors and auto editors.