Tuesday, 31 December 2019

How do I store binary data in MySQL?

Q: How do I store binary data in MySQL?

Solution:

The basic answer is in a BLOB data type / attribute domain. BLOB is short for Binary Large Object and that column data type is specific for handling binary data.

you should be aware that there are other binary data formats:
TINYBLOB/BLOB/MEDIUMBLOB/LONGBLOB
VARBINARY
BINARY
Each has their use cases. If it is a known (short) length (e.g. packed data) often times BINARY or VARBINARY will work. They have the added benefit of being able ton index on them.


For a table like this:
CREATE TABLE binary_data (
    id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,
    description CHAR(50),
    bin_data LONGBLOB,
    filename CHAR(50),
    filesize CHAR(50),
    filetype CHAR(50)
);

Monday, 23 December 2019

Quick book payment integration

I am attempting to incorporate quick book to send and receive payments. But I can't locate api for payment (To send and receive payments to others). Furthermore, I am unable to locate api  to get bank transactions linked with quick book. Client has quick book software but want to fetch transaction in other software.

Solution:

Quick Book does not support any APIs to send and receive payments to others. This is not something that Quick Book / Intuit Payments supports.

Saturday, 7 December 2019

The average monthly precipitation (in.) for Boston and Seattle during 2012 are given in the vectors below

Q: The average monthly precipitation (in.) for Boston and Seattle during 2012 are given in the vectors below (data from the U.S. National Oceanic and Atmospheric Administration) BOS = [2.67 1.00 1.21 3.09 3.43 4.71 3.88 3.08 4.10 2.62 1.01 5.93] SEA = [6.83 3.63 7.20 2.68 2.05 2.96 1.04 0.00 0.03 6.71 8.28 6.85] Where the elements in the vectors are in the order of the months (January, February, etc.) Write your program to answer the following: (a) Calculate the total precipitation for the year and monthly average precipitation in each city. Do NOT use MATLAB's built-in functions sum and mean. (b) How many months was the precipitation above the average in each city? (c) How many months, and on which months, was the precipitation in Boston lower than the precipitation in Seattle? 

Solution:

 
clear all;
close all;
bos=[2.67,1,1.21,3.09,3.43,4.71,3.88,3.08,4.10,2.62,1.01,5.93];
sea=[6.83,3.63,7.20,2.68,2.05,2.96,1.04,0,0.03,6.71,8.28,6.85];
tot_bos=0;
tot_sea=0;
for x=1:1:12
tot_bos=tot_bos+bos(x);
tot_sea=tot_sea+sea(x);
end
avg_bos=tot_bos/12;
avg_sea=tot_sea/12;
above_avg_bos=0;
above_avg_sea=0;
for y=1:1:12
if(bos(y)>avg_bos)
above_avg_bos=1+above_avg_bos
end;
if(sea(y)>avg_sea)
above_avg_sea=1+above_avg_sea
end;
end
i=1;
for z=1:1:12
if(bos(z)<sea(z));
a(i)=z;
i=i+1;
end
end
fprintf('Total participation for the year in BOS ans SEA are %0.2d %0.2d\n',tot_bos,tot_sea);
fprintf('Monthly avg participation for the year in BOS ans SEA are %0.2d %d\n',avg_bos,avg_sea);
fprintf('Totoal month of above avg participation in the year for BOS and SEA %i %i\n',above_avg_bos,above_avg_sea);
fprintf('Total month where BOS is less than SEA %i and months are %i',i-1,a);

The average monthly precipitation (in.) for Boston and Seattle during 2012 are given in the vectors below

Q: The average monthly precipitation (in.) for Boston and Seattle during 2012 are given in the vectors below (data from the U.S. National Oceanic and Atmospheric Administration). BOS = [2.67 1.00 1.21 3.09 3.43 4.71 3.88 3.08 4.10 2.62 1.01 5.93] SEA = [6.83 3.63 7.20 2.68 2.05 2.96 1.04 0.00 0.03 6.71 8.28 6.85] where the elements in the vectors are in the order of the months (January, February, etc.) Write a program to answer the following: Calculate the total precipitation for the year and monthly average precipitation in each city. How many months was the precipitation above the average in each city? (c) How many months, and on which months, was the precipitation in Boston lower than the precipitation in Seattle?

Solution:

 
bos = [2.67 1.00 1.21 3.09 3.43 4.71 3.88 3.08 4.10 2.62 1.01 5.93];
sea = [6.83 3.63 7.20 2.68 2.05 2.96 1.04 0.00 0.03 6.71 8.28 6.85];
fprintf('Total precipitation in Boston=%f \n',sum(bos));
fprintf('Total precipitation in Seattle=%f \n',sum(sea));
fprintf('Average monthly precipitation in Boston=%f \n',sum(bos)/12);
fprintf('Average monthly precipitation in Seattle=%f \n',sum(sea)/12);
numMonthBos=0;
for v=bos
if v > sum(bos)/12
numMonthBos+=1;
end
end
numMonthSea=0;
for v=bos
if v > sum(sea)/12
numMonthSea+=1;
end
end
fprintf('Number of months when precipitation is above average in Boston=%d \n',numMonthBos);
fprintf('Number of months when precipitation is above average in Seattle=%d \n',numMonthSea);
total1=0;
for i=1:12
if bos(i) < sea(i)
total1+=1;
end
end
fprintf('Number of months when precipitation is lower in boston than in Seattle=%d \n',total1);

