Implement the simulation of a biased 6-sided die which takes the values 1,2,3,4,5,6 with probabilities 1/8,1/12,1/8,1/12,1/12,1/2. In [ ]: # WRITE YOUR OWN CODE HERE! FEEL FREE TO INSERT MORE CELLS! # ADD SOME COMMENTS TO YOUR CODE! ​ Plot a histrogramm with 1,000,000 simulations to check if the relative counts of each number is approximately equal to the corresponding specified probabilities. Remark: Specify the bins of your histogram correctly.

Answers

Answer 1

Answer:

see explaination

Explanation:

import numpy as np

import matplotlib.pyplot as plt

a = [1, 2, 3, 4, 5, 6]

prob = [1.0/8.0, 1.0/12.0, 1.0/8.0, 1.0/12.0, 1.0/12.0, 1.0/2.0]

smls = 1000000

rolls = list(np.random.choice(a, smls, p=prob))

counts = [rolls.count(i) for i in a]

prob_exper = [float(counts[i])/1000000.0 for i in range(6)]

print("\nProbabilities from experiment : \n\n", prob_exper, end = "\n\n")

plt.hist(rolls)

plt.title("Histogram with counts")

plt.show()

check attachment output and histogram

Implement The Simulation Of A Biased 6-sided Die Which Takes The Values 1,2,3,4,5,6 With Probabilities
Implement The Simulation Of A Biased 6-sided Die Which Takes The Values 1,2,3,4,5,6 With Probabilities
Answer 2
Final answer:

To simulate a biased 6-sided die with specified probabilities, use the random.choices() function from the Python random module. Run the simulation for a large number of times and create a histogram to plot the relative counts of each number.

Explanation:

To simulate a biased 6-sided die with specified probabilities, you can use the random.choices() function from the Python random module. You will need to provide the possible values and their corresponding probabilities as inputs to this function. Then, you can run the simulation for a large number of times, such as 1,000,000, and store the results in a list. Finally, you can create a histogram using the matplotlib.pyplot library to plot the relative counts of each number.

import random

import matplotlib.pyplot as plt

# Define the probabilities of each side of the die

probs = {

   1: 0.1764,

   2: 0.1764,

   3: 0.1764,

   4: 0.1764,

   5: 0.1764,

   6: 0.0972

}

# Define the number of times to simulate the die

num_simulations = 1000000

# Create a histogram of the relative counts of each number

die_hist = []

for i in range(num_simulations):

   die_result = [random.choices(range(1, 7), k=1)[0] for _ in range(6)]

   relative_count = len(die_result) / 6

   die_hist.append(relative_count)

# Plot the histogram

plt.hist(die_hist, bins=20)

plt.xlabel('Number of times the die shows 1')

plt.ylabel('Relative count')

plt.show()

Learn more about Simulating biased die here:

https://brainly.com/question/34272295

#SPJ3


Related Questions

Write a MATLAB script in which you initialize the following vector:

ANIMALS = ["cow", "cat", "dog", "fox", "lion", "bear", "sea lion", "deer", "dolphin"];

a. In the script, use logical indexing to create a vector called C_ANIMALS that is comprised of the animals from the above ANIMALS vector starting with the letter c. This should be done with just one line of code. HINT: MATLAB provides a built-in function that checks whether a string starts with a specified letter. Feel free to research and use this built-in function.

b. In the script, use logical indexing to create a vector called LETTERS_3 that is comprised of the animals from the above ANIMALS vector that are three letters long. This should be done with just one line of code. HINT: MATLAB provides a built-in function that checks whether a string’s length is equal to a certain number. Feel free to research and use this built-in function.

c. In the script, use logical indexing to create a vector called D_GREATER_3 that is comprised of the animals from the above ANIMALS vector that are greater than three letters long and start with the letter d. This should be done with just one line of code.

d. Display all the vectors created in this script: ANIMALS, C_ANIMALS, LETTERS_3, and D_GREATER_3.

Answers

Answer:

