Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfmohammadirfan136964
Part 1)
#include
#include
#include
#include
/*Error handling for pthread_create and pthread_join*/
/*from the pthread_create man page*/
#define handle_error_en(en, msg) \\
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
/* # of running threads */
volatile int running_threads = 0;
pthread_t thread[3]; /*Descriptors for our 3 threads*/
int numOfElements;/*Total # of elements from the user*/
struct Results{ /*Struct to hold the statistical results*/
int min;
int max;
int average;
}Results;
/*This function finds the minimum element of an array*/
void *findMin(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
Results.min = elements[0]; /*set minimum to first element */
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] < Results.min){ /*if the current element is less than the current min*/
Results.min = elements[i]; /*store the new min*/
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the maximum element of an array*/
void *findMax(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] > Results.max){ /*store the new max*/
Results.max = elements[i];
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the average of an array*/
void *findAverage(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
Results.average += elements[i]; /*add element @ i to average*/
}
Results.average = Results.average/numOfElements; /*Divide the sum by the number of
elements*/
running_threads -= 1; /*Decrement running threads counter*/
return NULL;
}
/* This method accepts a int n(initial size of array) and
pointer to an array and returns # of elements in the array
*/
int getArrayInput(int n, int *array_ptr){
int input;/*Store user input */
int numberOfElements = 0;/*Number of Integers inputed*/
printf(\"Creating Dynamic Array...\ -\ \");
for(;;){ /*infinite loop*/
printf(\"Enter a positive value:\ Negative Number to Stop\ -\ \");
//Get Int from console, store at address of input
if (scanf(\"%d\",&input) != 1){
printf(\"\ Oops that wasn\'t an Integer\ lets try filling the array again\ Remember
INTEGERS only!\ \");
exit(EXIT_FAILURE);
}
if (input >= 0){
if (numberOfElements == n){
n += 1; //Make room for the current input
array_ptr = realloc(array_ptr, n * sizeof(int));//realloc array and set pointer
}
array_ptr[numberOfElements++] = input;//Store input at next empty element
} else {
printf(\"\ Number of Integers: %d\ \", numberOfElements);
break;
}
}
return numberOfElements;
}
/*This function joins our n number of threads */
void joinThreads(int numberOfThreads){
int i; /*count*/
int s; /*error #*/
while(numberOfThreads >= 0){ /*Join our threads*/
s = pthread_jo.
Here is the code- I can't get it to work- I need a function that finds.pdfdoshirajesh75
Here is the code: I can't get it to work. I need a function that finds the maximum of two integers.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* declare global variables including a table structure to hold scheduling
information */
/* optional: define a function that finds the maximum of two integers */
int total_processes = 0;
struct node{
int id;
int arrival;
int total_cycles;
int total_remaining;
int done;
int start;
int already_started;
int end;
int turnaround;
}* table = NULL;
typedef struct node table_type;
/***************************************************************/
void print_table() {
/*
1.declare local variables
2. print table header
3. for each process
4. print the contents (id, arrival time, total_cycles) of
each field of the table's index
5. if process has been scheduled ("done" field is 1,
6. print other contents (start time, end time, turnaround time)
*/
printf("ID/tArrival/tTotal/tStart/tEnd/tTurnaround/n");
printf("--------------------------------------------\n");
int i;
for(i=0; i < total_processes; i++){
printf("%d\t", table[i].id);
printf("%d\t", table[i].arrival);
printf("%d\t", table[i].total_cycles);
printf("%d\t", table[i].start);
printf("%d\t", table[i].end);
printf("%d\t", table[i].turnaround);
}
return;
}
/***************************************************************/
void procedure_1() {
/*"PROCEDURE FOR OPTION #1"
/* declare local variables */
/* prompt for total number of processes */
/* allocate memory for table to hold process parameters */
/* for each process */
/* prompt for process id, arrival time, and total cycle
time */
/* print contents of table */
int i;
printf("Enter total number of processes: ");
scanf("%d", &table[i].arrival);
table = (table_type *)malloc(total_processes * sizeof(table_type));
for(i = 0; i < total_processes; i++){
int arrival = -1;
int total_cycles = -1;
printf("Enter process id: ");
scanf("%d", &table[i].id);
}
printf("Enter arrival cycle for process P[%d]: ", i);
scanf("%d", &table[i].total_cycles);
/*
table[i].id = i;
table[i].arrival = -1;
table[i].total_cycles = -1;
table[i].start = -1;
table[i].end = -1;
table[i].turnaround = -1;
*/
print_table();
return;
}
/***************************************************************/
void procedure_2() {
/* "PROCEDURE FOR OPTION #2"
/* declare (and initilize when appropriate) local variables */
/* for each process, reset "done" field to 0 */
/* while there are still processes to schedule */
/* initilize the earliest arrival time to INT_MAX
(largest integer value) */
/* for each process not yet scheduled */
/* check if process has earlier arrival time
than current earliest and update */
/* set start time, end time, turnaround time, done fields
for unscheduled process with earliest arrival time */
/* update current cycle time and increment number of
processes scheduled */
/* print contents of table */
int i;
int done;
int min_value;
int current_cycle = 0;
int max;
int min_index;
table[i].done = 0;
while(done < 1){
min.
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxcarliotwaycave
Instruction:
1. Please read the two articles. (Kincheloe part 1 & 2)
2. Please choose some of the topics covered in each chapter, provide a brief summary (2-3 sentences) of those topics.
3. Then add your reflections, insights, or relevant experiences, etc. to help illustrate or expand upon the course.
4. This journal should be at least 400 words.
p5-start.cppp5-start.cpp/**
* @author Jane Student
* @cwid 123 45 678
* @class CSci 430, Spring 2018
* @ide Visual Studio Express 2010
* @date November 15, 2018
* @assg prog-04
*
* @description This program implements a simulation of process
* scheduling policies. In this program, we implement round-robin
* scheduling, where the time slice quantum can be specified as
* as a command line parameter. And we also implement shortest
* remaining time (SRT) scheduling policy
*/
#include<stdlib.h>
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<list>
usingnamespace std;
// global constants
// I won't test your round robin implementation with more than 20 processes
constint MAX_PROCESSES =20;
constint NO_PROCESS =0;
// Simple structure, holds all of the information about processes, their names
// arrival and service times, that we are to simulate.
typedefstruct
{
string processName;
int arrivalTime;
int serviceTime;
// holds running count of time slices for current time quantum, when
// serviceTime == quantum, time slice is up
int sliceTime;
// holds total number of time steps currently run, when == to
// serviceTime process is done
int totalTime;
// holds time when process finishes, used to calculate final stats,
// like T_r, T_r/T_s
int finishTime;
// a boolean flag, we will set this to true when the process is complete
bool finished;
}Process;
// Process table, holds table of information about processes we are simulating
typedefstruct
{
int numProcesses;
Process* process[MAX_PROCESSES];
}ProcessTable;
/** Create process table
* Allocate memory for a new process table. Load the process
* information from the simulation file into a table with the process
* information needed to perform the simulation. At the same time we
* initialize other information in process table for use in the
* simulation. Return the newly created ProcessTable
*
* @param processFilanem The name (char*) of the file to open and read
* the process information from.
* @param processTable This is actually a return parameter. This
* should be a pointer to an already allocated array of
* Process structure items. We will fill in this structure
* and return the process information.
*
* @returns ProcessTable* The newly allocated and initialized ProcessTable
* structure.
*/
ProcessTable* createProcessTable(char* processFilename)
{
ifstream simprocessfile(processFilename);
ProcessTable* processTable;
int pid;
string processName;
int arrivalTime;
int serviceTime;
// If we can't open file, abort and let ...
Part 1)#include stdio.h #include stdlib.h #include pthrea.pdfmohammadirfan136964
Part 1)
#include
#include
#include
#include
/*Error handling for pthread_create and pthread_join*/
/*from the pthread_create man page*/
#define handle_error_en(en, msg) \\
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
/* # of running threads */
volatile int running_threads = 0;
pthread_t thread[3]; /*Descriptors for our 3 threads*/
int numOfElements;/*Total # of elements from the user*/
struct Results{ /*Struct to hold the statistical results*/
int min;
int max;
int average;
}Results;
/*This function finds the minimum element of an array*/
void *findMin(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
Results.min = elements[0]; /*set minimum to first element */
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] < Results.min){ /*if the current element is less than the current min*/
Results.min = elements[i]; /*store the new min*/
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the maximum element of an array*/
void *findMax(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
if(elements[i] > Results.max){ /*store the new max*/
Results.max = elements[i];
}
}
running_threads -= 1; /*Decrement thread count*/
return NULL;
}
/*This function finds the average of an array*/
void *findAverage(void *array_ptr){
int i; /*counter*/
int *elements = (int*)array_ptr; /*re reference void array pointer*/
for(i = 0; i < numOfElements; i++){ /*iterate through array*/
Results.average += elements[i]; /*add element @ i to average*/
}
Results.average = Results.average/numOfElements; /*Divide the sum by the number of
elements*/
running_threads -= 1; /*Decrement running threads counter*/
return NULL;
}
/* This method accepts a int n(initial size of array) and
pointer to an array and returns # of elements in the array
*/
int getArrayInput(int n, int *array_ptr){
int input;/*Store user input */
int numberOfElements = 0;/*Number of Integers inputed*/
printf(\"Creating Dynamic Array...\ -\ \");
for(;;){ /*infinite loop*/
printf(\"Enter a positive value:\ Negative Number to Stop\ -\ \");
//Get Int from console, store at address of input
if (scanf(\"%d\",&input) != 1){
printf(\"\ Oops that wasn\'t an Integer\ lets try filling the array again\ Remember
INTEGERS only!\ \");
exit(EXIT_FAILURE);
}
if (input >= 0){
if (numberOfElements == n){
n += 1; //Make room for the current input
array_ptr = realloc(array_ptr, n * sizeof(int));//realloc array and set pointer
}
array_ptr[numberOfElements++] = input;//Store input at next empty element
} else {
printf(\"\ Number of Integers: %d\ \", numberOfElements);
break;
}
}
return numberOfElements;
}
/*This function joins our n number of threads */
void joinThreads(int numberOfThreads){
int i; /*count*/
int s; /*error #*/
while(numberOfThreads >= 0){ /*Join our threads*/
s = pthread_jo.
Here is the code- I can't get it to work- I need a function that finds.pdfdoshirajesh75
Here is the code: I can't get it to work. I need a function that finds the maximum of two integers.
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
/* declare global variables including a table structure to hold scheduling
information */
/* optional: define a function that finds the maximum of two integers */
int total_processes = 0;
struct node{
int id;
int arrival;
int total_cycles;
int total_remaining;
int done;
int start;
int already_started;
int end;
int turnaround;
}* table = NULL;
typedef struct node table_type;
/***************************************************************/
void print_table() {
/*
1.declare local variables
2. print table header
3. for each process
4. print the contents (id, arrival time, total_cycles) of
each field of the table's index
5. if process has been scheduled ("done" field is 1,
6. print other contents (start time, end time, turnaround time)
*/
printf("ID/tArrival/tTotal/tStart/tEnd/tTurnaround/n");
printf("--------------------------------------------\n");
int i;
for(i=0; i < total_processes; i++){
printf("%d\t", table[i].id);
printf("%d\t", table[i].arrival);
printf("%d\t", table[i].total_cycles);
printf("%d\t", table[i].start);
printf("%d\t", table[i].end);
printf("%d\t", table[i].turnaround);
}
return;
}
/***************************************************************/
void procedure_1() {
/*"PROCEDURE FOR OPTION #1"
/* declare local variables */
/* prompt for total number of processes */
/* allocate memory for table to hold process parameters */
/* for each process */
/* prompt for process id, arrival time, and total cycle
time */
/* print contents of table */
int i;
printf("Enter total number of processes: ");
scanf("%d", &table[i].arrival);
table = (table_type *)malloc(total_processes * sizeof(table_type));
for(i = 0; i < total_processes; i++){
int arrival = -1;
int total_cycles = -1;
printf("Enter process id: ");
scanf("%d", &table[i].id);
}
printf("Enter arrival cycle for process P[%d]: ", i);
scanf("%d", &table[i].total_cycles);
/*
table[i].id = i;
table[i].arrival = -1;
table[i].total_cycles = -1;
table[i].start = -1;
table[i].end = -1;
table[i].turnaround = -1;
*/
print_table();
return;
}
/***************************************************************/
void procedure_2() {
/* "PROCEDURE FOR OPTION #2"
/* declare (and initilize when appropriate) local variables */
/* for each process, reset "done" field to 0 */
/* while there are still processes to schedule */
/* initilize the earliest arrival time to INT_MAX
(largest integer value) */
/* for each process not yet scheduled */
/* check if process has earlier arrival time
than current earliest and update */
/* set start time, end time, turnaround time, done fields
for unscheduled process with earliest arrival time */
/* update current cycle time and increment number of
processes scheduled */
/* print contents of table */
int i;
int done;
int min_value;
int current_cycle = 0;
int max;
int min_index;
table[i].done = 0;
while(done < 1){
min.
Instruction1. Please read the two articles. (Kincheloe part 1 &.docxcarliotwaycave
Instruction:
1. Please read the two articles. (Kincheloe part 1 & 2)
2. Please choose some of the topics covered in each chapter, provide a brief summary (2-3 sentences) of those topics.
3. Then add your reflections, insights, or relevant experiences, etc. to help illustrate or expand upon the course.
4. This journal should be at least 400 words.
p5-start.cppp5-start.cpp/**
* @author Jane Student
* @cwid 123 45 678
* @class CSci 430, Spring 2018
* @ide Visual Studio Express 2010
* @date November 15, 2018
* @assg prog-04
*
* @description This program implements a simulation of process
* scheduling policies. In this program, we implement round-robin
* scheduling, where the time slice quantum can be specified as
* as a command line parameter. And we also implement shortest
* remaining time (SRT) scheduling policy
*/
#include<stdlib.h>
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
#include<list>
usingnamespace std;
// global constants
// I won't test your round robin implementation with more than 20 processes
constint MAX_PROCESSES =20;
constint NO_PROCESS =0;
// Simple structure, holds all of the information about processes, their names
// arrival and service times, that we are to simulate.
typedefstruct
{
string processName;
int arrivalTime;
int serviceTime;
// holds running count of time slices for current time quantum, when
// serviceTime == quantum, time slice is up
int sliceTime;
// holds total number of time steps currently run, when == to
// serviceTime process is done
int totalTime;
// holds time when process finishes, used to calculate final stats,
// like T_r, T_r/T_s
int finishTime;
// a boolean flag, we will set this to true when the process is complete
bool finished;
}Process;
// Process table, holds table of information about processes we are simulating
typedefstruct
{
int numProcesses;
Process* process[MAX_PROCESSES];
}ProcessTable;
/** Create process table
* Allocate memory for a new process table. Load the process
* information from the simulation file into a table with the process
* information needed to perform the simulation. At the same time we
* initialize other information in process table for use in the
* simulation. Return the newly created ProcessTable
*
* @param processFilanem The name (char*) of the file to open and read
* the process information from.
* @param processTable This is actually a return parameter. This
* should be a pointer to an already allocated array of
* Process structure items. We will fill in this structure
* and return the process information.
*
* @returns ProcessTable* The newly allocated and initialized ProcessTable
* structure.
*/
ProcessTable* createProcessTable(char* processFilename)
{
ifstream simprocessfile(processFilename);
ProcessTable* processTable;
int pid;
string processName;
int arrivalTime;
int serviceTime;
// If we can't open file, abort and let ...
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
in this assignment you are asked to write a simple driver program and set of functions (maybein
a library) that can be performed on a binary search tree.
Your program should allow user to insert/delete integer values into the binary search tree along
with several other operations on the binary search tree. You can use the code given in slides. But
this time your key will be int! Specifically, your program will ask user to enter a command and
related parameters (if any) in a loop, and then perform the given commands. Here is the list of
commands that your program must implement:
* insert
*find\'
*delete
*list inorder
*list preorder
*list postorder
*list levelorder
* max
* min
* height
*count
* sum
*quit
As always, make sure you release (free) the dynamically allocated memories if you allocate any
memory in your programs. So, before submitting your program, run it with valgrind to see if
there is any memory leakage
//my proggram in C
struct tree_node {
int data;
struct tree_node *left, *right;
}
typedef struct nodeT {
int key;
struct nodeT *left, *right;
} nodeT, *treeT;
int main(){
while (TRUE) {
printf(\"> \");
line = GetLine();
ch = toupper(line[0]);
switch (ch) {
case \'I\': insert(); break;
case \'F\': find(); break;
case \'D\': delete(); break;
case \'LI\': listInorder; break;
case \'LPR\': listPreorder(); break;
case \'LPO\': listPostorder(); break;
case \'MAX\': max(); break;
case \'min\': min(); break;
case \'H\': height(); break;
case \'C\': count(); break;
case \'S\': sum(); break;
case \'Q\': exit(0);
default:printf(\"Illegal command\ \"); break;
}
}
}
nodeT *FindNode(nodeT *t, int key){
while(t !=NULL) {
if (key == t->key) return t;
if (key < t->key) {
t = t->left;
} else {
t = t->right;
}
return NULL;
}
void delete(nodeT **p){
nodeT
*target;
target=*p;
if (target->left==NULL && target->right==NULL) {
*p=NULL;
} else if (target->left == NULL) {
*p=target->right;
} else
if (target->right == NULL) {
*p=target->left;
} else {
/* target has two children, see next slide */
}
free(target);
}
void listInorder(nodeT *T){
if (t != NULL) {
DisplayTree(t->left);
printf(“%d “, t->key);
DisplayTree(t->right);
}
}
void listPreorder(nodeT *t) {
if (t != NULL) {
printf(“%d “, t->key);
DisplayTree(t->left);
DisplayTree(t->right);
}
}
void listPostOrder(nodeT *t){
if (t != NULL) {
DisplayTree(t->left);
DisplayTree(t->right);
printf(“%d “, t->key);
}
}
void intsert(nodeT **tptr, int key){
nodeT*t, *tmp;
t=*tptr;
if (t == NULL) {
tmp=New(nodeT*);
tmp->key = key;
tmp->left=tmp->right=NULL;
*tptr=tmp;
return;
}
if (key < t->key) {
InsertNode
(&t->left, key);
} else {
InsertNode(&t->right, key);
}
}
int height(nodeT *t){
if (t == NULL)
return 0;
else
return (1 + maximumof(
height(t->left),
height(t->right)) );
}
int sum(struct tree_node *p){
if (p == NULL)
return 0;
else
return (p->data +
sum(p->left) +
sum(p->right) );
}
Solution
1. /*
2. * Java Program to Implement Binary Search Tree
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class BSTNode */
8. cl.
**** Computer Architecture ****
5 Subtract - 12 from 27 by using 8-bit signed magnitude, one's complement, two's complement
arithmetic, respectively. ( 2 pts 3=6 pts) 6 Add 12 to -27 by using 8-bit signed magnitude, one's
complement, two's complement arithmetic, respectively. ( 2 pts 3=6 pts) 7 Perform the following
multiplications by using Booth's algorithm, assuming 8-bit two's complement integers: (4 pts) 1) 12
x27 8 Multiply the value 64 (expressed by 8-bit signed two's complement representation) by 2. (2
pts) 9 Divide the value -64 (expressed by 8-bit signed two's complement representation) by 4 . ( 2
pts) 10 Express the following binary fraction in normalized floating-point form using the simple
model with excess-15 bias: (2 pts) 1) 34.0625.
write recursive function that calculates and returns the length of a.pdfarpitcomputronics
write recursive function that calculates and returns the length of a linked list
Solution
// C code to determine length of linked list recursively
#include
#include
// node of linked list
struct node
{
int key;
struct node* next;
};
// push key to linked list
void push(struct node** root, int new_element)
{
struct node* nodeNew = (struct node*) malloc(sizeof(struct node));
nodeNew->key = new_element;
nodeNew->next = (*root);
(*root) = nodeNew;
}
// recursively get length of linked list
int lengthLinkedlist(struct node* root)
{
// base case
if (root == NULL)
return 0;
// recursively call the function
return 1 + lengthLinkedlist(root->next);
}
int main()
{
struct node* root = NULL;
push(&root, 11);
push(&root, 34);
push(&root, 4);
push(&root, 23);
push(&root, 14);
push(&root, 88);
push(&root, 56);
push(&root, 84);
push(&root, 6);
/* Check the count function */
printf(\"Length of Linked list: %d\ \", lengthLinkedlist(root));
return 0;
}
/*
output:
Length of Linked list: 9
*/.
in c languageTo determine the maximum string length, we need to .pdfstopgolook
in c language
To determine the maximum string length, we need to create a new callback function that utilizes
an alternative user data structure. This callback function should adhere to the same format as
demonstrated in the example.
The data provided to our callback consists of:
A node containing the node->data pointer, which will store our string.
A userdata argument, represented as (void *), capable of holding any desired content. We
possess complete control over the content at this pointer location, as it will be whatever value we
have passed. Consequently, we can:
Establish a structure to store any pertinent values we require.
Transmit the address of this structure into the function.
use this code and just add your code where it says TO DO
#include
#include
#include
#include
#include "LLGeneric.h"
/** define the maximum length of a line that we can read */
#defineLINE_BUFFER_SIZE1024
/**
* We can use this as our "user data" to help us calculate the maximum
* length string
*
* Add anything else to this structure that you wish
*/
struct maxData {
size_t maxLenSoFar;
char *maxStringSoFar;
};
/**
* our "user function" or "callback" for printing.
*
* We know what "void *userdata" is going to be because it is
* simply what we pass in at the call below, so it is safe to
* cast back to a FILE * as that is what we passed it.
*
* This is called a "callback" as it "call back into" our own
* code from within a generic routine.
*/
int myFindLongestStringNode(GenericListNode *node, int index, void *userdata)
{
/**
* Add more code here. You will need to:
* - convert the GenericListNode payload in the field "data" to your
* known (char *) type
* - conver the (void *) userdata into your known (struct maxData *)
* type
* - use the fact that you can examine and store the values provided
* through the userdata to see what has been calculated by earlier
* calls to this function and update based on what you see here,
* in order to determine what the longest string is in the whole
* set of nodes.
*/
return 1;
}
int
doListActivities(GenericListNode *list)
{
/** create an instance of our structure for use as the user data */
struct maxData maxDataWorkingStruct;
int nProcessed = 0;
/** initialize our structure -- if you added fields, set them up here */
maxDataWorkingStruct.maxLenSoFar = 0;
maxDataWorkingStruct.maxStringSoFar = NULL;
/**
* TO DO: Iterate using the callback, which should calculate what
* the longest string in the list is
*/
nProcessed = lstPerformIterativeAction(
list, /* pointer to the first list node */
myFindLongestStringNode, /* pointer to our function */
(void *) &maxDataWorkingStruct);
/** print out the result */
printf("The longest string has %ld characters\n",
maxDataWorkingStruct.maxLenSoFar);
printf("The longest string is: %s\n",
maxDataWorkingStruct.maxStringSoFar);
return nProcessed;
}
/**
**Tools provided below here you won't need to edit -- they
**simply process the command line, and load and free the
**generic linked list and the st.
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxGordonpACKellyb
IN C LANGUAGE: I've been trying to finish this program for the last few days, and I'm stuck on one part of it, and I can't figure out what to do.
The goal is to read in a file (separated by commas), put the information into a linked list, and then sort that linked list by either first or last name using function pointers.
Everything I have so far works, aside from the fact that my output is never sorted. I'm doing something wrong with the listSort function, and I don't know what it is.
Can anyone please just take a look at what I have and offer a suggestion or solution? It might not even be an issue with the function itself, but something somewhere else.
I would greatly appreciate it.
Please do not make any changes to the variables in the structs. Month has to be a string, it cannot be an integer.
driver.c:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
int main(int argc, char* argv[]) {
//creating input and output files
FILE* in = NULL;
FILE* out = NULL;
node_t* head = NULL;
node_t* temp = NULL;
//checking for 4 command line arguments
assert(argc == 4);
//opening input file
in = fopen(argv[1], "r");
assert(in != NULL);
//opening output file
out = fopen(argv[2], "w");
assert(out != NULL);
int sortBy = atoi(argv[4]);
temp = createList(in, &head);
if(sortBy == 1) {
sortList(&head, compare_by_firstname);
}
else if(sortBy == 2) {
sortList(&head, compare_by_lastname);
}
printList(out, temp);
deleteList(&head);
//closing files
fclose(in);
fclose(out);
return 0;
}
functions.c:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdbool.h>
bool isLeapYear(int year) {
if(year % 4 != 0) {
return false;
}
else if(year % 100 != 0) {
return true;
}
else if(year % 400 != 0) {
return false;
}
else {
return true;
}
}
void printBorder(FILE* out)
{
int i = 0;
for(i = 0; i < 80; i++)
fprintf(out,"*");
fprintf(out, "\n");
}
bool checkInvalidDate(node_t *node) {
int year = (int)node->birthday.year;
if(node->birthday.day < 1 || node->birthday.year < 1) {
return true;
}
if(strcmp(node->birthday.month, "February") == 0) {
if(isLeapYear(year)) {
if(node->birthday.day > 29) {
return true;
}
}
else if(node->birthday.day > 28) {
return true;
}
}
else if((strcmp(node->birthday.month, "April") == 0) || (strcmp(node->birthday.month, "June") == 0) ||
(strcmp(node->birthday.month, "September") == 0) || (strcmp(node->birthday.month, "November") == 0)) {
if(node->birthday.day > 30) {
return true;
}
}
else {
if(node->birthday.day > 31) {
return true;
}
}
return false;
}
void add(node_t **node, node_t **head) {
node_t* current = *head;
while(current != NULL) {
//comparing first and last names to check for duplicates; if duplicate the info isn't added to the list
if((strcmp(current->firstName, (*node)->firstName) == 0) && (strcmp(current->lastName, (*node)->lastName) == 0)) {
return;
}
current = current->next;
}
//adding information as a node to the list
(*node.
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
/* Lab Assignment 4 CSE330 Spring 2014 */
/* Skeleton Code for ex0 of lab4 */
/* No code will be provided for ex1 of lab4 */
#include <stdio.h> /* for NULL */
#include <ctype.h> /* for atoi() */
#include <errno.h> /* for perror() */
#include <signal.h> /* for sigvec() etc. */
#include <sys/types.h> /* for <arpa/inet.h> */
#include <sys/socket.h> /* for PF_INET, etc. */
#include <netinet/in.h> /* for struct sockaddr_in */
#include <arpa/inet.h> /* for inet_addr() */
#include <sys/time.h>
#include "lab4.h"
/* this is in netinet/in.h; included here for reference only.
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
*/
/***************************************************************************/
#define LINESIZE 80
#define TYPE0TIMEOUT 3
#define TYPE1TIMEOUT 30
/* You should give a long timeout, like 30sec, otherwise */
/* duplicated responses from the server may cause some problem */
#define MAXRETRY 3
/***************************************************************************/
static char *RCSId="$Id: client2.c,v 4 2014/04/20 03:15:07 cse3300 Exp $";
/***************************************************************************/
/* some functions you may find useful if you implement them */
extern int stringToAddress(char *s, struct sockaddr_in *a);
extern int msgok(LABMSG *);
extern u_short msgchecksum(u_short *);
extern void alarmCatcher(void);
extern int tries; /* for retransmission routines */
int numtries;
/***** this will die ****/
FILE *logFile;
void die(char *s)
{
perror(s);
exit(2);
}
void startTimer(int secs)
{
alarm(secs);
}
void stopTimer(void)
{
alarm(0);
}
/* should change it by yourself if needed!!! */
void printResponse(LABMSG *mp, int ck)
{
int type;
mp->courseEtc = ntohs(mp->courseEtc);
type = ( (mp->courseEtc & MESSAGETYPE) !=0)?1:0;
printf("course=%d, Type=%d\n", mp->courseEtc&0x3fff,type);
if (ntohl(mp->cookie) != ck)
printf("Cookies don't match: sent %x received %x\n",mp->cookie,ck);
if (mp->courseEtc & REQRESP)
printf("response ");
else {
printf("request??\n");
return;
}
mp->result = ntohs(mp->result);
/*printf(" result = %x: ",mp->result);*/
if (mp->result&TRANSOUTCOME) { /* Check outcome */
printf("error: ");
switch (mp->result & 0x7fff) {
case ERROR_CHECKSUM:
printf("checksum failure\n");
break;
case ERROR_SYNTAX:
printf("syntax error\n");
break;
case ERROR_UNKSSN:
printf("unknown SSN %d\n", ntohl(mp->reqSSN) );
break;
case ERROR_SERVER:
printf("Unspecified Server Error\n");
default:
printf("Unknown Error.\n");
} /* case switch */
} else { /* successful transaction */
if(type)printf("Test succeeded.");
if (!type) /* Type 0 -- print SSN and Response */
printf(": %d -> %d\n", ntohl(mp->reqSSN), mp->result&0x7fff);
else
printf("\n"); /* XXX print number of responses */
}
}
/*-----------------------------------*/
/* added by ZXC:
this fun ...
lab08/build.bat
@echo off
cls
set DRIVE_LETTER=%1:
set PATH=%DRIVE_LETTER%\MinGW\bin;%DRIVE_LETTER%\MinGW\msys\1.0\bin;%DRIVE_LETTER%\MinGW\gtkmm3\bin;%DRIVE_LETTER%\MinGW\gtk\bin;c:\Windows;c:\Windows\system32
set PROJECT_PATH=.
make DRIVE_LETTER="%DRIVE_LETTER%" PROJECT_DIR="%PROJECT_PATH%"
lab08/CSC2110/CD.h
#if !defined CD_H
#define CD_H
#include "Song.h"
#include "Text.h"
using CSC2110::String;
#include "ListArray.h"
using CSC2110::ListArray;
namespace CSC2110
{
class CD
{
private:
String* artist;
String* title;
int year;
int rating;
int num_tracks;
ListArray<Song>* songs;
public:
CD(String* artist, String* title, int year, int rating, int num_tracks);
virtual ~CD();
String* getKey();
void addSong(String* title, String* length);
void displayCD();
static ListArray<CD>* readCDs(const char* file_name);
static int compare_items(CD* one, CD* two);
static int compare_keys(String* sk, CD* cd);
static char getRadixChar(CD* cd, int index); //1-based
};
}
#endif
lab08/CSC2110/Double.h
#if !defined (DOUBLE_H)
#define DOUBLE_H
namespace CSC2110
{
class Double
{
private:
double value;
public:
Double(double val);
~Double();
double getValue();
};
}
#endif
lab08/CSC2110/HighPerformanceCounter.h
#if !defined (HIGHPERFORMANCECOUNTER_H)
#define HIGHPERFORMANCECOUNTER_H
namespace CSC2110
{
class HighPerformanceCounter
{
private:
double micro_spt; //micro_seconds per tick
HighPerformanceCounter();
static HighPerformanceCounter* hpc;
static int getTicksPerSecond();
public:
virtual ~HighPerformanceCounter();
static HighPerformanceCounter* getHighPerformanceCounter();
int getCurrentTimeInTicks();
double getTimeDifferenceInMicroSeconds(int start_time, int end_time);
};
}
#endif
lab08/CSC2110/Integer.h
#if !defined (INTEGER_H)
#define INTEGER_H
namespace CSC2110
{
class Integer
{
private:
int value;
public:
Integer(int val);
virtual ~Integer();
int getValue();
};
}
#endif
lab08/CSC2110/Keyboard.h
#if !defined KEYBOARD_H
#define KEYBOARD_H
#include "Text.h"
using CSC2110::String;
#include <string>
using namespace std;
namespace CSC2110
{
class Keyboard
{
private:
Keyboard();
public:
virtual ~Keyboard();
static Keyboard* getKeyboard();
//pre: the string (character literal) that will prompt the user for input
//post: the input read from the keyboard interpreted as an int is returned
int readInt(string prompt);
int getValidatedInt(string prompt, int min, int max);
//pre: the string that will prompt the user for input
//post: the input read from the keyboard interpreted as a double is returned
double readDouble(string prompt);
double getValidatedDouble(string prom ...
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
operating system ubuntu,linux,MacProgram will work only if you g.pdfaptcomputerzone
//operating system ubuntu,linux,Mac
Program will work only if you give command like
sum 2 3 or
sum 4 (sub 4 3)
#include
#include
#include
#include
/*Sum function implementation*/
int sum(int number1,int number2){
return number1+number2;
}
/*sub function implementation*/
int sub(int number1,int number2){
return number1-number2;
}
/*mul function implementation*/
int mul(int number1,int number2){
return number1*number2;
}
/*divide function implementation*/
float divide(int number1,int number2){
if(number2==0){
printf(\"We can not divide by 0 \ \");
return 0.0f;
}
return (float)(number1/number2);
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if (pointer == NULL)
{
printf(\"Unable to allocate memory.\ \");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = \'\\0\';
return pointer;
}
/*Main Function start*/
int main(int argc, char *argv[]){
/*Variable declarations*/
int number1,number2;
char *operator,*str1,*str2;
char line[50];
char s[2] = \" \";
int errorFlag=0;// checking if user entered more then one operands
while(1){
/*User input*/
printf(\"Please Enter the command \");
gets(line);
int len=0;
for(int i=0; line[i]!=\'\\0\'; ++i){len++;}
if(len==0){
return 1;
}
/*Spliting into Tokens*/
operator = strtok(line, \" \");
if(strcmp(operator,\"bye\")==0){
break;
}
/*String to integer --- token1*/
number1=atoi(strtok(NULL, s));
/*Removing ( and ) from String*/
str2=strtok(NULL, s);
char *content;int length=0;
for(int i=0; str2[i]!=\'\\0\'; ++i){length++;}
if(str2[0]==\'(\'){
content=substring(str2,2,length-1);
char *opr=content;
int n1=atoi(strtok(NULL, s));
int n2=atoi(strtok(NULL, s));
/*If user entered more then two operands then it will return some token otherwise it will
return NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}else{
if(strcmp(opr,\"sum\")==0){
number2=sum(n1,n2);
}else if(strcmp(opr,\"sub\")==0){
number2=sub(n1,n2);
}else if(strcmp(opr,\"mul\")==0){
number2=mul(n1,n2);
} else if(strcmp(opr,\"div\")==0){
number2=divide(n1,n2);
}
}
}else{
number2=atoi(str2);
/*If user entered more then two operands then it will return some token otherwise it will return
NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}
}
if(errorFlag!=1){
/*Checking operator by strcmp function*/
if(strcmp(operator,\"sum\")==0){
printf(\"Result %d \ \",sum(number1,number2));
}else if(strcmp(operator,\"sub\")==0){
printf(\"Result %d \ \",sub(number1,number2));
}else if(strcmp(operator,\"mul\")==0){
printf(\"Result %d \ \",mul(number1,number2));
} else if(strcmp(operator,\"div\")==0){
printf(\"Result %.2f \ \",divide(number1,number2));
}
}
}
return 0;
}
/*******************Output***********************/
gopal@gopal:~/Desktop/chegg$ gcc Calculator.c
Calculator.c: In function ‘main’:
Calculator.c:67:3: warning: implici.
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfcallawaycorb73779
C++ problem
Part 1: Recursive Print (40 pts)
Please write the recursive List reverse print function, whose iterative version we wrote in class.
Below are the function signatures for the functions you are going to need:
public:
/**Additional Operations*/
void print_reverse();
//Wrapper function that calls the reverse helper function to print a list in reverse
//prints nothing if the List is empty
private:
void reverse(Nodeptr node);
//Helper function for the public printReverse() function.
//Recursively prints the data in a List in reverse.
Why do we need the private helper function here?
Since we are going to be reversing our list node by node, in a recursive fashion, we want to pass
a one node at a time to our reverse function.
However, since our nodes are private, we cannot access them if we call the function inside of
main.
Add these function signatures to your List.h file along with your other function prototypes inside
the class definition.
Make sure that you place the reverse function inside the private portion of your List class
definition and the print_reverse function prototype to the public portion of your List class
definition.
Now, implement these two functions inside of List.h, under your section for additional
operations.
Important: Test each function carefully inside of your ListTest.cpp to make sure that it is
working properly.
Part 2: Adding an Index to Your List Nodes (20 pts)
Next, you will add the following functions to your List.h
/**Accessor Functions*/
int get_index();
//Indicates the index of the Node where the iterator is currently pointing
//Nodes are numbered from 1 to length of the list
//Pre: length != 0
//Pre: !off_end()
...
int List::get_index()
{
//Implement the function here
}
/**Manipulation Procedures*/
void scroll_to_index(int index);
//Moves the iterator to the node whose index is specified by the user
//Pre: length != 0
...
void scroll_to_index(int index)
{
//Implement function here
}
Part 3: Implementing Search as Part of Your List (40 pts)
Now, we are going to add two search functions to our List so that we can search for elements in
our List.
The first of these functions is going to be a simple linear search function.
You will need to add the following function prototype and function definition to your List.h:
/**Additional Operations*/
int linear_search(listitem item);
//Searchs the list, element by element, from the start of the List to the end of the List
//Returns the index of the element, if it is found in the List
//Returns -1 if the element is not in the List
//Pre: length != 0
...
int List::linear_search(listitem item)
{
//Implement the function here
}
You are also going to add a function to perform recursive binary search on your List.
You will need to add the following function prototype and function definition to your List.h:
int binary_search(int low, int high, listitem item);
//Recursively searchs the list by dividing the search space in half
//Returns the index of the element, if it is fo.
My question is pretty simple, I just want to know how to call my ope.pdfjeetumordhani
My question is pretty simple, I just want to know how to call my operator== function in
Stack.cpp using a list function.
Here is what I meant. This is my Stack.h file:
class Stack {
public:
/**constructors and destructors*/
Stack();
Stack(const Stack &S);
~Stack();
void pop();
void push(int data);
bool operator==(const Stack &S);
[ .......]
private:
List stack;
};
Here is my List.h file:
template
class List {
private:
struct Node {
listitem data;
Node* next;
Node* previous;
Node(listitem data) :
next(NULL), previous(NULL), data(data) {
}
};
typedef struct Node* NodePtr;
NodePtr start;
NodePtr end;
NodePtr cursor;
int length;
public:
........
bool operator==(const List &list);
[.......] }
[........]
template
bool List::operator==(const List& list) {
if (length != list.length)
return false;
NodePtr temp1 = start;
NodePtr temp2 = list.start;
while (temp1 != NULL) {
if (temp1->data != temp2->data)
return false;
temp1 = temp1->next;
temp2 = temp2->next;
}
return true;
}
[......]
So I already define my functions in List.h and I only need to call my function from List again in
my Stack.cpp file. For example from my Stack.cpp:
Stack::Stack(const Stack &S) :
stack(S.stack) {
}
void Stack::pop() {
stack.remove_start();
}
[......]
And I don\'t know how to call my operator== function in Stack.cpp from the List.h like the way
above. This is what my guess so far but did not work:
bool Stack::operator==(const Stack &S) {
stack.operator==(S.stack);
}
Thank you
Solution
When we wish to make a comparison, such as in an if statement, we use the double equals sign
(==).
1)bool operator==(const Stack &S); [ .......]
It means whatever the boolean operator it should be belongs to stack or equal to.
2) bool operator==(const List &list);
Likewise link list also compare with the constructor link list.
and constructor need not to call explicitly. it will call itself when program called first..
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfmdameer02
Merge Sort implementation in C++ The implementation for Mergesort given in Section 7.4 takes
an array as input and soils that array. At the beginning of Section 7.4 there is a simple
pseudocode implementation for sorting a linked list using Mergesort. Implement both a linked
list-based version of Mergesort and the array-based version of Mergesort. and compare and
analyze their running times.
Solution
/* Merger sort array-based version */
/* C program for Merge Sort */
#include
#include
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf(\"%d \", A[i]);
printf(\"\ \");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf(\"Given array is \ \");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf(\"\ Sorted array is \ \");
printArray(arr, arr_size);
return 0;
}
--------------------------------------------------------------------------------------------------------------------
/* merge sort link-list version
#include
#include
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* function prototypes */
struct node* SortedMerge(struct node* a, struct node* b);
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef);
/* sorts the linked list by changing next pointers (not data) */
void MergeSort(struct node** headRef)
{
struct node* head = *headRef;
struct node* a;
struct node* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
{
return;
}
/* Split head into \'a\' and \'b\' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
MergeSort(&a);
MergeSort(&b);
/* answer = merge the two sorted lists together */
*.
The purpose of this C++ programming project is to allow the student .pdfRahul04August
The purpose of this C++ programming project is to allow the student to perform parallel array
and multidimensional array processing. The logic for string and Cstring has already been
completed, so the assignment can be started before we actually cover string and Cstring in detail.
This program has the following three menu options:
Solution
/*
This program uses simple arrays, multidimensional arrays, cstrings, strings, and files.
It allows a payroll clerk to choose an option from a menu. The choices are:
A: List the Payroll Information by Employee Name
B: Search Payroll Information by Employee Name
X: Exit the Payroll Information Module
The following items for each employee are saved in the file p10.txt:
Employee ID (1000 - 9999)
Last Name (15 characters)
First Name (15 characters)
Rate (5.00 - 10.00)
Hours W1,W2,W3,W4 (0-60)
*/
#include // file processing
#include // cin and cout
#include // toupper
#include // setw
#include // cstring functions strlen, strcmp, strcpy stored in string.h
#include // string class
#define stricmp strcasecmp
#define strnicmp strncasecmp
using namespace std;
//Disable warning messages C4267 C4996.
//To see the warnings, comment out the following line.
//#pragma warning( disable : 4267 4996)
//Warning C4267: coversion from size_t to int, possible lost of data
//size_t is a data type defined in and is an unsigned integer.
//The function strlen returns a value of the type size_t, but in
//searchByName we assign the returned value to an int.
//We could also declare the variable as size_t instead of int.
// size_t stringLength;
//Warning C4996: strnicmp strcpy, stricmp was declared deprecated, means
//the compiler encountered a function that was marked with deprecated.
//The deprecated function may no longer be supported in a future release.
//Global Constants
//When using to declare arrays, must be defined with const modifier
const int ARRAY_SIZE = 20, HOURS_SIZE = 4, NAME_SIZE = 16;
//Declare arrays as global so we don\'t have to pass the arrays to each function.
//Normally we wouldn\'t declare variables that change values a global.
int employeeId[ARRAY_SIZE];
string firstName[ARRAY_SIZE];
char lastName[ARRAY_SIZE][NAME_SIZE];
double rate[ARRAY_SIZE];
int hours[ARRAY_SIZE][HOURS_SIZE];
int numberOfEmps; //count of how many employees were loaded into arrays
int sumHours[ARRAY_SIZE] = {0}; //initialize arrays to zero by providing a
double avgHours[ARRAY_SIZE] = {0}; //value for the first element in the array
//Function Prototypes
void loadArray( );
void sumAndComputeAvgHours( );
void listByName( );
void searchByName( );
void sortByName( );
void swapValues(int i, int minIndex);
void listEmployees( );
void listEmployeesHeadings( );
void listEmployeesDetails(int i);
void listEmployeesTotals( );
void displayContinuePrompt( );
//Program starts here
int main()
{
//Declare and initialize local main variables
char choice; //menu option
//Load the arrays with data
loadArray();
//Sum and compute the average hours
sumAndComputeAv.
Program In C You are required to write an interactive C program that.pdfamitbagga0808
Program In C You are required to write an interactive C program that prompts the user for
commands, accepts commands from the keyboard (stdin) and executes those commands. When a
command requires output, it must be written to stdout. The program must continue to accept and
process commands until the user types the end command ourput, it must be writen to stdout. The
program must continue to accept and proces.commands The program deals with linked lists.
Each node of such a list contains a string of length at most 10, a positive integer (i.e., an integer
value 2 1) and a pointer to the next node of the list. For any node, the string and the integer
stored in that node will be referred to as the symbol and count for that node respectively. At all
times, the list must satisfy the following two important properties. 1. The symbols appearing in
the list are all distinct; that is, no two nodes have the same symbol. 2. When the list is scanned
from left to right, the counts must be in non-increasing order. An example of such a linked list is
shown below. Search 4 Maxval4 begin/ Loop head
Solution
/**********************************************/
/****** NAMES ******************** COMMANDS ***/
/* Insert Command : ins str */
/* Delete Command : del str */
/* Forced Delete Command : fde val */
/* Print Statistics Command : pst */
/* Print List Command : prl */
/* Print using Count Range Command: pcr v1 v2 */
/* Print Prefix Command : ppr str */
/* Print Suffix Command : psu str */
/* End Command : end */
/***********************************************/
#include
#include
#include
#define CSIZE 4
#define SSIZE 11
/* Struct for each node in the linked list */
struct node
{
int count;
char symbol[SSIZE];
struct node *next;
};
struct node *head;
/* Prototypes for the functions */
void insert(char *);
void delete(char *);
void forced_delete(int value);
void print_stats();
void print_list();
void print_count(int, int);
void print_prefix(char pre[]);
void print_suffix(char suf[]);
void sort_list();
/****************
** Main Method **
****************/
int main(void)
{
int count;
char symbol[SSIZE];
char cmd[CSIZE];
int v1;
int v2;
/* Enter commands */
printf(\"Command? \"); fflush(stdout);
scanf(\"%s\", cmd);
/* Check for command*/
while(strcmp(cmd,\"end\") != 0)
{
/* check which function to use */
if(strcmp(cmd,\"ins\") == 0) { scanf(\"%s\", symbol); insert(symbol); }
if(strcmp(cmd,\"del\") == 0) { scanf(\"%s\", symbol); delete(symbol); }
else if(strcmp(cmd,\"fde\")==0){scanf(\"%d\",&count); forced_delete(count); }
if(strcmp(cmd,\"pst\") == 0) { print_stats();}
if(strcmp(cmd,\"prl\") == 0) { print_list(); }
if(strcmp(cmd,\"pcr\") == 0) { scanf(\"%d %d\",&v1,&v2); print_count(v1,v2); }
if(strcmp(cmd,\"ppr\") == 0) { scanf(\"%s\", symbol); print_prefix(symbol);}
if(strcmp(cmd,\"psu\") == 0) { scanf(\"%s\", symbol); print_suffix(symbol);}
printf(\"Command? \"); fflush(stdout);
scanf(\"%s\", cmd);
}// End of While Loop
return 0;
}// End of main method
/*********.
Per the text, computers are playing an increasingly important role i.docxodiliagilby
Per the text, computers are playing an increasingly important role in the practice of law. Successful paralegals must be comfortable with using electronic databases and research tools.
Write a two to three (2-3) page paper in which you:
Discuss a paralegal’s ethical obligation to conduct competent electronic research. Provide two (2) examples of the potential consequences of inept electronic research practices.
Determine whether or not traditional reference materials (e.g., State and Federal Reporters, West’s Encyclopedia, etc.) can be as current as electronic resources. Provide two (2) advantages and two (2) disadvantages to using traditional resource materials.
Use at least two (2) quality references.
Note:
Wikipedia and other Websites do not qualify as academic resources.
THIS IS PART 1.
.
Pennsylvania was the leader in sentencing and correctional reform .docxodiliagilby
Pennsylvania was the leader in sentencing and correctional reform in the early history of the United States. Discuss what groups were associated with this reform.
Why did they want the reform?
Examine whether it was successful and if the reform brought forth further changes.
What influences does the system have on the correctional system today?
What influences have changed? Why?
Use the Internet, library, and any other resources available to research your answer. Submit a 4 page paper (double-spaced) to your instructor. Support your reasoning with outside sources. Be sure to reference all sources using APA style.
The following will be the grading criteria for this assignment:
20%:
Discuss what groups were associated with this reform.
10%:
Why did they want the reform?
20%:
Examine whether it was successful and if the reform brought forth further changes.
25%:
What direct influences do you see the Pennsylvania system in the correctional systems used today?
25%:
What influences have changed? Why?
4 pages. APA format. No plagerism. 5 sources referenced throughout the paper. Reference Page and Abstract.
.
More Related Content
Similar to __MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
How do you stop infinite loop? Because I believe that it is making an infinite circular list.
c++ code:
Here is the list class:
#ifndef LIN_J_LIST
#define LIN_J_LIST
typedef unsigned int uint;
#include
#include
using namespace std;
/**
* a simplified generic singly linked list class to illustrate C++ concepts
* @author Jerry Lin
* @version 2/17/17
*/
template< typename Object >
class List
{
private:
/**
* A class to store data and provide a link to the next node in the list
*/
class Node
{
public:
/**
* The constructor
* @param data the data to be stored in this node
*/
explicit Node( const Object & data )
: data{ data }, next{ nullptr } {}
Object data;
Node * next;
};
public:
/**
* The constructor for an empty list
*/
List()
: size{ 0 }, first{ nullptr }, last{ nullptr } {}
/**
* the copy constructor-creates and copy the list
*/
List( List && rhs ) = delete;
List( const List & rhs )
{
count = 0;
size = 0;
if(rhs.size != 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first;
size++;
while(current->next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op.
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode->next;
size++;
}
}
// you document and implement this method
}
/**
* the operator= method-copies the list
*/
List & operator=( List && rhs) = delete;
List & operator=( const List & rhs )
{
count = 0;
size = 0;
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
if(rhs.size!= 0)
{
push_front(rhs.front());
Node * current = rhs.first;
Node * tempNode = first; //create a temporary to store
size++;
while(current -> next != nullptr)
{
current = current->next;
Node *newNode = new Node(current->data); //transfer the data. basic op
count++;
tempNode->next = newNode;
last = newNode;
tempNode = tempNode -> next;
size++;
}
}
return *this;
// you document and implement this method
}
/**
* accessor
* @return count
*/
int get_count() const
{
return count;
}
/**
* The destructor that gets rid of everything that\'s in the list and
* resets it to empty. If the list is already empty, do nothing.
*/
~List()
{
if( size != 0 )
{
Node * current = first;
Node * temp;
while( current != nullptr )
{
temp = current;
current = current->next;
delete temp;
}
}
}
/**
* Put a new element onto the beginning of the list
* @param item the data the new element will contain
*/
void push_front( const Object& item )
{
Node * new_node = new Node( item );//basic op.
if(is_empty())
{
last = new_node;
}
else
{
new_node->next = first;
}
first = new_node;
size++;
/* you complete the rest */
}
/**
* Remove the element that\'s at the front of the list. Causes an
* assertion error if the list is empty.
*/
void pop_front()
{
assert( !is_empty() );
Node * temp = first;
if( first == last )
{
first = last = nullptr;
}
else
{
first = first->next;
}
delete temp;
size--;
}
/**
* Accessor to return the da.
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
in this assignment you are asked to write a simple driver program and set of functions (maybein
a library) that can be performed on a binary search tree.
Your program should allow user to insert/delete integer values into the binary search tree along
with several other operations on the binary search tree. You can use the code given in slides. But
this time your key will be int! Specifically, your program will ask user to enter a command and
related parameters (if any) in a loop, and then perform the given commands. Here is the list of
commands that your program must implement:
* insert
*find\'
*delete
*list inorder
*list preorder
*list postorder
*list levelorder
* max
* min
* height
*count
* sum
*quit
As always, make sure you release (free) the dynamically allocated memories if you allocate any
memory in your programs. So, before submitting your program, run it with valgrind to see if
there is any memory leakage
//my proggram in C
struct tree_node {
int data;
struct tree_node *left, *right;
}
typedef struct nodeT {
int key;
struct nodeT *left, *right;
} nodeT, *treeT;
int main(){
while (TRUE) {
printf(\"> \");
line = GetLine();
ch = toupper(line[0]);
switch (ch) {
case \'I\': insert(); break;
case \'F\': find(); break;
case \'D\': delete(); break;
case \'LI\': listInorder; break;
case \'LPR\': listPreorder(); break;
case \'LPO\': listPostorder(); break;
case \'MAX\': max(); break;
case \'min\': min(); break;
case \'H\': height(); break;
case \'C\': count(); break;
case \'S\': sum(); break;
case \'Q\': exit(0);
default:printf(\"Illegal command\ \"); break;
}
}
}
nodeT *FindNode(nodeT *t, int key){
while(t !=NULL) {
if (key == t->key) return t;
if (key < t->key) {
t = t->left;
} else {
t = t->right;
}
return NULL;
}
void delete(nodeT **p){
nodeT
*target;
target=*p;
if (target->left==NULL && target->right==NULL) {
*p=NULL;
} else if (target->left == NULL) {
*p=target->right;
} else
if (target->right == NULL) {
*p=target->left;
} else {
/* target has two children, see next slide */
}
free(target);
}
void listInorder(nodeT *T){
if (t != NULL) {
DisplayTree(t->left);
printf(“%d “, t->key);
DisplayTree(t->right);
}
}
void listPreorder(nodeT *t) {
if (t != NULL) {
printf(“%d “, t->key);
DisplayTree(t->left);
DisplayTree(t->right);
}
}
void listPostOrder(nodeT *t){
if (t != NULL) {
DisplayTree(t->left);
DisplayTree(t->right);
printf(“%d “, t->key);
}
}
void intsert(nodeT **tptr, int key){
nodeT*t, *tmp;
t=*tptr;
if (t == NULL) {
tmp=New(nodeT*);
tmp->key = key;
tmp->left=tmp->right=NULL;
*tptr=tmp;
return;
}
if (key < t->key) {
InsertNode
(&t->left, key);
} else {
InsertNode(&t->right, key);
}
}
int height(nodeT *t){
if (t == NULL)
return 0;
else
return (1 + maximumof(
height(t->left),
height(t->right)) );
}
int sum(struct tree_node *p){
if (p == NULL)
return 0;
else
return (p->data +
sum(p->left) +
sum(p->right) );
}
Solution
1. /*
2. * Java Program to Implement Binary Search Tree
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class BSTNode */
8. cl.
**** Computer Architecture ****
5 Subtract - 12 from 27 by using 8-bit signed magnitude, one's complement, two's complement
arithmetic, respectively. ( 2 pts 3=6 pts) 6 Add 12 to -27 by using 8-bit signed magnitude, one's
complement, two's complement arithmetic, respectively. ( 2 pts 3=6 pts) 7 Perform the following
multiplications by using Booth's algorithm, assuming 8-bit two's complement integers: (4 pts) 1) 12
x27 8 Multiply the value 64 (expressed by 8-bit signed two's complement representation) by 2. (2
pts) 9 Divide the value -64 (expressed by 8-bit signed two's complement representation) by 4 . ( 2
pts) 10 Express the following binary fraction in normalized floating-point form using the simple
model with excess-15 bias: (2 pts) 1) 34.0625.
write recursive function that calculates and returns the length of a.pdfarpitcomputronics
write recursive function that calculates and returns the length of a linked list
Solution
// C code to determine length of linked list recursively
#include
#include
// node of linked list
struct node
{
int key;
struct node* next;
};
// push key to linked list
void push(struct node** root, int new_element)
{
struct node* nodeNew = (struct node*) malloc(sizeof(struct node));
nodeNew->key = new_element;
nodeNew->next = (*root);
(*root) = nodeNew;
}
// recursively get length of linked list
int lengthLinkedlist(struct node* root)
{
// base case
if (root == NULL)
return 0;
// recursively call the function
return 1 + lengthLinkedlist(root->next);
}
int main()
{
struct node* root = NULL;
push(&root, 11);
push(&root, 34);
push(&root, 4);
push(&root, 23);
push(&root, 14);
push(&root, 88);
push(&root, 56);
push(&root, 84);
push(&root, 6);
/* Check the count function */
printf(\"Length of Linked list: %d\ \", lengthLinkedlist(root));
return 0;
}
/*
output:
Length of Linked list: 9
*/.
in c languageTo determine the maximum string length, we need to .pdfstopgolook
in c language
To determine the maximum string length, we need to create a new callback function that utilizes
an alternative user data structure. This callback function should adhere to the same format as
demonstrated in the example.
The data provided to our callback consists of:
A node containing the node->data pointer, which will store our string.
A userdata argument, represented as (void *), capable of holding any desired content. We
possess complete control over the content at this pointer location, as it will be whatever value we
have passed. Consequently, we can:
Establish a structure to store any pertinent values we require.
Transmit the address of this structure into the function.
use this code and just add your code where it says TO DO
#include
#include
#include
#include
#include "LLGeneric.h"
/** define the maximum length of a line that we can read */
#defineLINE_BUFFER_SIZE1024
/**
* We can use this as our "user data" to help us calculate the maximum
* length string
*
* Add anything else to this structure that you wish
*/
struct maxData {
size_t maxLenSoFar;
char *maxStringSoFar;
};
/**
* our "user function" or "callback" for printing.
*
* We know what "void *userdata" is going to be because it is
* simply what we pass in at the call below, so it is safe to
* cast back to a FILE * as that is what we passed it.
*
* This is called a "callback" as it "call back into" our own
* code from within a generic routine.
*/
int myFindLongestStringNode(GenericListNode *node, int index, void *userdata)
{
/**
* Add more code here. You will need to:
* - convert the GenericListNode payload in the field "data" to your
* known (char *) type
* - conver the (void *) userdata into your known (struct maxData *)
* type
* - use the fact that you can examine and store the values provided
* through the userdata to see what has been calculated by earlier
* calls to this function and update based on what you see here,
* in order to determine what the longest string is in the whole
* set of nodes.
*/
return 1;
}
int
doListActivities(GenericListNode *list)
{
/** create an instance of our structure for use as the user data */
struct maxData maxDataWorkingStruct;
int nProcessed = 0;
/** initialize our structure -- if you added fields, set them up here */
maxDataWorkingStruct.maxLenSoFar = 0;
maxDataWorkingStruct.maxStringSoFar = NULL;
/**
* TO DO: Iterate using the callback, which should calculate what
* the longest string in the list is
*/
nProcessed = lstPerformIterativeAction(
list, /* pointer to the first list node */
myFindLongestStringNode, /* pointer to our function */
(void *) &maxDataWorkingStruct);
/** print out the result */
printf("The longest string has %ld characters\n",
maxDataWorkingStruct.maxLenSoFar);
printf("The longest string is: %s\n",
maxDataWorkingStruct.maxStringSoFar);
return nProcessed;
}
/**
**Tools provided below here you won't need to edit -- they
**simply process the command line, and load and free the
**generic linked list and the st.
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxGordonpACKellyb
IN C LANGUAGE: I've been trying to finish this program for the last few days, and I'm stuck on one part of it, and I can't figure out what to do.
The goal is to read in a file (separated by commas), put the information into a linked list, and then sort that linked list by either first or last name using function pointers.
Everything I have so far works, aside from the fact that my output is never sorted. I'm doing something wrong with the listSort function, and I don't know what it is.
Can anyone please just take a look at what I have and offer a suggestion or solution? It might not even be an issue with the function itself, but something somewhere else.
I would greatly appreciate it.
Please do not make any changes to the variables in the structs. Month has to be a string, it cannot be an integer.
driver.c:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
int main(int argc, char* argv[]) {
//creating input and output files
FILE* in = NULL;
FILE* out = NULL;
node_t* head = NULL;
node_t* temp = NULL;
//checking for 4 command line arguments
assert(argc == 4);
//opening input file
in = fopen(argv[1], "r");
assert(in != NULL);
//opening output file
out = fopen(argv[2], "w");
assert(out != NULL);
int sortBy = atoi(argv[4]);
temp = createList(in, &head);
if(sortBy == 1) {
sortList(&head, compare_by_firstname);
}
else if(sortBy == 2) {
sortList(&head, compare_by_lastname);
}
printList(out, temp);
deleteList(&head);
//closing files
fclose(in);
fclose(out);
return 0;
}
functions.c:
#include "functions.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdbool.h>
bool isLeapYear(int year) {
if(year % 4 != 0) {
return false;
}
else if(year % 100 != 0) {
return true;
}
else if(year % 400 != 0) {
return false;
}
else {
return true;
}
}
void printBorder(FILE* out)
{
int i = 0;
for(i = 0; i < 80; i++)
fprintf(out,"*");
fprintf(out, "\n");
}
bool checkInvalidDate(node_t *node) {
int year = (int)node->birthday.year;
if(node->birthday.day < 1 || node->birthday.year < 1) {
return true;
}
if(strcmp(node->birthday.month, "February") == 0) {
if(isLeapYear(year)) {
if(node->birthday.day > 29) {
return true;
}
}
else if(node->birthday.day > 28) {
return true;
}
}
else if((strcmp(node->birthday.month, "April") == 0) || (strcmp(node->birthday.month, "June") == 0) ||
(strcmp(node->birthday.month, "September") == 0) || (strcmp(node->birthday.month, "November") == 0)) {
if(node->birthday.day > 30) {
return true;
}
}
else {
if(node->birthday.day > 31) {
return true;
}
}
return false;
}
void add(node_t **node, node_t **head) {
node_t* current = *head;
while(current != NULL) {
//comparing first and last names to check for duplicates; if duplicate the info isn't added to the list
if((strcmp(current->firstName, (*node)->firstName) == 0) && (strcmp(current->lastName, (*node)->lastName) == 0)) {
return;
}
current = current->next;
}
//adding information as a node to the list
(*node.
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
/* Lab Assignment 4 CSE330 Spring 2014 */
/* Skeleton Code for ex0 of lab4 */
/* No code will be provided for ex1 of lab4 */
#include <stdio.h> /* for NULL */
#include <ctype.h> /* for atoi() */
#include <errno.h> /* for perror() */
#include <signal.h> /* for sigvec() etc. */
#include <sys/types.h> /* for <arpa/inet.h> */
#include <sys/socket.h> /* for PF_INET, etc. */
#include <netinet/in.h> /* for struct sockaddr_in */
#include <arpa/inet.h> /* for inet_addr() */
#include <sys/time.h>
#include "lab4.h"
/* this is in netinet/in.h; included here for reference only.
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
*/
/***************************************************************************/
#define LINESIZE 80
#define TYPE0TIMEOUT 3
#define TYPE1TIMEOUT 30
/* You should give a long timeout, like 30sec, otherwise */
/* duplicated responses from the server may cause some problem */
#define MAXRETRY 3
/***************************************************************************/
static char *RCSId="$Id: client2.c,v 4 2014/04/20 03:15:07 cse3300 Exp $";
/***************************************************************************/
/* some functions you may find useful if you implement them */
extern int stringToAddress(char *s, struct sockaddr_in *a);
extern int msgok(LABMSG *);
extern u_short msgchecksum(u_short *);
extern void alarmCatcher(void);
extern int tries; /* for retransmission routines */
int numtries;
/***** this will die ****/
FILE *logFile;
void die(char *s)
{
perror(s);
exit(2);
}
void startTimer(int secs)
{
alarm(secs);
}
void stopTimer(void)
{
alarm(0);
}
/* should change it by yourself if needed!!! */
void printResponse(LABMSG *mp, int ck)
{
int type;
mp->courseEtc = ntohs(mp->courseEtc);
type = ( (mp->courseEtc & MESSAGETYPE) !=0)?1:0;
printf("course=%d, Type=%d\n", mp->courseEtc&0x3fff,type);
if (ntohl(mp->cookie) != ck)
printf("Cookies don't match: sent %x received %x\n",mp->cookie,ck);
if (mp->courseEtc & REQRESP)
printf("response ");
else {
printf("request??\n");
return;
}
mp->result = ntohs(mp->result);
/*printf(" result = %x: ",mp->result);*/
if (mp->result&TRANSOUTCOME) { /* Check outcome */
printf("error: ");
switch (mp->result & 0x7fff) {
case ERROR_CHECKSUM:
printf("checksum failure\n");
break;
case ERROR_SYNTAX:
printf("syntax error\n");
break;
case ERROR_UNKSSN:
printf("unknown SSN %d\n", ntohl(mp->reqSSN) );
break;
case ERROR_SERVER:
printf("Unspecified Server Error\n");
default:
printf("Unknown Error.\n");
} /* case switch */
} else { /* successful transaction */
if(type)printf("Test succeeded.");
if (!type) /* Type 0 -- print SSN and Response */
printf(": %d -> %d\n", ntohl(mp->reqSSN), mp->result&0x7fff);
else
printf("\n"); /* XXX print number of responses */
}
}
/*-----------------------------------*/
/* added by ZXC:
this fun ...
lab08/build.bat
@echo off
cls
set DRIVE_LETTER=%1:
set PATH=%DRIVE_LETTER%\MinGW\bin;%DRIVE_LETTER%\MinGW\msys\1.0\bin;%DRIVE_LETTER%\MinGW\gtkmm3\bin;%DRIVE_LETTER%\MinGW\gtk\bin;c:\Windows;c:\Windows\system32
set PROJECT_PATH=.
make DRIVE_LETTER="%DRIVE_LETTER%" PROJECT_DIR="%PROJECT_PATH%"
lab08/CSC2110/CD.h
#if !defined CD_H
#define CD_H
#include "Song.h"
#include "Text.h"
using CSC2110::String;
#include "ListArray.h"
using CSC2110::ListArray;
namespace CSC2110
{
class CD
{
private:
String* artist;
String* title;
int year;
int rating;
int num_tracks;
ListArray<Song>* songs;
public:
CD(String* artist, String* title, int year, int rating, int num_tracks);
virtual ~CD();
String* getKey();
void addSong(String* title, String* length);
void displayCD();
static ListArray<CD>* readCDs(const char* file_name);
static int compare_items(CD* one, CD* two);
static int compare_keys(String* sk, CD* cd);
static char getRadixChar(CD* cd, int index); //1-based
};
}
#endif
lab08/CSC2110/Double.h
#if !defined (DOUBLE_H)
#define DOUBLE_H
namespace CSC2110
{
class Double
{
private:
double value;
public:
Double(double val);
~Double();
double getValue();
};
}
#endif
lab08/CSC2110/HighPerformanceCounter.h
#if !defined (HIGHPERFORMANCECOUNTER_H)
#define HIGHPERFORMANCECOUNTER_H
namespace CSC2110
{
class HighPerformanceCounter
{
private:
double micro_spt; //micro_seconds per tick
HighPerformanceCounter();
static HighPerformanceCounter* hpc;
static int getTicksPerSecond();
public:
virtual ~HighPerformanceCounter();
static HighPerformanceCounter* getHighPerformanceCounter();
int getCurrentTimeInTicks();
double getTimeDifferenceInMicroSeconds(int start_time, int end_time);
};
}
#endif
lab08/CSC2110/Integer.h
#if !defined (INTEGER_H)
#define INTEGER_H
namespace CSC2110
{
class Integer
{
private:
int value;
public:
Integer(int val);
virtual ~Integer();
int getValue();
};
}
#endif
lab08/CSC2110/Keyboard.h
#if !defined KEYBOARD_H
#define KEYBOARD_H
#include "Text.h"
using CSC2110::String;
#include <string>
using namespace std;
namespace CSC2110
{
class Keyboard
{
private:
Keyboard();
public:
virtual ~Keyboard();
static Keyboard* getKeyboard();
//pre: the string (character literal) that will prompt the user for input
//post: the input read from the keyboard interpreted as an int is returned
int readInt(string prompt);
int getValidatedInt(string prompt, int min, int max);
//pre: the string that will prompt the user for input
//post: the input read from the keyboard interpreted as a double is returned
double readDouble(string prompt);
double getValidatedDouble(string prom ...
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
operating system ubuntu,linux,MacProgram will work only if you g.pdfaptcomputerzone
//operating system ubuntu,linux,Mac
Program will work only if you give command like
sum 2 3 or
sum 4 (sub 4 3)
#include
#include
#include
#include
/*Sum function implementation*/
int sum(int number1,int number2){
return number1+number2;
}
/*sub function implementation*/
int sub(int number1,int number2){
return number1-number2;
}
/*mul function implementation*/
int mul(int number1,int number2){
return number1*number2;
}
/*divide function implementation*/
float divide(int number1,int number2){
if(number2==0){
printf(\"We can not divide by 0 \ \");
return 0.0f;
}
return (float)(number1/number2);
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if (pointer == NULL)
{
printf(\"Unable to allocate memory.\ \");
exit(1);
}
for (c = 0 ; c < length ; c++)
{
*(pointer+c) = *(string+position-1);
string++;
}
*(pointer+c) = \'\\0\';
return pointer;
}
/*Main Function start*/
int main(int argc, char *argv[]){
/*Variable declarations*/
int number1,number2;
char *operator,*str1,*str2;
char line[50];
char s[2] = \" \";
int errorFlag=0;// checking if user entered more then one operands
while(1){
/*User input*/
printf(\"Please Enter the command \");
gets(line);
int len=0;
for(int i=0; line[i]!=\'\\0\'; ++i){len++;}
if(len==0){
return 1;
}
/*Spliting into Tokens*/
operator = strtok(line, \" \");
if(strcmp(operator,\"bye\")==0){
break;
}
/*String to integer --- token1*/
number1=atoi(strtok(NULL, s));
/*Removing ( and ) from String*/
str2=strtok(NULL, s);
char *content;int length=0;
for(int i=0; str2[i]!=\'\\0\'; ++i){length++;}
if(str2[0]==\'(\'){
content=substring(str2,2,length-1);
char *opr=content;
int n1=atoi(strtok(NULL, s));
int n2=atoi(strtok(NULL, s));
/*If user entered more then two operands then it will return some token otherwise it will
return NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}else{
if(strcmp(opr,\"sum\")==0){
number2=sum(n1,n2);
}else if(strcmp(opr,\"sub\")==0){
number2=sub(n1,n2);
}else if(strcmp(opr,\"mul\")==0){
number2=mul(n1,n2);
} else if(strcmp(opr,\"div\")==0){
number2=divide(n1,n2);
}
}
}else{
number2=atoi(str2);
/*If user entered more then two operands then it will return some token otherwise it will return
NULL pointer*/
if(strtok(NULL, s)!=NULL){
printf(\"You need to enter operator operand1 operand2 \ \");
errorFlag=1;
}
}
if(errorFlag!=1){
/*Checking operator by strcmp function*/
if(strcmp(operator,\"sum\")==0){
printf(\"Result %d \ \",sum(number1,number2));
}else if(strcmp(operator,\"sub\")==0){
printf(\"Result %d \ \",sub(number1,number2));
}else if(strcmp(operator,\"mul\")==0){
printf(\"Result %d \ \",mul(number1,number2));
} else if(strcmp(operator,\"div\")==0){
printf(\"Result %.2f \ \",divide(number1,number2));
}
}
}
return 0;
}
/*******************Output***********************/
gopal@gopal:~/Desktop/chegg$ gcc Calculator.c
Calculator.c: In function ‘main’:
Calculator.c:67:3: warning: implici.
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfcallawaycorb73779
C++ problem
Part 1: Recursive Print (40 pts)
Please write the recursive List reverse print function, whose iterative version we wrote in class.
Below are the function signatures for the functions you are going to need:
public:
/**Additional Operations*/
void print_reverse();
//Wrapper function that calls the reverse helper function to print a list in reverse
//prints nothing if the List is empty
private:
void reverse(Nodeptr node);
//Helper function for the public printReverse() function.
//Recursively prints the data in a List in reverse.
Why do we need the private helper function here?
Since we are going to be reversing our list node by node, in a recursive fashion, we want to pass
a one node at a time to our reverse function.
However, since our nodes are private, we cannot access them if we call the function inside of
main.
Add these function signatures to your List.h file along with your other function prototypes inside
the class definition.
Make sure that you place the reverse function inside the private portion of your List class
definition and the print_reverse function prototype to the public portion of your List class
definition.
Now, implement these two functions inside of List.h, under your section for additional
operations.
Important: Test each function carefully inside of your ListTest.cpp to make sure that it is
working properly.
Part 2: Adding an Index to Your List Nodes (20 pts)
Next, you will add the following functions to your List.h
/**Accessor Functions*/
int get_index();
//Indicates the index of the Node where the iterator is currently pointing
//Nodes are numbered from 1 to length of the list
//Pre: length != 0
//Pre: !off_end()
...
int List::get_index()
{
//Implement the function here
}
/**Manipulation Procedures*/
void scroll_to_index(int index);
//Moves the iterator to the node whose index is specified by the user
//Pre: length != 0
...
void scroll_to_index(int index)
{
//Implement function here
}
Part 3: Implementing Search as Part of Your List (40 pts)
Now, we are going to add two search functions to our List so that we can search for elements in
our List.
The first of these functions is going to be a simple linear search function.
You will need to add the following function prototype and function definition to your List.h:
/**Additional Operations*/
int linear_search(listitem item);
//Searchs the list, element by element, from the start of the List to the end of the List
//Returns the index of the element, if it is found in the List
//Returns -1 if the element is not in the List
//Pre: length != 0
...
int List::linear_search(listitem item)
{
//Implement the function here
}
You are also going to add a function to perform recursive binary search on your List.
You will need to add the following function prototype and function definition to your List.h:
int binary_search(int low, int high, listitem item);
//Recursively searchs the list by dividing the search space in half
//Returns the index of the element, if it is fo.
My question is pretty simple, I just want to know how to call my ope.pdfjeetumordhani
My question is pretty simple, I just want to know how to call my operator== function in
Stack.cpp using a list function.
Here is what I meant. This is my Stack.h file:
class Stack {
public:
/**constructors and destructors*/
Stack();
Stack(const Stack &S);
~Stack();
void pop();
void push(int data);
bool operator==(const Stack &S);
[ .......]
private:
List stack;
};
Here is my List.h file:
template
class List {
private:
struct Node {
listitem data;
Node* next;
Node* previous;
Node(listitem data) :
next(NULL), previous(NULL), data(data) {
}
};
typedef struct Node* NodePtr;
NodePtr start;
NodePtr end;
NodePtr cursor;
int length;
public:
........
bool operator==(const List &list);
[.......] }
[........]
template
bool List::operator==(const List& list) {
if (length != list.length)
return false;
NodePtr temp1 = start;
NodePtr temp2 = list.start;
while (temp1 != NULL) {
if (temp1->data != temp2->data)
return false;
temp1 = temp1->next;
temp2 = temp2->next;
}
return true;
}
[......]
So I already define my functions in List.h and I only need to call my function from List again in
my Stack.cpp file. For example from my Stack.cpp:
Stack::Stack(const Stack &S) :
stack(S.stack) {
}
void Stack::pop() {
stack.remove_start();
}
[......]
And I don\'t know how to call my operator== function in Stack.cpp from the List.h like the way
above. This is what my guess so far but did not work:
bool Stack::operator==(const Stack &S) {
stack.operator==(S.stack);
}
Thank you
Solution
When we wish to make a comparison, such as in an if statement, we use the double equals sign
(==).
1)bool operator==(const Stack &S); [ .......]
It means whatever the boolean operator it should be belongs to stack or equal to.
2) bool operator==(const List &list);
Likewise link list also compare with the constructor link list.
and constructor need not to call explicitly. it will call itself when program called first..
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfmdameer02
Merge Sort implementation in C++ The implementation for Mergesort given in Section 7.4 takes
an array as input and soils that array. At the beginning of Section 7.4 there is a simple
pseudocode implementation for sorting a linked list using Mergesort. Implement both a linked
list-based version of Mergesort and the array-based version of Mergesort. and compare and
analyze their running times.
Solution
/* Merger sort array-based version */
/* C program for Merge Sort */
#include
#include
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf(\"%d \", A[i]);
printf(\"\ \");
}
/* Driver program to test above functions */
int main()
{
int arr[] = {12, 11, 13, 5, 6, 7};
int arr_size = sizeof(arr)/sizeof(arr[0]);
printf(\"Given array is \ \");
printArray(arr, arr_size);
mergeSort(arr, 0, arr_size - 1);
printf(\"\ Sorted array is \ \");
printArray(arr, arr_size);
return 0;
}
--------------------------------------------------------------------------------------------------------------------
/* merge sort link-list version
#include
#include
/* Link list node */
struct node
{
int data;
struct node* next;
};
/* function prototypes */
struct node* SortedMerge(struct node* a, struct node* b);
void FrontBackSplit(struct node* source,
struct node** frontRef, struct node** backRef);
/* sorts the linked list by changing next pointers (not data) */
void MergeSort(struct node** headRef)
{
struct node* head = *headRef;
struct node* a;
struct node* b;
/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL))
{
return;
}
/* Split head into \'a\' and \'b\' sublists */
FrontBackSplit(head, &a, &b);
/* Recursively sort the sublists */
MergeSort(&a);
MergeSort(&b);
/* answer = merge the two sorted lists together */
*.
The purpose of this C++ programming project is to allow the student .pdfRahul04August
The purpose of this C++ programming project is to allow the student to perform parallel array
and multidimensional array processing. The logic for string and Cstring has already been
completed, so the assignment can be started before we actually cover string and Cstring in detail.
This program has the following three menu options:
Solution
/*
This program uses simple arrays, multidimensional arrays, cstrings, strings, and files.
It allows a payroll clerk to choose an option from a menu. The choices are:
A: List the Payroll Information by Employee Name
B: Search Payroll Information by Employee Name
X: Exit the Payroll Information Module
The following items for each employee are saved in the file p10.txt:
Employee ID (1000 - 9999)
Last Name (15 characters)
First Name (15 characters)
Rate (5.00 - 10.00)
Hours W1,W2,W3,W4 (0-60)
*/
#include // file processing
#include // cin and cout
#include // toupper
#include // setw
#include // cstring functions strlen, strcmp, strcpy stored in string.h
#include // string class
#define stricmp strcasecmp
#define strnicmp strncasecmp
using namespace std;
//Disable warning messages C4267 C4996.
//To see the warnings, comment out the following line.
//#pragma warning( disable : 4267 4996)
//Warning C4267: coversion from size_t to int, possible lost of data
//size_t is a data type defined in and is an unsigned integer.
//The function strlen returns a value of the type size_t, but in
//searchByName we assign the returned value to an int.
//We could also declare the variable as size_t instead of int.
// size_t stringLength;
//Warning C4996: strnicmp strcpy, stricmp was declared deprecated, means
//the compiler encountered a function that was marked with deprecated.
//The deprecated function may no longer be supported in a future release.
//Global Constants
//When using to declare arrays, must be defined with const modifier
const int ARRAY_SIZE = 20, HOURS_SIZE = 4, NAME_SIZE = 16;
//Declare arrays as global so we don\'t have to pass the arrays to each function.
//Normally we wouldn\'t declare variables that change values a global.
int employeeId[ARRAY_SIZE];
string firstName[ARRAY_SIZE];
char lastName[ARRAY_SIZE][NAME_SIZE];
double rate[ARRAY_SIZE];
int hours[ARRAY_SIZE][HOURS_SIZE];
int numberOfEmps; //count of how many employees were loaded into arrays
int sumHours[ARRAY_SIZE] = {0}; //initialize arrays to zero by providing a
double avgHours[ARRAY_SIZE] = {0}; //value for the first element in the array
//Function Prototypes
void loadArray( );
void sumAndComputeAvgHours( );
void listByName( );
void searchByName( );
void sortByName( );
void swapValues(int i, int minIndex);
void listEmployees( );
void listEmployeesHeadings( );
void listEmployeesDetails(int i);
void listEmployeesTotals( );
void displayContinuePrompt( );
//Program starts here
int main()
{
//Declare and initialize local main variables
char choice; //menu option
//Load the arrays with data
loadArray();
//Sum and compute the average hours
sumAndComputeAv.
Program In C You are required to write an interactive C program that.pdfamitbagga0808
Program In C You are required to write an interactive C program that prompts the user for
commands, accepts commands from the keyboard (stdin) and executes those commands. When a
command requires output, it must be written to stdout. The program must continue to accept and
process commands until the user types the end command ourput, it must be writen to stdout. The
program must continue to accept and proces.commands The program deals with linked lists.
Each node of such a list contains a string of length at most 10, a positive integer (i.e., an integer
value 2 1) and a pointer to the next node of the list. For any node, the string and the integer
stored in that node will be referred to as the symbol and count for that node respectively. At all
times, the list must satisfy the following two important properties. 1. The symbols appearing in
the list are all distinct; that is, no two nodes have the same symbol. 2. When the list is scanned
from left to right, the counts must be in non-increasing order. An example of such a linked list is
shown below. Search 4 Maxval4 begin/ Loop head
Solution
/**********************************************/
/****** NAMES ******************** COMMANDS ***/
/* Insert Command : ins str */
/* Delete Command : del str */
/* Forced Delete Command : fde val */
/* Print Statistics Command : pst */
/* Print List Command : prl */
/* Print using Count Range Command: pcr v1 v2 */
/* Print Prefix Command : ppr str */
/* Print Suffix Command : psu str */
/* End Command : end */
/***********************************************/
#include
#include
#include
#define CSIZE 4
#define SSIZE 11
/* Struct for each node in the linked list */
struct node
{
int count;
char symbol[SSIZE];
struct node *next;
};
struct node *head;
/* Prototypes for the functions */
void insert(char *);
void delete(char *);
void forced_delete(int value);
void print_stats();
void print_list();
void print_count(int, int);
void print_prefix(char pre[]);
void print_suffix(char suf[]);
void sort_list();
/****************
** Main Method **
****************/
int main(void)
{
int count;
char symbol[SSIZE];
char cmd[CSIZE];
int v1;
int v2;
/* Enter commands */
printf(\"Command? \"); fflush(stdout);
scanf(\"%s\", cmd);
/* Check for command*/
while(strcmp(cmd,\"end\") != 0)
{
/* check which function to use */
if(strcmp(cmd,\"ins\") == 0) { scanf(\"%s\", symbol); insert(symbol); }
if(strcmp(cmd,\"del\") == 0) { scanf(\"%s\", symbol); delete(symbol); }
else if(strcmp(cmd,\"fde\")==0){scanf(\"%d\",&count); forced_delete(count); }
if(strcmp(cmd,\"pst\") == 0) { print_stats();}
if(strcmp(cmd,\"prl\") == 0) { print_list(); }
if(strcmp(cmd,\"pcr\") == 0) { scanf(\"%d %d\",&v1,&v2); print_count(v1,v2); }
if(strcmp(cmd,\"ppr\") == 0) { scanf(\"%s\", symbol); print_prefix(symbol);}
if(strcmp(cmd,\"psu\") == 0) { scanf(\"%s\", symbol); print_suffix(symbol);}
printf(\"Command? \"); fflush(stdout);
scanf(\"%s\", cmd);
}// End of While Loop
return 0;
}// End of main method
/*********.
Per the text, computers are playing an increasingly important role i.docxodiliagilby
Per the text, computers are playing an increasingly important role in the practice of law. Successful paralegals must be comfortable with using electronic databases and research tools.
Write a two to three (2-3) page paper in which you:
Discuss a paralegal’s ethical obligation to conduct competent electronic research. Provide two (2) examples of the potential consequences of inept electronic research practices.
Determine whether or not traditional reference materials (e.g., State and Federal Reporters, West’s Encyclopedia, etc.) can be as current as electronic resources. Provide two (2) advantages and two (2) disadvantages to using traditional resource materials.
Use at least two (2) quality references.
Note:
Wikipedia and other Websites do not qualify as academic resources.
THIS IS PART 1.
.
Pennsylvania was the leader in sentencing and correctional reform .docxodiliagilby
Pennsylvania was the leader in sentencing and correctional reform in the early history of the United States. Discuss what groups were associated with this reform.
Why did they want the reform?
Examine whether it was successful and if the reform brought forth further changes.
What influences does the system have on the correctional system today?
What influences have changed? Why?
Use the Internet, library, and any other resources available to research your answer. Submit a 4 page paper (double-spaced) to your instructor. Support your reasoning with outside sources. Be sure to reference all sources using APA style.
The following will be the grading criteria for this assignment:
20%:
Discuss what groups were associated with this reform.
10%:
Why did they want the reform?
20%:
Examine whether it was successful and if the reform brought forth further changes.
25%:
What direct influences do you see the Pennsylvania system in the correctional systems used today?
25%:
What influences have changed? Why?
4 pages. APA format. No plagerism. 5 sources referenced throughout the paper. Reference Page and Abstract.
.
Penetration testing is a simulated cyberattack against a computer or.docxodiliagilby
Penetration testing is a simulated cyberattack against a computer or network that checks for exploitable vulnerabilities. Pen tests can involve attempting to breach application systems, APIs, servers, inputs, and code injection attacks to reveal vulnerabilities. In a well-written, highly-detailed research paper, discuss the following:
What is penetration testing
Testing Stages
Testing Methods
Testing, web applications and firewalls
Your paper should meet the following requirements:
Be approximately four to six pages in length, not including the required cover page and reference page.
Follow APA7 guidelines. Your paper should include an introduction, a body with fully developed content, and a conclusion.
Support your answers with the readings from the course and at least two scholarly journal articles to support your positions, claims, and observations, in addition to your textbook. The UC Library is a great place to find resources.
Be clearly and well-written, concise, and logical, using excellent grammar and style techniques. You are being graded in part on the quality of your writing.
.
Perform an analysis of the social demographic, technological, econ.docxodiliagilby
Perform an analysis of the social / demographic, technological, economic, environmental / geographic, and political/legal / governmental segments to understand the general environment facing Union Pacific.
Descri
be how Union Pacific will be affected by each of these external factors.
this is a strategic mangement course business 499.
.
Perform research and discuss whether text messaging is cheaper or mo.docxodiliagilby
Perform research and discuss whether text messaging is cheaper or more expensive than voice. Explain how text messaging works.
Perform research and discuss how an audio CD and an audio DVD compare. Find out why it is said that a vinyl long play record produces sounds much better. Are we going backwards with digital technology in music recording? Explain.
.
People in developed nations are fond of warning people in developing.docxodiliagilby
People in developed nations are fond of warning people in developing nations to stop
destroying rainforest.
People of developing nations often respond that this is hypocritical,
because the developed nations became wealthy by deforesting their land and exploiting its
resources in the past.
What would you say to the president of a developing nation, such as
Indonesia, in which a great deal of forest is being cleared?
.
Pease read and incorporate the following articles from the EBSCO h.docxodiliagilby
Pease read and incorporate the following articles from the EBSCO host database into your paper:
Deakin, A. (2004, November). Finding your organization's hidden treasure.
Behavioral Health Management
, 24(6), 27-29.
Droppa, D., & Luczak, R. (2004, January). Collaboration, technology,
and outcomes—A recipe to improve service delivery.
Behavioral Health Management
, 24(1), 41-44.
To complete the research paper, you will need to include an introduction and conclusion section as well as a title page and reference section. The title of the research paper will be the
Current Issues in the Behavioral Healthcare System
.
Your final paper is due for submission. The paper should adhere to the following guidelines:
The length of the paper should be eight to ten double-spaced pages (not including the title and reference pages).
The main sections should have a:
Title page
Introduction
Body of the paper (with subheadings)
Conclusion
Reference page(s)
The paper must use the APA format for citing sources and references.
Your final paper introduction (one page) should include the following points:
An overview of the research paper
The purpose or objective of the research paper
The body of the paper (five to six pages) should address each of the following topics using information learned in the course, in combination with outside references:
Based on your previous assignments and review of the literature, what are some of the major issues faced by today’s behavioral healthcare system? How have the current and future trends that are evolving in the industry addressed some of those issues?
Do you think there is a difference between the changing trends taking place in the private sector and that of public behavioral healthcare inpatient facilities? Based on your understanding about behavioral health services and the populations being served by them, do you agree that both private and public organizations are able to provide the necessary clinical services? Provide a rationale in support of your response.
In behavioral healthcare, outcomes are the established norm for measuring the success or lack of services. What are some of the major challenges in collecting the data needed to support and report behavioral health outcomes? Provide a rationale for your response.
Quality of care and services is an important part of an outcome-based strategy. The objective behind maintaining and improving quality is to provide competent and efficient services to consumers. In your opinion, do the current regulatory and accreditation standards for the behavioral health industry help to meet that objective? How?
Your conclusion (one to two pages) should include the following points:
What conclusions can you draw from your research that would demonstrate the role played by behavioral health in the healthcare industry?
What changes would you like to bring to today's behavioral healthcare system in order to resolve the current issues identified?
Based on your literature rev.
Peer Review Journal Paper Overview of assignment due 17 April 2014 I.docxodiliagilby
Peer Review Journal Paper Overview of assignment due 17 April 2014 I want you to find a peer review article that falls into our time frame: world history from the emergence of humanity to 1500 CE. I want you to present the thesis [argument] the author is putting forward. I want you then to find two other sources on the same subject and determine if those sources agree or disagree with your original source. The theme here is peer review and the notion of historiography; whether or not how we look at an event or theme of history changes over time? The choice of topic is up to you but please let me know what you are doing by email and let me know what your peer review source is so I can be sure it is appropriate for the course. If you want some help in finding an article; please let me or a librarian know what you might be interested in. I really need to know what your article is before you start so you have something good to start with and send me a link to your article, so that I can approve it.
1. Find a peer review article on some aspect of history associated with this course.
2. Explain the thesis that author is putting forth.
3. Find two secondary sources, they need not be peer review which relate to the main article you are presenting. Do these sources compliment or contrast the thesis being put forth by the original author?
4. Leave some time & space at the end to present your perspective and opinion on the thesis as well.
5. 5-7 pages; typed doubled spaced standard borders & fonts. Please use citation; APA, MLA, Chicago are all acceptable.
The requirement of the paper starts at the middle of the 3rd page that I attached here.
We can discuss more later.
.
Perception is all EXCEPT [removed] [removed]Structuring and orga.docxodiliagilby
Perception is all EXCEPT
[removed]
[removed]Structuring and organizing incoming impulses (information)
[removed]a prognosis (guess) about what is being received
[removed]the reconstruction of reality by our brain
[removed]the transduction of incoming stimuli
[removed]a process which takes time
.
Performance Based Factors and Measures for Quality AssessmentWri.docxodiliagilby
Performance Based Factors and Measures for Quality Assessment
Write a 700- to 1,000-word paper about the Performance Based Factors and Measures for Quality Assessment. Include the following in your paper:
For any health care activity, three performance factors can be measured: structure, process, and outcome. Identify one structure measure, one process measure, and one outcome measure that could be used to evaluate the following hospital admission process:
Upon arrival, the patient reports to the hospital registration or admitting area. The patient completes paperwork and provides an insurance identification card, if insured. Often, patients register before the date of hospital admission to facilitate the registration process. An identification bracelet including the patient’s name and doctor’s name is placed around the patient’s wrist. Before any procedure is performed or any form of medical care is provided, the patient is asked to sign a consent form. If the patient is not feeling well, a family member or caregiver can help the patient complete the admission process.
Include a minimum of three peer-reviewed references, not including the textbook.
Format your paper consistent with APA 6th guidelines.
.
People. I need some help with this assignment that needs to be done .docxodiliagilby
People. I need some help with this assignment that needs to be done in Excel
Problem 1:
Oregon Surplus Inc. qualifies to use the installment-sales method for tax purposes and sold an investment on an installment basis. The total gain of $75000 was reported for financial reporting purposes in the period of sale. The installment period is 3 years; one-third of the sale price is collected in 2014 and the rest in 2015 and 2016. The tax rate was 35% in 2014, 30% in 2015, and 30% in 2016. The enacted tax rates of 2015 and 2016 are not known until 2015.
The accounting and tax data are shown below.
Financial Accounting
Tax Return
2014 (35% tax rate)
Income before temporary difference
$
175,000
$
175,000
Temporary difference
$
75,000
$
25,000
Income
$
250,000
$
200,000
2015 (30% tax rate)
Income before temporary difference
$
200,000
$
200,000
Temporary difference
$
-
$
25,000
Income
$
200,000
$
225,000
2016 (30% tax rate)
Income before temporary difference
$
180,000
$
180,000
Temporary difference
$
-
$
25,000
Income
$
180,000
$
205,000
Required:
1)
Prepare the journal entries to record the income tax expense, deferred income taxes, and the income taxes payable for 2014, 2015, and 2016. No deferred income taxes existed at the beginning of 2012.
2)
Explain how the deferred taxes will appear on the balance sheet at the end of each year. (Assume Installment Accounts Receivable is classified as a current asset.)
3)
Show the income tax expense section of the income statement for each year, beginning with “Income before income taxes.”
Problem 2:
Philadelphia Co. incurred a net operating loss of $850,000 in 2014. Combined income of 2012 and 2013 was $650,000. The tax rate for all years is 30%. Trenton elects the carry back option.
Required:
a.
Prepare the journal entries to record the benefit of loss carry back and loss carry forward option.
b.
Assuming that it is more likely than not that the entire net operating loss carry forward will not be realized in future years, prepare all the journal entries necessary at the end of 2014.
.
Perceptions and Causes of Psychopathology PaperPrepare a 1,0.docxodiliagilby
Perceptions and Causes of Psychopathology
Paper
Prepare
a 1,050- to 1,400-word paper in which you discuss causes of psychopathology.
Address
the following:
Provide a brief overview of how culture is a factor determining the expression of psychopathology.
Examine causes of psychopathology by using either the biopsychosocial or the diathesis-stress models.
Explain the changes in society’s perception of psychopathology as a function of historical time period.
Cite
at least two peer-reviewed sources.
Format
your paper consistent with APA guidelines.
Click
the Assignment Files tab to submit your assignment
.
People are attracted to occupations that complement their personalit.docxodiliagilby
People are attracted to occupations that complement their personalities. In a Word doc, compose a 500 word essay naming and describing the six personality types identified by John Holland. Give an example of a vocational choice for each. Then
analyze how dualistic and relativistic thinking
contribute to our vocational choices and discuss the role of commitment within relativistic thinking.
.
Perception of Pleasure and Pain Presentation3 slides- An explanati.docxodiliagilby
Perception of Pleasure and Pain Presentation
3 slides- An explanation of the role of the somatosensory cortex in the perception of pleasure and pain
3 slides- A description of how the damage to the cutaneous system can affect the quality of life
- Include 1 peer reviewed source
- APA Format
-Include speaker notes please
Need on time by 12pm Eastern May 4th, 2015. Thanks.
.
Pennsylvania v. MarkMark Davis has been charged with Driving W.docxodiliagilby
Pennsylvania v. Mark
Mark Davis has been
charged
with Driving While Intoxicated (DWI) for reckless driving, speeding, four counts of felony assault, and one count of involuntary manslaughter as the result of a crash that occurred on a night out with his friends. Mark has been out on bail and pleaded not guilty when he was arraigned. The Judge set a date for Mark's trial and his defense team has been working to collect information about the technology used by the Highway Patrol to reconstruct the crash.
District Attorney O'Malley offered Mark a plea bargain, but Mark chose to take his chances at trial. Mark's attorney, Mr. Chen Long, advised Mark that accepting the plea offer was completely up to Mark, although Mr. Long advised against accepting it because the defense planned to highlight mistakes made by law enforcement during the investigation that could create reasonable doubt in the minds of the jurors.
The trial begins and during the voir dire of potential jurors, several individuals are excused because they have previous knowledge of Mark's case from the media. Two individuals stated that they could not be impartial because they had loved ones
killed
in alcohol related crashes as well. Eventually, two men and ten women were seated in Mark's trial.
District Attorney O'Malley presented the State's case clearly and concisely depicting a night on the town full of heavy drinking, which ultimately resulted in Mark's actions causing the death of one individual and injuring four others. Highway Patrolman Green explained to the jury that he immediately suspected alcohol when he arrived on scene because Mark appeared to be intoxicated when they spoke. Following the Judge ruling that it was admissible and not prejudicial, Sergeant Rodney Monroe, from the Highway Patrol Reconstruction Team presented their reconstruction complete with a high-tech computer animated reenactment of the crash. During the cross examination, Defense Attorney Long challenged the reconstruction because the Defense Crash Reconstruction Expert had discovered errors in the mathematical calculations for vehicle speed. The jury appeared to have liked the reconstruction very much regardless of the errors highlighted by the defense.
Mark was convicted of DWI, four counts of felony assault, and one count of involuntary manslaughter; however, he was acquitted of reckless driving and speeding. The Jury said they could not convict Mark of those offenses because of the mistakes made by law enforcement officers during the investigation.
Because Mark pleads not guilty, but was convicted during trial and had two prior DWI offenses, he was sentenced to ten years in the State Prison. Defense Attorney Long immediately notified the court of an impending appeal that would be filed by the defendant. In a report, using external sources to support your claims, answer the following:
Compare and contrast the roles of the Judge, Jury, District Attorney (Prosecutor), and Defense Attorney. What ar.
PBAD201-1501A-02 Public AdministrationTask NamePhase 3 Individu.docxodiliagilby
PBAD201-1501A-02 Public Administration
Task Name:
Phase 3 Individual Project
Deliverable Length:
750–1,000 words; Tabular budget
Details:
Weekly tasks or assignments (Individual or Group Projects) will be due
by
Monday and late submissions will be assigned a late penalty in accordance with the late penalty policy found in the syllabus. NOTE: All submission posting times are based on midnight Central Time.
Concern among the public sector is the demand for public organizations to be transparent about their budgets and spending habits. You have been scheduled to conduct a presentation for the State Budgeting Committee about the type of budget that the organization operates under. Identify the type of public organization for which you work, as well as what types of services, goods, or activities the organization provides to the public. Identify the size and scope of the organization.
Construct a budget using Excel that will provide a breakdown of the various budget items. Copy and paste the Excel spreadsheet of your budget into a Word document. Finally, explain how the budget is made available to the public for review. For example, is the budget made available at public meetings, on a special request, published in a newsletter, on the organization’s premises during regular business hours, via the organization’s Web site, or by some other means? If the budget is not available for the public to review, explain why. Furthermore, are there any provisions in place regarding the budget being made available for public view? Explain in detail.
Assignment Guidelines
Address the following in 750–1,000 words:
Identify the type of public organization for which you work, as well as what types of services, goods, or activities the organization provides to the public. Identify the size and scope of the organization.
Construct a budget using Excel that will provide a breakdown of the various organizational budget items.
Copy and paste the Excel spreadsheet of your budget into a Word document.
Is the budget made available to the public for review?
If yes, explain how in detail.
If no, explain in detail why it is not.
Are there any types of provisions in place regarding the budget being made available for public view? Identify and explain.
Be sure to reference all sources using APA style.
.
Part1 Q1. Classify each of the following as- (i)qual.docxodiliagilby
Part1
Q1. Classify each of the following as:-
(i)
qualitative or quantitative
(ii)
nominal, ordinal, interval or ratio scale.
a.
Times for swimmers to complete a 50meters race.
b.
Months of the year: Meskerem, Tikimit, Hidat, ---.
c.
Region numbers of Riyadh: 1, 2, 3, 4, ---.
d.
Pollen counts provided as numbers between 1 and 10 where 1 means there is almost no pollen and 10 means that it is rampant, but for which the values do not represent an actual count of grains of pollen.
e.
Packages in the city of Cleveland telephone book.
f.
Rankings of tennis players.
g.
Weights of air conditioners.
h.
Personal ID numbers
i.
Telephone numbers
j.
Temperatures inside 10 refrigerators.
k.
Salaries of the top five CEOs in the United States.
l.
Ratings of eight local plays ( poor, fair, good, excellent)
m.
Times required for mechanics to do a tune up.
n.
Ages of students in a classroom.
o.
Marital Status of patients in a physician’s office.
p.
Horsepower of tractor engines.
q.
Colors of baseball caps in a store.
r.
Classification of kids at a day care (infant, toddler, pre-school)
Q2. The following are the grades which 40 students obtained in a certain course in 1997E.C. here in Mekelle University of the Arid Campus.
75 89 66 52 90 68 83 94 77 60 38 47 87 65 97 49 65 72 73 81 63 77 31 88 74 37 85 76 74 63 69 72 91 87 76 58 63 70 72 65
a. Construct an absolute frequency distribution.
b. Convert the distribution obtained in (a) into a Relative & Percentage distribution.
c. Convert the distribution in (a) into a “Less than” &
a “More than” cumulative distribution
d. Construct a histogram, frequency polygon and ogive curve
Q3. The following distribution shows that the result obtained by 100 accounting students in the final examination of statistics in
Saudi Electronic University.
Mark of students.
0-10
10-20
20-30
30-40
40-50
No. of students
14
f1
28
f2
15
If the median mark of students is 22.5, compute:-
i.
The missing frequencies, f1 and f2.
ii.
the mode, and
iii.
the arithmetic mean
iv.
variance
Part 2
Q1.
a. (Smoking and Coffee Drinking)
Coffee
No Coffee
Total
Smoker
60
40
100
Non-Smoker
115
85
200
Total
175
125
300
What is the probability that a randomly selected person from the sample either smokes or drinks coffee.
Q1. b. What is the probability that I flip a coin and get a Head, Roll a die and get a 4 or a 6, and then pull the king of Spades and a diamond from a deck of cards.
Q2: The random variable X has the following probability distribution:
X
0
1
2
3
Total
P(x)
0.22
0.38
0.1
0.3
1
Find the expected value (E(x)) & the Variance.
Q3: A radar unit is used to measure speeds of cars on a highway. The speeds are
normally
distributed with a mean of 90 km/hr and a standard deviation of 10 km/hr. What is the probability that a car picked at random is travelling at:
a-
More than 100 km/hr?
b-
Less than 85 Km/hr?
c-
Between them?
Part 3
Q-1..
Paul’s Letter to the EphesiansThe First Letter of PeterThe Fir.docxodiliagilby
Paul’s Letter to the Ephesians
The First Letter of Peter
The First Letter to Timothy
For each document above; Identify specific content, features, or themes which permit classifying each text early Catholic in character.
At least one credible source
one and half pages
.
Past and FuturePlease respond to the followingImagine back .docxodiliagilby
"Past and Future"
Please respond to the following:
Imagine back in time to pre-Internet days. Describe how you would have established communications for international trade in these time periods: 1935 and 1977.
Imagine it is now 2050. Predict the ease and speed of international trade communications and how it will occur.
2-
"Backtracking from Globalization"
Please respond to the following:
From the e-Activity, illustrate with two examples how the U.S. has restrained trade over the past 60 years and state why you think that happened.
Some believe these restraints have been deleterious to national economic prosperity. In your estimation, speculate as to how these restraints have affected national economic prosperity.
.
Partisan considerations have increasingly influenced the selection.docxodiliagilby
Partisan considerations have increasingly influenced the selection of federal judges. Interest groups on the right and the left have insisted on the appointment of judges who hold compatible views. Presidents and members of Congress have also increasingly sought appointees who will decide issues in ways they prefer. What is your view? Should politics play such a large role in judicial appointments? Or should merit be given greater weight?
Does a merit based system favor ONLY those with money and the connections? needs to be at least 200 words APA
.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
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.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
Normal Labour/ Stages of Labour/ Mechanism of LabourWasim Ak
Normal labor is also termed spontaneous labor, defined as the natural physiological process through which the fetus, placenta, and membranes are expelled from the uterus through the birth canal at term (37 to 42 weeks
4. assign3/assign3_part2/worker.c
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include "scheduler.h"
/****************************************************
***************************
*
* Implement these functions.
*
*****************************************************
*************************/
/* Handler for SIGTERM signal */
void cancel_thread()
{
printf("Thread %u: terminating.n", (unsigned
int)pthread_self());
/* signal that done in queue */
sem_post(&queue_sem);
pthread_exit(NULL);
}
/* TODO: Handle the SIGUSR1 signal */
void suspend_thread()
{
printf("Thread %u: suspending.n", (unsigned
5. int)pthread_self());
/*add your code here to wait for a resume signal from the
scheduler*/
printf("Thread %u: resuming.n",(unsigned int)
pthread_self());
}
/****************************************************
***************************
*
*
*
*****************************************************
*************************/
/*
* waits to gain access to the scheduler queue.
*/
static int enter_scheduler_queue(thread_info_t *info)
{
/*
* wait for available room in queue.
* create a new list entry for this thread
* store this thread info in the new entry.
*/
sem_wait(&queue_sem);
list_elem *item = (list_elem*)malloc(sizeof(list_elem));
info->le = item;
item->info = info;
item->prev = 0;
item->next = 0;
list_insert_tail(&sched_queue, item);
return 0;
}
6. /*
* leaves the scheduler queue
*/
void leave_scheduler_queue(thread_info_t *info)
{
printf("Thread %lu: leaving scheduler queue.n", info-
>thrid);
/*
* remove the given worker from queue
* clean up the memory that we malloc'd for the list
* clean up the memory that was passed to us
*/
list_remove(&sched_queue, info->le);
free(info->le);
free(info);
}
/*
* Initialize thread, enter scheduling queue, and execute
instructions.
* arg is a pointer to thread_info_t
*/
void *start_worker(void *arg)
{
thread_info_t *info = (thread_info_t *) arg;
float calc = 0.8;
int j = 0;
/* TODO: Block SIGALRM and SIGUSR2. */
/* TODO: Unblock SIGUSR1 and SIGTERM. */
/* compete with other threads to enter queue. */
15. my_wait++;
}
} else {
queue[queue_index] = 0;
in_queue--;
}
} else {
term = 0;
susp = 1;
}
prev = tid;
my_run++;
my_wait += in_queue+(num_workers-worker_index)-1+term;
queue_index= (queue_index+1)%queue_size;
}
quit_if(fscanf(stream, "Th%c",&dummyc) != 1);
if (dummyc=='r') {
quit_if(fscanf(stream, "ead %lu: terminating.nThe",&tid)!=1
|| tid != prev);
}
quit_if(fscanf(stream, " total wait time is %f
seconds.n",&tot_wait) != 1);
quit_if(fscanf(stream, "The total run time is %f
seconds.n",&tot_run) != 1);
quit_if(fscanf(stream, "The average wait time is %f
seconds.n",&ave_wait) != 1);
quit_if(fscanf(stream, "The average run time is %f
seconds.n",&ave_run) != 1);
if (dummyc=='e')
quit_if(fscanf(stream, "Thread %lu: terminating.nThe",&tid)
!= 1|| tid != prev);
quit_if(abs(tot_wait-my_wait)>1);
quit_if(abs(tot_run-my_run)>1);
quit_if(abs(tot_wait/num_workers-ave_wait)>.5);
quit_if(abs(tot_run/num_workers-ave_run)>.5);
return 0;
16. }
int general_test(int argc, const char **argv) {
FILE *f;
int nw, qs, *q;
run_test(argc,argv);
f = fopen("smp5.out","r");
args_to_nums(argc,argv,&nw,&qs,&q);
test_output(f,nw,qs,q);
return EXIT_SUCCESS;
}
int specific_test(int nw, int qs, int *q) {
FILE *f;
int argc;
char **argv;
nums_to_args(nw,qs,q,&argc,&argv);
run_test(argc,(const char **)argv);
f = fopen("smp5.out","r");
test_output(f,nw,qs,q);
return EXIT_SUCCESS;
}
int test_3_1_2_2_2() {
int q[3] = {2,2,2};
return specific_test(3,1,q);
}
int test_2_2_2_2() {
int q[2]={2,2};
return specific_test(2,2,q);
}
int test_5_7_1_2_1_2_1() {
int q[5] = {1,2,1,2,1};
17. return specific_test(5,7,q);
}
int test_4_1_1_2_3_4() {
int q[4] = {1,2,3,4};
return specific_test(4,1,q);
}
int test_3_3_4_3_2() {
int q[3] = {4,3,2};
return specific_test(3,3,q);
}
/*
* Main entry point for SMP% test harness
*/
int run_smp5_tests(int argc, const char **argv)
{
/* Tests can be invoked by matching their name or their
suite name
* or 'all' */
testentry_t tests[] = {
{"test_3_1_2_2_2", "rr", test_3_1_2_2_2},
{"test_2_2_2_2", "rr", test_2_2_2_2},
{"test_5_7_1_2_1_2_1", "rr", test_5_7_1_2_1_2_1},
{"test_4_1_1_2_3_4", "rr", test_4_1_1_2_3_4},
{"test_3_3_4_3_2", "rr", test_3_3_4_3_2},
{"general", "gen", general_test}
};
int result = run_testrunner(argc, argv, tests, sizeof(tests) /
sizeof(testentry_t));
unlink("smp5.out");
return result;
}
/* The real main function. */
18. int main(int argc, const char **argv)
{
if (argc > 1 && !strcmp(argv[1], "-test")) {
return run_smp5_tests(argc - 1, argv + 1);
} else {
return smp5_main(argc, argv);
}
}
__MACOSX/assign3/assign3_part2/._smp5_tests.c
assign3/assign3_part2/testrunner.h
/*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************/
typedef int (*test_fp) (int, const char **);
typedef struct {
const char *name;
const char *suite;
test_fp test_function;
} testentry_t;
int run_testrunner(int argc, const char **argv, testentry_t *
entries,
int entry_count);
void set_testrunner_default_timeout(int s);
void set_testrunner_timeout(int s);
__MACOSX/assign3/assign3_part2/._testrunner.h
assign3/assign3_part2/worker.h
#ifndef __WORKER_H_
#define __WORKER_H_
20. __MACOSX/assign3/assign3_part2/._list.h
assign3/assign3_part2/README.txt
SMP5: Scheduler with Signals
============================
This MP is a variation of SMP4.
In the last MP, we built a simulated OS process scheduler. The
scheduler can
hold only a certain number of processes (workers) at one time.
Once the process
has been accepted into the scheduler, the scheduler decides in
what order the
processes execute. We implemented two scheduling algorithms:
FIFO and Round
Robin.
In this MP, we are to simulate a time-sharing system by using
signals and
timers. We will only implement the Round Robin algorithm.
Instead of using
iterations to model the concept of "time slices" (as in the last
MP), we use
interval timers. The scheduler is installed with an interval
timer. The timer
starts ticking when the scheduler picks a thread to use the CPU
which in turn
signals the thread when its time slice is finished thus allowing
the scheduler
to pick another thread and so on. When a thread has completely
finished its work
it leaves the scheduler to allow a waiting thread to enter. Please
note that in
this MP, only the timer and scheduler send signals. The threads
passively handle
21. the signals without signaling back to the scheduler.
The program takes a number of arguments. Arg1 determines the
number of jobs
(threads in our implementation) created; arg2 specifies the
queue size of the
scheduler. Arg3 through argN gives the duration (the required
time slices to
complete a job) of each job. Hence if we create 2 jobs, we
should supply arg3
and arg4 for the required duration. You can assume that the
autograder will
always supply the correct number of arguments and hence you
do not have to
detect invalid input.
Here is an example of program output, once the program is
complete:
% scheduler 3 2 3 2 3
Main: running 3 workers with queue size 2 for quanta:
3 2 3
Main: detaching worker thread 3075926960.
Main: detaching worker thread 3065437104.
Main: detaching worker thread 3054947248.
Main: waiting for scheduler 3086416816.
Scheduler: waiting for workers.
Thread 3075926960: in scheduler queue.
Thread 3075926960: suspending.
Thread 3065437104: in scheduler queue.
Thread 3065437104: suspending.
Scheduler: scheduling.
Scheduler: resuming 3075926960.
Thread 3075926960: resuming.
Scheduler: suspending 3075926960.
Scheduler: scheduling.
23. Thread 3054947248: resuming.
Scheduler: suspending 3054947248.
Thread 3054947248: leaving scheduler queue.
Thread 3054947248: terminating.
The total wait time is 12.062254 seconds.
The total run time is 7.958618 seconds.
The average wait time is 4.020751 seconds.
The average run time is 2.652873 seconds.
The goal of this MP is to help you understand (1) how signals
and timers work,
and (2) how to evaluate the performance of your program. You
will first
implement the time-sharing system using timers and signals.
Then, you will
evaluate the overall performance of your program by keeping
track of how long
each thread is idle, running, etc.
The program will use these four signals:
SIGALRM: sent by the timer to the scheduler, to indicate
another time
quantum has passed.
SIGUSR1: sent by the scheduler to a worker, to tell it to
suspend.
SIGUSR2: sent by the scheduler to a suspended worker, to tell
it to resume.
SIGTERM: sent by the scheduler to a worker, to tell it to
cancel.
You will need to set up the appropriate handlers and masks for
these signals.
24. You will use these functions:
clock_gettime
pthread_sigmask
pthread_kill
sigaction
sigaddset
sigemptyset
sigwait
timer_settime
timer_create
Also, make sure you understand how the POSIX:TMR interval
timer works.
There are two ways you can test your code. You can run the
built-in grading
tests by running "scheduler -test -f0 rr". This runs 5 tests, each
of which can
be run individually. You can also test you program with
specific parameters by
running "scheduler -test gen ..." where the ellipsis contains the
parameters you
would pass to scheduler.
Programming
===========
Part I: Modify the scheduler code (scheduler.c)
-----------------------------------------------
We use the scheduler thread to setup the timer and handle the
scheduling for the
system. The scheduler handles the SIGALRM events that come
from the timer, and
sends out signals to the worker threads.
25. Step 1.
Modify the code in init_sched_queue() function in scheduler.c
to initialize the
scheduler with a POSIX:TMR interval timer. Use
CLOCK_REALTIME in timer_create().
The timer will be stored in the global variable "timer", which
will be started
in scheduler_run() (see Step 4 below).
Step 2.
Implement setup_sig_handlers(). Use sigaction() to install
signal handlers for
SIGALRM, SIGUSR1, and SIGTERM. SIGALRM should
trigger timer_handler(), SIGUSR1
should trigger suspend_thread(), and SIGTERM should trigger
cancel_thread().
Notice no handler is installed for SIGUSR2; this signal will be
handled
differently, in step 8.
Step 3.
In the scheduler_run() function, start the timer. Use
timer_settime(). The
time quantum (1 second) is given in scheduler.h. The timer
should go off
repeatedly at regular intervals defined by the timer quantum.
In Round-Robin, whenever the timer goes off, the scheduler
suspends the
currently running thread, and tells the next thread to resume its
operations
26. using signals. These steps are listed in timer_handler(), which is
called every
time the timer goes off. In this implementation, the timer
handler makes use of
suspend_worker() and resume_worker() to accomplush these
steps.
Step 4.
Complete the suspend_worker() function. First, update the
info->quanta value.
This is the number of quanta that remain for this thread to
execute. It is
initialized to the value passed on the command line, and
decreases as the thread
executes. If there is any more work for this worker to do, send
it a signal to
suspend, and update the scheduler queue. Otherwise, cancel the
thread.
Step 5.
Complete the cancel_worker() function by sending the
appropriate signal to the
thread, telling it to kill itself.
Step 6.
Complete the resume_worker() function by sending the
appropriate signal to the
thread, telling it to resume execution.
Part II: Modify the worker code (worker.c)
------------------------------------------
27. In this section, you will modify the worker code to correctly
handle the signals
from the scheduler that you implemented in the previous
section.
You need to modify the thread functions so that it immediately
suspends the
thread, waiting for a resume signal from the scheduler. You will
need to use
sigwait() to force the thread to suspend itself and wait for a
resume signal.
You need also to implement a signal handler in worker.c to
catch and handle the
suspend signals.
Step 7.
Modify start_worker() to (1) block SIGUSR2 and SIGALRM,
and (2) unblock SIGUSR1
and SIGTERM.
Step 8.
Implement suspend_thread(), the handler for the SIGUSR1
signal. The
thread should block until it receives a resume (SIGUSR2)
signal.
Part III: Modify the evaluation code (scheduler.c)
--------------------------------------------------
This program keeps track of run time, and wait time. Each
thread saves these
two values regarding its own execution in its thread_info_t.
Tracking these
28. values requires also knowing the last time the thread suspended
or resumed.
Therefore, these two values are also kept in thread_info_t. See
scheduler.h.
In this section, you will implement the functions that calculate
run time and
wait time. All code that does this will be in scheduler.c. When
the program
is done, it will collect all these values, and print out the total
and average
wait time and run time. For your convenience, you are given a
function
time_difference() to compute the difference between two times
in microseconds.
Step 9.
Modify create_workers() to initialize the various time variables.
Step 10.
Implement update_run_time(). This is called by
suspend_worker().
Step 11.
Implement update_wait_time(). This is called by
resume_worker().
Questions
==========
Question 1.
Why do we block SIGUSR2 and SIGALRM in worker.c? Why
29. do we unblock SIGUSR1 and
SIGTERM in worker.c?
Question 2.
We use sigwait() and sigaction() in our code. Explain the
difference between the
two. (Please explain from the aspect of thread behavior rather
than syntax).
Question 3.
When we use POSIX:TMR interval timer, we are using relative
time. What is the
alternative? Explain the difference between the two.
Question 4.
Look at start_worker() in worker.c, a worker thread is executing
within an
infinite loop at the end. When does a worker thread terminate?
Question 5.
When does the scheduler finish? Why does it not exit when the
scheduler queue
is empty?
Question 6.
After a thread is scheduled to run, is it still in the sched_queue?
When is it
removed from the head of the queue? When is it removed from
the queue completely?
Question 7.
We've removed all other condition variables in SMP4, and
replaced them with a
timer and signals. Why do we still use the semaphore
queue_sem?
30. Question 8.
What's the purpose of the global variable "completed" in
scheduler.c? Why do we
compare "completed" with thread_count before we
wait_for_queue() in
next_worker()?
Question 9.
We only implemented Round Robin in this SMP. If we want to
implement a FIFO
scheduling algorithm and keep the modification as minimum,
which function in
scheduler.c is the one that you should modify? Briefly describe
how you would
modify this function.
Question 10.
In this implementation, the scheduler only changes threads
when the time quantum
expires. Briefly explain how you would use an additional signal
to allow the
scheduler to change threads in the middle of a time quantum. In
what situations
would this be useful?
__MACOSX/assign3/assign3_part2/._README.txt
assign3/assign3_part2/scheduler.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <signal.h>
31. #include "scheduler.h"
#include "worker.h"
/*
* define the extern global variables here.
*/
sem_t queue_sem; /* semaphore for scheduler queue
*/
thread_info_list sched_queue; /* list of current workers */
static int quit = 0;
static timer_t timer;
static thread_info_t *currentThread= 0;
static long wait_times;
static long run_times;
static int completed = 0;
static int thread_count = 0;
static void exit_error(int); /* helper function. */
static void wait_for_queue();
/****************************************************
***************************
*
* Implement these functions.
*
*****************************************************
*************************/
/*
* This function intializes the queue semaphore and the queue
itself.
*/
/*
32. * Update the worker's current running time.
* This function is called every time the thread is suspended.
*/
void update_run_time(thread_info_t *info) {
/* TODO: implement this function */
}
/*
* Update the worker's current waiting time.
* This function is called every time the thread resumes.
*/
void update_wait_time(thread_info_t *info) {
/* TODO: implement this function */
}
static void init_sched_queue(int queue_size)
{
/* set up a semaphore to restrict access to the queue */
sem_init(&queue_sem, 0, queue_size);
/* initialize the scheduler queue */
sched_queue.head = sched_queue.tail = 0;
pthread_mutex_init(&sched_queue.lock, NULL);
/* TODO: initialize the timer */
}
/*
* signal a worker thread that it can resume.
*/
static void resume_worker(thread_info_t *info)
{
printf("Scheduler: resuming %lu.n", info->thrid);
33. /*
* TODO: signal the worker thread that it can resume
*/
/* update the wait time for the thread */
update_wait_time(info);
}
/*send a signal to the thread, telling it to kill itself*/
void cancel_worker(thread_info_t *info)
{
/* TODO: send a signal to the thread, telling it to kill
itself*/
/* Update global wait and run time info */
wait_times += info->wait_time;
run_times += info->run_time;
completed++;
/* Update schedule queue */
leave_scheduler_queue(info);
if (completed >= thread_count) {
sched_yield(); /* Let other threads terminate. */
printf("The total wait time is %f seconds.n",
(float)wait_times / 1000000);
printf("The total run time is %f seconds.n",
(float)run_times / 1000000);
printf("The average wait time is %f seconds.n",
(float)wait_times / 1000000 / thread_count);
printf("The average run time is %f seconds.n",
(float)run_times / 1000000 / thread_count);
}
}
34. /*
* signals a worker thread that it should suspend.
*/
static void suspend_worker(thread_info_t *info)
{
int whatgoeshere = 0;
printf("Scheduler: suspending %lu.n", info->thrid);
/*update the run time for the thread*/
update_run_time(info);
/* TODO: Update quanta remaining. */
/* TODO: decide whether to cancel or suspend thread */
if(whatgoeshere) {
/*
* Thread still running: suspend.
* TODO: Signal the worker thread that it should
suspend.
*/
/* Update Schedule queue */
list_remove(&sched_queue,info->le);
list_insert_tail(&sched_queue,info->le);
} else {
/* Thread done: cancel */
cancel_worker(info);
}
}
/*
* this is the scheduling algorithm
* pick the next worker thread from the available list
* you may need to add new information to the thread_info
35. struct
*/
static thread_info_t *next_worker()
{
if (completed >= thread_count)
return 0;
wait_for_queue();
printf("Scheduler: scheduling.n");
/* return the thread_info_t for the next thread to run */
return sched_queue.head->info;
}
void timer_handler()
{
thread_info_t *info = 0;
/* once the last worker has been removed, we're done. */
if (list_size(&sched_queue) == 0) {
quit = 1;
return;
}
/*suspend the current worker*/
if (currentThread)
suspend_worker(currentThread);
//resume the next worker
info = next_worker();
/* Update currentThread */
currentThread = info;
if (info)
resume_worker(info);
36. else
quit = 1;
}
/*
* Set up the signal handlers for SIGALRM, SIGUSR1, and
SIGTERM.
* TODO: Implement this function.
*/
void setup_sig_handlers() {
/* Setup timer handler for SIGALRM signal in scheduler */
/* Setup cancel handler for SIGTERM signal in workers */
/* Setup suspend handler for SIGUSR1 signal in workers
*/
}
/****************************************************
***************************
*
*
*
*****************************************************
*************************/
/*
* waits until there are workers in the scheduling queue.
*/
static void wait_for_queue()
{
while(!list_size(&sched_queue)) {
37. printf("Scheduler: waiting for workers.n");
sched_yield();
}
}
/*
* runs at the end of the program just before exit.
*/
static void clean_up()
{
/*
* destroy any mutexes/condition variables/semaphores
that were created.
* free any malloc'd memory not already free'd
*/
sem_destroy(&queue_sem);
pthread_mutex_destroy(&sched_queue.lock);
}
/*
* prints the program help message.
*/
static void print_help(const char *progname)
{
printf("usage: %s <num_threads> <queue_size> <i_1, i_2
... i_numofthreads>n", progname);
printf("tnum_threads: the number of worker threads to
runn");
printf("tqueue_size: the number of threads that can be in
the scheduler at one timen");
printf("ti_1, i_2 ...i_numofthreads: the number of quanta
each worker thread runsn");
}
/*
* prints an error summary and exits.
38. */
static void exit_error(int err_num)
{
fprintf(stderr, "failure: %sn", strerror(err_num));
exit(1);
}
/*
* creates the worker threads.
*/
static void create_workers(int thread_count, int *quanta)
{
int i = 0;
int err = 0;
for (i = 0; i < thread_count; i++) {
thread_info_t *info = (thread_info_t *)
malloc(sizeof(thread_info_t));
info->quanta = quanta[i];
if ((err = pthread_create(&info->thrid, NULL,
start_worker, (void *)info)) != 0) {
exit_error(err);
}
printf("Main: detaching worker thread %lu.n", info-
>thrid);
pthread_detach(info->thrid);
/* TODO: initialize the time variables for each thread
for performance evalution*/
}
}
/*
* runs the scheduler.
39. */
static void *scheduler_run(void *unused)
{
wait_for_queue();
/* TODO: start the timer */
/*keep the scheduler thread alive*/
while( !quit )
sched_yield();
return NULL;
}
/*
* starts the scheduler.
* returns 0 on success or exits program on failure.
*/
static int start_scheduler(pthread_t *thrid)
{
int err = 0;
if ((err = pthread_create(thrid, NULL, scheduler_run, 0))
!= 0) {
exit_error(err);
}
return err;
}
/*
* reads the command line arguments and starts the scheduler &
worker threads.
*/
int smp5_main(int argc, const char** argv)
{
40. int queue_size = 0;
int ret_val = 0;
int *quanta,i;
pthread_t sched_thread;
/* check the arguments. */
if (argc < 3) {
print_help(argv[0]);
exit(0);
}
thread_count = atoi(argv[1]);
queue_size = atoi(argv[2]);
quanta = (int*)malloc(sizeof(int)*thread_count);
if (argc != 3 + thread_count) {
print_help(argv[0]);
exit(0);
}
for ( i = 0; i < thread_count; i++)
quanta[i] = atoi(argv[i+3]);
printf("Main: running %d workers with queue size %d for
quanta:n", thread_count, queue_size);
for ( i = 0; i < thread_count; i++)
printf(" %d", quanta[i]);
printf("n");
/*setup the sig handlers for scheduler and workers*/
setup_sig_handlers();
/* initialize anything that needs to be done for the
scheduler queue. */
init_sched_queue(queue_size);
/* creates a thread for the scheduler. */
41. start_scheduler(&sched_thread);
/* creates the worker threads and returns. */
create_workers(thread_count, quanta);
/* wait for scheduler to finish */
printf("Main: waiting for scheduler %lu.n",
sched_thread);
pthread_join(sched_thread, (void **) &ret_val);
/* clean up our resources */
clean_up();
/* this will wait for all other threads */
pthread_exit(0);
}
long time_difference(const struct timespec *time1, const struct
timespec *time2) {
return (time1->tv_sec - time2->tv_sec) * 1000000 +
(time1->tv_nsec - time2->tv_nsec) / 1000;
}
__MACOSX/assign3/assign3_part2/._scheduler.c
assign3/assign3_part2/testrunner.c
/*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************/
/*
A simple testrunner framework
Original Author: L. Angrave
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
43. return s1 && s2 && !strcmp(s1, s2);
}
/* Callback function for qsort on strings */
static int mystrcmp(const void *p1, const void *p2)
{
return eql((const char *) p1, (const char *) p2);
}
/* Stats of all tests run so far */
typedef struct {
int ran, passed, failed;
} stats_t;
/* -- Signal handlers -- */
static pid_t child_pid;
static int sent_child_timeout_kill_signal;
static void kill_child_signal_handler(intsigno)
{
if (!child_pid)
return;
char m[] = "-Timeout(Killing test process)-";
write(0, m, sizeof(m) - 1);
kill(child_pid, SIGKILL);
sent_child_timeout_kill_signal = 1;
}
/* Internal function to run a test as a forked child. The child
process is terminated if it runs for more than a few seconds */
static int invoke_test_with_timelimit(testentry_t * test,
int redirect_stdouterr, int argc,
const char **argv)
{
45. sent_child_timeout_kill_signal = 0;
alarm(timeout_seconds);
wait_val = waitpid(child_pid, &wait_status, 0);
int child_exited_normally = WIFEXITED(wait_status);
int child_exit_value = WEXITSTATUS(wait_status);
int child_term_by_signal = WIFSIGNALED(wait_status);
int child_term_signal = WTERMSIG(wait_status);
if (child_term_by_signal) {
fprintf(stderr, "testrunner:Test terminated by signal
%dn",
child_term_signal);
fprintf(stderr,
"testrunner:waitpid returned %d
(child_pid=%d,wait_status=%d)",
wait_val, child_pid, wait_status);
}
if (child_pid != wait_val)
fprintf(stderr,
"testrunner: strange... wait_val != child_pidn");
int passed = (child_pid == wait_val) && (child_exit_value
== 0)
&& (child_exited_normally != 0);
alarm(0);
kill(child_pid, SIGKILL);
child_pid = 0;
return sent_child_timeout_kill_signal ? test_killed : passed
? 0 :
1;
}
}
46. /*
* run a test and update the stats. The main guts of this
functionality is provided by invoke_test_with_timelimit
* This outer wrapper updates thes output and statistics before
and after running the test.
*/
static int
run_one_test(stats_t * stats, testentry_t * test, int
redirect_stdouterr,
int argc, const char **argv)
{
int test_result;
assert(stats && test->name && argc > 0 && argv && *argv);
stats->ran++;
stats->failed++;
printf("%2d.%-20s:", stats->ran, test->name);
fflush(stdout);
test_result =
invoke_test_with_timelimit(test, redirect_stdouterr, argc,
argv);
if (test_result == 0) {
stats->failed--;
stats->passed++;
}
printf(":%sn", (test_result == 0 ? "pass" : test_result ==
2 ? "TIMEOUT * " : "FAIL *"));
return test_result != 0;
}
47. /* Help functionality to print out sorted list of test names and
suite names */
static void print_targets(testentry_t tests[], int count)
{
const char **array;
const char *previous;
int i;
array = (const char **) calloc(sizeof(const char *), count);
/* Sort the test names and print unique entries */
for (i = 0; i < count; i++)
array[i] = tests[i].name;
qsort(array, count, sizeof(array[0]), mystrcmp);
printf("nValid tests : all");
for (i = 0, previous = ""; i < count; i++)
if (!eql(previous, array[i]))
printf(" %s", (previous = array[i]));
/* Sort the suite names and print unique entries */
for (i = 0; i < count; i++)
array[i] = tests[i].suite;
qsort(array, count, sizeof(array[0]), mystrcmp);
printf("nValid suites:");
for (i = 0, previous = ""; i < count; i++)
if (!eql(previous, array[i]))
printf(" %s", (previous = array[i]));
printf("n");
}
48. /*
* Main entry point for test harness
*/
int
run_testrunner(int argc, const char **argv, testentry_t tests[],
int test_count)
{
const char *test_name, *target;
int i;
stats_t stats;
int target_matched, max_errors_before_quit,
redirect_stdouterr;
memset(&stats, 0, sizeof(stats));
max_errors_before_quit = 1;
redirect_stdouterr = 0;
assert(tests != NULL);
assert(test_count > 0);
assert(argc > 0 && argv && *argv);
while (true) {
target = argc > 1 ? argv[1] : "";
assert(target);
if (*target != '-')
break;
argc--;
argv++;
if (target[1] == 'f' && target[2])
max_errors_before_quit = atoi(target + 1);
else if (target[1] == 'r')
redirect_stdouterr = 1;
}
target_matched = false;