sh-4.3$ octave -qf --no-window-system demo.m octave: X11 DISPLAY environment variable not set octave: disabling warning: func

Write a program that will collect numbers from the user until the user enters a non-numeric value.

Q:
MATLAB Help:
Write a program that will collect numbers from the user until the user enters a non-numeric value. It then returns the sum and the average of all the numbers entered. Example below:
-----
Enter a number: 2.5
Enter a Number: 2
Enter a Number: 59
Enter a Number: 2
Enter a Number: 9
Enter a Number: 1.1
Enter a Number: k
The sum of the 6 numbers entered is 75.6. The average is 12.6.

Solution:

result = 0;
count = 0;
while(1)
val = input("Enter a number: ",'s')
val = str2double(val)
if(val == NaN)
break;
else
result = result + val;
end
count = count + 1;
end
fprintf("The sum of the %d numbers entered is %f. The average is %f.\n",count,result, (result/count));

Write a program that will collect one positive integer from the user. Validation is required.

Q:
MATLAB Help:
Write a program that will collect one positive integer from the user. Validation is required. Specifications:
1. The program should collect the input as a string and convert it to a numeric number
2. The program will check if the user enters nothing, a non-numeric value, or not a positive integer. It will keep prompting until the user enters a positive integer.
3. Design a prompt/feedback
Functions you may need: isempty(), isnan(), length(), str2double(), str2num()

Solution:


k=1;
while k==1
    k=0;
    num=input('Enter number: ','s');
    if isempty(num)
        k=1;
        fprintf('you did not enter anything\n')
    elseif isnan(str2double(num))
        k=1;
        fprintf('You entered a non numeric value\n')
    elseif str2double(num)<0
        k=1;
        fprintf('Please enter a positive value\n')
    else
        num=str2double(num);
    end
end
fprintf('You entered :%i\n',num)

Mini-program: Write a console program that prompts the user for an integer.

Q: Mini-program: Write a console program that prompts the user for an integer. As long as the user keeps entering positive integers, continue prompting for the next integer. Once the user enters an integer of 0 or less, report the largest integer that was entered and end the program.

Solution:

save it as test.c and in linux or ubuntu
Please run it using command : gcc -o test test.c
                                                        :./test
#include <stdio.h>
void main(){
int i;
int big=0;
printf("enter number : ");
scanf("%d",&i);
while(1){
printf("enter number : ");
if(i>0) {if(i>big) big=i;}
else {printf("largest number entered : %d\n",big);
return;}
scanf("%d",&i);}
}

Write a console program that prompts the user for an integer.

Q: Mini-program: Write a console program that prompts the user for an integer. As long as the user keeps entering positive integers, continue prompting for the next integer. Once the user enters an integer of 0 or less, report the largest integer that was entered and end the program.

Solution:


import java.util.ArrayList;
import java.util.Scanner;

public class LargestNumber

{
public static void main(String args[])
{
int ending=0;
ArrayList<Integer> list=new ArrayList<Integer>();/* declare arrylist to store the value*/
int value=1;
while(value>0)
{
System.out.println("Please Enter the number");/* promt the user to give the number*/
Scanner in=new Scanner(System.in);
value=in.nextInt();/* store the entered value */
ending =value;
if(value>0){/* check if the value is greater than zero than only it will store*/
list.add(value);
}
 
}
int max=0;
for(int i=0;i<list.size();i++)
{
if(list.get(i).intValue()>max)
max=list.get(i).intValue();
 
}
System.out.println("----------------------------------------");
System.out.println("largest number is=");/* print the largest number*/
System.out.println(max);
}
}

Design and implement a reusable program that takes any standard Shape and returns a Rectangle that completely incloses the Shape.

Q: Design and implement a reusable program that takes any standard Shape and returns a Rectangle that completely incloses the Shape. I expect you to write a class that defines a method to handle a shape. Let's name the class as MyClass and the method as reusable. For simplicity, consider only Rectangle 2 cap D.Double and Line2D.Double whenever you need to show s Shapes in your answer. You don't have to concern about drawing shapes for this question. Your job is to answer the subquestions (a) through (d). API is on the last page. Identify required classe(s) and interface(s) to solve the problem and draw the corresponding class diagram to depict their relationship. Include specific Shapes in your class diagram. Implement the reusable program MyClass. Write a tester that calls the reusable method with two different specific Shape objects. public class Tester {public static void main (String [] args) {//your work goes here.}} Briefly explain how polymorphism is used in the execution of the reusable method.

Solution:
 
a) Rectangle and Circle both are Shape.
So we selected Rectangle and Circle as Classes and Shape as interface for both, becouse shape has common funtionality fot both.
Classes Rectangle is a Shape and Circle is a Shape so both has "IS A" relationship with Shape
b)Implematation =>
//================== Shape.java ===========================//
public interface Shape {
   public double getArea();
   public double perimeter();
}
//========================== Rectangle.java ===========================//
public class Rectangle implements Shape {
   private double height;
   private double length;
 