ANIMALS = ["cow", "cat", "dog", "fox", "lion", "bear", "sea lion", "deer", "dolphin"];

C_ANIMALS = ANIMALS(startsWith(ANIMALS,"c"));

LETTERS_3 = ANIMALS(strlength(ANIMALS)==3);

D_GREATER_3 = ANIMALS(strlength(ANIMALS)>3 & startsWith(ANIMALS,"d"));

disp(ANIMALS)

disp(C_ANIMALS)

disp(LETTERS_3)

disp(D_GREATER_3

Jayden wants to take a current theme but just change a little bit of it. Complete the steps to help Jayden.

Answers

Answer:The theme can be automatically changed via the default settings

Explanation:

Answer:

Go to the ✔ Page Layout  tab on the ribbon and the ✔ Themes  group.  Click Themes and select one.  Go into the workbook, make the changes, and return to the Themes gallery.  Select ✔ Save Current Theme  to save the changes.

Explanation:

2. Now write a program named filereader.py that reads and displays the data in friends.txt. This program should also determine and print the average age of the friends on file. That will require an accumulator and a counter. Use a while loop to process the file, print the data, and modify the accumulator and counter. Then close the file and display the average age accurate to one decimal place. See the Sample Output.. SAMPLE OUTPUT My friend Denny is 24 My friend Penny is 28 My friend Lenny is 20 My friend Jenny is 24 Average age of friends is 24.0

Answers

Answer:

see explaination

Explanation:

# python code filereader.py

import sys

import readline

from sys import stdin

import random

## Open the file with read only permit

f = open('inputfile.txt')

## Read the first line

sum = 0.0

count = 0

#read file till the file is empty

while True:

line = f.readline()

if ("" == line):

print "Average age of friends is", sum/count

break

list = line.split()

print "My friend ",list[0], " is", list[1]

sum = sum + int(list[1])

count = count + 1

f.close()

'''

inputfile.txt

Denny 24

Penny 28

Lenny 20

Jenny 24

output:

My friend Denny is 24

My friend Penny is 28

My friend Lenny is 20

My friend Jenny is 24

Average age of friends is 24.0

see screenshot at attachment

Final answer:

To display data from a file and calculate the average age, write a Python program that opens 'friends.txt', uses a while loop to read lines, prints the content, adds up the ages, and then calculates and prints the average age to one decimal place.

Explanation:

To accomplish this task, you need to write a Python script named filereader.py that will open a file named friends.txt, read the content, and calculate the average age of friends listed in the file.

Additionally, the program should handle the file contents with a while loop and keep track of the total number of ages read (counter) and the sum of those ages (accumulator). After reading all ages and calculating their sum, the program will close the file and compute the average age to one decimal place.

import sys

try:
   f = open('friends.txt', 'r')
   age_sum = 0
   age_count = 0
   line = f.readline()
   while line:
       friend_info = line.split()
       print(f'My friend {friend_info[0]} is {friend_info[1]}')
       age_sum += int(friend_info[1])
       age_count += 1
       line = f.readline()
   f.close()
   average_age = age_sum / age_count
   print(f'Average age of friends is {average_age:.1f}')
except FileNotFoundError:
   sys.stderr.write('Error: friends.txt file does not exist.')
except Exception as e:
   sys.stderr.write('An error occurred: ' + str(e))
Make sure that the file friends.txt is in the same directory as your script, or provide the correct path to the file. The logic in the code reads each line of the file, splits the line into the friend's name and age, prints out the friend's details, and calculates the average age after reading through all the lines.

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.

Answers

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)

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

Answers

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):
   if int_list[index] < 5:
       int_list[index] = "small"
   else:
       int_list[index] = "large"
   return int_list
When the function is called with a list and an index, it evaluates the item at that index and performs the replacement as specified.

g Select an appropriate expression to complete the following method, which is designed to return the sum of the two smallest values in the parameter array numbers. public static int sumTwoLowestElements(int[] numbers) { PriorityQueue values = new PriorityQueue<>(); for (int num: numbers) { values.add(num); } ______________________ }

Answers

Answer:

import java.util.Comparator;

import java.util.PriorityQueue;

 

public class PriorityQueueTest {

 

static class PQsort implements Comparator<Integer> {

 

 public int compare(Integer one, Integer two) {

  return two - one;

 }

}

 

public static void main(String[] args) {

 int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };

 PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();

 

 // use offer() method to add elements to the PriorityQueue pq1

 for (int x : ia) {

  pq1.offer(x);

 }

 

 System.out.println("pq1: " + pq1);

 

 PQsort pqs = new PQsort();

 PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs);

 // In this particular case, we can simply use Collections.reverseOrder()

 // instead of self-defined comparator

 for (int x : ia) {

  pq2.offer(x);

 }

 

 System.out.println("pq2: " + pq2);

 

 // print size

 System.out.println("size: " + pq2.size());

 // return highest priority element in the queue without removing it

 System.out.println("peek: " + pq2.peek());

 // print size

 System.out.println("size: " + pq2.size());

 // return highest priority element and removes it from the queue

 System.out.println("poll: " + pq2.poll());

 // print size

 System.out.println("size: " + pq2.size());

 

 System.out.print("pq2: " + pq2);

 

}

}

The Daily Trumpet newspaper accepts classified advertisements in 15 categories such as Apartments for Rent and Pets for Sale. Develop the logic for a program that accepts classified advertising data, including a category code (an integer 1 through 15) and the number of words in an ad. Store these values in parallel arrays. Then sort the arrays so that the records are sorted in ascending order by category. The output lists each category number, the number of ads in the category, and the total number of words in the ads in the category. Using the following pseudocode. Thank you.

// Pseudocode PLD Chapter 8 #7a pg. 366

// Start

// Declarations

// num MAXADS = 100

// num adcatcode[MAXADS]

// num adwords[MAXADS]

// num curCode

// num numads

// num i

// num j

// num k

// num subtotal

// num temp

// output "Please enter the number of ads: "

// input numads

// if ((numads > 0) and (numads <= MAXADS))

// for i = 0 to numads - 1

// output "Please enter Advertisement Category Code (1 - 15): "

// input adcatcode[i]

// output "Please enter number of words for the advertisement: "

// input adwords[i]

// endfor

// for i = 0 to numads - 2

// for j = 0 to numads - 2

// if (adcatcode[j] > adcatcode[j+1])

// temp = adcatcode[j]

// adcatcode[j] = adcatcode[j+1]

// adcatcode[j+1] = temp

// temp = adwords[j]

// adwords[j] = adwords[j+1]

// adwords[j+1] = temp

// endif

// endfor

// endfor

// output "Total Word Counts Sorted By Category Code"

// output "========================================="

// k = 0

// while k <= numads - 1

// subtotal = 0

// curCode = adcatcode[k]

// while ( (curCode == adcatcode[k]) and (k <= numads - 1) )

// subtotal = subtotal + adwords[k]

// k = k + 1

// endwhile

// output "Category: ",adcatcode[k - 1], " ","Word Count: ", subtotal

// endwhile

// else

// output "Number adds requested less than 1 or is too large; ad limit is ", MAXADS

// endif

// Stop

Answers

Answer:

see explaination

Explanation:

#include<iostream>

using namespace std;

#define MAXDAS 100

int main()

{

//int MAXADS = 100;

int adcatcode[MAXDAS];

int adwords[MAXDAS];

int curCode;

int numads;

int i,j,k;

int subtotal;

int temp;

cout<<"Please enter the number of ads: ";

cin>>numads;

if((numads > 0) and (numads <= MAXDAS))

{

for (i = 0;i<numads;i++)

{

cout<<"Please enter Advertisement Category Code (1 - 15): ";

cin>>adcatcode[i];

cout<<"Please enter number of words for the advertisement: ";

cin>>adwords[i];

}

for (i=0;i<numads-1;i++)

{

for (j = 0;j<numads-1;j++)

{

if (adcatcode[j] > adcatcode[j+1])

{

temp = adcatcode[j];

adcatcode[j] = adcatcode[j+1];

adcatcode[j+1] = temp;

temp = adwords[j];

adwords[j] = adwords[j+1];

adwords[j+1] = temp;

}

}

}

cout<<"Total Word Counts Sorted By Category Code"<<endl;

cout<<"========================================="<<endl;

k = 0;

while(k<=numads-1)

{

subtotal = 0;

curCode = adcatcode[k];

while ( (curCode == adcatcode[k])&& (k <= numads - 1) )

{

subtotal = subtotal + adwords[k];

k = k + 1;

}

cout<<"Category: "<<adcatcode[k - 1]<<" "<<"Word Count: "<<subtotal<<endl;

}

}

else

{

cout<<"Number adds requested less than 1 or is too large; ad limit is :"<<MAXDAS;

}

return 0;

}

See attachment for output

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.

Answers

Answer:

See attached solution

Explanation:

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

Answers

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.

Write a Python function LetterGame() that repeatedly asks the user to input a letter. The function is to count the number of vowels the user entered. The function should stop if the user enters a digit (0-9). a) Use a while-loop and in the while loop ask the user to input a letter or to input a digit to stop. b) Check if the user entered a vowel (if command is your friend) c) If the user entered a vowel increase the counter by one d) If the user entered a digit, output the number of letters the user entered and the number and percentage of vowels among them. e) Call the function. Expected output: You entered 10 letters, 2 of which were vowels. The percentage of vowels was 20%.

Answers

Answer:

def LetterGame():

   vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]

   count1 = count2 = 0

   while True:

       choice = input("Enter a letter / digit to stop: ")

       if choice.isdigit():

           break

       elif choice.isalpha():

           count1 += 1

           if choice in vowels:

               count2 += 1

   print("You entered " + str(count1) + " letters, " + str(count2) + " of which weere vowels.")

   print("The percentage of vowels was " + str(count2 / count1 * 100) + "%")

LetterGame()

Explanation:

Create a function called LetterGame

Inside the function:

Create a list of vowels

Initialize count1, counts the total letters, and count2, counts the vowels

Initialize a while loop that iterates until the specified condition is met in the loop

Get the input from the user. If it is a digit, stop the loop. If it is an alphabet, increase the count1 by 1, and also check if it is a vowel. If it is a vowel, increment the count2 by 1

When the loop is done, print the required information

Finally, call the function

Keyshia adds an image of a triple beam balance and a
Bunsen burner to a slide in her presentation. Now she
wants to group these images so she can modify them
together.
Order the steps to outline how images are grouped in
PowerPoint
Step 1:
Step 2:
Step 3
Step 4

Answers

Answer:

Step 1:

✔ Select all images.

Step 2:

✔ Go to the Picture Tools Format tab.

Step 3:

✔ Choose the Arrange group.

Step 4:

✔ Choose the Group option.

Explanation:

The order of the steps to outline how images are grouped in PowerPoint are:

Step 1: Select all images.

Step 2: Go to the Picture Tools Format tab.

Step 3: Choose the Arrangement group.

Step 4: Choose the Group option.

What is PowerPoint?

A PowerPoint slideshow (PPT) is a presentation made using Microsoft software that enables users to include audio, visual, and audio/visual components. It is regarded as a multimedia technology that also serves as a tool for sharing and collaborating on content.

And so he set out to develop a presentation application that would offera simple way to produce and deliver slides, working with engineers Thomas Rudkin and Dennis Austin. They called it Presenter, but PowerPoint eventually replaced it.

Therefore, the steps are:

Step 1: Select all images.Step 2: Go to the Picture Tools Format tab.Step 3: Choose the Arrangement group.Step 4: Choose the Group option

To learn more about PowerPoint, refer to the link:

https://brainly.com/question/14498361

#SPJ2

Write a regular expression pattern that matches strings representing trains. A single letter stands for each kind of car in a train: Engine, Caboose, Boxcar, Passenger car, and Dining car. There are four rules specifying how to form trains. 1. One or more Engines appear at the front; one Caboose at the end. 2. Boxcars always come in pairs: BB, BBBB, etc. 3. There cannot be more than four Passenger cars in a series. 4. One dining car must follow each series of passenger cars. These cars cannot appear anywhere other than these locations. Here are some legal and illegal exemplars. EC Legal: the smallest train EEEPPDBBPDBBBBC Legal : simple train showing all the cars EEBB Illegal: no caboose (everything else OK) EBBBC Illegal: three boxcars in a row EEPPPPPDBBC Illegal: more than four passenger cars in a row EEPPBBC Illegal: no dining car after passenger cars EEBBDC Illegal: dining car after box car Hint: my RE pattern was 16 characters.

Answers

Answer:

See explaination

Explanation:

import re

def isValidTrain(train):

pattern = r'^E+(((P|PP|PPP|PPPP)D)*(BB)*)*C$'

if re.match(pattern, train):

return True

return False

def checkAndPrintTrain(train):

print("Train", train, "is valid:", isValidTrain(train))

checkAndPrintTrain("EC")

checkAndPrintTrain("EEEPPDBBPDBBBBC")

checkAndPrintTrain("EEBB")

checkAndPrintTrain("EBBBC")

checkAndPrintTrain("EEPPPPPPDBBC")

checkAndPrintTrain("EEPPBBC")

checkAndPrintTrain("EEBBDC")

Sample output

Train EC is valid: True

Train EEEPPDBBPDBBBBC is valid: True

Train EEBB is valid: False

Train EBBBC is valid: False

Train EEPPPPPPDBBC is valid: False

Train EEPPBBC is valid: False

Train EEBBDC is valid: False

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.

Answers

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.

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

Answers

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))

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.

Answers

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 -> n

This 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 -.

On computer X, a nonpipelined instruction execution would require 12 ns. A pipelined implementation uses 6 equal-length stages of 2 ns each. Assuming one million instructions execute and ignoring empty stages at the start/end, what is the speedup of the pipelined vs. non-pipelined implementation

Answers

Answer:

5.99997

Explanation:

We can refer to Pipelining as an implementation technique where multiple instructions are overlapped in execution. The computer pipeline is divided in stages. Each stage completes a part of an instruction in parallel.

It increases instruction throughput

see attachment for the step by step solution

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?

Answers

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 plays a reverse guessing game with the user. The user thinks of a number between 1 and 10, and the computer repeatedly tries to guess it by guessing random numbers. It’s fine for the computer to guess the same random number more than once. At the end of the game, the program reports how many guesses it made.

Answers

Answer:

import random   target = 7  count = 0 for i in range(100):    guess = random.randint(1,10)          if(guess == target):        count += 1 print("Total of correct guess: " + str(count))

Explanation:

The solution is written in Python 3.

Firstly, import the random module since we are going to simulate the random guess by computer. Next, we presume user set a target number 7 (Line 3). Create a counter variable to track the number of correct guess (Line 4).

Presume the computer will attempt one hundred times of guessing and we use randint to repeatedly generate a random integer between 1 - 10 as guess number (Line 6). If the guess number is equal to the target, increment count by one (Line 8-9).

Display the total number of right guess to terminal (Line 11).  

In a class named InputTextToOutputFile.java use the following prompt to get the fileName of the output file from the user: "What is the name of your output file?" Once the output file is opened, write everything the user types until the input contains "STOP!" Note: Include the line containing "STOP!" as the last thing written to the file. This work must be completed in your textbook ZYBooks -- CMP-326: Programming Methods II No other forms of submission will be accepted.

Answers

Answer:

Detailed program code is written at explaination

Explanation:

Program:

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;

public class InputTextToOutputFile

{

public static void main(String[] args) throws IOException

{

Scanner in=new Scanner(System.in);//Scanner object to get user input

System.out.println("What is the name of your output file? ");

String fileName = in.nextLine();//get output file name

File file = new File(fileName);//File object with fileName as input

//Create the file by method file.createNewFile()

if (file.createNewFile())

{

System.out.println("File is created!");

} else {

System.out.println("File already exists.");

}

//FileWriter object with user file name given as input

FileWriter writer = new FileWriter(file);

System.out.println("Enter text to write to a file : ");

String line;//variable to store line content

do {

line=in.nextLine();//get line content from user

writer.write(line+"\n"); //write content to file by adding new line(\n) character

}while(!line.equals("STOP!"));//repeat a loop until user enters "STOP!" line

writer.close();//close the file object

}

Final answer:

To solve this problem, use the Scanner class to get user input and the FileWriter and BufferedWriter classes to write to a file. Prompt the user for the output file name and write everything the user types to the file until they enter "STOP!"

Explanation:

In order to solve this problem in the class named InputTextToOutputFile.java, you can use the Scanner class to get user input. First, create a Scanner object to read user input from the console. Then, prompt the user with the message "What is the name of your output file?" and store their response in a variable called 'fileName'.

Next, you can use the FileWriter and BufferedWriter classes to create and write to a file. Open the output file using the 'fileName' variable, and create a FileWriter and BufferedWriter object to write to the file.

Now, you can use a while loop to continuously read user input and write it to the file until the input contains the string "STOP!". Inside the while loop, read the user input using the Scanner object, and use the BufferedWriter object to write the input to the file. Finally, outside of the while loop, write the string "STOP!" to the file and close the BufferedWriter object to ensure that all the data is written to the file.

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.

Answers

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.

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;

Answers

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();

}

}

}

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

Answers

Answer:

Explanation:

CHECK THE ANSWER IN THE ATTACHMENT CORNNER

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

Answers

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

Answers

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

You are trying to appreciate how important the principle of locality is in justifying the use of a cache memory, so you experiment with a computer having an L1 data cache and a main memory (you exclusively focus on data accesses). The latencies (in CPU cycles) of the different kinds of accesses are as follows: cache hit, 1 cycle; cache miss, 105 cycles; main memory access with cache disabled, 100 cycles.

a. [10] When you run a program with an overall miss rate of 5%, what will the average memory access time (in CPU cycles) be?
b. [10] Next, you run a program specifically designed to produce completely random data addresses with no locality. Toward that end, you use an array of size 256 MB (all of it fits in the main memory). Accesses to random elements of this array are continuously made (using a uniform random number generator to generate the elements indices). If your data cache size is 64 KB, what will the average memory access time be?
c. [10] If you compare the result obtained in part (b) with the main memory access time when the cache is disabled, what can you conclude about the role of the principle of locality in justifying the use of cache memory? d. [15] You observed that a cache hit produces a gain of 99 cycles (1 cycle vs. 100), but it produces a loss of 5 cycles in the case of a miss (105 cycles vs. 100). In the general case, we can express these two quantities as G (gain) and L (loss). Using these two quantities (G and L), identify the highest miss rate after which the cache use would be disadvantageous.

Answers

Answer:

Explanation:

Attached is the solution

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

Answers

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

You have been asked to design a high performing and highly redundant storage array with a minimum of 64 TB of usable space for files. 4 TB hard drives cost $200, 6 TB hard drives cost $250, 8 TB hard drives cost $300, and 10 TB hard drives cost $350. Explain which type of RAID you would choose and the quantity and types of drives you would use for your solution. Weigh the cost vs redundancy in your solution.

Answers

Answer:

Check the explanation

Explanation:

Number of 4 TB hard drive need = 32/4 = 8 and cost = 200*8 = $1600

Number of 6 TB hard drive need = max(32/6) = 6 and cost = 250*6 = $1500

Number of 8 TB hard drive need = 32/8 = 4 and cost = 300*4 = $1200

Number of 10 TB hard drive need = 32/10 = 4 and cost = 350*4 = $1400

Hence using 4 hard drive of 8 TB will minimize the cost.

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.

Answers

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.

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.

Answers

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

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.

Answers

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

Other Questions
Recall some of the recipes you read and write a recipe of your own using some of the vocabulary you learned.Your response should include at least some of the following terms:Para prepararEs necesarioNecesitashervirfreragregaraadir Please I need help on the last one the number seven on is across and it the desription is in the picture and I'll give you 41 points The A. J. Croft Company (AJC) currently has $200,000 market value (and book value) of perpetual debt outstanding carrying a coupon rate of 6%. Its earnings before interest and taxes (EBIT) are $100,000, and it is a zero growth company. AJC's current cost of equity is 8.8%, and its tax rate is 40%. The firm has 10,000 shares of common stock outstanding selling at a price per share of $60.00 The firm is considering moving to a capital structure that is comprised of 40% debt and 60% equity, based on market values. The new funds would be used to replace the old debt and to repurchase stock. It is estimated that the increase in risk resulting from the additional leverage would cause the required rate of return on debt to rise to 7%, while the required rate of return on equity would rise to 9.5%. If this plan were carried out, what would be AJC's new WACC and total value A regular convex polygon has 14 sides. What is the sum of the measures of the interior angles? How do the temperature compare? Fro The diameter of a circle is 9 centimeters. Find the area to the nearest tenth. The law of _____ is a principle proposed by American psychologist Edward Thorndike that states that behaviors are more likely to be repeated when followed by pleasurable outcomes, and less likely to be repeated when followed by unpleasant outcomes. Jay just graduated from college and he has decided to open a retirement account that pays 1.75% interest compounded monthly. If he has direct deposits of $100 per month taken out of his paycheck, how much will he have in the account after 42 years? Which statement is true about point F? a.F is the midpoint of AA' because bisects AA'. b.F is the midpoint of EG because AA' bisects EG. c.F is the midpoint of AA' because AA' bisects EG. d.F is the midpoint of EG because bisects AA'. Which is involved in the formation of sinkholes?O acidic rainwaterO miningrising sea levelO winds Two oligopolists have to decide on their pricing strategy. Each can choose either a high or a low price. If they both choose a high price, each will make $12 million, but if they both choose a low price, each will make only $8 million. If one sets a high price and the other a low one, the low-priced firm will make $16 million, but the high-priced firm will make only $4 million. In the absence of collusion, each will _________. Solve the following: -3x(x-8)+7x=12 An aqueous solution of Na2CrO4 at 25oC is slowly added to an aqueous solution containing 0.001 M Pb(NO3)2and 0.100 M Ba(NO3)2. Which solid will precipitate first? The Ksp of BaCrO4 is 1.17 1010, and Ksp of PbCrO4 is 2.80 1013. Maurilio est a la izquierda de la tienda y enfrente de la escuela. Dnde est Maurilio? (1 point)Select one:a. Est en la oficina de correos.b. Est en la escuela.c. Est en la tienda.d. Est en el campo. What is the food manufacturing process in plants called? A large rainwater collection tub is shaped like a cylinder. The diameter is 28 inches and the height is 40 inches. If the tub is 75% filled, what is the volume of water in the tub? Round to the nearest tenth. Germany Italy Japan TurkeyIn the decade following World War I, ALL of these countries:A)turned to fascist dictators to lead their countries.B)turned to imperialism to help their depressed economies.C)formed an alliance that would lead to a second world war.D)saw powerful nationalist movements sweep through their countries. Qu acciones son sancionadas en el Cdigo de Hammurabi? A man is admitted to the hospital suffering from an abnormally low body temperature, a loss of appetite, and extreme thirst. A brain scan shows a tumor located in the _____. a.corpus b.callosum c.hypothalamus d.cerebellum e.pons 10 POINTS Which organisms belong to the Kingdom Protista?Select the two correct answers.amoebasea anemonebeetleseaweed