Answer:
Kindly check explaination for code
Explanation:
/* Java program for Merge Sort */
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
Answer:
Check the explanation
Explanation:
/* Java program for Merge Sort */
class MergeSort
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.length-1);
System.out.println("\nSorted array");
printArray(arr);
}
}
/* This code is contributed by Rajat Maurya */
Write an application that prompts a user for a month, day, and year. Display a message that specifies whether the entered date is not this year, in an earlier month this year, in a later month this year, or this month. Save the file as PastPresentFuture.java.
Answer:
See explaination
Explanation:
The program code
PastPresentFuture.java
import java.util.*;
import java.time.LocalDate;
public class PastPresentFuture
{
public static void main(String args[])
{
/*Initializing an array with days of month in a sequence, february with 28 days - it would be changed afterwards if the year entered is a leap year.*/
int daysOfmonth[]={31,28,31,30,31,30,31,31,30,31,30,31};
LocalDate today=LocalDate.now();
int mo,da,yr;
int todayMo,todayDa,todayYr;
//storing the values of today's day,month & year in 3 variables
todayMo=today.getMonthValue();
todayDa=today.getDayOfMonth();
todayYr=today.getYear();
//taking inputs of day,month & year from console which would be used later for checking
Scanner input=new Scanner(System.in);
System.out.println(":::Program to find whether a date is in past/present/future:::");
System.out.print("Enter month::");
mo=input.nextInt();
System.out.print("Enter day::");
da=input.nextInt();
System.out.print("Enter year::");
yr=input.nextInt();
/*finding whether the entered year is leap year or not based on standard logic and making the days of february to 29 if it is a leap year.*/
if(yr%100==0)
{
if(yr%400==0)
daysOfmonth[1]++;
}
else
{
if(yr%4==0)
daysOfmonth[1]++;
}
System.out.print("The date you entered -- ");
/*checking if the month value is between 1 to 12 and day entered is with in the boundary limits of the respective month using the array initialized above.
if the date entered is invalid, we are informing the user about the same and stopping the program.*/
if(!(mo>=1 && mo<=12 && da>=0 && da<=daysOfmonth[mo-1]))
{
System.out.println("invalid !!");
System.exit(0);
}
//logic to print the 4 statements as per the question
if(yr!=todayYr)
System.out.println(yr+" not this year.");
else
if(mo<todayMo)
System.out.println("month "+mo+" in an earlier month this year.");
else
if(mo>todayMo)
System.out.println("month "+mo+" in a later month this year.");
else
System.out.println("month "+mo+" is this month.");
}
}
You are a network administrator for a large bagel manufacturer that has 32 bakeries located throughout the United States, United Kingdom, and Switzerland. It is one year after you designed and implemented DHCP for IPv4, and now you must design and implement a DHCPv6 solution for an IPv6 rollout. Because you have a DHCP services system in place, what are the key components that must be researched to verify whether the current infra- structure will support the IPv6 projec
Answer:
See the components in explaination
Explanation:
In order to make it as IPv6, few key components should be supported, those components are given below:
The infrastructure must support the enhanced protocol StateLess Address Auto-Configuration (SLAAC).
Static addressing with DHCPv6, dynamic addressing with DHCPv6 and SLAAC are the methods used to configure the IPv6. The network administrator should able to understand and implement the IPv6 through the DHCPv6.
Other than the implementation, working of IPv4 and IPv6 are same. Therefore, the administrator need not to learn new information for its working.
As the IPv6 address length is 128-bit and purpose is for everything on line to have an IP address. It must allow the internet to expand faster devices to get internet access quickly.
The DHCPv6 is not supported by all windows. Therefore, network administrator should check the corresponding Operating system (OS) would support the DHCPv6 for IPv6.
The network administrator must have good knowledge and skills on the IPv6.
The above mentioned key components should be verified by the network administrator in order to support for IPv6 project with DHCPv6.
A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: the name of the client the service sold ( Dinner, Conference, Lodging) the amount of the sale the date of the event. Write a program that reads such a file and displays the total amount of each service category. Display an error if the file does not exist or the format is incorrect. Homework
Answer:
see explaination
Explanation:
Java code
//Header file section
import java.util.Scanner;
import java.io.*;
//main class
public class SalesTestDemo
{
//main method
public static void main(String[] args) throws IOException
{
String inFile;
String line;
double total = 0;
Scanner scn = new Scanner(System.in);
//Read input file name
System.out.print("Enter input file Name: ");
inFile = scn.nextLine();
FileReader fr = new FileReader(new File(inFile));
BufferedReader br = new BufferedReader(fr);
System.out.println("Name \t\tService_Sold \tAmount \tEvent Date");
System.out.println("=====================================================");
line = br.readLine();
//Each line contains the following, separated by semicolons:
//The name of the client, the service sold
//(such as Dinner, Conference, Lodging, and so on)
while(line != null)
{
String temp[] = line.split(";");
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]+"\t");
if(i == 1)
System.out.print("\t");
}
//Calculate total amount for each service category
total += Double.parseDouble(temp[2]);
System.out.println();
line = br.readLine();
}
//Display total amount
System.out.println("\nTotal amount for each service category: "+total);
}
}
inputSale.txt:
Peter;Dinner;1500;30/03/2016
Bill;Conference;100.00;29/03/2016
Scott;Lodging;1200;29/03/2016
Output:
Enter input file Name: inputSale.txt
Name Service_Sold Amount Event Date
=====================================================
Peter Dinner 1500 30/03/2016
Bill Conference 100.00 29/03/2016
Scott Lodging 1200 29/03/2016
Total amount for each service category: 2800.0
1) a) Create an unambiguous grammar which generates basic mathematical expressions (using numbers and the four operators , -, *, /). Without parentheses, parsing and mathematically evaluating expressions created by this string should give the result you'd get while following the order of operations. For now, you may abstract "number" as a single terminal, n. In the order of operations, * and / should be given precendence over and -. Aside from that, evaluation should occur from left to right. So 8/4*2 would result in 4, not 1. 1 2*3 would be 7. 4 3*5-6/2*4 would be 4 15-6/2*4
Answer:
Explanation:
CHECK THE ANSWER IN THE ATTACHMENT CORNNER
Give the Linux bash pipelined command that would take the output of the "cat /etc/passwd" command (that lists the contents of the system "password" file) and give us the single number showing how many accounts are configured in this file and store this information into the variable NUM_ACCOUNTS. Put only single spaces between commands, flags, piping operators, etc.
Answer:
See attached solution
Explanation:
Consider a demand-paging system with the following time-measured utilizations: CPU utilization 20% Paging disk 97.7% Other I/O devices 5% For each of the following, indicate whether it will (or is likely to) improve CPU utilization. Explain your answers. a. Install a faster CPU. 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. g. Add prepaging to the page-fetch algorithms. h. Increase the page size.
Answer:
see explaination please
Explanation:
a. Install a faster CPU. Answer:NO
Optional: a faster CPU reduces the CPU utilizationfurther since the CPU will spend more time waiting for a process toenter in the ready queue.
b. Install a bigger paging disk. Answer:NO
Optional: the size of the paging disk does not affect theamount of memory that is needed to reduce the pagefaults.
c. Increase the degree of multiprogramming Answer:NO
Since each process would have fewer frames available andthe page fault rate would increase
d. Decrease the degree of multiprogramming.Answer: YES
Optional: by suspending some of the processes, the otherprocesses will have more frames in order to bring their pages inthem, hence reducing the page faults.
e. Install more main memory. Answer:Likely
Optional: more pages can remain resident and do notrequire paging to or from the disks.
f. Install a faster hard disk or multiplecontrollers with multiple hard disks. Answer:Likely
(Optional)
g. Add prepaging to the page-fetchalgorithms.Answer: Likely
(Optional.)
h. Increase the page size. Answer:NO
Since each process would have fewer frames available and the page fault rate would increase
JAVA
Given an array of Student names, create and return an array of Student objects.
I wrote some code but I'm not sure if I'm doing this right (see the attachment).
Answer:
Answer is in the attached screenshot!
Explanation:
Iterate through the given input strings, create a student class with the given name, assign the output array to the value of the class created from the given input string. Finally, return the array.
Race conditions are possible in many computer systems. Consider a banking system with two functions:
deposit (amount) and withdraw (amount).
These two functions are past the amount that is to be deposited or withdrawn from a bank account. Assume a shared bank account exists between a husband and wife, and concurrently the husband calls the withdraw() function and the wife calls deposit().
1. Describe how a race condition is possible, and what might be done to prevent the race condition from occurring?
Answer:
A race condition is actually possible in this scenario.
Explanation:
A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time. In order to prevent the race condition from occurring the operations must be done in the proper sequence to be done correctly.
Here is an example of the race condition: Let's assume the Current Balance of the shared bank account is $600. The husband's program calls the withdraw($100) function and accesses the Current Balance of $600. But right before it stores the new Current Balance, the wife's program calls function deposit($100) function and accesses the Current Balance of $600. At this point, the husband's program changes the shared variable Current Balance to $500, followed by the wife's program changing the Current Balance variable to $700. Based on calling both withdraw($100) and deposit($100) functions, the Current Balance should again be $600, but it is $700. Alternatively, the Current Balance could also have been $500.
To prevent the race condition from occurring, the solution will be to create a method to "Lock" on the Current Balance variable. Each method must "Lock" the variable before accessing it and changing it. If a method determines that the variable is "Locked," then it must wait before accessing it.
Write a program that accepts an ISBN number and displays whether it is valid or not. An ISBN (International Standard Book Number) is a ten digit code which uniquely identifies a book. The first nine digits represent Group, Publisher and Title of the book and the last digit is used as a checksum (to check whether the given ISBN is valid). Each of the digits can take any value between 0 and 9. In addition, the last digit may also take a value X (stands for 10). To verify an ISBN, calculate 10 times the first digit, plus 9 times the second digit, plus 8 times the third and so on until we add 1 time the last digit. If the number 11 can divide the sum (no remainder), the code is a valid ISBN.
Answer:
is_isbn = True
total = 0
number = input("Enter the ISBN: ")
if len(number) != 10:
is_isbn = False
for i in range(9):
if 0 <= int(number[i]) <= 9:
total += int(number[i]) * (10 - i)
else:
is_isbn = False
if number[9] != 'X' and int(number[9]) > 9:
is_isbn = False
if number[9] == 'X':
total += 10
else:
total += int(number[9])
if total % 11 != 0:
is_isbn = False
if is_isbn:
print("It is a valid ISBN")
else:
print("It is NOT a valid ISBN")
Explanation:
Initialize the variables, total and is_isbn - keeps the value for the number if it is valid or not
Ask the user for the ISBN number
If number's length is less than 10, it is not valid, set is_isbn to false
Then, make calculation to verify the ISBN
Check the last digit, if it is not "X" and greater than 10, it is not valid, set is_isbn to false
Again, check the last digit, if it is "X", add 10 to the total, otherwise add its value
Check if total can divide 11 with no remainder. If not, it is not valid, set is_isbn to false
Finally, depending on the is_isbn variable, print the result
(Temperature Conversions) Write a program that converts integer Fahrenheit temperatures from 0 to 212 degrees to floating-point Celsius temperatures with 3 digits of precision. Perform the calculation using the formula celsius = 5.0 / 9.0 * ( fahrenheit - 32 ); The output should be printed in two right-justified columns of 10 characters each, and the Celsius temperatures should be preceded by a sign for both positive and negative values.
Answer:
#include <stdio.h>
int main()
{
//Store temp in Fahrenheit
int temp_fahrenheit;
//store temp in Celsius
float temp_celsius;
printf("\nTemperature conversion from Fahrenheit to Celsius is given below: \n\n");
printf("\n%10s\t%12s\n\n", "Fahrenheit", "Celsius");
//For loop to convert
temp_fahrenheit=0;
while(temp_fahrenheit <= 212)
{
temp_celsius = 5.0 / 9.0 *(temp_fahrenheit - 32);
printf("%10d\t%12.3f\n", temp_fahrenheit, temp_celsius);
temp_fahrenheit++;
}
return 0;
}
Explanation:
The program above used a while loop for its implementation.
It is a temperature conversion program that converts integer Fahrenheit temperatures from 0 to 212 degrees to floating-point Celsius temperatures with 3 digits of precision.
This can be calculated or the calculation was Perform using the formula celsius = 5.0 / 9.0 * ( fahrenheit - 32 ).
The expected output was later printed in two right-justified columns of 10 characters each, and the Celsius temperatures was preceded by a sign for both positive and negative values.
Back injuries are very common in humans and are often caused by lifting objects with the legs straight while leaning over; also known as "lifting with the back." Use the concepts learned in this lab to explain why one should "lift with the legs" rather than with the back. Make sure to discuss the forces and torques involved, and how they differ in the two lifting techniques.
Answer:
Back injuries are some of the most common injuries that occur when handling heavy objects, for example, when working in truck loading and unloading jobs, or lifting weights in a gym.
This type of injury is mainly caused by incorrect posture or body position when handling these weights. In essence, it is recommended that the back remain rigid and upright to avoid pressure on the lumbar zone and the cervical discs, transferring the center of force towards the legs (which have a capacity to exert much greater force than the mid-torso and back area). low).
In this way, the torque or upward pushing force that lifts the manipulated weights arises from the hamstrings and quadriceps, rather than directly out of the waist area. This prevents injuries such as herniated disc or low back pain, which are very painful and difficult to treat.
For the following two transactions and the initial table values as shown complete the missing blanks in the transaction log below:
Part_ID
Desrption
OnHand
OnOrder
57
Assembled Foo
5
0
987
Foo Fastener
12
7
989
Foo Half
7
0
BEGIN TRANSACTION;
UPDATE Part SET OnHand = OnHand + 7, OnOrder = OnOrder – 7 WHERE Part_ID = 987;
COMMIT;
BEGIN TRANSACTION;
UPDATE Part SET OnHand = OnHand - 4 WHERE Part_ID = 987;
UPDATE Part SET OnHand = OnHand - 2 WHERE Part_ID = 989;
UPDATE Part SET OnHand = OnHand + 1 WHERE Part_ID = 57;
COMMIT
TRL_ID
TRX_ID
PREV_PTR
NEXT_PTR
OPERATION
TABLE
ROW ID
ATTRIBUTE
BEFORE VALUE
AFTER VALUE
1787
109
NULL
START
****
1788
109
1787
UPDATE
PART
987
OnHand
12
1789
109
UPDATE
PART
987
OnOrder
7
1790
109
NULL
COMMIT
****
1791
110
NULL
START
****
Final answer:
The provided transaction log represents updates made to the 'Part' table in a database, recording the details of each transaction and the changes made to specific rows.
Explanation:
The transaction log provided represents a series of updates made to the 'Part' table in a database. Each transaction is recorded with a unique 'TRL_ID' and 'TRX_ID'. The 'OPERATION' column indicates the type of operation performed (e.g., START, UPDATE, COMMIT). The 'TABLE' column specifies the table that was updated, and the 'ROW ID' column represents the specific row that was modified. The 'BEFORE VALUE' and 'AFTER VALUE' columns show the original and final values of the updated attribute.
3. Write a script that uses an anonymous block of PL/SQL code that attempts to insert a new flight into the flights table for flight_number 165. Check to see whether there is a sequence being used for flight_id and then adjust your INSERT statement accordingly. Remember, you can use select statements to determine which values are appropriate to insert. If the insert is successful, the procedure should display this message:
Answer:
We will use script in oracle and SQl(Structured Query Language) and use of algorithms like cipher for encryption to insert a new flight into the flights table for the flight number 165 and that Cipher will show the desired message.
Write a Bare Bones program that takes as input two variables X and Y. (Again, assume these values are set before your program begins to execute.) Your program should place a 0 in the variable Z if the variable X is less than or equal to Y, and your program should place a 1 in the variable Z if the variable X is greater than Y.
Answer:
import java.util.Scanner;
public class num8 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter first number");
int X = in.nextInt();
System.out.println("Enter second number");
int Y = in.nextInt();
int Z;
if(X <= Y){
Z = 0;
}
else if(X >= Y){
Z = 1;
}
}
}
Explanation:
The program is implemented in JavaIn order to set the values for X and Y, The Scanner class is used to receive and store the values in the variables (Although the questions says you should assume these values are set)The if conditional statement is used to assign values (either 0 or 1) to variable Z as required by the question.Answer:
#The program sets Z to 0 if the X <= Y. otherwise sets Z to 1 , if the X > Y.
clear Z; # sets Z to 0
clear U; # sets U to 0
clear V; # sets v to 0
clear T; # sets T to 0
while Y not 0 # repeat until Y times
# process to decrement Y by 1
while Y not 0
incr U;
decr Y;
decr U;
while U not 0
incr Y;
decr U;
#process to decrement X by 1
while X not 0
incr V
decr X;
while V not 0
decr V;
while V not 0
incr T;
decr V;
while T not 0
incr X
decr T
#end of main while loop
#after running the main while loop, X will be positive and non - zero number, # #if X > Y. otherwise X and Y will be zero.
#process to increment Z by 1, if X is positive and non - zero number
while X not 0
while X not 0
decr X;
incr Z;
#end of while
Explanation:
The program is totakes in as input two variables X and Y.
The main function of the program is to return or place a 0 in the variable Z if the variable X is less than or equal to Y, and place a 1 in the variable Z if the variable X is greater than Y.
When these conditions are met, end program.
Modify the definition of the throttle class on page 35, to create a new throttle ADT, which allows the user of the ADT to specify the number of shift levels when creating objects of that class. You don't need to provide an implementation of the new throttle ADT, just the class definition.
Answer:
seeexplaination
Explanation:
Code(header file):
#ifndef THROTTLESHIFTLVEL_H
#define THROTTLESHIFTLVEL_H
class throttle
{
int position;
public:
throttle()
{
position = 0;
}
// specify the number of shift levels when creating objects
throttle(int level)
{
position = level;
}
void shut_off()
{
position = 0;
}
void shift(int amount)
{
if(amount >= 0)
position = position + amount;
}
double flow() const
{
return position;
}
bool is_on() const
{
if (position > 0)
return true;
else
false;
}
};
#endif
Please kindly check attachment for screenshot
Final answer:
To create a new throttle ADT with a customizable number of shift levels, define the class with an additional parameter in the constructor. Provide methods for shifting the throttle to a specific level and releasing it.
Explanation:
The modified definition of the throttle class to create a new throttle ADT, which allows the user to specify the number of shift levels, can be written as follows:
class Throttle:
def __init__(self, shift_levels):
self.shift_levels = shift_levels
def shift(self, level):
# shift the throttle to the specified level
pass
def release(self):
# release the throttle
pass
Write a SELECT statement that returns these columns from the Orders table: The order_id column The order_date column A column named approx_ship_date that’s calculated by adding 5 days to the order_date column The ship_date column A column named days_to_ship that shows the number of days between the order date and the ship date When you have this working, add a WHERE clause that retrieves just the orders for March 2018.
Answer:
SELECT order_id, order_date,
DATEADD(DAY,5,order_date) AS approx_ship_date,
ship_date,
DATEDIFF(DAY,ship_date,DATEADD(DAY,2,order_date)) AS days_to_ship
FROM Orders
WHERE YEAR(order_date) = 2018 AND MONTH(order_date) = 3
Explanation:
The first line of the SQL statement is a SELECT statement which selects order_id, order_date and ship_date columns from Orders table.
The DATEADD() is used to add date and here it is used to add 5 days to order_date column and the resultant column is named as approx_ship_date using ALIAS.
DATEDIFF() function is used to return the difference between two dates and here it shows number of days between order_date and ship_date columns.
WHERE clause is used to retrieve orders from March 2018. YEAR function represents the year of order_date which is set as 2018 to retrieve the orders for 2018. MONTH function represents the month of order_date which is set to 3 which means March in order to retrieve the orders for March.
Final answer:
To retrieve order details with calculated shipping dates and filter for March 2018 orders from an Orders table, use an SQL SELECT statement with DATE_ADD for approx_ship_date, DATEDIFF for days_to_ship, and a WHERE clause for the date range.
Explanation:
The question involves writing an SQL SELECT statement to retrieve specific columns from an Orders table, including calculated columns for approx_ship_date and days_to_ship, and filtering the results for orders made in March 2018. Here's how you can do it:
SELECT
order_id,
order_date,
DATE_ADD(order_date, INTERVAL 5 DAY) AS approx_ship_date,
ship_date,
DATEDIFF(ship_date, order_date) AS days_to_ship
FROM
Orders
WHERE
order_date BETWEEN '2018-03-01' AND '2018-03-31';
This SELECT statement fetches the order_id, order_date, and ship_date directly from the Orders table. It also calculates approx_ship_date by adding 5 days to the order_date and calculates days_to_ship as the difference between ship_date and order_date. The WHERE clause filters records to include only those with order_dates in March 2018.
Task 1 – File Input
The first piece of information we need is a text file’s name and location. Ask the user through the console what the file’s name and location are. After that, please ensure that the file does exist and at the given location. If the file does not exist or cannot be read, please return a message to the user stating that and ask them to enter another name and location.
Finally, if the file can be read then simply copy/read every line from the file. The contents of this file will be used in the next task.
Task 2 – File Output
Ask the user, through the console, what the name of the copy of the previous file should be called and where it should be saved. Check to see if a file with the same name already exists at the location given and if one does ask the user if they want to overwrite the file that already exists or if they would like to change the name and location of the new file. If they wish to change the name and location, go through the process of getting their input again through the console and checking if the newly given name and location are taken already too.
If they want to overwrite or no file already exists in the given location with the given name, then place the copied contents of the file that was read in the first task into this new file.
After successfully copying the contents of the first file into the second file, print to the console the name and location of both of those files.
A sample text file named "textfile.txt" has been supplied in case you need a file to test the above code on. The contents of that file is the declaration of independence.
Answer:
Check the explanation
Explanation:
using System;
using System.IO;
public class Program
{
public static void Main()
{
string[] lines;
Console.WriteLine("enter name of the file");
String fileName=Console.ReadLine();
Console.WriteLine("enter path of the file");
String filePath=Console.ReadLine();
using (StreamReader streamReader = File.OpenText(filePath))
{
String text = streamReader.ReadToEnd();
lines = File.ReadAllLines(filePath);
}
Console.WriteLine("Enter path of the file to write");
String outputFilePath = Console.ReadLine();
bool fileExist = File.Exists(outputFilePath);
if (fileExist)
{
overWriteOrChangeFileName(outputFilePath);
}
else
{
File.Create(outputFilePath);
File.WriteAllLines(outputFilePath, lines);
}
Console.Write("Input file Path"+filePath);
Console.Write("output file path"+outputFilePath);
void overWriteOrChangeFileName(String filePathtoCheck){
Console.WriteLine("File exists. Do you want to overwrite the file or do you want to change the location and file name of the new file.Press Y to overwrite and press C to change the location and filename");
String userInput=Console.ReadLine();
if(userInput.Equals("Y")){
File.WriteAllLines(outputFilePath, lines);
}else{
Console.WriteLine("enter new path of the file including filename");
String NewFileName=Console.ReadLine();
outputFilePath=NewFileName;
if(File.Exists(outputFilePath)){
overWriteOrChangeFileName(outputFilePath);
}
else
{
File.Create(outputFilePath);
File.WriteAllLines(outputFilePath, lines);
}
}
}
}
}
Use the single-server drive-up bank teller operation referred to in Problems 1 and 2 to determine the following operating characteristics for the system: a.) The probability that no customers are in the system. b.) The average number of customers waiting. c.) The average number of customers in the system. d.) The average time a customer spends waiting. e.) The average time a customer spends in the system. f.) The probability that arriving customers will have to wait for service.
Answer:
This question is incomplete, here's the complete question:
1. Willow Brook National Bank operates a drive-up teller window that allows customers to complete bank transactions without getting out of their cars. On weekday mornings, arrivals to the drive-up teller window occur at random, with an arrival rate of 24 customers per hour or 0.4 customers per minute. 3. Use the single-server drive-up bank teller operation referred to in Problems 1 to determine the following operating characteristics for the system: a.) The probability that no customers are in the system. b.) The average number of customers waiting. c.) The average number of customers in the system. d.) The average time a customer spends waiting. e.) The average time a customer spends in the system. f.) The probability that arriving customers will have to wait for service.
Explanation:
Arrival rate \lambda = 24 customers per hour or 0.4 customers per minute
Service rate \mu = 36 customers per hour or 0.6 customers per minute (from problem 1)
a.) The probability that no customers are in the system , P0 = 1 - \lambda / \mu
= 1 - (24/36) = 1/3 = 0.3333
b.) The average number of customers waiting
Lq = \lambda^2 / [\mu(\mu - \lambda)] = 242 / [36 * (36 - 24)] = 1.33
c.) The average number of customers in the system.
L = Lq + \lambda / \mu = 1.33 + (24/36) = 2
d.) The average time a customer spends waiting.
Wq = \lambda / [\mu(\mu - \lambda)] = 24 / [36 * (36 - 24)] = 0.0555 hr = 3.33 min
e.) The average time a customer spends in the system
W = Wq + 1/\mu = 0.0555 + (1/36) = 0.0833 hr = 5 min
f.) The probability that arriving customers will have to wait for service.
= 1 - P0 = 1 - 0.3333 = 0.6667
Develop a Python module that will prompt the user for a target sum that is greater than 0 and less than 1 for the following Geometric series: Geometric Series Equation The program should first make sure the target sum is within the range specified above. If not, continue to prompt the user for a target sum until it is in the specified range. The program should then compute the Geometric Series until it is greater than or equal to the target sum. The program should output the final sum as well as the number of terms required in the sequence to reach that final sum.
Answer:
see explaination
Explanation:
target_sum=float(input("Enter a target sum > 0 and <1 : ")) #asking user to enter the sum
while (target_sum<0 or target_sum>1): #if target sum not in range print the message
print("The target sum is not between 0 and 1")
target_sum=float(input("Please Enter a target sum > 0 and <1 : "))
computed_sum=0.00 #declare computed_sum
term_count=0 #declare term count and initalize to 0
r=1 #variable used to create the difference value
while computed_sum<target_sum: #iterate loop till computed sum is less than target sum
computed_sum=computed_sum+(1/(2**r)) #add previous computed sum with current term (1/2,1/4,1/8 etc)
term_count+=1 #increment term count
r+=1 #increment r value
print("Final Sum = " ,computed_sum) #finally print term count and final sum
print("Number of Terms= " ,term_count)
You created several workbooks (Accounting, Finance, Management, and Marketing) in the same folder as the main workbook SchoolOfBusiness. What formula correctly links to cell D20 in the Fall 2018 worksheet within the Finance workbook?
Answer:
='[Finance.xlsx]Fall2018'!$D$20
Explanation:
The formula that will correctly links to cell D20 in the Fall 2018 worksheet within the Finance workbook is given as:
='[Finance.xlsx]Fall2018'!$D$20
This will perform the operation and produce the required output.
Write a program that calculates payments for loan system. Implement for both client and Server. - The client sends loan information to the server o annual interest rate o number of years o loan amount - The server computes monthly payment and total payment. - When the user presses the ‘Submit’ key, the server sends them back to the client. - Must use JavaFX - For computation follow the formulas below o monthlyInterestRate = annualInterestRate / 1200; o monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)); o totalPayment = monthlyPayment * numberOfYears * 12;
Answer:
Check the explanation
Explanation:
//Define the class.
public class Loan implements java.io.Serializable {
//Define the variables.
private static final long serialVersionUID = 1L;
private double annualInterestRate;
private int numberOfYears;
private double loanAmount;
private java.util.Date loanDate;
//Define the default constructor.
public Loan() {
this(2.5, 1, 1000);
}
//Define the multi argument constructor.
protected Loan(double annualInterestRate, int numberOfYears,
double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
//Define the getter and setter method.
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public int getNumberOfYears() {
return numberOfYears;
}
public void setNumberOfYears(int numberOfYears) {
this.numberOfYears = numberOfYears;
}
public double getLoanAmount() {
return loanAmount;
}
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
//Define the method to compute the monthly payment.
public double getMonthlyPayment() {
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1 -
(Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12)));
return monthlyPayment;
}
//Define the method to get the total payment.
public double getTotalPayment() {
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
public java.util.Date getLoanDate() {
return loanDate;
}
}
//Define the client class.
public class ClientLoan extends Application {
//Create the server object.
ServerLoan serverLoan;
//Declare the variables.
int y;
double r, a, mp=0, tp=0;
String result,d1;
//Create the button.
Button b = new Button("Submit");
//Define the method stage.
public void start(Stage primaryStage) throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
TimeZone.getDefault();
d1 = "Server Started at " +new Date();
//Create the GUI.
Label l1=new Label("Annual Interest Rate");
Label l2 = new Label("Number Of Years:");
Label l3 = new Label("Loan Amount");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
TextArea ta = new TextArea();
//Add the components in the gridpane.
GridPane root = new GridPane();
root.addRow(0, l1, t1);
root.addRow(1, l2, t2, b);
root.addRow(5,l3, t3);
root.addRow(6, ta);
//Add gridpane and text area to vbox.
VBox vb = new VBox(root, ta);
//Add vbox to the scene.
Scene scene=new Scene(vb,400,250);
//Add button click event.
b.setOnAction(value -> {
//Get the user input from the text field.
r = Double.parseDouble(t1.getText());
y = Integer.parseInt(t2.getText());
a = Double.parseDouble(t3.getText());
//Create the loan class object.
Loan obj = new Loan(r, y, a);
//Call the method to compute the results.
mp = obj.getMonthlyPayment();
tp = obj.getTotalPayment();
//Format the results.
result = "Annual Interest Rate: "+ r+"\n"+
"Number of Years: "+y+"\n"+
"Loan Amount: "+a+"\n"+
"monthlyPayment: "+mp+"\n"+
"totalPayment: "+tp;
//Add the result to the textarea.
ta.setText(result);
//Create an object of the server class.
serverLoan = new ServerLoan(this);
});
//Set the scene to the stage.
//Set the stage title.
//Make the scene visible.
primaryStage.setScene(scene);
primaryStage.setTitle("ClientLoan");
primaryStage.show();
}
//Define the main method lauch the application.
public static void main(String args[])
{
launch(args);
}
//Define the server class.
class ServerLoan extends Stage {
//Create the client loan object.
ClientLoan parent;
//Create the stage object.
Stage subStage;
//Create the text area.
TextArea ta = new TextArea();
//Define the constructor.
private ServerLoan(ClientLoan aThis) {
//Get the time in desired timezone.
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
TimeZone.getDefault();
//Format the date with message.
String d2 = "Connected to client at " +new Date();
//Initialize the object.
parent = aThis;
//Add the date and the result to
//the text area.
ta.setText(d1);
ta.appendText("\n"+ d2);
ta.appendText("\n"+result);
//Create the grouppane.
GridPane root = new GridPane();
//Add text area to the group pane.
root.addRow(0, ta);
//Initialise the stage object.
subStage = new Stage();
//Add gridpane to the scene.
Scene scene = new Scene(root, 400, 200);
//Set the scene to the stage.
//Set the stage title.
//Make the scene visible.
subStage.setScene(scene);
subStage.setTitle("ServerLoan");
subStage.show();
}
}
}
Kindly check the Output in the attached image below.
Answer:
see explaination
Explanation:
Program code below:
oan.java:
//Define the class.
public class Loan implements java.io.Serializable {
//Define the variables.
private static final long serialVersionUID = 1L;
private double annualInterestRate;
private int numberOfYears;
private double loanAmount;
private java.util.Date loanDate;
//Define the default constructor.
public Loan() {
this(2.5, 1, 1000);
}
//Define the multi argument constructor.
protected Loan(double annualInterestRate, int numberOfYears,
double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
//Define the getter and setter method.
public double getAnnualInterestRate() {
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public int getNumberOfYears() {
return numberOfYears;
}
public void setNumberOfYears(int numberOfYears) {
this.numberOfYears = numberOfYears;
}
public double getLoanAmount() {
return loanAmount;
}
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
//Define the method to compute the monthly payment.
public double getMonthlyPayment() {
double monthlyInterestRate = annualInterestRate / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1 -
(Math.pow(1 / (1 + monthlyInterestRate), numberOfYears * 12)));
return monthlyPayment;
}
//Define the method to get the total payment.
public double getTotalPayment() {
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
public java.util.Date getLoanDate() {
return loanDate;
}
}
ClientLoan.java:
package application;
//Import the required packages.
import java.util.Date;
import java.util.TimeZone;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
//Define the client class.
public class ClientLoan extends Application {
//Create the server object.
ServerLoan serverLoan;
//Declare the variables.
int y;
double r, a, mp=0, tp=0;
String result,d1;
//Create the button.
Button b = new Button("Submit");
//Define the method stage.
public void start(Stage primaryStage) throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
TimeZone.getDefault();
d1 = "Server Started at " +new Date();
//Create the GUI.
Label l1=new Label("Annual Interest Rate");
Label l2 = new Label("Number Of Years:");
Label l3 = new Label("Loan Amount");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
TextArea ta = new TextArea();
//Add the components in the gridpane.
GridPane root = new GridPane();
root.addRow(0, l1, t1);
root.addRow(1, l2, t2, b);
root.addRow(5,l3, t3);
root.addRow(6, ta);
//Add gridpane and text area to vbox.
VBox vb = new VBox(root, ta);
//Add vbox to the scene.
Scene scene=new Scene(vb,400,250);
//Add button click event.
b.setOnAction(value -> {
//Get the user input from the text field.
r = Double.parseDouble(t1.getText());
y = Integer.parseInt(t2.getText());
a = Double.parseDouble(t3.getText());
//Create the loan class object.
Loan obj = new Loan(r, y, a);
//Call the method to compute the results.
mp = obj.getMonthlyPayment();
tp = obj.getTotalPayment();
//Format the results.
result = "Annual Interest Rate: "+ r+"\n"+
"Number of Years: "+y+"\n"+
"Loan Amount: "+a+"\n"+
"monthlyPayment: "+mp+"\n"+
"totalPayment: "+tp;
//Add the result to the textarea.
ta.setText(result);
//Create an object of the server class.
serverLoan = new ServerLoan(this);
});
//Set the scene to the stage.
//Set the stage title.
//Make the scene visible.
primaryStage.setScene(scene);
primaryStage.setTitle("ClientLoan");
primaryStage.show();
}
//Define the main method lauch the application.
public static void main(String args[])
{
launch(args);
}
//Define the server class.
class ServerLoan extends Stage {
//Create the client loan object.
ClientLoan parent;
//Create the stage object.
Stage subStage;
//Create the text area.
TextArea ta = new TextArea();
//Define the constructor.
private ServerLoan(ClientLoan aThis) {
//Get the time in desired timezone.
TimeZone.setDefault(TimeZone.getTimeZone("EST"));
TimeZone.getDefault();
//Format the date with message.
String d2 = "Connected to client at " +new Date();
//Initialize the object.
parent = aThis;
//Add the date and the result to
//the text area.
ta.setText(d1);
ta.appendText("\n"+ d2);
ta.appendText("\n"+result);
//Create the grouppane.
GridPane root = new GridPane();
//Add text area to the group pane.
root.addRow(0, ta);
//Initialise the stage object.
subStage = new Stage();
//Add gridpane to the scene.
Scene scene = new Scene(root, 400, 200);
//Set the scene to the stage.
//Set the stage title.
//Make the scene visible.
subStage.setScene(scene);
subStage.setTitle("ServerLoan");
subStage.show();
}
}
}
how your requirements as high-level flowcharts (15 points) Create UML document to represent your idea. you can also include word file or pdf to explain what you are trying to do in simple words. (15 points) Inheritance (20 points) 2 level hierarchy using subclass, superclass concepts like, person, employee, manager Interface (10 points) At least one interface that can be extended later like Polymorphism (20 points) Method overloading Method overriding Constructor overloading Constructor overriding Object oriented programming concepts (30 points) Proper testing methods Use of Static methods Use of Array/ArrayList Use of Loops Data Validations Try/Catch Block for exception handling
Answer:
We will use hierarchical concepts,superclass and manager interference and use of object oriented programing in python and java and we need to create and call functions as well to solve that problem.
Create a function, str_replace, that takes 2 arguments: int list and index in list is a list of single digit integers index is the index that will be checked - such as with int_list[index] Function replicates purpose of task "replace items in a list" above and replaces an integer with a string "small" or "large" return int_list
Answer:
def str_replace(int_list, index):
if int_list[index] < 7:
int_list[index] = "small"
elif int_list[index] > 7:
int_list[index] = "large"
return int_list
Explanation:
I believe you forgot to mention the comparison value. I checked if the integer at the given index is smaller/greater than 7. If that is not your number to check, you may just change the value.
Create a function called def str_replace that takes two parameters, an integer list and an index
Check if the number in given index is smaller than 7. If it is replace the number with "small".
Check if the number in given index is greater than 7. If it is replace the number with "large".
Return the list
The str_replace function replaces an integer in a list with 'small' or 'large' depending on the value. It demonstrates basic list manipulation and conditional logic in programming.
The str_replace function is designed to take a list of integers and an index. The function will check the value at the given index, and if the integer is less than 5, it will be replaced with the string "small"; if the integer is 5 or greater, it will be replaced with the string "large". This is a basic operation in programming, often related to the concept of list manipulation and conditional statements. Here's a step-by-step example in Python:
def str_replace(int_list, index):Write a program that lets the user enter in a file name (numbers.txt) to read, keeps a running total of how many numbers are in the file, calculates and prints the average of all the numbers in the file. This must use a while loop that ends when end of file is reached. This program should include FileNotFoundError and ValueError exception handling. Sample output: Enter file name: numbers.txt There were 20 numbers in the file. The average is 4.35
Answer:
Check the explanation
Explanation:
The code will be
name=input('Enter file name:')
ls=open(name,'r').read().split('\n')
count=0;sums=0
for i in range(ls):
sums+=int(i)
count+=1
print('There were {} numbers in the file'.format(count))
print('The average is {}'.format(sums/count))
The output is
Assume the variable date has been set to a string value of the form mm/dd/yyyy, for example 09/08/2010. (Actual numbers would appear in the string.) Write a statement to assign to a variable named dayStr the characters in date that contain the day. Then set a variable day to the integer value corresponding to the two digits in dayStr.
Answer:
String date = "21/05/2020";
String dayStr = date.substring(0,2);
int day = Integer.parseInt(dayStr);
System.out.println(day);
Explanation:
Create a variable called date which holds the current date
Create a variable called dayStr. Initialize it to the day part of the date using the substring method
Create a variable called day. Parse the dayStr and assign it to the day
Print the day
Consider a disk queue with requests for I/O to blocks on cylinders.
98 183 37 122 14 124 65 67
Considering SSTF (shortest seek time first) scheduling, the total number of head movements is, if the disk head is initially at 53 is?
A. 224
B. 236
C. 240
D. 200
Create an unambiguous grammar which generates basic mathematical expressions (using numbers and the four operators +, -, *, /). Without parentheses, parsing and mathematically evaluating expressions created by this string should give the result you'd get while following the order of operations. For now, you may abstract "number" as a single terminal, n. In the order of operations, * and / should be given precedence over + and -. Aside from that, evaluation should occur from left to right. So 8/4*2 would result in 4, not 1.
Answer:
Explanation:
Let G denote an unambiguous Grammar capable of producing simple mathematical expressions, involving operators +,-,*,/. These operators are left associative (which ensures left to right evaluation). S is the start symbol of the Grammar i.e. the production starts from S. n denotes a number and is a terminal i.e. we can't produce anything further from n. Then, the solution is as follows :
S → S + T |S - T | S
T→T | F | T*F|F
F → n
Here, S, T and F are variables. Note that /,* have been given precedence over +,-.
An unambiguous grammar for basic mathematical expressions without parentheses can be created using operator precedence. It defines a set of production rules that ensure expressions are evaluated following the order of operations.
An unambiguous grammar for basic mathematical expressions without parentheses can be created using the concept of operator precedence. We can define a grammar where the multiplication and division operators have higher precedence than the addition and subtraction operators. This way, expressions will be evaluated following the order of operations.
For example, the grammar could be defined as follows:
expression -> term expression'expression' -> + term expression' | - term expression' | epsilonterm -> factor term'term' -> * factor term' | / factor term' | epsilonfactor -> nThis grammar allows for the creation of unambiguous mathematical expressions using the basic operators +, -, *, and /, without the need for parentheses. The evaluation of these expressions will follow the order of operations, with * and / taking precedence over + and -.
Now it's your turn. Implement a class for representing segments. We want to be able to create an interval with: s = Interval(2, 3) Once we have an interval, we want to be able to ask for its length, and for the position of its center:
s.length
s.center Given two intervals, we also want to implement a method intersect that tells us if they intersect or not. There are many ways of doing this; perhaps the simplest is to rely on the properties length and center developed above. Each of these methods can be implemented in one line of code, except for the initializer, which takes two.
class Interval(object):
def __init_(self, a, b):
self.a = a property def length(self):
**Returns the length of the interval."**
return self.a
def center(self):
"*"Returns the center of the interval."**
return self.b det intersects(self, other):
***Returns True/False depending on whether the interval intersects with interval other."**
if a / b = 2
return true
else
return false
Answer:
Kindly note that, you're to replace "at" with shift 2 as the brainly text editor can't take the symbol
Explanation:
Copiable code:
# Define the class Interval.
class Interval(object):
# Define the initializer.
def __init__(self, a, b):
# Set the minimum value as a and the maximum
# value as b.
self.a = min(a, b)
self.b = max(a, b)
# Define the function to return the length
# of the interval.
"at"property
def length(self):
return (self.b - self.a)
# Define the function to return the center of
# the interval.
"at"property
def center(self):
# Divide the first and the last value by
# 2 to compute the center.
return (self.a + self.b)/2
# Define the function to check if the two intervals
# intersect or not.
def intersects(self, other):
# Compute the absolute difference between the
# centers of the two intervals and compare it with
# the sum of the half lengths of the intervals
# to check if they intersect or not.
return abs(self.center - other.center) <= (self.length/2 + other.length/2)
The complete program to test the above class is as follows:
Note: No output is generated by the code since all the test cases have been passed successfully.
Code to copy:
# Import the required packages to test the class.
from nose.tools import assert_equal, assert_false, assert_true
# Define the class Interval.
class Interval(object):
# Define the initializer.
def __init__(self, a, b):
# Set the minimum value as a and the maximum
# value as b.
self.a = min(a, b)
self.b = max(a, b)
# Define the function to return the length
# of the interval.
"at"property
def length(self):
return (self.b - self.a)
# Define the function to return the center of
# the interval.
"at"property
def center(self):
# Divide the first and the last value by
# 2 to compute the center.
return (self.a + self.b)/2
# Define the function to check if the two intervals
# intersect or not.
def intersects(self, other):
# Compute the absolute difference between the
# centers of the two intervals and compare it with
# the sum of the half lengths of the intervals
# to check if they intersect or not.
return abs(self.center - other.center) <= (self.length/2 + other.length/2)
# Create different intervals to check the working
# of the above class using assert test cases.
i = Interval(3, 5)
assert_equal(i.length, 2)
i = Interval(3, 5)
assert_equal(i.center, 4)
i = Interval(2, 5)
j = Interval(6, 7)
assert_false(i.intersects(j))
assert_false(j.intersects(i))
k = Interval(4, 6)
assert_true(i.intersects(k))
assert_true(k.intersects(i))
m = Interval(0, 8)
assert_true(i.intersects(m))
assert_true(m.intersects(i))
Employee Payroll Summary: PYTHON 3 CODE WITHOUT USING ARRAY AND CORRECT INDENTATION WITH ALL VARIABLES DECLARED WINDOWS
For this assignment, you will write a program that reads employee work data from a text file, and then calculates payroll information based on this file. The text file contains one line of text for each employee. Each line consists of the following data (delimited by tabs):
employee’s name
employee’s hourly wage rate
hours worked Monday
hours worked Tuesday
hours worked Wednesday
hours worked Thursday
hours worked Friday
Answer:
Check the explanation
Explanation:
If raw_input() shows some error in Python v3 then call input() instead of raw_input().
def menu():
option = 'n'
while option not in ['r','p','d','h','l','q']:
print("Menu of choices:")
print("\t(r)ead employee data")
print("\t(p)rint employee payroll")
print("\t(d)isplay an employee by name")
print("\tfind (h)ighest paid employee")
print("\tfind (l)owest paid employee")
print("\t(q)uit")
option = input("Please enter your choice: ")
if option not in ['r','p','d','h','q']:
print("Invalid choice. Please try again\n")
return option
def readEmployees(names,wages,hours):
fileRead = 0
try:
filename = input("Enter the file name: ")
f = open(filename,"r")
for line in f:
values = line.split("\t")
names.append(values[0])
wages.append(float(values[1]))
i=0
total = 0
while i < 5:
total = total + float(values[2+i])
i = i+1
hours.append(total)
fileRead = 1
f.close()
except ValueError:
print("Bad data in file " + filename)
except IOError:
print("Error reading file " + filename)
return fileRead
def printPayroll(names,wages,hours):
print("")
print("Name"+" "+"Hours"+" "+"Pay")
print("----"+" "+"-----"+" "+"---")
i = 0
sortedNames = names
sortedNames.sort()
totalpay = 0
for name in sortedNames:
i = names.index(name)
pay = hours[i] * wages[i]
name = names[i]
totalpay = totalpay + pay
name = repr(name).ljust(10)
name = name.replace("'","")
print( name + repr(hours[i]).ljust(9) + repr(pay).ljust(6))
i = i + 1
print("\nTotal payroll = $" + str(totalpay))
def displayName(names,wages,hours):
name = ""
i=0
size = len(names)
name = input("Enter the employee's name: ")
while i < size:
if names[i].lower() == name.lower():
wage = wages[i]
hour = hours[i]
break
i = i +1
if i == size:
print("Employee not found")
else:
print(name + " worked " + str(hour) + " hours at $" + str(wage) + " per hour, and earned $" + str(wage * hour) + "\n")
def showHighLow(names,wages,hours, ind):
highestIndex = 0
if ind == 'h':
i =1
size = len(names)
wage = 0;
while i < size:
wage = hours[i] * wages[i]
if wage > (hours[highestIndex] * wages[highestIndex]):
highestIndex = i
i = i + 1
print(names[highestIndex] + " earned $" + str(hours[highestIndex] * wages[highestIndex]) + "\n")
elif ind == 'l':
lowestIndex = 0;
i =1
size = len(names)
wage = 0;
while i < size:
wage = hours[i] * wages[i]
if wage < (hours[lowestIndex] * wages[lowestIndex]):
lowestIndex = i
i = i + 1
print(names[lowestIndex] + " earned $" + str(hours[lowestIndex] * wages[lowestIndex]) + "\n")
def main():
option = 'n'
names = list()
wages = list()
hours = list()
fileRead = 0
while option != 'q':
option = menu()
if option == 'r':
fileRead = readEmployees(names,wages,hours)
elif option == 'p':
if fileRead == 0:
print("Employee data has not been read.")
print("Please read the file before making this choice")
else:
printPayroll(names,wages,hours)
elif option == 'd':
if fileRead == 0:
print("Employee data has not been read.")
print("Please read the file before making this choice")
else:
displayName(names,wages,hours)
elif option == 'h':
if fileRead == 0:
print("Employee data has not been read.")
print("Please read the file before making this choice")
else:
showHighLow(names,wages,hours,'h')
elif option == 'l':
if fileRead == 0:
print("Employee data has not been read.")
print("Please read the file before making this choice")
else:
showHighLow(names,wages,hours,'l')
elif option == 'q':
print("GoodBye")
if __name__ == "__main__":
main()
Kindly check the OUTPUT in the attached image below.
According to the best practices most widely adopted to protect users and organizations, _______________ employs an approach that sets up overlapping layers of security as the preferred means of mitigating threats. patch management unique identity layered defense / defense-in-depth encryption
Answer:
layered defense / defense-in-depth
Explanation:
Layered defence is majorly used to describe a security system that is build using multiple tools and policies to safeguard multiple areas of the network against multiple threats including worms, theft, unauthorized access, insider attacks and other security considerations.
A layered defense at the same time is meant to provide adequate security at the following levels: system level security, network level security, application level security, and transmission level security.
Also called a multi-layered defense.