   public Rectangle() {
     
   }
   public Rectangle(double h,double l) {
       height = h;
       length = l;
   }
 
   @Override
   public double getArea() {
       return height*length;
   }
   @Override
   public double perimeter() {
       return 2.0d*(height+length);
   }
   public double getHeight() {
       return height;
   }
   public void setHeight(double height) {
       this.height = height;
   }
   public double getLength() {
       return length;
   }
   public void setLength(double length) {
       this.length = length;
   }
}
//============================= Circle.java ========================//
public class Circle implements Shape {
   private double radius;
   final private double PI = 22.0d/7.0d;
   public Circle() {
     
   }
   public Circle(double r) {
       radius = r;
   }
   @Override
   public double getArea() {
       return PI*radius*radius;
   }
 
   @Override
   public double perimeter() {
       return 2.0*PI*radius;
   }
   public double getRadius() {
       return radius;
   }
   public void setRadius(double radius) {
       this.radius = radius;
   }
   public double getPI() {
       return PI;
   }
}
c) Test Program
//============================= ReusableTest.java==================================//
public class ReusableTest {
   public static void main(String[] args) {
       Shape[] shapes = new Shape[2];
       shapes[0] = new Rectangle(40.0d, 30.0d);
       shapes[1] = new Circle(20.0d);
       for(int i = 0;i<2;i++){
           System.out.println("Shape "+i+" Area :"+shapes[i].getArea());
           System.out.println("Shape "+i+" Perimeter :"+shapes[i].perimeter());
       }
   }
}
d)
We have careated Shape refrence variable and storing the object of circle and rectangel
by using shape only we are calling method area and perimeter but actual method is called from respective objcet only, so that is the example of run time polimorphysm

Friday, 6 December 2019

What will the following code fragment printout?

What will the following code fragment printout? 
String myString = "Java": System.out.println(myString.toUppercase() + "or" + myString): 
 A. java or Java 
B. Java or Java 
C. JAVA or JAVA 
D. JAVA or Java

Solution:

 
D (JAVA or Java)

The below program has two varints the first variant which converts all characters in the string to upper case and second variant takes locale as argument and converts into upper case

Write a complete Java program for the following questions

Q. Write a complete Java program for the following questions:    
         Write a program that print the following on the screen.
Java
Java Java
Java Java Java
Java Java Java Java
Java Java Java Java Java

Solution:

 
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
   public static void main (String[] args) throws java.lang.Exception
   {
       int i,j;
       for(i=0;i<5;i++)
       {
           for(j=0;j<=i;j++)
               System.out.print("JAVA ");
             
           System.out.println();
       }
   }
}

Southridge Company incurred the following costs related to its purchase of a new assembly line

1. Southridge Company incurred the following costs related to its purchase of a new assembly line: Purchase cost: Php 9,435,000 (including Php 435,000 freight and purchase taxes)
Recoverable purchase taxes: Php 960,000
Irrecoverable purchase taxes: Php 870,000
Installation of assembly line: Php 975,000
Training of employees: Php 195,000
Estimated repair and maintenance costs over useful life: Php 500,000
What is the amount to be recognized as asset related to the assembly line?
a.
Php 11,280,000
b.
Php 9,450,000
c.
Php 9,645,000


Solution:

Answer: b) Php 9,450,000
Note:
1.As per IAS 16-Property Plant & Equipment, Employee Training cost will not be part of Assets capitalization. unless those cost is directly associated to bring assets to required condition & use as intended by management.
2. Repair & Maintenance cost can not be part assets capitalization..

Php
Cost of New assembly    9,435,000.00
Less:Recoverable Tax     (960,000.00)
Add:Installation cost        975,000.00
Asset to be Recognized 9,450,000.00

Wednesday, 4 December 2019

Write a program that has a declaration in main() to store the string "Vacation"

Q: Write a program that has a declaration in main() to store the string "Vacation" i near in an array named message. Also, add a function call to display() that accepts message in an argument named strng and then displays the contents of message by using pointer notation *(strng + i), modify the display() function to use the expressions *strng rather than *(strng + i). The program I compiled from this question is listed below, I am struggling with placements of notations on the latter part of the question.

#include <iostream>
using namespace std;

int main(){
void dispstr(char*);
char str[] = "Vacation";

display(str);
return 0;
}

void display(char* ps)
{
while( *ps )
cout << *ps++;
cout << endl;
}

Solution:

 #include <iostream>
using namespace std;

int main(){
void dispstr(char*);
char str[] = "Vacation";

display(str);
return 0;
}

void display(char* ps)
{
while( *ps )
cout << *ps++;
cout << endl;
}

Write a program that has a declaration in main() to store the string Vacation

Q: Write a program that has a declaration in main() to store the string Vacation is near in an array named message. Include a function call to display () that accepts message in an argument named string and then displays the contents of message by using the pointer notation *(strng + i).
Then modify the display() function written to use the expression *strng rather than *(strng +i) to retrieve the correct element.


Solution:

#include <iostream>

using namespace std;

