Fill in the missing code for C++.
Code from part B is below to make copy-pasting easier:
*-------------------------------------------------------------------------*/
/* * $ g++ -lpthread -g buyTheCandy.cpp -o buyTheCandy */
//-- Standard inclusions: --//
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <pthread.h>
//-- Constants: --//
// PURPOSE: To the names of the children
const char* CHILD_NAME_ARRAY[] = {"Alice", "Bob", "Cathy", "David" };
// PURPOSE: To tell the number of children.
const int NUM_CHILDREN = sizeof(CHILD_NAME_ARRAY)/sizeof(const char*);
// PURPOSE: To tell the possible denominations of the Coin instances.
const int COIN_DENOMINATION_ARRAY[] = {1,5,10,25};
// PURPOSE: To tell the number of coins in each new Purse.
const int NUM_COINS_PER_NEW_PURSE = 4;
// PURPOSE: To tell the number of denominations.
const int NUM_DENOMINATIONS = sizeof(COIN_DENOMINATION_ARRAY)/sizeof(int);
// PURPOSE: To tell how much money needs to be collected to buy the candy.
const int CANDY_COST = 100;
//-- Classes: --//
// PURPOSE: To represent coins.
class Coin {
// I. Member vars:
// PURPOSE: To tell the denomination of '*this' Coin instance.
int denomination_;
// PURPOSE: To hold the address of the next Coin after '*this' one,
// or 'NULL' if there is no such Coin instance.
Coin* nextPtr_;
// II. Disallowed auto-generated methods:
// No default constructor:
Coin ();
// No copy constructor:
Coin (const Coin&);
// No copy assignment op:
Coin operator= (const Coin&);
protected :
// III. Protected methods:
public :
// IV. Constructor(s), assignment op(s), factory(s) and destructor:
// PURPOSE: To make a coin of denomination 'newDom'. No return value.
Coin (int newDom ) : denomination_(newDom), nextPtr_(NULL) { }
// PURPOSE: To release the resources of '*this'. No parameters.
// No return value.
~Coin () { }
// V. Accessors:
// PURPOSE: To return the denomination of '*this' Coin instance.
// No parameters.
int getDenomination () const { return(denomination_); }
// PURPOSE: To return the address of the next Coin after '*this' one,
// or 'NULL' if there is no such Coin instance. No parameters.
Coin* getNextPtr () const { return(nextPtr_); }
// VI. Mutators:
// PURPOSE: To note that the Coin instance with address 'coinPtr' comes
// after '*this' one. No return value.
void setNextPtr (Coin* coinPtr ) { nextPtr_ = coinPtr; }
// VII. Methods that do main and misc work of class:
// PURPOSE: Try creating and return the address of a random coin.
// No parameters.
static Coin* makeRandom () {
// I. Application validity check:
// II. Try creating and return a coin:
return(new Coin(COIN_DENOMINATION_ARRAY[rand() % NUM_DENOMINATIONS]));
} };
// PURPOSE: To implement a list of Coin instances.
class Purse {
// 0. Constants:
enum { NO_OWNER_INDEX = -1 };
// I. Member var:
// PURPOSE: To hold the index of the name of the owner of '*this' Purse
// instance, or 'NO_OWNER_INDEX' if '*this' has no owner. int index_;
// ADD YOUR VARIABLES HERE
// II. Disall.
files/Heap.h
#ifndef HEAP_H
#define HEAP_H
#include <vector>
#include <stdexcept> // std::out_of_range
#include <math.h> // pow()
using namespace std;
template<typename T>
class Heap
{
private:
vector<T> _items; // Main vector of elements for heap storage
/**
* Used to take unsorted data and heapify it
*/
void buildHeap()
{
for (int i = _items.size() / 2; i >= 0; i--)
{
percolateDown(i);
}
}
/*********************************************************************/
/********************* Microassignment zone *************************/
/**
* Percolates the item specified at by index down
* into its proper location within a heap.
* Used for dequeue operations and array to heap conversions
* MA TODO: Implement percolateDown!
*/
void percolateDown(int index)
{
}
/**
* Percolate up from a given index to fix heap property
* Used in inserting new nodes into the heap
* MA TODO: Implement percolateUp
*/
void percolateUp( int current_position )
{
}
/************************** Microassigment zone DONE *********************/
public:
/**
* Default empty constructor
*/
Heap()
{
}
/**
* Constructor with a vector of elements
*/
Heap(const vector<T> &unsorted)
{
for (int i = 0; i < unsorted.size(); i++)
{
_items.push_back(unsorted[i]);
}
buildHeap();
}
/**
* Adds a new item to the heap
*/
void insert(T item)
{
int current_position = size(); // Get index location
_items.push_back(item); // Add data to end
percolateUp( current_position ); // Adjust up, as needed
}
/**
* Returns the top-most item in our heap without
* actually removing the item from the heap
*/
T& getFirst()
{
if( size() > 0 )
return _items[0];
else
throw std::out_of_range("No elements in Heap.");
}
/**
* Removes minimum value from heap and returns it to the caller
*/
T deleteMin()
{
int last_index = size() - 1; // Calc last item index
int root_index = 0; // Root index (for readability)
T min_item = _items[root_index]; // Keep item to return
_items[root_index] = _items[last_index]; // Move last item to root
_items.erase(_items.end() - 1); // Erase last element entry
percolateDown(0); // Fix heap property
return min_item;
}
/**
* Returns true if heap is empty, else false
*/
bool isEmpty() const
{
return _items.size() == 0;
}
/**
* Returns current quantity of elements in heap (N)
*/
int size() const
{
return _items.size();
}
/**
* Return heap data in order from the _items vector
*/
string to_s() const
{
string ret = "";
for(int i = 0; i < _items.size(); i++)
{
ret += to_string(_items[i]) + " ";
}
return ret;
}
/**
...
InternetService.java
import java.text.DecimalFormat;
import java.util.Scanner;
public class InternetService
{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat(\"#.##\");
//initialize variable
char packageType;
int time;
double totalCharges;
double packA;
double packB;
double packC;
// create an object for Scanner class
Scanner input = new Scanner(System.in);
// prompt the user to enter the package purchased
System.out.print(\"\ Enter the package purchased: \");
packageType = input.next().charAt(0);
//prompt the user to enter the number of minutes used
System.out.print(\"Enter the number of minutes used: \");
time = input.nextInt();
//Calculate the bill amount of the particular month using the type of package and the number of
minutes.
//Then print results to the screen
switch(packageType)
{
case \'A\':
//Calling the Method for Package A charges
totalCharges=calPackA(time);
//Displaying the package A charges.
System.out.println(\"For Package A:\ The total charges for this month is $\" + totalCharges);
//Calling the Method for Package B charges
packB=calPackB(time);
//Calling the Method for Package C charges
packC=calPackC(time);
//If the package B is Less Than package A then display the difference amount
if(totalCharges>packB)
System.out.println(\"Amount of Money Package A customer would save, if he Purchased
Package B is:$\"+df.format(totalCharges-packB));
//If the package C is Less Than package A then display the difference amount
if(totalCharges>packC)
System.out.println(\"Amount of Money Package A customer would save, if he Purchased
Package C is:$\"+df.format(totalCharges-packC));
break;
case \'B\':
//Calling the Method for Package B charges
totalCharges=calPackB(time);
//Displaying the package B charges.
System.out.println(\"For Package B:\ The total charges for this month is $\"
+df.format(totalCharges));
//Calling the Method for Package C charges
packC=calPackC(time);
//If the package B is Less Than package A then display the difference amount
if(totalCharges>packC)
System.out.println(\"Amount of Money Package B customer would save, if he Purchased
Package C is:$\"+df.format(totalCharges-packC));
break;
case \'C\':
//Calling the Method for Package C charges
totalCharges=calPackC(time);
//Displaying the package C charges.
System.out.print(\"For Package C:\ The total charges for this month is $\" + totalCharges);
break;
default:
System.out.println(\"\ The package should be A or B or C.\");
}
}
/*This method will calculate the total Charges for Package C
* Params:Time
* Return:total charges of type double
*/
private static double calPackC(int time) {
double totalCharges = 69.99;
return totalCharges;
}
/*This method will calculate the total Charges for Package B
* Params:Time
* Return:total charges of type double
*/
private static double calPackB(int time) {
double totalCharges=0.0;
if(time <= 900)
totalCharges = 59.99;
else
totalCharges = 59.99 + (0.40 * (time - 900));
return totalCharges;
}
/*This method will c.
Given the following class in Java- public class ThreeTenDynArray-T- {.pdfNicholasflqStewartl
Given the following class in Java :
public class ThreeTenDynArray<T> {
//default initial capacity / minimum capacity
private static final int MIN_CAPACITY = 2;
//underlying array for storage -- you MUST use this for credit!
//Do NOT change the name or type
private T[] data;
private int size = 0;
private int capacity = 0;
// ADD MORE PRIVATE MEMBERS HERE IF NEEDED!
/**
*
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray() {
// Constructor
// Initial capacity of the storage should be MIN_CAPACITY
// Hint: Can't remember how to make an array of generic Ts? It's in the textbook...
data = (T[])(new Object[MIN_CAPACITY]);
size = 0;
capacity = MIN_CAPACITY;
}
/**
* @param initCapacity
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray(int initCapacity) {
// Constructor
// Initial capacity of the storage should be initCapacity.
// - Throw IllegalArgumentException if initCapacity is smaller than
// MIN_CAPACITY 2
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Capacity must be at least 2!"
if (initCapacity < MIN_CAPACITY) {
throw new IllegalArgumentException("Capacity must be at least 2!");
}
}
/**
* @return
*/
public int size() {
// Report the current number of elements
// O(1)
return size; //default return, remove/change as needed
}
/**
* @return
*/
public int capacity() {
// Report max number of elements of the current storage
// (subject to change since this is a _dynamic_ )
// O(1)
return capacity; //default return, remove/change as needed
}
/**
* @param index index you're changing
* @param value what you're adding
* @return the old item at the index
*/
public T set(int index, T value) {
// Replace the item at the given index to be the given value.
// Return the old item at that index.
// Note: You cannot add new items (i.e. cannot increase size) with this method.
// O(1)
//return firstIndexOf(value);
// - Throw IndexOutOfBoundsException if index is not valid
// - Use this code to produce the correct error message for
// the exception (do not use a different message):
// "Index: " + index + " out of bounds!"
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// - Throw IllegalArgumentException if value is null.
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Cannot include null values!"
if (value==null) {
throw new IllegalArgumentException("Cannot include null values!");
}
T oldValue = data[index];
data[index] = value;
return oldValue; //default return, remove/change as needed
}
/**
* @param index
* @return
*/
public T get(int index) {
// Return the item at the given index
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// O(1)
// Use the exception (and error message) described in set()
// for invalid indicies.
return data[index]; //default return, remove/change as needed
}
/**
* @param value
*/
@SuppressWarn.
Pratik Bakane C++ programs...............This are programs desingedby sy diploma student from Governement Polytecnic Thane.....programsare very easy alongwith coding andscreen shot of the output
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfrohit219406
C++, Implement the class BinarySearchTree, as given in listing 16-4 (below) Please include
main function.
//************************************* Here is listing 16-4
// Created by Frank M. Carrano and Timothy M. Henry.
// Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.
// Listing 16-4.
/** Link-based implementation of the ADT binary search tree.
@file BinarySearchTree.h */
#ifndef BINARY_SEARCH_TREE_
#define BINARY_SEARCH_TREE_
#include \"BinaryTreeInterface.h\"
#include \"BinaryNode.h\"
#include \"BinaryNodeTree.h\"
#include \"NotFoundException.h\"
#include \"PrecondViolatedExcept.h\"
#include
template
class BinarySearchTree : public BinaryNodeTree
{
private:
std::shared_ptr> rootPtr;
protected:
//------------------------------------------------------------
// Protected Utility Methods Section:
// Recursive helper methods for the public methods.
//------------------------------------------------------------
// Places a given new node at its proper position in this binary
// search tree.
auto placeNode(std::shared_ptr> subTreePtr,
std::shared_ptr> newNode);
// Removes the given target value from the tree while maintaining a
// binary search tree.
auto removeValue(std::shared_ptr> subTreePtr,
const ItemType target,
bool& isSuccessful) override;
// Removes a given node from a tree while maintaining a binary search tree.
auto removeNode(std::shared_ptr> nodePtr);
// Removes the leftmost node in the left subtree of the node
// pointed to by nodePtr.
// Sets inorderSuccessor to the value in this node.
// Returns a pointer to the revised subtree.
auto removeLeftmostNode(std::shared_ptr>subTreePtr,
ItemType& inorderSuccessor);
// Returns a pointer to the node containing the given value,
// or nullptr if not found.
auto findNode(std::shared_ptr> treePtr,
const ItemType& target) const;
public:
//------------------------------------------------------------
// Constructor and Destructor Section.
//------------------------------------------------------------
BinarySearchTree();
BinarySearchTree(const ItemType& rootItem);
BinarySearchTree(const BinarySearchTree& tree);
virtual ~BinarySearchTree();
//------------------------------------------------------------
// Public Methods Section.
//------------------------------------------------------------
bool isEmpty() const;
int getHeight() const;
int getNumberOfNodes() const;
ItemType getRootData() const throw(PrecondViolatedExcept);
void setRootData(const ItemType& newData);
bool add(const ItemType& newEntry);
bool remove(const ItemType& target);
void clear();
ItemType getEntry(const ItemType& anEntry) const throw(NotFoundException);
bool contains(const ItemType& anEntry) const;
//------------------------------------------------------------
// Public Traversals Section.
//------------------------------------------------------------
void preorderTraverse(void visit(ItemType&)) const;
void inorderTraverse(void visit(ItemType&)) const;
void postorderTraverse(void visit(ItemType&)) const;
//----------.
files/Heap.h
#ifndef HEAP_H
#define HEAP_H
#include <vector>
#include <stdexcept> // std::out_of_range
#include <math.h> // pow()
using namespace std;
template<typename T>
class Heap
{
private:
vector<T> _items; // Main vector of elements for heap storage
/**
* Used to take unsorted data and heapify it
*/
void buildHeap()
{
for (int i = _items.size() / 2; i >= 0; i--)
{
percolateDown(i);
}
}
/*********************************************************************/
/********************* Microassignment zone *************************/
/**
* Percolates the item specified at by index down
* into its proper location within a heap.
* Used for dequeue operations and array to heap conversions
* MA TODO: Implement percolateDown!
*/
void percolateDown(int index)
{
}
/**
* Percolate up from a given index to fix heap property
* Used in inserting new nodes into the heap
* MA TODO: Implement percolateUp
*/
void percolateUp( int current_position )
{
}
/************************** Microassigment zone DONE *********************/
public:
/**
* Default empty constructor
*/
Heap()
{
}
/**
* Constructor with a vector of elements
*/
Heap(const vector<T> &unsorted)
{
for (int i = 0; i < unsorted.size(); i++)
{
_items.push_back(unsorted[i]);
}
buildHeap();
}
/**
* Adds a new item to the heap
*/
void insert(T item)
{
int current_position = size(); // Get index location
_items.push_back(item); // Add data to end
percolateUp( current_position ); // Adjust up, as needed
}
/**
* Returns the top-most item in our heap without
* actually removing the item from the heap
*/
T& getFirst()
{
if( size() > 0 )
return _items[0];
else
throw std::out_of_range("No elements in Heap.");
}
/**
* Removes minimum value from heap and returns it to the caller
*/
T deleteMin()
{
int last_index = size() - 1; // Calc last item index
int root_index = 0; // Root index (for readability)
T min_item = _items[root_index]; // Keep item to return
_items[root_index] = _items[last_index]; // Move last item to root
_items.erase(_items.end() - 1); // Erase last element entry
percolateDown(0); // Fix heap property
return min_item;
}
/**
* Returns true if heap is empty, else false
*/
bool isEmpty() const
{
return _items.size() == 0;
}
/**
* Returns current quantity of elements in heap (N)
*/
int size() const
{
return _items.size();
}
/**
* Return heap data in order from the _items vector
*/
string to_s() const
{
string ret = "";
for(int i = 0; i < _items.size(); i++)
{
ret += to_string(_items[i]) + " ";
}
return ret;
}
/**
...
InternetService.java
import java.text.DecimalFormat;
import java.util.Scanner;
public class InternetService
{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat(\"#.##\");
//initialize variable
char packageType;
int time;
double totalCharges;
double packA;
double packB;
double packC;
// create an object for Scanner class
Scanner input = new Scanner(System.in);
// prompt the user to enter the package purchased
System.out.print(\"\ Enter the package purchased: \");
packageType = input.next().charAt(0);
//prompt the user to enter the number of minutes used
System.out.print(\"Enter the number of minutes used: \");
time = input.nextInt();
//Calculate the bill amount of the particular month using the type of package and the number of
minutes.
//Then print results to the screen
switch(packageType)
{
case \'A\':
//Calling the Method for Package A charges
totalCharges=calPackA(time);
//Displaying the package A charges.
System.out.println(\"For Package A:\ The total charges for this month is $\" + totalCharges);
//Calling the Method for Package B charges
packB=calPackB(time);
//Calling the Method for Package C charges
packC=calPackC(time);
//If the package B is Less Than package A then display the difference amount
if(totalCharges>packB)
System.out.println(\"Amount of Money Package A customer would save, if he Purchased
Package B is:$\"+df.format(totalCharges-packB));
//If the package C is Less Than package A then display the difference amount
if(totalCharges>packC)
System.out.println(\"Amount of Money Package A customer would save, if he Purchased
Package C is:$\"+df.format(totalCharges-packC));
break;
case \'B\':
//Calling the Method for Package B charges
totalCharges=calPackB(time);
//Displaying the package B charges.
System.out.println(\"For Package B:\ The total charges for this month is $\"
+df.format(totalCharges));
//Calling the Method for Package C charges
packC=calPackC(time);
//If the package B is Less Than package A then display the difference amount
if(totalCharges>packC)
System.out.println(\"Amount of Money Package B customer would save, if he Purchased
Package C is:$\"+df.format(totalCharges-packC));
break;
case \'C\':
//Calling the Method for Package C charges
totalCharges=calPackC(time);
//Displaying the package C charges.
System.out.print(\"For Package C:\ The total charges for this month is $\" + totalCharges);
break;
default:
System.out.println(\"\ The package should be A or B or C.\");
}
}
/*This method will calculate the total Charges for Package C
* Params:Time
* Return:total charges of type double
*/
private static double calPackC(int time) {
double totalCharges = 69.99;
return totalCharges;
}
/*This method will calculate the total Charges for Package B
* Params:Time
* Return:total charges of type double
*/
private static double calPackB(int time) {
double totalCharges=0.0;
if(time <= 900)
totalCharges = 59.99;
else
totalCharges = 59.99 + (0.40 * (time - 900));
return totalCharges;
}
/*This method will c.
Given the following class in Java- public class ThreeTenDynArray-T- {.pdfNicholasflqStewartl
Given the following class in Java :
public class ThreeTenDynArray<T> {
//default initial capacity / minimum capacity
private static final int MIN_CAPACITY = 2;
//underlying array for storage -- you MUST use this for credit!
//Do NOT change the name or type
private T[] data;
private int size = 0;
private int capacity = 0;
// ADD MORE PRIVATE MEMBERS HERE IF NEEDED!
/**
*
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray() {
// Constructor
// Initial capacity of the storage should be MIN_CAPACITY
// Hint: Can't remember how to make an array of generic Ts? It's in the textbook...
data = (T[])(new Object[MIN_CAPACITY]);
size = 0;
capacity = MIN_CAPACITY;
}
/**
* @param initCapacity
*/
@SuppressWarnings("unchecked")
public ThreeTenDynArray(int initCapacity) {
// Constructor
// Initial capacity of the storage should be initCapacity.
// - Throw IllegalArgumentException if initCapacity is smaller than
// MIN_CAPACITY 2
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Capacity must be at least 2!"
if (initCapacity < MIN_CAPACITY) {
throw new IllegalArgumentException("Capacity must be at least 2!");
}
}
/**
* @return
*/
public int size() {
// Report the current number of elements
// O(1)
return size; //default return, remove/change as needed
}
/**
* @return
*/
public int capacity() {
// Report max number of elements of the current storage
// (subject to change since this is a _dynamic_ )
// O(1)
return capacity; //default return, remove/change as needed
}
/**
* @param index index you're changing
* @param value what you're adding
* @return the old item at the index
*/
public T set(int index, T value) {
// Replace the item at the given index to be the given value.
// Return the old item at that index.
// Note: You cannot add new items (i.e. cannot increase size) with this method.
// O(1)
//return firstIndexOf(value);
// - Throw IndexOutOfBoundsException if index is not valid
// - Use this code to produce the correct error message for
// the exception (do not use a different message):
// "Index: " + index + " out of bounds!"
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// - Throw IllegalArgumentException if value is null.
// - Use this _exact_ error message for the exception
// (quotes are not part of the message):
// "Cannot include null values!"
if (value==null) {
throw new IllegalArgumentException("Cannot include null values!");
}
T oldValue = data[index];
data[index] = value;
return oldValue; //default return, remove/change as needed
}
/**
* @param index
* @return
*/
public T get(int index) {
// Return the item at the given index
if (index < 0 && index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + " out of bounds!");
}
// O(1)
// Use the exception (and error message) described in set()
// for invalid indicies.
return data[index]; //default return, remove/change as needed
}
/**
* @param value
*/
@SuppressWarn.
Pratik Bakane C++ programs...............This are programs desingedby sy diploma student from Governement Polytecnic Thane.....programsare very easy alongwith coding andscreen shot of the output
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfrohit219406
C++, Implement the class BinarySearchTree, as given in listing 16-4 (below) Please include
main function.
//************************************* Here is listing 16-4
// Created by Frank M. Carrano and Timothy M. Henry.
// Copyright (c) 2017 Pearson Education, Hoboken, New Jersey.
// Listing 16-4.
/** Link-based implementation of the ADT binary search tree.
@file BinarySearchTree.h */
#ifndef BINARY_SEARCH_TREE_
#define BINARY_SEARCH_TREE_
#include \"BinaryTreeInterface.h\"
#include \"BinaryNode.h\"
#include \"BinaryNodeTree.h\"
#include \"NotFoundException.h\"
#include \"PrecondViolatedExcept.h\"
#include
template
class BinarySearchTree : public BinaryNodeTree
{
private:
std::shared_ptr> rootPtr;
protected:
//------------------------------------------------------------
// Protected Utility Methods Section:
// Recursive helper methods for the public methods.
//------------------------------------------------------------
// Places a given new node at its proper position in this binary
// search tree.
auto placeNode(std::shared_ptr> subTreePtr,
std::shared_ptr> newNode);
// Removes the given target value from the tree while maintaining a
// binary search tree.
auto removeValue(std::shared_ptr> subTreePtr,
const ItemType target,
bool& isSuccessful) override;
// Removes a given node from a tree while maintaining a binary search tree.
auto removeNode(std::shared_ptr> nodePtr);
// Removes the leftmost node in the left subtree of the node
// pointed to by nodePtr.
// Sets inorderSuccessor to the value in this node.
// Returns a pointer to the revised subtree.
auto removeLeftmostNode(std::shared_ptr>subTreePtr,
ItemType& inorderSuccessor);
// Returns a pointer to the node containing the given value,
// or nullptr if not found.
auto findNode(std::shared_ptr> treePtr,
const ItemType& target) const;
public:
//------------------------------------------------------------
// Constructor and Destructor Section.
//------------------------------------------------------------
BinarySearchTree();
BinarySearchTree(const ItemType& rootItem);
BinarySearchTree(const BinarySearchTree& tree);
virtual ~BinarySearchTree();
//------------------------------------------------------------
// Public Methods Section.
//------------------------------------------------------------
bool isEmpty() const;
int getHeight() const;
int getNumberOfNodes() const;
ItemType getRootData() const throw(PrecondViolatedExcept);
void setRootData(const ItemType& newData);
bool add(const ItemType& newEntry);
bool remove(const ItemType& target);
void clear();
ItemType getEntry(const ItemType& anEntry) const throw(NotFoundException);
bool contains(const ItemType& anEntry) const;
//------------------------------------------------------------
// Public Traversals Section.
//------------------------------------------------------------
void preorderTraverse(void visit(ItemType&)) const;
void inorderTraverse(void visit(ItemType&)) const;
void postorderTraverse(void visit(ItemType&)) const;
//----------.
20145-5SumII_CSC374-407_assign3.html
CSC 374/407: Computer Systems II: 2015 Summer II, Assignment #3
Last modified 2015 August 6
Purpose:
To practice working with POSIX threads, mutexes and conditions;
and to practice good pointer programming in CAssignment:The "telephone" game (70 Points)Overview
We are going to simulate the children's game of "telephone".
In this game N (in our case, 10) children are in a circle.
The first one says something to the second.
The second one may or may not hear what the first one said accurately but he/she passes what he/she thinks was said to the third.
This continues until the message gets to the last child.
The program for our game has two classes.
The first one, Sentence holds the current state of a sentence.
It has been written for you, and all you have to do is use it.
The second one, MessageSystem holds mutexes, conditions and sentence pointer buffers between each child.
You'll have to finish this one.
For this assignment you have to:
You have to fill in the mutex and condition portions of MessageSystem.
Write the function void* child (void*) that the child threads will run.
Finish main() to invoke and wait for the child threads.
Each child i will get the pointer to its sentence from i-1 and will transmit it (imperfectly) to i.
Thus it needs to access two buffers: one at i-1 and the other at i.
All buffers are protected by mutexes, so child i-1 and child i don't step on each other's toes when trying to access the buffer at i-1.
Before child i can get the sentence pointer from the buffer at i-1 the sentence has to be there.
If it is not it should temporarily surrender the lock (if it obtained it) and wait until the sentence becomes available.
AssignmentCut and paste the following/*--------------------------------------------------------------------------*
*---- ----*
*---- telephoneGame ----*
*---- ----*
*---- This program simulates the children's game of "telephone", ----*
*---- where an original message mutates as it is imperfectly ----*
*---- transmited among children in a pairwise manner. ----*
*---- ----*
*---- It demonstrates Linux/Unix thread programming using ----*
*---- pthread_mutex_t and pthread_cond_t. ----*
*---- ----*
*---- Compile with: ----*
*---- linux> g++ -lpthread telephoneGame.cpp -o telephoneGame ----*
*---- ----*
*---- ---- ---- ---- ---- ---- ---- ---- ---- ----*
*---- ----*
*---- Version 1.0 Joseph Phillips 2010 October 23 ----*
*---- ----*
*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*
*---- ----*
*---- Includes and namespace designations: ----*
*---- ----*
*----------------------------------------------------------------------.
Perl code for a SADI service that calculates BMI. The first panel is the code for a traditional SADI service, the second panel highlights the minor changes required to convert the service into a service that outputs NanoPublications.
Example code for the SADI BMI Calculator Web ServiceMark Wilkinson
Two versions of the code for the SADI Web Service demonstrated at the Using the Semantic Web for faster (Bio-)Research workshop hosted by the Swiss Institute for Bioinformatics, Geneva, December, 2015. The first version of the code is a bare-bones service that consumes individuals with height and weight and returns individuals with a BMI. The second piece of code is functionally identical to the first, but highlights the small changes required to make the service a NanoPublisher (NanoPublishing services respond to Accept n-quads HTTP headers by returning NanoPublications, rather than just a stream of triples)
public class Point { Insert your name here private dou.pdfanandshingavi23
public class Point {
/* Insert your name here */
private double x;
private double y;
public static final double EPSILON = 1e-5;
public static boolean debug = false;
// TODO Implement Point.Point(double x, double y)
/**
* instantiate a point \"this.x\" refers to the instance variable of the
* object x refers to the parameter same for this.y and y
*/
public Point(double x, double y) {
// System.out.println(\"Point(x,y) not implemented yet\");
this.x = x;
this.y = y;
}
// TODO Implement Point.Point()
/**
* Point() creates the origin by appropriately calling the general Point
* constructor
*/
public Point() {
// System.out.println(\"Point() not implemented yet\");
this.x = 0;
this.y = 0;
}
// TODO Implement Point.getX
/**
* return x
*/
public double getX() {
// System.out.println(\"getX not implemented yet\");
return this.x;
}
// TODO Implement Point.getY
/**
* return y
*/
public double getY() {
// System.out.println(\"getY not implemented yet\");
return this.y;
}
// Given Point.toString
/**
* convert to String
*/
public String toString() {
return \"(\" + x + \",\" + y + \")\";
}
// TODO Implement Point.equals
/**
*
* param p other point return test for equality using epsilon, because we
* are dealing with doubles,so roundoff can occur
*/
public boolean equals(Point p) {
// System.out.println(\"equals not implemented yet\");
if (p.getX() == this.getX() && p.getY() == this.getY())
return true;
else
return false;
}
// Given equals(Object o)
/**
* We need this equals method for ArrayList, because the generic
* ArrayList is really an ArrayList of Object. In the case of equals, the
* signature is public boolean equals(Object o) and the method below
* overrides the Object equals method and the calls the class\'s
* equals(Point) method
*
* see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj instanceof Point) {
Point p = (Point) obj;
return equals(p);
}
return false;
}
// TODO Implement Point.euclidDist
/**
*
* param p return Euclidean distance of this point to point p
*/
public double euclidDist(Point p) {
// System.out.println(\"euclidDist not implemented yet\");
double X = this.getY() - p.getY();
double Y = this.getX() - p.getX();
double result = Math.sqrt(X * X + Y * Y);
return result;
}
/**
* param args: no args
*/
public static void main(String[] args) {
// test all methods
if (debug)
System.out.println(\"debug ON\");
else
System.out.println(\"debug OFF\");
System.out.println(\"EPSILON: \" + Point.EPSILON);
Point origin = new Point();
Point p1 = new Point(0.0, 4.0);
Point p2 = new Point(3.0000001, 3.9999999);
Point p3 = new Point(3.0, 4.0);
Point p4 = new Point(0.0, 5.0);
Point p5 = new Point(12.0, 0.0);
System.out.println(\"origin: \" + origin);
System.out.println(\"p1: \" + p1);
System.out.println(\"p2: \" + p2);
System.out.println(\"p3: \" + p3);
System.out.println(\"p4: \" + p4);
System.out.println(\"p5: \" + p5);
if (p2.equals(p3))
System.out.println(p2 + \" equals \" + p3);
else
System.out.println(p2 +.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
public class SavingAccount //MUST match the file name!
{
public static void main(String[] args)throws IOException
{
//Create a decimal format for displaying dollars
DecimalFormat dollar = new DecimalFormat(\"#,###.##\");
//Constants
double depositSum = 0.0;
double withdrawalSum = 0.0;
double earnedInt = 0.0;
double startBalance = 500; //Starting balance
// Executables
System.out.println(\"This program solves Programming Challenge 6.11\");
System.out.println();
//Create Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Get interest rate
System.out.print(\"Enter the annual interest: \");
double testInterest = keyboard.nextDouble();
//Create an object that accept the starting balance and annual interest
SavingAccount1 account = new SavingAccount1(startBalance, testInterest);
//Open Deposit file.
File file = new File (\"BankDeposits.txt\");
Scanner inputFile = new Scanner(file);
//Read line in file
while (inputFile.hasNext());
{
//Read numbers
double num = inputFile.nextDouble();
//Add the numbers
depositSum += num;
}
//Deposit the file input.
account.deposit(depositSum);
//Close the file
inputFile.close();
//Open Withdrawal file
File file2 = new File(\"BankWithdrawal.txt\");
Scanner inputFile2 = new Scanner(file2);
//Read lines in file
while (inputFile2.hasNext());
{
//Read numbers
double num2 = inputFile2.nextDouble();
//Add the numbers
withdrawalSum += num2;
}
//Withdrawal the file input from account.
account.withdraw(withdrawalSum);
//Close the file
inputFile2.close();
//Add the monthly interest
account.addInt();
//Get amount of interest earned.
earnedInt += account.getInterest();
//Display the data
System.out.println(\"Account balance $\" + dollar.format(account.getBalance()));
System.out.println(\"Total interest earned $\" + dollar.format(account.getInterest()));
}
}//end class
public class SavingAccount1 //MUST match the file name!
{
public static void main(String[] args)
{
System.out.println(\"This program solves Programming Challenge 6.10\");
System.out.println();
}
//Fields
private double balance; //Account balance
private double annualInterest; //annual interest
private double monthInt; //monthly interest
private double earnedInt; //earned interest
double totalWithdraw;
double totalDeposit;
/**
018
This constructor sets the starting balance
019
and the annual interest at 0.0.
020
*/
public void Ward_Tassinda_SavingAccount1()
{
balance = 0.0;
annualInterest = 0.0;
}
/**
029
This constructor set the starting balance and the annual interest rate
030
to the value passed as an argument.
031
@param startBalance The starting balance.
032
*/
public void Ward_Tassinda_SavingAccount1(double startBalance, double interestRate)
{
balance = startBalance;
annualInterest = interestRate;
}
/**
041
This constructor sets the starting balance to
042
the value in the String argument.
043
@param str The starting balance, as a String.
044
*/
public void .
Can you please debug this Thank you in advance! This program is sup.pdfFashionBoutiquedelhi
Can you please debug this? Thank you in advance! This program is supposed to use stacks and
find the paths of an airplane. It should tell you whether or not the plane goes from the requested
city to the requested destination. requestFile.txt contains the requests, flightFile.txt contains the
flights and cityFile.txt contains the city\'s that the airline serves.
My errors: my output is simply \"Hpair does not serve Los Angeles.\" Thats it and it stops.
It should look something like (these are not real values of the file just an example):
\"Request is to fly from cityA to CityB.
Hpair flight from cityA to CityB.
Request is to fly from cityC to cityD.
Sorry, HPAir does not serve City D
Request is to fly from cityE to CityF
Sorry, HPAir does not fly from cityE to CityF\"
**It said to use ispath.cpp but I got confused on how to implement it completely.\"
isPath.cpp
//***I did not include ispath.cpp in my program. Parts of it are in the map.h portion.
main.cpp
#include
#include
#include \"Map.h\"
using namespace std;
int main()
{
Map aMap;
aMap.readFlights();
aMap.verifyRequestedFile();
}
StackInterface.h
#ifndef StackInterface_h
#define StackInterface_h
template
class StackInterface
{
/** Checks if the stack is empty.
@return True if the stack is empty or false if the stack is not.*/
virtual bool isEmpty() const = 0;
/** Adds a new item to the stack
@post newEntry is at the top of the stack
@param newEntry is the object to be added to the stack
@return True if successfully added, otherwise false. */
virtual bool push(const ItemType& newEntry) = 0;
/** Removes item from stack
@post The top item in the stack is removed
@return True if the item was removed, false if it was not. */
virtual bool pop() = 0;
/** Returns the top item in the stack
@pre The stack is not empty
@post The top item in the stack is returned
@return The top of the stack */
virtual ItemType peek() const = 0;
};
#endif /* StackInterface_h */
Node.h
#ifndef node_h
#define node_h
template
class Node {
public:
Node();
Node (const ItemType &anItem);
Node(const ItemType &anItem, Node * nextNodePtr);
void setItem(const ItemType &anItem);
void setNext(Node * nextNodePtr);
ItemType getItem() const;
Node* getNext() const;
private:
ItemType item;
Node* next;
};
template
Node::Node():next(nullptr){}
template
Node::Node(const ItemType &anItem):item(anItem), next(nullptr){}
template
Node::Node(const ItemType &anItem, Node * nextNodePtr):item(anItem), next(nextNodePtr)
{
}
template
void Node::setItem(const ItemType &anItem){
item = anItem;
}
template
void Node::setNext(Node * nextNodePtr) {
next = nextNodePtr;
}
template
ItemType Node::getItem() const {
return item;
}
template
Node* Node::getNext()const{
return next;
}
#endif /* node_h */
LinkedStack.h
#include
#ifndef LinkedStack_h
#define LinkedStack_h
#include \"Node.h\"
#include \"StackInterface.h\"
template
class LinkedStack:public StackInterface{
public:
LinkedStack();
LinkedStack(const LinkedStack &aStack); //space matter?***********
virt.
Write a class that implements the BagInterface. BagInterface should .pdffashiongallery1
Which one is NOT a duty of MySQL Administration? (Points : 2) Server startup and
shutdown
User account maintenance
Log maintenance
Running SQL statementsQuestion 2.2. (TCO A) How do you display the current system
variable values? (Points : 2) SHOW SYSTEM;
SHOW VARIABLES;
SHOW VALUES;
SHOW SYSTEM VARIABLES;Question 3.3. (TCO A) How do you display the global
variable values? (Points : 2) SHOW SYSTEM;
SHOW VARIABLES;
SHOW VALUES;
SHOW GLOBAL VARIABLES;Question 4.4. (TCO A) Which statement enables you to
rename tables or modify their structure? (Points : 2) MODIFY TABLE
ALTER TABLE
CHANGE TABLE
CREATE TABLEQuestion 5.5. (TCO A) Which is the statement that will rename the
instructor table to a new name? (Points : 2) ALTER TABLE instructor RENAME TO instr;
RENAME instructor instr;
This task is not available in MySQL.
ALTER TABLE instructor TO instr;Question 6.6. (TCO A) Review the following SQL
statement:
CHECKSUM TABLE instructor;
What is going to be the result if there is no table named instructor? (Points : 2)
CHECKSUM value is zero.
CHECKSUM value is negative.
CHECKSUM value is NULL.
An error occurs.Which one is NOT a duty of MySQL Administration? (Points : 2)
Server startup and shutdown
User account maintenance
Log maintenance
Running SQL statements
Solution
1.1 Which one is NOT a duty of MySQL Administration?
a) log maintainance
2.2 How do you display the current system variable values?
show variables
3.3 How do you display the global variable values?
SHOW GLOBAL VARIABLES;
4.4 Which statement enables you to rename tables or modify their structure?
ALTER TABLE
5.5 Which is the statement that will rename the instructor table to a new name?
This task is not available in MySQL.
6.6. CHECKSUM TABLE instructor;
CHECKSUM value is NULL..
SinglyLinkedListPseudoCode.txt
CLASS SinglyLinkedList:
set linkedList as Node
FUNCTION getLinkedList()
return linkedList
END FUNCTION
FUNCTION add(object)
found = find(object)
IF found
create newNode object using object
IF linkList is null
set linkedList as newNode
ELSE
set rear as linkedList
WHILE rear is not null
IF rear.next is null
breaK
END IF
set rear as rear.next
END WHILE
rear.next = newNode
ELSE
END IF
return true
END IF
return false
END FUNCTION
FUNCTION find(object)
IF linkedlist is null return false
set iterable as linkedList
IF iterable.data is equal to object
create newNode object
newNode.next = linkedList.nex
set linkedList as newNode
return true
END IF
WHILE iterable is not null
IF iterable.next is not null
IF iterable.next is equal to object
set target as iterable.next
create newNode object
newNode.next = target.next
iterable.next = newNode
dispose target
END IF
END IF
set iterable as iterable.next
END WHILE
return false
END FUNCTION
FUNCTION delete(object)
IF linkedlist is null return false
set iterable as linkedList
IF iterable.data is equal to object
set linkedList as iterable.next
return true
END IF
WHILE iterable is not null
IF iterable.next is not null
IF iterable.next is equal to object
set target as iterable.next
iterable.next = target.next
dispose target
END IF
END IF
set iterable as iterable.next
END WHILE
return false
END FUNCTION
FUNCTION traverse()
set iterable as linkedList
WHILE iterable is not null
PRINT(iterable.data)
set iterable as iterable.next
END WHILE
END FUNCTION
Account_Bhusal.javaAccount_Bhusal.java/**
* @author Deepak Bhusal
* Assignment SP2019_PROJECT
* Account_Bhusal class represents a bank account for a user and harbours
* necessary methods for deposit, withdrawal and balance checking. This class is abstract in nature
* and contain abstract methods that are implemented by child classes
*/
publicabstractclassAccount_Bhusal{
protectedString accountNumber;
protectedfloat balance;
/**
* Default constructor
*/
publicAccount_Bhusal(){
this.accountNumber="";
this.balance=.
operating system Ubunut,Linux,Mac filename messageService.cpp.pdfannethafashion
// operating system Ubunut,Linux,Mac
// filename messageService.cpp
#include
#include // for vector
#include
using namespace std;
/*Main function start*/
int main()
{
std::vector > store;// we are using vector for storing pair of name and message
std::vector >::reverse_iterator it;// used to reverse iteration
std::string name,message,input,choice;// variable for purpose
do{
std::cout<<\"Enter User Name> \";
std::cin>>name;
std::cout<<\"Enter Message> \";// prompt for user input
/* we are taking input from user as string
* if line contains $$ then it will break and come out from loop
* otherwise it will create pair and insert it into vector*/
while(std::getline(std::cin,input)){
if(input==\"$$\")
break;
message+=input+\"\ \";
}
store.push_back(std::pair(name,message));// inserting pair into vector
message=\"\";
std::cout<<\"Any More Users? > \";
std::cin>>choice;
}while(choice==\"yes\");
/*while loop break if choice value other then \"yes\" */
std::cout << \"The current messages are: \ \";
/*Iterating vector in reverse order for printing desirable output*/
for (it=store.rbegin(); it!=store.rend(); ++it){
std::cout << it->first << \" >> \"<second << \'\ \';
}
return 0;
}
/*Main function End*/
/*Output*/
gopal@gopal:~/Desktop/chegg$ g++ messageService.cpp
gopal@gopal:~/Desktop/chegg$ ./a.out
Enter User Name> Kate
Enter Message> Get in the loop and join our War Eagle group!
Sunner in st. John\'s islands was fun.
How was your summer?
$$
Any More Users? > yes
Enter User Name> Daniel
Enter Message> I\'m in!
$$
Any More Users? > yes
Enter User Name> Joey
Enter Message> Count me in.
We were in Tokyo; intersting!
$$
Any More Users? > yes
Enter User Name> Kevin
Enter Message> What\'s new?
we had a great time in the Outback.
$$
Any More Users? > no
The current messages are:
Kevin >>
What\'s new?
we had a great time in the Outback.
Joey >>
Count me in.
We were in Tokyo; intersting!
Daniel >>
I\'m in!
Kate >>
Get in the loop and join our War Eagle group!
Sunner in st. John\'s islands was fun.
How was your summer?
Solution
// operating system Ubunut,Linux,Mac
// filename messageService.cpp
#include
#include // for vector
#include
using namespace std;
/*Main function start*/
int main()
{
std::vector > store;// we are using vector for storing pair of name and message
std::vector >::reverse_iterator it;// used to reverse iteration
std::string name,message,input,choice;// variable for purpose
do{
std::cout<<\"Enter User Name> \";
std::cin>>name;
std::cout<<\"Enter Message> \";// prompt for user input
/* we are taking input from user as string
* if line contains $$ then it will break and come out from loop
* otherwise it will create pair and insert it into vector*/
while(std::getline(std::cin,input)){
if(input==\"$$\")
break;
message+=input+\"\ \";
}
store.push_back(std::pair(name,message));// inserting pair into vector
message=\"\";
std::cout<<\"Any More Users? > \";
std::cin>>choice;
}while(choice==\"yes\");
/*while loop break if choice value other then \"yes\.
Meet Elcodi, the flexible e-commerce components built on Symfony2Aldo Chiecchia
Elcodi is a suite of bundles for Symfony2 which aim to help developers build and quickly scale e-commerce websites. It is written in a clean, straightforward way to ease and smooth the learning curve and it promotes development productivity, SOLID, DRY principles without adding too many layers of indirection. Some of the goals we think we've reached: Balance between flexibility and development speed, Reusable components and foundations for writing custom Model. We'd like to share some insights on how we are approaching those topics by using rigorous coding standards, enforcing coherence and loose coupling, aiming for comprehensible and self-explaining code. See how you can leverage Symfony components for addressing similar challenges and let's discuss the rationales behind some good practices. And above all, see how to do it without pain, because we think that coding should always be a pleasure and crafting developer-friendly software is in our DNA!
20145-5SumII_CSC374-407_assign3.html
CSC 374/407: Computer Systems II: 2015 Summer II, Assignment #3
Last modified 2015 August 6
Purpose:
To practice working with POSIX threads, mutexes and conditions;
and to practice good pointer programming in CAssignment:The "telephone" game (70 Points)Overview
We are going to simulate the children's game of "telephone".
In this game N (in our case, 10) children are in a circle.
The first one says something to the second.
The second one may or may not hear what the first one said accurately but he/she passes what he/she thinks was said to the third.
This continues until the message gets to the last child.
The program for our game has two classes.
The first one, Sentence holds the current state of a sentence.
It has been written for you, and all you have to do is use it.
The second one, MessageSystem holds mutexes, conditions and sentence pointer buffers between each child.
You'll have to finish this one.
For this assignment you have to:
You have to fill in the mutex and condition portions of MessageSystem.
Write the function void* child (void*) that the child threads will run.
Finish main() to invoke and wait for the child threads.
Each child i will get the pointer to its sentence from i-1 and will transmit it (imperfectly) to i.
Thus it needs to access two buffers: one at i-1 and the other at i.
All buffers are protected by mutexes, so child i-1 and child i don't step on each other's toes when trying to access the buffer at i-1.
Before child i can get the sentence pointer from the buffer at i-1 the sentence has to be there.
If it is not it should temporarily surrender the lock (if it obtained it) and wait until the sentence becomes available.
AssignmentCut and paste the following/*--------------------------------------------------------------------------*
*---- ----*
*---- telephoneGame ----*
*---- ----*
*---- This program simulates the children's game of "telephone", ----*
*---- where an original message mutates as it is imperfectly ----*
*---- transmited among children in a pairwise manner. ----*
*---- ----*
*---- It demonstrates Linux/Unix thread programming using ----*
*---- pthread_mutex_t and pthread_cond_t. ----*
*---- ----*
*---- Compile with: ----*
*---- linux> g++ -lpthread telephoneGame.cpp -o telephoneGame ----*
*---- ----*
*---- ---- ---- ---- ---- ---- ---- ---- ---- ----*
*---- ----*
*---- Version 1.0 Joseph Phillips 2010 October 23 ----*
*---- ----*
*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*
*---- ----*
*---- Includes and namespace designations: ----*
*---- ----*
*----------------------------------------------------------------------.
Perl code for a SADI service that calculates BMI. The first panel is the code for a traditional SADI service, the second panel highlights the minor changes required to convert the service into a service that outputs NanoPublications.
Example code for the SADI BMI Calculator Web ServiceMark Wilkinson
Two versions of the code for the SADI Web Service demonstrated at the Using the Semantic Web for faster (Bio-)Research workshop hosted by the Swiss Institute for Bioinformatics, Geneva, December, 2015. The first version of the code is a bare-bones service that consumes individuals with height and weight and returns individuals with a BMI. The second piece of code is functionally identical to the first, but highlights the small changes required to make the service a NanoPublisher (NanoPublishing services respond to Accept n-quads HTTP headers by returning NanoPublications, rather than just a stream of triples)
public class Point { Insert your name here private dou.pdfanandshingavi23
public class Point {
/* Insert your name here */
private double x;
private double y;
public static final double EPSILON = 1e-5;
public static boolean debug = false;
// TODO Implement Point.Point(double x, double y)
/**
* instantiate a point \"this.x\" refers to the instance variable of the
* object x refers to the parameter same for this.y and y
*/
public Point(double x, double y) {
// System.out.println(\"Point(x,y) not implemented yet\");
this.x = x;
this.y = y;
}
// TODO Implement Point.Point()
/**
* Point() creates the origin by appropriately calling the general Point
* constructor
*/
public Point() {
// System.out.println(\"Point() not implemented yet\");
this.x = 0;
this.y = 0;
}
// TODO Implement Point.getX
/**
* return x
*/
public double getX() {
// System.out.println(\"getX not implemented yet\");
return this.x;
}
// TODO Implement Point.getY
/**
* return y
*/
public double getY() {
// System.out.println(\"getY not implemented yet\");
return this.y;
}
// Given Point.toString
/**
* convert to String
*/
public String toString() {
return \"(\" + x + \",\" + y + \")\";
}
// TODO Implement Point.equals
/**
*
* param p other point return test for equality using epsilon, because we
* are dealing with doubles,so roundoff can occur
*/
public boolean equals(Point p) {
// System.out.println(\"equals not implemented yet\");
if (p.getX() == this.getX() && p.getY() == this.getY())
return true;
else
return false;
}
// Given equals(Object o)
/**
* We need this equals method for ArrayList, because the generic
* ArrayList is really an ArrayList of Object. In the case of equals, the
* signature is public boolean equals(Object o) and the method below
* overrides the Object equals method and the calls the class\'s
* equals(Point) method
*
* see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
if (obj instanceof Point) {
Point p = (Point) obj;
return equals(p);
}
return false;
}
// TODO Implement Point.euclidDist
/**
*
* param p return Euclidean distance of this point to point p
*/
public double euclidDist(Point p) {
// System.out.println(\"euclidDist not implemented yet\");
double X = this.getY() - p.getY();
double Y = this.getX() - p.getX();
double result = Math.sqrt(X * X + Y * Y);
return result;
}
/**
* param args: no args
*/
public static void main(String[] args) {
// test all methods
if (debug)
System.out.println(\"debug ON\");
else
System.out.println(\"debug OFF\");
System.out.println(\"EPSILON: \" + Point.EPSILON);
Point origin = new Point();
Point p1 = new Point(0.0, 4.0);
Point p2 = new Point(3.0000001, 3.9999999);
Point p3 = new Point(3.0, 4.0);
Point p4 = new Point(0.0, 5.0);
Point p5 = new Point(12.0, 0.0);
System.out.println(\"origin: \" + origin);
System.out.println(\"p1: \" + p1);
System.out.println(\"p2: \" + p2);
System.out.println(\"p3: \" + p3);
System.out.println(\"p4: \" + p4);
System.out.println(\"p5: \" + p5);
if (p2.equals(p3))
System.out.println(p2 + \" equals \" + p3);
else
System.out.println(p2 +.
import java.util.Scanner;
import java.text.DecimalFormat;
import java.io.*;
public class SavingAccount //MUST match the file name!
{
public static void main(String[] args)throws IOException
{
//Create a decimal format for displaying dollars
DecimalFormat dollar = new DecimalFormat(\"#,###.##\");
//Constants
double depositSum = 0.0;
double withdrawalSum = 0.0;
double earnedInt = 0.0;
double startBalance = 500; //Starting balance
// Executables
System.out.println(\"This program solves Programming Challenge 6.11\");
System.out.println();
//Create Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Get interest rate
System.out.print(\"Enter the annual interest: \");
double testInterest = keyboard.nextDouble();
//Create an object that accept the starting balance and annual interest
SavingAccount1 account = new SavingAccount1(startBalance, testInterest);
//Open Deposit file.
File file = new File (\"BankDeposits.txt\");
Scanner inputFile = new Scanner(file);
//Read line in file
while (inputFile.hasNext());
{
//Read numbers
double num = inputFile.nextDouble();
//Add the numbers
depositSum += num;
}
//Deposit the file input.
account.deposit(depositSum);
//Close the file
inputFile.close();
//Open Withdrawal file
File file2 = new File(\"BankWithdrawal.txt\");
Scanner inputFile2 = new Scanner(file2);
//Read lines in file
while (inputFile2.hasNext());
{
//Read numbers
double num2 = inputFile2.nextDouble();
//Add the numbers
withdrawalSum += num2;
}
//Withdrawal the file input from account.
account.withdraw(withdrawalSum);
//Close the file
inputFile2.close();
//Add the monthly interest
account.addInt();
//Get amount of interest earned.
earnedInt += account.getInterest();
//Display the data
System.out.println(\"Account balance $\" + dollar.format(account.getBalance()));
System.out.println(\"Total interest earned $\" + dollar.format(account.getInterest()));
}
}//end class
public class SavingAccount1 //MUST match the file name!
{
public static void main(String[] args)
{
System.out.println(\"This program solves Programming Challenge 6.10\");
System.out.println();
}
//Fields
private double balance; //Account balance
private double annualInterest; //annual interest
private double monthInt; //monthly interest
private double earnedInt; //earned interest
double totalWithdraw;
double totalDeposit;
/**
018
This constructor sets the starting balance
019
and the annual interest at 0.0.
020
*/
public void Ward_Tassinda_SavingAccount1()
{
balance = 0.0;
annualInterest = 0.0;
}
/**
029
This constructor set the starting balance and the annual interest rate
030
to the value passed as an argument.
031
@param startBalance The starting balance.
032
*/
public void Ward_Tassinda_SavingAccount1(double startBalance, double interestRate)
{
balance = startBalance;
annualInterest = interestRate;
}
/**
041
This constructor sets the starting balance to
042
the value in the String argument.
043
@param str The starting balance, as a String.
044
*/
public void .
Can you please debug this Thank you in advance! This program is sup.pdfFashionBoutiquedelhi
Can you please debug this? Thank you in advance! This program is supposed to use stacks and
find the paths of an airplane. It should tell you whether or not the plane goes from the requested
city to the requested destination. requestFile.txt contains the requests, flightFile.txt contains the
flights and cityFile.txt contains the city\'s that the airline serves.
My errors: my output is simply \"Hpair does not serve Los Angeles.\" Thats it and it stops.
It should look something like (these are not real values of the file just an example):
\"Request is to fly from cityA to CityB.
Hpair flight from cityA to CityB.
Request is to fly from cityC to cityD.
Sorry, HPAir does not serve City D
Request is to fly from cityE to CityF
Sorry, HPAir does not fly from cityE to CityF\"
**It said to use ispath.cpp but I got confused on how to implement it completely.\"
isPath.cpp
//***I did not include ispath.cpp in my program. Parts of it are in the map.h portion.
main.cpp
#include
#include
#include \"Map.h\"
using namespace std;
int main()
{
Map aMap;
aMap.readFlights();
aMap.verifyRequestedFile();
}
StackInterface.h
#ifndef StackInterface_h
#define StackInterface_h
template
class StackInterface
{
/** Checks if the stack is empty.
@return True if the stack is empty or false if the stack is not.*/
virtual bool isEmpty() const = 0;
/** Adds a new item to the stack
@post newEntry is at the top of the stack
@param newEntry is the object to be added to the stack
@return True if successfully added, otherwise false. */
virtual bool push(const ItemType& newEntry) = 0;
/** Removes item from stack
@post The top item in the stack is removed
@return True if the item was removed, false if it was not. */
virtual bool pop() = 0;
/** Returns the top item in the stack
@pre The stack is not empty
@post The top item in the stack is returned
@return The top of the stack */
virtual ItemType peek() const = 0;
};
#endif /* StackInterface_h */
Node.h
#ifndef node_h
#define node_h
template
class Node {
public:
Node();
Node (const ItemType &anItem);
Node(const ItemType &anItem, Node * nextNodePtr);
void setItem(const ItemType &anItem);
void setNext(Node * nextNodePtr);
ItemType getItem() const;
Node* getNext() const;
private:
ItemType item;
Node* next;
};
template
Node::Node():next(nullptr){}
template
Node::Node(const ItemType &anItem):item(anItem), next(nullptr){}
template
Node::Node(const ItemType &anItem, Node * nextNodePtr):item(anItem), next(nextNodePtr)
{
}
template
void Node::setItem(const ItemType &anItem){
item = anItem;
}
template
void Node::setNext(Node * nextNodePtr) {
next = nextNodePtr;
}
template
ItemType Node::getItem() const {
return item;
}
template
Node* Node::getNext()const{
return next;
}
#endif /* node_h */
LinkedStack.h
#include
#ifndef LinkedStack_h
#define LinkedStack_h
#include \"Node.h\"
#include \"StackInterface.h\"
template
class LinkedStack:public StackInterface{
public:
LinkedStack();
LinkedStack(const LinkedStack &aStack); //space matter?***********
virt.
Write a class that implements the BagInterface. BagInterface should .pdffashiongallery1
Which one is NOT a duty of MySQL Administration? (Points : 2) Server startup and
shutdown
User account maintenance
Log maintenance
Running SQL statementsQuestion 2.2. (TCO A) How do you display the current system
variable values? (Points : 2) SHOW SYSTEM;
SHOW VARIABLES;
SHOW VALUES;
SHOW SYSTEM VARIABLES;Question 3.3. (TCO A) How do you display the global
variable values? (Points : 2) SHOW SYSTEM;
SHOW VARIABLES;
SHOW VALUES;
SHOW GLOBAL VARIABLES;Question 4.4. (TCO A) Which statement enables you to
rename tables or modify their structure? (Points : 2) MODIFY TABLE
ALTER TABLE
CHANGE TABLE
CREATE TABLEQuestion 5.5. (TCO A) Which is the statement that will rename the
instructor table to a new name? (Points : 2) ALTER TABLE instructor RENAME TO instr;
RENAME instructor instr;
This task is not available in MySQL.
ALTER TABLE instructor TO instr;Question 6.6. (TCO A) Review the following SQL
statement:
CHECKSUM TABLE instructor;
What is going to be the result if there is no table named instructor? (Points : 2)
CHECKSUM value is zero.
CHECKSUM value is negative.
CHECKSUM value is NULL.
An error occurs.Which one is NOT a duty of MySQL Administration? (Points : 2)
Server startup and shutdown
User account maintenance
Log maintenance
Running SQL statements
Solution
1.1 Which one is NOT a duty of MySQL Administration?
a) log maintainance
2.2 How do you display the current system variable values?
show variables
3.3 How do you display the global variable values?
SHOW GLOBAL VARIABLES;
4.4 Which statement enables you to rename tables or modify their structure?
ALTER TABLE
5.5 Which is the statement that will rename the instructor table to a new name?
This task is not available in MySQL.
6.6. CHECKSUM TABLE instructor;
CHECKSUM value is NULL..
SinglyLinkedListPseudoCode.txt
CLASS SinglyLinkedList:
set linkedList as Node
FUNCTION getLinkedList()
return linkedList
END FUNCTION
FUNCTION add(object)
found = find(object)
IF found
create newNode object using object
IF linkList is null
set linkedList as newNode
ELSE
set rear as linkedList
WHILE rear is not null
IF rear.next is null
breaK
END IF
set rear as rear.next
END WHILE
rear.next = newNode
ELSE
END IF
return true
END IF
return false
END FUNCTION
FUNCTION find(object)
IF linkedlist is null return false
set iterable as linkedList
IF iterable.data is equal to object
create newNode object
newNode.next = linkedList.nex
set linkedList as newNode
return true
END IF
WHILE iterable is not null
IF iterable.next is not null
IF iterable.next is equal to object
set target as iterable.next
create newNode object
newNode.next = target.next
iterable.next = newNode
dispose target
END IF
END IF
set iterable as iterable.next
END WHILE
return false
END FUNCTION
FUNCTION delete(object)
IF linkedlist is null return false
set iterable as linkedList
IF iterable.data is equal to object
set linkedList as iterable.next
return true
END IF
WHILE iterable is not null
IF iterable.next is not null
IF iterable.next is equal to object
set target as iterable.next
iterable.next = target.next
dispose target
END IF
END IF
set iterable as iterable.next
END WHILE
return false
END FUNCTION
FUNCTION traverse()
set iterable as linkedList
WHILE iterable is not null
PRINT(iterable.data)
set iterable as iterable.next
END WHILE
END FUNCTION
Account_Bhusal.javaAccount_Bhusal.java/**
* @author Deepak Bhusal
* Assignment SP2019_PROJECT
* Account_Bhusal class represents a bank account for a user and harbours
* necessary methods for deposit, withdrawal and balance checking. This class is abstract in nature
* and contain abstract methods that are implemented by child classes
*/
publicabstractclassAccount_Bhusal{
protectedString accountNumber;
protectedfloat balance;
/**
* Default constructor
*/
publicAccount_Bhusal(){
this.accountNumber="";
this.balance=.
operating system Ubunut,Linux,Mac filename messageService.cpp.pdfannethafashion
// operating system Ubunut,Linux,Mac
// filename messageService.cpp
#include
#include // for vector
#include
using namespace std;
/*Main function start*/
int main()
{
std::vector > store;// we are using vector for storing pair of name and message
std::vector >::reverse_iterator it;// used to reverse iteration
std::string name,message,input,choice;// variable for purpose
do{
std::cout<<\"Enter User Name> \";
std::cin>>name;
std::cout<<\"Enter Message> \";// prompt for user input
/* we are taking input from user as string
* if line contains $$ then it will break and come out from loop
* otherwise it will create pair and insert it into vector*/
while(std::getline(std::cin,input)){
if(input==\"$$\")
break;
message+=input+\"\ \";
}
store.push_back(std::pair(name,message));// inserting pair into vector
message=\"\";
std::cout<<\"Any More Users? > \";
std::cin>>choice;
}while(choice==\"yes\");
/*while loop break if choice value other then \"yes\" */
std::cout << \"The current messages are: \ \";
/*Iterating vector in reverse order for printing desirable output*/
for (it=store.rbegin(); it!=store.rend(); ++it){
std::cout << it->first << \" >> \"<second << \'\ \';
}
return 0;
}
/*Main function End*/
/*Output*/
gopal@gopal:~/Desktop/chegg$ g++ messageService.cpp
gopal@gopal:~/Desktop/chegg$ ./a.out
Enter User Name> Kate
Enter Message> Get in the loop and join our War Eagle group!
Sunner in st. John\'s islands was fun.
How was your summer?
$$
Any More Users? > yes
Enter User Name> Daniel
Enter Message> I\'m in!
$$
Any More Users? > yes
Enter User Name> Joey
Enter Message> Count me in.
We were in Tokyo; intersting!
$$
Any More Users? > yes
Enter User Name> Kevin
Enter Message> What\'s new?
we had a great time in the Outback.
$$
Any More Users? > no
The current messages are:
Kevin >>
What\'s new?
we had a great time in the Outback.
Joey >>
Count me in.
We were in Tokyo; intersting!
Daniel >>
I\'m in!
Kate >>
Get in the loop and join our War Eagle group!
Sunner in st. John\'s islands was fun.
How was your summer?
Solution
// operating system Ubunut,Linux,Mac
// filename messageService.cpp
#include
#include // for vector
#include
using namespace std;
/*Main function start*/
int main()
{
std::vector > store;// we are using vector for storing pair of name and message
std::vector >::reverse_iterator it;// used to reverse iteration
std::string name,message,input,choice;// variable for purpose
do{
std::cout<<\"Enter User Name> \";
std::cin>>name;
std::cout<<\"Enter Message> \";// prompt for user input
/* we are taking input from user as string
* if line contains $$ then it will break and come out from loop
* otherwise it will create pair and insert it into vector*/
while(std::getline(std::cin,input)){
if(input==\"$$\")
break;
message+=input+\"\ \";
}
store.push_back(std::pair(name,message));// inserting pair into vector
message=\"\";
std::cout<<\"Any More Users? > \";
std::cin>>choice;
}while(choice==\"yes\");
/*while loop break if choice value other then \"yes\.
Meet Elcodi, the flexible e-commerce components built on Symfony2Aldo Chiecchia
Elcodi is a suite of bundles for Symfony2 which aim to help developers build and quickly scale e-commerce websites. It is written in a clean, straightforward way to ease and smooth the learning curve and it promotes development productivity, SOLID, DRY principles without adding too many layers of indirection. Some of the goals we think we've reached: Balance between flexibility and development speed, Reusable components and foundations for writing custom Model. We'd like to share some insights on how we are approaching those topics by using rigorous coding standards, enforcing coherence and loose coupling, aiming for comprehensible and self-explaining code. See how you can leverage Symfony components for addressing similar challenges and let's discuss the rationales behind some good practices. And above all, see how to do it without pain, because we think that coding should always be a pleasure and crafting developer-friendly software is in our DNA!
Find the following in the thin section of a lime stone sample below (1).pdfAKPLAYZONEKOTA255
Find the following in the thin section of a lime stone sample below
Rock Type
Cleavage
Cement or matrix type
Presure of porousity
Fossil
Sorting and Texture
Minerological composition
Relief
Twinning
Pleochroism/interference colour.
Find the average annual growth rate of the dividends for each firm lis.pdfAKPLAYZONEKOTA255
Find the average annual growth rate of the dividends for each firm listed in the following table:
What is the average annual growth rate of the dividends paid by Loewen? 6 (Round to two
decimal places.) What is the average annual growth rate of the dividends paid by Morse? \%
(Round to two decimal places.) Data table (Click on the following icon p in order to copy its
contents into a spreadsheet.).
Find the ares of the shaded repon- The grach depicts the standard norm.pdfAKPLAYZONEKOTA255
Find the ares of the shaded repon. The grach depicts the standard normat distrbution of bont
decishy soores with mean and slanday deviation 1. The urea of stie studed region =.
Find the area of the shaded region- The graph depicts the standard nor (1).pdfAKPLAYZONEKOTA255
Find the area of the shaded region. The graph depicts the standard normal distribution with mean
0 and standard deviation 1. Click to view page 1 of the table. Click to view page 2 of the table.
The area of the shaded region is (Round to four decimal places as needed.) Standard Normal
Table (Page 1) NEGATIVE z Scores POSITIVE z Scores.
Find the area of the shaded region- The graph to the right depicts IQ (1).pdfAKPLAYZONEKOTA255
Find the area of the shaded region. The graph to the right depicts IQ scores of adults, and those
scores are normally distributed with a mean of 100 and a standard deviation of 15 Click to view
page 1 of the table. Click to view page 2 of the table The area of the shaded region is (Round to
four decimal places as needed.).
Find and install a Wi-Fi analyzer application on your computer or mobi.pdfAKPLAYZONEKOTA255
Find and install a Wi-Fi analyzer application on your computer or mobile device. Pick a location
and using the Wi-Fi analyzer to do the following:
Create and submit a document with your answers..
Find a current event tbqt relates to the case and write the connection.pdfAKPLAYZONEKOTA255
Find a current event tbqt relates to the case and write the connection between the event and the
case provide link to current event
Smart Phones: Promoting Communication Connectedness or Disconnectedness? In carly 2007.
Anjali Athavaley, writiag in The Wall. promoted incivality in the communications preccss. Street
Journal, observed that "/wlireless email devices */F]riends hardly call each other. People resist
proused to be largely the domain of harricd executives and tocols that call for verbal
communication. . . People protessionals. Now, the so-called Cirackkerry effect is don't like asing
their phones to make calls or listen beginning to afflice the masses. The Blackberry has be- to
voice mails." - Texting seems to be the preferted come ingrained in daily life, mucb hke the
cellpbonc and mode, cspecially for younger people, when communicomputer. "1 Indeed, since
this observation was penned, cating with others. stnartphones, lake the Black Berry, have becotre
ubiqui- Among college stiadents, texting is a daminant form of tous in the general population.
People froan all walks of commanication, and as nost any college student knowr, life, young and
old, all sociocconamic strata, etc., have texting goes on at inappropriate times, For instance,
texeabraced the potential of smartphones for communi- timg during class-even when it's not
allowed-is a comcating with ochers, searching for intormation, doing, mon occurtence, "la a
sarvey of 1,043 college stadents work, playing pames, and a myriad other applications. at the
University of New Hampshire, almost balf said - Elveryone froas stay-at-home parents to college
sta- they feel guilfy aboat texting during clask when at's not dents is depending on BlackBerrys
ee similat . . devices allowed, Even soy, texting is quaite commont 65 percent for busic daily
tasiks, such as checking sports scores, find- said they send at least one text message duaring a
typical ing directiops, enailing the children's baschall coach and clas."? keeping in up-to-the-
minute touch with friends." -They -People calling. fextirg and responding to e-masls at are
talking, ont mobile plones, checking entatl on hand- irappropriate tanes and places have becoene
an isse in held computers or intcerated coenmanicater, or getting both a profestional and business
context, s joseph De an instant or a text message on cither device. Some are Avala, reporting for
The Wall Street loarnal, notes peolistening to music and playing games on personal game ple
have a pervasive expectation that they have instant consoles, while others are checking sports
scores, watch- access to email, and rapid replies to one's mesiagek are ing replays, or cven
making dimmer reservations, No expected." matfer age, gender, national identify, or
iociocconomic Incivilify in interperional commanacation is manisatus, bread mobule device
adoption seces to know ao fested in the level of empathy that people display tobounds." ward
cach other. "Recent research has saiown.
Fill in the missing information on the cost of goods manufactured sche.pdfAKPLAYZONEKOTA255
Fill in the missing information on the cost of goods manufactured schedule of Sandhill
Manufacturing Company: (Assume all raw materials used were direct materials.) Direct labor
Manufacturing overhead Indirect labor Factory depreciation Factory utilities Total overhead
Total manufacturing costs Total cost of work in process Less: Work in process inventory (12/31)
Cost of goods manufactured.
Find (a) marginal distributions f(x) and g(y)- (b) E(X) and E(Y)- (c).pdfAKPLAYZONEKOTA255
Find (a) marginal distributions f ( x ) and g ( y ) , (b) E ( X ) and E ( Y ) , (c) Cov ( X , Y ) , ( d )
X , Y and (e) ( X , Y ) for the following joint distribution, (f) Are X and Y independent random
variables?.
Financial analysts forecast Safeco Corp's (SAF) growth rate for the fu.pdfAKPLAYZONEKOTA255
Financial analysts forecast Safeco Corp's (SAF) growth rate for the future to be 11 percent.
Safeco's recent dividend was $1.40 : What is the value of Safeco stock when the required retum
is 13 percent? (Round your answer to 2 decimal places.).
Finance RatesDetermine the monthly payment for the installment loan- C.pdfAKPLAYZONEKOTA255
Finance Rates Determine the monthly payment for the installment loan. Click the icon to view
the partial APR table. The monthly payment is $ (Round to the nearest cent as needed.).
Fill in the P(X-x) values to give a legitimate probability distributio.pdfAKPLAYZONEKOTA255
Fill in the P ( X = x ) values to give a legitimate probability distribution for the discrete random
variable X , whose possible values are 0 , 1 , 3 , 5 , and 6 ..
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
This is a presentation by Dada Robert in a Your Skill Boost masterclass organised by the Excellence Foundation for South Sudan (EFSS) on Saturday, the 25th and Sunday, the 26th of May 2024.
He discussed the concept of quality improvement, emphasizing its applicability to various aspects of life, including personal, project, and program improvements. He defined quality as doing the right thing at the right time in the right way to achieve the best possible results and discussed the concept of the "gap" between what we know and what we do, and how this gap represents the areas we need to improve. He explained the scientific approach to quality improvement, which involves systematic performance analysis, testing and learning, and implementing change ideas. He also highlighted the importance of client focus and a team approach to quality improvement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
Fill in the missing code for C++- Code from part B is below to make co.pdf
1. Fill in the missing code for C++.
Code from part B is below to make copy-pasting easier:
*-------------------------------------------------------------------------*/
/* * $ g++ -lpthread -g buyTheCandy.cpp -o buyTheCandy */
//-- Standard inclusions: --//
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
#include <pthread.h>
//-- Constants: --//
// PURPOSE: To the names of the children
const char* CHILD_NAME_ARRAY[] = {"Alice", "Bob", "Cathy", "David" };
// PURPOSE: To tell the number of children.
const int NUM_CHILDREN = sizeof(CHILD_NAME_ARRAY)/sizeof(const char*);
// PURPOSE: To tell the possible denominations of the Coin instances.
const int COIN_DENOMINATION_ARRAY[] = {1,5,10,25};
// PURPOSE: To tell the number of coins in each new Purse.
const int NUM_COINS_PER_NEW_PURSE = 4;
// PURPOSE: To tell the number of denominations.
const int NUM_DENOMINATIONS = sizeof(COIN_DENOMINATION_ARRAY)/sizeof(int);
// PURPOSE: To tell how much money needs to be collected to buy the candy.
const int CANDY_COST = 100;
//-- Classes: --//
2. // PURPOSE: To represent coins.
class Coin {
// I. Member vars:
// PURPOSE: To tell the denomination of '*this' Coin instance.
int denomination_;
// PURPOSE: To hold the address of the next Coin after '*this' one,
// or 'NULL' if there is no such Coin instance.
Coin* nextPtr_;
// II. Disallowed auto-generated methods:
// No default constructor:
Coin ();
// No copy constructor:
Coin (const Coin&);
// No copy assignment op:
Coin operator= (const Coin&);
protected :
// III. Protected methods:
public :
// IV. Constructor(s), assignment op(s), factory(s) and destructor:
// PURPOSE: To make a coin of denomination 'newDom'. No return value.
Coin (int newDom ) : denomination_(newDom), nextPtr_(NULL) { }
// PURPOSE: To release the resources of '*this'. No parameters.
// No return value.
3. ~Coin () { }
// V. Accessors:
// PURPOSE: To return the denomination of '*this' Coin instance.
// No parameters.
int getDenomination () const { return(denomination_); }
// PURPOSE: To return the address of the next Coin after '*this' one,
// or 'NULL' if there is no such Coin instance. No parameters.
Coin* getNextPtr () const { return(nextPtr_); }
// VI. Mutators:
// PURPOSE: To note that the Coin instance with address 'coinPtr' comes
// after '*this' one. No return value.
void setNextPtr (Coin* coinPtr ) { nextPtr_ = coinPtr; }
// VII. Methods that do main and misc work of class:
// PURPOSE: Try creating and return the address of a random coin.
// No parameters.
static Coin* makeRandom () {
// I. Application validity check:
// II. Try creating and return a coin:
return(new Coin(COIN_DENOMINATION_ARRAY[rand() % NUM_DENOMINATIONS]));
} };
// PURPOSE: To implement a list of Coin instances.
class Purse {
// 0. Constants:
enum { NO_OWNER_INDEX = -1 };
4. // I. Member var:
// PURPOSE: To hold the index of the name of the owner of '*this' Purse
// instance, or 'NO_OWNER_INDEX' if '*this' has no owner. int index_;
// ADD YOUR VARIABLES HERE
// II. Disallowed auto-generated methods:
// No copy constructor:
Purse (const Purse&);
// No copy-assignment op:
Purse operator= (const Purse&);
protected :
// III. Protected methods: public :
// IV. Constructor(s), assignment op(s), factory(s) and destructor:
// PURPOSE: To initialize '*this' to an empty purse
Purse () :
index_(NO_OWNER_INDEX) {
// INITIALIZE YOUR VARS HERE
}
// PURPOSE: To initialize '*this' Purse instance to have
// NUM_COINS_PER_NEW_PURSE random Coin instances owned by the child with
// index 'newIndex'. No return value.
Purse (int newIndex ) : index_(newIndex) {
// INITIALIZE YOUR VARS HERE
for (int i = 0; i < NUM_COINS_PER_NEW_PURSE; i++) {
5. addToBack(Coin::makeRandom());
}
}
// PURPOSE: To release the resources of '*this'. No parameters.
// No return value.
~Purse () {
Coin* run;
Coin* nextPtr;
// GET RID OF YOUR VARS HERE
}
// V. Accessors:
// PURPOSE: To return the index of the name of the owner of '*this' Purse
// instance, or 'NO_OWNER_INDEX' if '*this' has no owner.
int getIndex () const { return(index_); }
// PURPOSE: To return the name of the owner of '*this' Purse instance.
// No parameters.
const char* getOwnerNameCPtr() const { return( (getIndex() == NO_OWNER_INDEX) ?
"common" : CHILD_NAME_ARRAY[getIndex()] ); }
// PURPOSE: To return the value of the money in '*this' wallet.
// No parameters.
int getValue () const {
const Coin* run;
int sum = 0;
// YOUR CODE HERE
6. return(sum);
}
// PURPOSE: To tell the number of Coin instances in '*this'.
int getNumCoins () const { return(numCoins_); }
// VI. Mutators:
// PURPOSE: To add the Coin with address 'coinPtr' to '*this' Purse.
// No return value.
void addToBack (Coin* coinPtr ) {
// YOUR CODE HERE
}
// PURPOSE: To remove the Coin at the beginning of '*this' and return
// its address. No parameters.
Coin* removeFromFront () {
Coin* returnMe = NULL;
// YOUR CODE HERE
return(returnMe);
}
// VII. Methods that do main and misc. work of class:
// PURPOSE: To print the status of '*this' Purse to 'stdout'.
// No parameters. No return value.
void print () const {
printf ("%s has %d coins worth %d cents.n", getOwnerNameCPtr(),getNumCoins(),getValue()
); }
};
7. // PURPOSE: To implement a thread-safe version of Purse.
class CommonPurse : public Purse {
// I. Member vars:
// ADD YOUR VARIABLES HERE
// PURPOSE: To tell the current turn.
int turn_;
// II. Disallowed auto-generated methods:
// No copy constructor:
CommonPurse (const CommonPurse&);
// No copy assignment op:
CommonPurse operator= (const CommonPurse&);
protected :
// III. Protected methods:
public :
// IV. Constructor(s), assignment op(s), factory(s) and destructor:
// PURPOSE: To initialize '*this' to an empty shared Purse instance.
CommonPurse () : turn_(NUM_CHILDREN-1) {
// INITIALIZE YOUR VARS HERE
}
// PURPOSE: To release the resources of '*this'. No parameters.
// No return value.
~CommonPurse () {
// GET RID OF YOUR VARS HERE
8. }
// V. Accessors:
// PURPOSE: To tell the current turn.
int getTurn () const { return(turn_); }
// VI. Mutators:
// VII. Methods that do the main and misc. work of class:
// PURPOSE: To consolidate the Coin instances of '*donorPursePtr' into
// '*this' one.
// (Note to the professional C++ coders: Yeah, I know it is better to use
// call-by-reference. I use pointers for consistency.)
// PUT CODE 3 PLACES IN HERE . . . I WONDER WHERE?
void consolidate (Purse* donorPursePtr ) {
// I. Application validity check:
// II. Transfer the wealth:
while (getTurn() != donorPursePtr->getIndex()) {
printf ("%s: "I want candy! Let's put our money together!"n", donorPursePtr-
>getOwnerNameCPtr() );
}
while (donorPursePtr->getNumCoins() > 0) {
addToBack(donorPursePtr->removeFromFront());
}
printf ("%s: "I added my money."n", donorPursePtr->getOwnerNameCPtr() );
turn_--;
// III. Finished: } };
9. //-- Global vars: --//
// PURPOSE: To represent the shared, thread-safe Purse instance.
CommonPurse sharedPurse;
//-- Main functions: --//
// PURPOSE: To add the Coin instances in '*(Purse*)vPtr' to 'sharedPurse'.
// Returns 'NULL'.
void* consolidate (void* vPtr ) {
Purse* pursePtr = NULL; // CHANGE THAT NULL
// YOUR CODE HERE
return(NULL); }
// PURPOSE: To have the children add their money to 'sharedPurse', and
// then attempt to buy the candy. Ignores parameters. Returns /
/ 'EXIT_SUCCESS' to OS.
int main () {
// I. Application validity check:
// II. Try to buy candy:
// II.A. Initialize data-structures:
Purse* pursePtrArray[NUM_CHILDREN];
srand(getpid());
for (int i = 0; i < NUM_CHILDREN; i++) {
pursePtrArray[i] = new Purse(i);
pursePtrArray[i]->print();
}
10. // II.B. Consolidate the money:
// YOUR CODE HERE TO START THREADS
// II.C. Close program down:
// YOUR CODE HERE TO WAIT FOR THREADS
for (int i = 0; i < NUM_CHILDREN; i++) {
delete(pursePtrArray[i]);
}
printf("All: "We have %d cents. ",sharedPurse.getValue());
if (sharedPurse.getValue() >= CANDY_COST) {
printf("Yay! We can afford the candy!"n");
} else {
printf("Time to beg mom for more money!"n");
}
// III. Finished:
return(EXIT_SUCCESS);
}
A package of 4 candy candies cost 100 cents. (It can be 1 USD, 1 Euro, 1 whatever). Four
siblings (brothers or sisters) want a candy, and each has some money. Unfortunately, probably
none of the siblings has enough money to buy the candies by themself. So they will all pool their
money and jointly buy the candy. There are 3 classes: - Coin: Represents some money - Purse:
Implements a container (a linked list) of Coin instances. - Commonpurse: a thread-safe version
of purse Each sibling has their money in a purse instance. Additionally, there is a Commonpurse
called sharedpurse to which all siblings will add their money. Because each sibling is
implemented with its own thread, the individual Purse instances do not need to be thread safe.
However, sharedpurse needs to be made thread-safe because all four threads can access it. B.
Cut-and-paste the following: // PURPOSE: To have the children add their money to
'sharedPurse', and // then attempt to buy the candy. Ignores parameters. Returns //
'EXIT_SUCCESS' to OS. int main () { I/ I. Application validity check: // II. Try to buy candy: //
II.A. Initialize data-structures: Purse* pursePtrarray[NUM_CHILDREN]; srand (getpid()); for (
int i = 0 ; i < NUM_CHILDREN; i + + ) { purseptrarray[i] [ i ] new Purse ( i ) ; pursePtrarray
11. [i]->print (); } // II.B. Consolidate the money: I/ YOUR CODE HERE TO START THREADS
// II.C. Close program down: I/ YOUR CODE HERE TO WAIT FOR THREADS for (int i = 0 ;
i < NUM_CHILDREN; i + + ) { delete (purseptrarray [i]); } printf("All: "We have ofd cents. ",
sharedPurse.getValue()); if (sharedPurse.getValue ( ) >= CANDY_COST) { printf("Yay! We
can afford the candy! " "); } else { printf("Time to beg mom for more money! "n"); } // III.
Finished: return(EXIT_SUCCESS); } Purse must implement a linked list of Coin instances
using the coin methods getNext.ptr() and setNextPtr ( ). (No cheating and using C++ containers
like std: 1 ist, std x vector, etc.) 1. Give class Purse 3 member variables: - A coin to point to the
beginning of the list. - A Coin* to point to the end of the list. - An int that keeps track of the
length of the list. 2. Initialize your variables in the constructor. 3. Get rid of your list in the
destructor method: -Purse (). In C one gets memory with malloc ( ) and gives it back with free (
). However, in C++ one gets memory and builds an instance of an object with new, and one
dismantles the instance with delete(). Please have a local variable like coinPtr and say delete
(coinPtr) for cach coin in the list. 4. Make getvalue() loop thru the coin instances. It should sum
all the getDenomination () values of the coin instances, and return() the sum. 5. Make
getNumcoins () returns the how many coin instances are in the list. 6. Make addToBack () add
coinPtr to the back of the list. It should also increment your list-length variable. 7. Make
removefromfront () remove the first coin instance from the linked list. It should also decrement
your list-length variable, and return () the address of the first coin. D. Make it multi-threaded: 1.
In main () you will need an array of NUN_CHILDREN pthread_t instances for the bee hive
threads. a. In section II . declare your array variable. Have a loop that starts all
NUN_CHILDREN threads. Each thread should run consolidate (), and pass the address of the
corresponding purse as an argument. b. In section II . C wait for all child threads to finish. 2. In
consolidate (), argument vPtr comes in pointing to a Purse. Set pursePtr cqual to vPtr (you will
need to cast it). The only thing the function needs to do is run sharedpurse, consolidate
(purseptr). 3. Now run it! E. Make it thread-safe: Congratulations! If you got this far you have
made it multi-threaded, but not thread-safe. To make it thread-safe you will have to add some
mutex(es) and condition(s). You need to protect access to the linked list and turn_in
Commonpurse method consolidate( ) . a. It needs one pthread_mutex_t variable and an array of
NUM_CHILDREN + 1 pthread_cond_t instances. b. Initialize those variables in CommonPurse
() . c. Destroy those variables in CommonPurse ( ). d. Use them in consolidate ( ) in
Commonpurse. Where does the critical section begin? Where does the critical section end? Note:
all threads should wait on the pthread_cond_t with index donorpursePtr->getindex () + 1 . Also,
all threads should signal the pthread_cond_t with index donorPursePtr->getindex ( ). F.
Questions: How well did your program work before making it thread safe? How well did your
program work after making it thread safe? G. Sample output: $ ./buyTheCandy Alice has 4 coins
worth 41 cents. Bob has 4 coins worth 50 cents. Cathy has 4 coins worth 16 cents. David has 4
coins worth 50 cents. Bob: "I want candy! Let's put our money together!" Cathy: "I want candy!
Let's put our money together!" David: "I added my money." Alice: "I want candy! Let's put our
money together!" Cathy: "I added my money." Bob: "I added my money." Alice: "I added my
money." All: "We have 157 cents. Yay! We can afford the candy!" $ . /buyTheCandy Alice has 4
coins worth 12 cents. Bob has 4 coins worth 36 cents. Cathy has 4 coins worth 8 cents. David has
4 coins worth 16 cents. Alice: "I want candy! Let's put our money together!" Cathy: "I want
candy! Let's put our money together!" Bob: "I want candy! Let's put our money together!"
David: "I added my money." Cathy: "I added my money." Bob: "I added my money." Alice: "I
added my money." All: "We have 72 cents. Time to beg mom for more money!" $
12. ./buyTheCandy Alice has 4 coins worth 37 cents. Bob has 4 coins worth 22 cents. Cathy has 4
coins worth 80 cents. David has 4 coins worth 21 cents. Alice: "I want candy! Let's put our
money together!" Bob: "I want candy! Let's put our money together!" David: "I added my
money." Cathy: "I added my money." Bob: "I added my money." Alice: "I added my money."
All: "We have 160 cents. Yay! We can afford the candy!"