void display(char* string)
{
for(int i=0; i<strlen(string); i++)
cout << *(string+i);
}

void display2(char* string)
{
int len = strlen(string);
for(int i=0; i<len; i++)
{
cout << *string;
string++;
}
}

int main()
{
char message[50] = "Vacation is near";


display(message);
cout << endl;
display2(message);
return 0;

Saturday, 23 November 2019

A bit string, 0111101111101111110, needs to be transmitted

Q: A bit string, 0111101111101111110, needs to be transmitted at the data link layer.
What is the string actually transmitted after bit stuffing?
 
Solution:
 
 The output is 011110111110011111010.

The following data fragment occurs in the middle of a data

Q: The following data fragment occurs in the middle of a data stream for which the byte-stuffing algorithm described in the text is used: A B ESC C ESC FLAG FLAG D.
What is the output after stuffing?
 
Solution:
 
 After stuffing we get: A B ESC ESC C ESC ESC ESC FLAG ESC FLAG D.

The following character encoding is used in a data link protocol

Q: The following character encoding is used in a data link protocol:
A:01000111; B:11100011; FLAG:01111110; ESC: 11100000
Show the bit sequence transmitted (in binary) for the four-character frame: A B ESC
FLAG when each of the following framing methods are used:
(a) Character count.
(b) Flag bytes with byte stuffing.
(c) Starting and ending flag bytes, with bit stuffing.
 
Solution:
 

a. 00000100 0100011111100011 11100000 01111110
b. 01111110 0100011111100011 11100000 11100000 11100000 01111110
01111110
c. 01111110 01000111110100011 111000000 011111010 01111110

An upper-layer packet is split into 10 frames, each of which has an 80 percent chance of arriving undamaged.

Q: An upper-layer packet is split into 10 frames, each of which has an 80 percent chance of arriving undamaged. If no error control is done by the data link protocol, how many times must the message be sent on average to get the entire thing through?

Solution:

First notice that no error checking is done by the data link protocol. What this means is that if an error occurs in a frame this information will not be known until all 10 frames have been transmitted and reassembled(the transport layer is doing some error control presumably, and will detect if there was an error in 1 or more frames and if so, request re-transmission). So in the case of this problem, we can't just repeatedly send the first frame until it gets through without error, then do the same for the second,etc. Instead, we must send all 10 frames. If they all get through without error we are done. Otherwise, we must send all 10again.
Because each frame has a probability of 0.8 of getting through correctly and errors can be considered independent events, the probability of the whole message getting through correctly on any given attempt is which is about 0.107 (or 10.7%). Call this value p.
Now notice that the probability of the message requiring i transmissions is .The reason is that if it takes exactly i transmissions, the first i-1 attempts must have failed(this happens with probability since the probability of a failed transmission is (1- probability of successful transmission) = (1-p). After these failed attempts,the ith attempt must succeed. This happens with probability p.
To compute the expected number of transmissions required(i.e.the average transmissions required) we weight all the possible transmissions required with their respective probabilities and then sum over all these possibilities. So the expected number of transmissions, E, is:

Notice that the last sum starts at i=0. This is fine since at i=0 =0, so we are just adding 0, something that doesn't change the value of the expression.
To evaluate this sum, we again use the trick of differentiating a series for which we already know the sum to get a form that is useful in the problem at hand.
It was proven in class that
Taking the derivative of both sides shows that .
Now, we just set r=1-p to get .Notice that we must have r<1 for the above equations to hold. But since r=1-p and ,r < 1 as needed.
So the answer is 1/0.107 or about 9.3 transmissions.
Now, we do the same problem, but take the probability of error-free transmission for a frame to be 0.99. In this case which is about 0.904 (quite a bit higher than the first part). The work we did in the first part still holds, so al lwe need to do is calculate which in this case is about 1.1.

Date Rate of noiseless 4-kHz

Q: Compare the maximum data rate of a noiseless 4-kHz channel using
(a) Analog encoding (e.g.,QPSK)with 2 bits per sample.
(b) The T1 PCM system.
 
Solution:

a) Maximum sampling rate = 2 x 30 = 60 Kbps.
4 level PCM will need 2 bits/sample.
Maximum datarate = 60 x 2 =120 Kbps
 
b)Maximum sampling rate = 2 x 30 = 60 Kbps.
6 level PCM will need 3 bits/sample.
Maximum datarate = 60 x 3 =180 Kbps

Saturday, 9 November 2019

Setting up a database and have auto-commit turned off

Q: You are working on setting up a database and have auto-commit turned off so you can easily undo mistakes. Unfortunately, your session crashes – the database itself is fine but your remote connection failed due to network troubles. You are disconnected long enough for your mysql session to terminate.
Once you manage to reconnect and start a new session, what happens to the changes that you made since your last manual commit (or entry of a statement equivalent to a commit) and why? Select the best answer.
You may want to read up the details.


1.
Because auto-commit is turned off, you have lost all of your work since you last manually committed your work. Any changes made since then have been rolled back.
2.
You will not have lost any work, because MySQL sessions automatically continue from where they left off last time. Any uncommitted work is still not committed.
3.
Whether or not you lost work depends on the type of commands in the current transaction. Actions less likely to interfere with another transaction are more likely to have been accepted.
4.
You will not have lost any work, because the end of a session acts as a commit.


Solution:
Option 4
Because a commit or rollback command will ends the current session and starts a new one
 

Best practice for securing user accounts for a MySQL

Q:
Which of the following are considered best practice for securing user accounts for a MySQL installation? Select all that apply.
Hint: This question goes somewhat further than what was covered in the lecture so you will probably need to do some reading to correctly answer this question.
1.
When connecting to a database, never send the password on the command line or code it in plain text into the front end. You can use a properties file, and can hide it by moving it elsewhere and/or changing its name. Better yet, use the mysql_config_editor to store authentication details in an encrypted file.
2.
Any code used to set up users and/or update passwords from the front end needs to ensure that communications with the database are encrypted so that passwords are not sent across the network in plain text.
3.
A MySQL account should only have the privileges that it absolutely needs; different user profiles generally warrant the creation of different accounts. Only administrative accounts should have access to things like triggers and procedures, and they should be restricted to logging in from specific IP addresses (or localhost) where possible.
4.
When giving edit privileges to a user, it is best to have them log in through a front end that does initial checks for attacks such as SQL injection. This front end should communicate via the database through specific procedure calls to insert or update data, to limit the ways in which data is changed. Such procedures should also perform data integrity checks before allow data to be changed.
5.
None of the above.
 
Solution:
1>
When connecting to a database, never send the password on the command line or
code it in plain text into the front end. You can use a properties file,
and can hide it by moving it elsewhere and/or changing its name.
Better yet, use the mysql_config_editor to store authentication details in an encrypted file

I feel the proper method to get passwords for MYSQL servers is to , to have a sign on prompt and get client to enter
the passwords. or have a secured , protected file to save the password.
so coding password in a plain text is highly unadvisable or getting it from command line.
and saving it in a config file using mysql_config editor is advisable.
so option A in your question is one among the best options to secure accounts.

2>Any code used to set up users and/or update passwords from the front end needs to ensure that communications with the database are encrypted
so that passwords are not sent across the network in plain text.
   Communications with database should always be encrypted because, any insert or update statements
might log user passwords as it is. Here privileges comes into picture, only user with super privileges should be allowed to update passwords.
so when password is entered from front end , it should be shown as ******.
also hashing the password , before it travels from user end to database also using secure networks such as https instead of http is a plus.
storing passwords in encrypted way , there is also unique salts for each encrypted passwords, ensure double security.
so option B in your question is one among the best options to secure accounts.
3>yes this is right, we cannot give all privileges to all users in system.
we should have administrative accounts/admins at different levels.
so option C is also one among the best options to secure accounts.
4>so when we are granting edit privileges to user, initially we would have to login as super user or root user.
I feel when entered as super user, we are compromising a lot on security.
its not just the procedures to perform integrity checks, privileges at table level, columns level, proxy privil, along with procedure privileges should be taken care of.
so option 4 is all good, but not the best among 4 described here.
 

Performance of the database

Q: A shop stores information on Customers(cid, name, address, last_visit), Inventory(iid, name, cost, price, stock) and Purchases( cid, iid, when, price, quantity) FK cid REF Customers(cid) ON DELETE RESTRICT ON UPDATE CASCADE, FK iid REF Inventory(iid) ON DELETE RESTRICT ON UPDATE CASCADE.
Which of the following actions are more likely than not to be true regarding the performance of the database? Select all that apply.

 
1. Using the CREATE INDEX statement to create an index to cid in Customers would make no difference at all.
2. Creating indexes on Purchases may be harmful if we are expecting very frequent INSERT operations.
3. Attribute iid of Inventory having an index is likely to assist with an INSERT operation on Customers.
4. Creating an index on the stock attribute of Inventory would be useful if changes are often due to customers purchasing items (the integer stored in stock decreases by the quantity of every purchase for the product with the iid given in the Purchases tuple), but there are few INSERT operations on the table.


Solution:
NOTE : The INSERT and UPDATE statements take more time on tables having indexes, whereas the SELECT statements become fast on those tables. The reason is that while doing insert or update, a database needs to insert or update the index values as well.
1. False
Explanation : Indexing in Customers is likely to improve its performance because it is less likely to have new customers very often so INSERT (or UPDATE) operations will be less on Customers. On the other hand, INSERT operations on Purchases is more likely and that would require lookup of cid in Customers table due to the presence of foreign key. So, indexing will decrease the lookup time in Customers table and hence, will increase the performance.
2. True
Explanation : As INSERT operations are expected to be more frequent, the indexing may slow down the operations and hence, may degrade the performance.
3. False
Explanation : INSERT operation on Customers has nothing to do with attribute iid of Inventory.
4. False
Explanation : Changes in stock attribute of Inventory due to customers purchasing items would be UPDATE operations. And UPDATE operations also take more time on tables having indexes and hence, may degrade the performance.
 

Triggers in MySQL

Q: Which of the following is true of triggers in MySQL? Select all that apply.
Note: The way triggers works has changed slightly in recent versions. This question refers to the most recent version (after 6 or later).

Solution:


1.
A trigger can call a stored procedure.
2.
A trigger attached to table A that performs an operation on a table B, can cause the activation (triggering) of one or more triggers that are attached to table B.
3.
Specifying a trigger as FOR EACH ROW means the trigger is activated once for each row that is inserted, updated, or deleted.
4.
It is not possible to have multiple triggers with the same trigger event and action time (before/after).
5.
A trigger that attempts to alter the table that it is attached to will result in an error.


Solution:
Solution for 1: False, you can only execute stored procedures and Triggers in a stored procedure cannot be called directly.
Solution for 2: False, it does not create activation of several triggers at table B.
Solution for 3: True, trigger is activated when DML operations are triggered once for each row that is updated
Solution for 4: False, you can only create one trigger for an event per table as well as trigger event and action time
Solution for 5: False, unless the trigger and table posses the same name
 

C-programming problem

Let R be a sequence. The inverse sequence of R is the sequence by reading the symbols in R backwards. For example, the inverse of 0113 is 3110. If the inverse of R is identical to R, then R is called a palindrome sequence. For example, R[9] = 011303110 is a palindrome sequence. Given a sequence S, if R is a subsequence of S and R is palindrome, then R is called a palindrome subsequence of S. One can then similarly define what a longest palindrome subsequence (LPS for short) of S is.
Problem:
Write a program that reads in a sequence of max length = 10,000. Then compute the LPS of a sequence input by the user. Output will print the LPS and its length.
Sample run:
Enter a sequence: 13112301728031631251841324
# an LPS (length = 13) for the second sequence is:
3112136312113

Solution:

/* C program to find the the longest palindromic substring */

#include <stdio.h> //for standard I/O
#include <stdbool.h> //for boolean variable
#include <string.h> //for string functions strlen
// function to find the longest palindromic substring and
//print the substring & its length
int longestPalinStr(char str[])
{
// find the length of the input string
int n = strlen(str);
//array for memoization
bool array[n][n];

//declare array as false(0) initially
memset(array, 0, sizeof(array));
//length of 1 character substring
int maxLen = 1;
//for length 1 substring set true(1)
for (int k = 0; k < n; k++)
array[k][k] = true;
//checking for substring of length 2.
int start = 0;
for (int i = 0; i < n-1; i++)
{
if (str[i] == str[i+1])
{
array[i][i+1] = true;
start = i;
maxLen = 2;
}
}
//loop for substrings of lengths > 2
for (int k = 3; k <= n; k++)
{
for (int i = 0; i < n-k+1 ; i++)
{
//for last index
int j = i + k - 1;
//check for the contained substring to be palindrome
//using array[i+1][j-1] and boundary characters using str[i] and str[j]
if (array[i+1][j-1] && str[i] == str[j])
{
//if above 'if' is true then set position of array[i][j] to be true
array[i][j] = true;
//to set position of start
//and update maxLen
if (k > maxLen)
{
maxLen = k;
start = i;
}
}
}
}
printf(" The longest palindromic substring is: ");
int last = start + maxLen - 1;
//print the substring from start index to last index
for( int i = start; i <= last; i++ )
printf("%c",str[i]);

printf("\nLength is: %d" , maxLen);
}
//main function
int main()
{
//decalre a character array of size 10000
char ch[10000];
//read the string from console
scanf("%s",&ch);
//call thelongestPalinStr() to find the longest palindromic substring of ch[]
longestPalinStr(ch);
return 0;
}


Scheduling, Synchronization and Deadlock (Quiz)

Question 1
Which of the following scheduling algorithms must be nonpreemptive?
  1. Shortest Job First
  2. Round Robin
  3. First Come, First Served
  4. Priority Algorithms
Solution: First Come, First Served

Question 2
____ scheduling is approximated by predicting the next CPU burst with an exponential average of the measured lengths of previous CPU bursts. 
  1. Shortest Job First
  2. Round Robin
  3. Multilevel queue
  4. First Come, First Served 
 Solution: Shortest Job First

Question 3
With the following process list, what is the Average Turnaround Time for the Round Robin scheduling algorithm with a time quantum of 5ms? 

Submission Time Process Run Time
0ms 10ms
5ms 20ms
15ms 10ms
30ms 20ms
40ms 10ms
60ms 10ms
  1.  20
  2. 23
  3. 25
  4. 27
Solution: 27

Question 4
____ is the number of processes that are completed per time unit.
  1. Response time
  2. Turnaround time
  3. Throughput
  4. CPU utilization 
 Solution: Throughput

Question 5
Which of the following is true of cooperative scheduling?
  1.  A process keeps the CPU until it releases the CPU either by terminating or by switching to the waiting state.
  2. A process switches from the running state to the ready state when an interrupt occurs.
  3. It requires a timer.
  4. It incurs a cost associated with access to shared data. 
Solution: A process keeps the CPU until it releases the CPU either by terminating or by switching to the waiting state.

Question 6
A significant problem with priority scheduling algorithms is _____.
  1. determining the length of the time quantum
  2. complexity
  3. determining the length of the next CPU burst
  4. starvation
Solution: starvation

Question 7
______ allows a thread to run on only one processor.
  1. Load balancing
  2. Processor affinity
  3. Processor set
  4. NUMA
Solution: Processor affinity

Question 8
With the following process list, what is the Average Response Time for the First Come, First Served scheduling algorithm? 
 

Submission Time Process Run Time
0ms 10ms
5ms 20ms
15ms 10ms
30ms 20ms
40ms 10ms
60ms 10ms
  1. 10ms
  2. 7.5ms
  3. 12.5ms
  4. 5ms
Solution: 10ms

Question 9
The ______ occurs in First Come, First Served scheduling when a process with a long CPU burst occupies the CPU. 
  1. waiting time
  2. convoy effect
  3. systemcontention scope
  4. dispatch latency 
 Solution: convoy effect

 

Stored procedures and functions are available in the current database

Q: Which of the following commands is the best way to generate an overview of what stored procedures and functions are available in the current database and what each does? Assume that the developer(s) of the database have followed the good coding guidelines laid out in this unit.


1.
SHOW PROCEDURES;
2.
SHOW PROCEDURE STATUS WHERE db = DATABASE();
3.
SELECT * FROM INFORMATION_SCHEMA.ROUTINES;
4.
SELECT name, comment, type FROM mysql.proc WHERE db = DATABASE();

Solution:
 
2.SHOW PROCEDURE STATUS WHERE db = DATABASE();
This is the ideal statement to list the procedures stored in the database mentioned in the search condition.
Only SHOW PROCEDURES is not a valid statement as it also needs STATUS
SELECT * FROM INFORMATION_SCHEMA.ROUTINES; this statement selects all the rows from the table ROUTINES and displays the result.
SELECT name, comment, type FROM mysql.proc WHERE db = DATABASE(); This is the selective display of certain columns from the table mysql.proc from the database db.

Saturday, 24 August 2019

Processes and Threads (Quiz)

Question 1
The list of processes waiting for a particular I/O device is called a(n) ____.
  1. standby queue
  2. device queue
  3. ready queue
  4. interrupt queue
Solution: device queue

Question 2
A _________________ saves the state of the currently running process and restores the state of the next process to run.
  1. save-and-restore
  2. state switch
  3. context switch
  4. process control block
Solution: context switch

Question 3
The ____ of a process contains temporary data such as function parameters, return addresses, and local variables. 
  1. text section
  2. data section
  3. program counter
  4. stack 
 Solution: stack

Question 4
A process that has terminated, but whose parent has not yet called wait(), is known as a ________ process. 
  1. zombie
  2. orphan
  3. terminated
  4. init 
 Solution: zombie

Question 5
The _______ process is assigned as the parent to orphan processes.
  1. zombie
  2. init
  3. main
  4. renderer 
 Solution: init

Question 6
Which of the following statements is true?
  1.  Shared memory is typically faster than message passing.
  2. Message passing is typically faster than shared memory.
  3. Message passing is most useful for exchanging large amounts of data.
  4. Shared memory is far more common in operating systems than message passing. 
Solution: Shared memory is typically faster than message passing.

Question 7
A process control block ____.
  1. includes information on the process's state
  2. stores the address of the next instruction to be processed by a different process
  3. determines which process is to be executed next
  4. is an example of a process queue 
 Solution: includes information on the process's state

 Question 8
All processes in UNIX first translate to a zombie process upon termination.
  1. True
  2. False 
 Solution: True

Question 9
Child processes inherit UNIX ordinary pipes from their parent process because:
  1.  The pipe is part of the code and children inherit code from their parents.
  2. A pipe is treated as a file descriptor and child processes inherit open file descriptors from their parents.
  3. The STARTUPINFO structure establishes this sharing.
  4. All IPC facilities are shared between the parent and child processes. 
Solution: A pipe is treated as a file descriptor and child processes inherit open file descriptors from their parents.

Question 10
The _____________ refers to the number of processes in memory.
  1. process count
  2. long-term scheduler
  3. degree of multiprogramming
  4. CPU scheduler
Solution: degree of multiprogramming

Question 11
_____ is not considered a challenge when designing applications for multicore systems.
  1. Deciding which activities can be run in parallel
  2. Ensuring there is a sufficient number of cores
  3. Determining if data can be separated so that it is accessed on separate cores
  4. Identifying data dependencies between tasks.

Solution: Ensuring there is a sufficient number of cores

Question 12
Which of the following would not be an acceptable signal handling scheme for a
multithreaded program?
  1. Deliver the signal to the thread to which the signal applies.
  2. Deliver the signal to every thread in the process.
  3. Deliver the signal to only certain threads in the process.
  4. Do not deliver the signal to any of the threads in the process.
Solution: Do not deliver the signal to any of the threads in the process.

Question 13
The ____ multithreading model multiplexes many user-level threads to a smaller or equal number of kernel threads.
  1. many-to-one model
  2. one-to-one model
  3. many-to-many model
  4. many-to-some model
Solution: many-to-many model

Question 14
A _____ uses an existing thread — rather than creating a new one — to complete a task.
  1. lightweight process
  2. thread pool
  3. scheduler activation
  4. asynchronous procedure call
Solution: thread pool

Question 15
_________ involves distributing tasks across multiple computing cores.
  1. Concurrency
  2. Task parallelism
  3. Data parallelism
  4. Parallelism
Solution: Task parallelism

Question 16
A ____ provides an API for creating and managing threads.
  1. set of system calls
  2. multicore system
  3. thread library
  4. multithreading model
Solution: thread library

Question 17
Thread-local storage is data that ____.
  1. is not associated with any process
  2. has been modified by the thread, but not yet updated to the parent process
  3. is generated by the thread independent of the thread's process
  4. is unique to each thread
Solution: is unique to each thread

Question 18
Signals can be emulated in windows through ____.
  1. asynchronous procedure calls
  2. local procedure calls
  3. remote procedure calls
  4. synchronous procedure calls 
 Solution: asynchronous procedure calls

Question 19
Pthreads refers to ____.
  1. the POSIX standard.
  2. an implementation for thread behavior. 
  3. a specification for thread behavior.
  4. an API for process creation and synchronization. 
 Solution: a specification for thread behavior.

Question 20
According to Amdahl's Law, what is the speedup gain for an application that is 60% parallel and we run it on a machine with 4 processing cores? 
  1. 1.82
  2. 0.7
  3. 0.55
  4. 1.43 
 Solution: 1.43 

Open Source Development Tools and Overview (Quiz)

Question 1
________ is the proper filename for the file that contains targets, dependencies and rules which are used to define how your source code should be built into a binary executable.
  1. compiler
  2. make
  3. gcc
  4. Makefile
Solution:  Makefile

Question 2
What editor are you required to use in order to write source code on Linux?
  1. nano
  2. vim
  3. Any editor you are comfortable with
  4. emacs
Solution:  Any editor you are comfortable with

Question 3
Which gcc compiler option should you use in order to include symbols for debugging?
  1. -Wextra
  2. -o
  3. -Wall
  4. -g  
Solution: -g

Question 4
Before committing changes, what git command is used in order to include updates made to files that already exist in a local git repository? 
  1. update
  2. pull
  3. add
  4. push  
Solution: add

Question 5
When working with a remote git repository, what command should be used in order to synchronize changes from the the remote repository into the local repository? 
  1. update
  2. add
  3. push
  4. pull  
Solution: pull

Question 6
Which is not another term for kernel mode?
  1. system mode
  2. operating mode
  3. privileged mode 
  4. supervisor mode 
Solution: operating mode

Question 7
A(n) ________ is the unit of work in a system
  1. timer
  2. process
  3. operating system
  4. mode bit  
Solution: process

Question 8
What statement concerning privileged instructions is considered false?
  1. They can be executed in user mode.
  2. They are used to manage interrupts.
  3. They can be executed in kernel mode.
  4. They may cause harm to the system. 
Solution: They can be executed in user mode.

Question 9
A(n) ____ is a custom build of the Linux operating system
  1. installation
  2. LiveCD
  3. distribution
  4. VMWare Player
 Solution: distribution

Question 10
The most common secondary storage device is ____.
  1. magnetic disk
  2. tape drives
  3. random access memory
  4. solid state disks
 Solution: magnetic disk

Question 11
The two separate modes of operating in a system are
  1. user mode and kernel mode
  2. supervisor mode and system mode
  3. physical mode and logical mode
  4. kernel mode and privileged mode  
Solution: user mode and kernel mode

Question 12
Embedded computers typically run ____ operating system
  1. a clustered
  2. a network
  3. the Windows XP
  4. a real-time
Solution: a real-time

Question 13
Which of the following operating systems is not open source?
  1. PCLinuxOS
  2. BSD UNIX
  3. Linux
  4. Windows 
Solution:  Windows

Question 14
Microkernels use _____ for communication.
  1. virtualization
  2. message passing
  3. shared memory
  4. system calls 
Solution: message passing

Question 15
If a program terminates abnormally, a dump of memory may be examined by a ____ to determine the cause of the problem. 
  1. module
  2. control card
  3. debugger
  4. shell 
 Solution: debugger

Question 16
_____ allow operating system services to be loaded dynamically.
  1. Virtual machines
  2. Modules
  3. File systems
  4. Graphical user interfaces
Solution: Modules

Question 17
_____ provide(s) an interface to the services provided by an operating system.
  1. System calls
  2. Communication
  3. Simulators
  4. Shared memory
Solution: System calls

Question 18
A microkernel is a kernel ____.
  1. that is compressed before loading in order to reduce its resident memory size
  2. that is compiled to produce the smallest size possible when stored to disk
  3. containing many components that are optimized to reduce resident memory size
  4. that is stripped of all nonessential components 
 Solution: that is stripped of all nonessential components

Question 19
A _____ is an example of a systems program.
  1.  text formatter
  2. database system
  3. command interpreter
  4. Web browser 
Solution: command interpreter

Question 20
A boot block ____.
  1. typically only knows the location and length of the rest of the bootstrap program
  2. is composed of multiple disk blocks
  3. typically is sophisticated enough to load the operating system and begin its execution
  4. is composed of multiple disk cylinders 
Solution:
typically only knows the location and length of the rest of the bootstrap program