assign4-2/.DS_Store
assign4-2/assign4_part2/mymem.h
#include <stddef.h>
typedef enum strategies_enum
{
NotSet = 0,
Best = 1,
Worst = 2,
First = 3,
Next = 4
} strategies;
char *strategy_name(strategies strategy);
strategies strategyFromString(char * strategy);
void initmem(strategies strategy, size_t sz);
void *mymalloc(size_t requested);
void myfree(void* block);
int mem_holes();
int mem_allocated();
int mem_free();
int mem_total();
int mem_largest_free();
int mem_small_free(int size);
char mem_is_alloc(void *ptr);
void* mem_pool();
void print_memory();
void print_memory_status();
void try_mymem(int argc, char **argv);
assign4-2/assign4_part2/memorytests.c
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <unistd.h>
#include "mymem.h"
#include "testrunner.h"
/* performs a randomized test:
totalSize == the total size of the memory pool, as passed to initmem2
totalSize must be less than 10,000 * minBlockSize
fillRatio == when the allocated memory is >= fillRatio * totalSize, a block is freed;
otherwise, a new block is allocated.
If a block cannot be allocated, this is tallied and a random block is freed immediately thereafter in the next iteration
minBlockSize, maxBlockSize == size for allocated blocks is picked uniformly at random between these two numbers, inclusive
*/
void do_randomized_test(int strategyToUse, int totalSize, float fillRatio, int minBlockSize, int maxBlockSize, int iterations)
{
void * pointers[10000];
int storedPointers = 0;
int strategy;
int lbound = 1;
int ubound = 4;
int smallBlockSize = maxBlockSize/10;
if (strategyToUse>0)
lbound=ubound=strategyToUse;
FILE *log;
log = fopen("tests.log","a");
if(log == NULL) {
perror("Can't append to log file.\n");
return;
}
fprintf(log,"Running randomized tests: pool size == %d, fill ratio == %f, block size is from %d to %d, %d iterations\n",totalSize,fillRatio,minBlockSize,maxBlockSize,iterations);
fclose(log);
for (strategy = lbound; strategy <= ubound; strategy++)
{
double sum_largest_free = 0;
double sum_hole_size = 0;
double sum_allocated = 0;
int failed_allocations = 0;
double sum_small = 0;
struct timespec execstart, execend;
int force_free = 0;
int i;
storedPointers = 0;
initmem(strategy,totalSize);
clock_gettime(CLOCK_REALTIME, &execstart);
for (i = 0; i < iterations; i++)
{
if ( (i % 10000)==0 )
srand ( time(NULL) );
if (!force_free && (mem_free() > (totalSize * (1-fillRatio))))
{
int newBlockSize = (rand()%(maxBlockSize-minBlockSize+1))+minBlockSize;
/* allocate */
void * pointer = mymalloc(newBlockSize);
if (pointer != NULL)
pointers[storedPointers++] = pointer;
else
{
failed_allocations++;
force_free = 1;
}
}
else
{
int chosen;
void * pointe ...
gptips1.0/concrete.mat
Concrete_Data:[1030x9 double array]
tr_ind:[1030x1 uint8 (logical) array]
te_ind:[1030x1 uint8 (logical) array]
tr_ind2:[773x1 uint8 (logical) array]
val_ind:[773x1 uint8 (logical) array]
gptips1.0/crossover.m
function [son,daughter]=crossover(mum,dad,gp)
%CROSSOVER GPTIPS function to crossover 2 GP expressions to produce 2 new
%GP expressions.
%
% [SON,DAUGHTER]=CROSSOVER(MUM,DAD,GP) uses standard subtree
% crossover on the expressions MUM and DAD to produce the offspring
% expressions SON and DAUGHTER.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also MUTATE
% select random crossover nodes in mum and dad expressions
m_position=picknode(mum,0,gp);
d_position=picknode(dad,0,gp);
% extract main and subtree expressions
[m_main,m_sub]=extract(m_position,mum);
[d_main,d_sub]=extract(d_position,dad);
%combine to form 2 new GPtrees
daughter=strrep(m_main,'$',d_sub);
son=strrep(d_main,'$',m_sub);
gptips1.0/demo2data.mat
gptips1.0/displaystats.m
function displaystats(gp)
%DISPLAYSTATS GPTIPS function to display run stats periodically.
%
% DISPLAYSTATS(GP) updates the screen with run stats at the interval
% specified in GP.RUN.VERBOSE
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also: UPDATESTATS
%only display info if required
if ~gp.runcontrol.verbose || gp.runcontrol.quiet || mod(gp.state.count-1,gp.runcontrol.verbose)
return
end
gen=gp.state.count-1;
disp(['Generation ' num2str(gen)]);
disp(['Best fitness: ' num2str(gp.results.best.fitness)]);
disp(['Mean fitness: ' num2str(gp.state.meanfitness)]);
disp(['Best nodecount: ' num2str(gp.results.best.numnodes)]);
disp(' ');
gptips1.0/evalfitness.m
function [gp]=evalfitness(gp)
%EVALFITNESS GPTIPS function to call the user specified fitness function.
%
% [GP]=EVALFITNESS(GP) evaluates the the fitnesses of individuals stored
% in the GP structure and updates various other fields of GP accordingly.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also TREE2EVALSTR
% Loop through population and calculate fitnesses
for i=1:gp.runcontrol.pop_size
% update state to reflect the index of the individual that is about to
% be evaluated
gp.state.current_individual=i;
%First preprocess the cell array of string expressions into a form that
%Matlab can evaluate
evalstr=tree2evalstr(gp.pop{i},gp);
%store number of nodes (sum total for all genes)
gp.fitness.numnodes(i,1)=getnumnodes(gp.pop{i});
% Evaluate gp individual using fitness function
% (the try catch is to assign a poor fitness value
% to trees that violate Matlab's
% daft 'Nesting of {, [, and ( cannot exceed a depth of 32.' error.
try
[fitness,gp]=feval(gp.fitness.fitfun,evalstr,gp);
gp.fitness.values(i)=fitness;
catch
if ~strncmpi(lasterr,'Nesting of {',12);
error(lasterr);
...
Add a 3rd field help that contains a short help string for each of t.pdfinfo245627
Add a 3rd field help that contains a short help string for each of the commands you were to
implement in assignment #3. Make sure that your array(s) are big enough to handle 5 extra items
beyond your initialization. To save time only include help for exercises 4, 5, 6 and 8 in this
assignment, and use No help for the other entries.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
void ctrlCHandler(int signum)
{
fprintf(stderr,"Command server terminated using C\n");
exit(1);
}
char * fExport(char *cmd, char *tokensleft[])
{
setenv(tokensleft[0],tokensleft[1],1);
return "Command 'export' was received";
}
char * fChdir(char *cmd,char *tokensleft[])
{
int ch=chdir(tokensleft[0]);
if(ch<0)
perror("chdir change of directory not successful\n");
else
printf("chdir change of directory successful\n");
return "Command 'chdir' was received\n";
}
char * fAccess(char *cmd,char *tokensleft[])
{
int exists =0;
for(int i=0;tokensleft[i]; i++) {
exists =0;
if(access(tokensleft[i],F_OK)==0){
exists = 1;
printf("file %s exists\n",tokensleft[i]);
}else{
printf("file %s does not exists\n",tokensleft[i]);
}
if (exists == 1){
if(access(tokensleft[i],R_OK)==0) {
printf("file %s is readable\n",tokensleft[i]);
}else{printf("file %s is not readable\n",tokensleft[i]);}
if(access(tokensleft[i],W_OK)==0) {
printf("file %s is writeable\n",tokensleft[i]);
}else{
printf("file %s is not writeable\n",tokensleft[i]);
}
if(access(tokensleft[i],X_OK)==0) {
printf("file %s is executeable\n",tokensleft[i]);
}else{
printf("file %s is not executeable\n",tokensleft[i]);
}
}// exists if
} //for
return "Command 'acsess' was received\n";
}
char * fChmod(char *cmd,char *tokensleft[])
{
unsigned int octalPerm;
sscanf(tokensleft[0],"%o",&octalPerm);
for(int i=1;tokensleft[i]; i++) {
if(chmod(tokensleft[i],octalPerm)==0 ){
chmod(tokensleft[i],octalPerm);
}else{
printf("Error: %s \n",strerror(errno));
}
}
return "Command 'chmod' was received";
}
char * fPath(char *cmd,char *tokensleft[])
{
char *pathLink;
char actualPath[PATH_MAX+1];
char *pointer;
char *bName;
char *dName;
for(int i=0;tokensleft[i]; i++) {
pathLink = tokensleft[i];
pointer =realpath(pathLink,actualPath);
bName = basename(actualPath);
dName = dirname(tokensleft[i]);
if (pointer){
printf("The Real path of %s is: %s\n",tokensleft[i],actualPath);
printf("The Dir name path of %s is: %s\n",tokensleft[i],dName);
printf("The Base name of %s is: %s\n",tokensleft[i],bName);
}else{
printf("Error: %s \n",strerror(errno));
}
}
return "Command 'path' was received";
}
char * fTouch(char *cmd,char *tokensleft[])
{
extern int optind,optopt,opterr;
struct FLAG{
bool aFlag;
bool mFlag;
} flags = { false, false };
int t1 = time(NULL), t2 = time(NULL);
int argc = 0;
int flag;
for (int i = 0; tokensleft[i]; i++) {
argc++;
}
while ((flag = getopt(argc, tokensleft, "m.
gptips1.0/concrete.mat
Concrete_Data:[1030x9 double array]
tr_ind:[1030x1 uint8 (logical) array]
te_ind:[1030x1 uint8 (logical) array]
tr_ind2:[773x1 uint8 (logical) array]
val_ind:[773x1 uint8 (logical) array]
gptips1.0/crossover.m
function [son,daughter]=crossover(mum,dad,gp)
%CROSSOVER GPTIPS function to crossover 2 GP expressions to produce 2 new
%GP expressions.
%
% [SON,DAUGHTER]=CROSSOVER(MUM,DAD,GP) uses standard subtree
% crossover on the expressions MUM and DAD to produce the offspring
% expressions SON and DAUGHTER.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also MUTATE
% select random crossover nodes in mum and dad expressions
m_position=picknode(mum,0,gp);
d_position=picknode(dad,0,gp);
% extract main and subtree expressions
[m_main,m_sub]=extract(m_position,mum);
[d_main,d_sub]=extract(d_position,dad);
%combine to form 2 new GPtrees
daughter=strrep(m_main,'$',d_sub);
son=strrep(d_main,'$',m_sub);
gptips1.0/demo2data.mat
gptips1.0/displaystats.m
function displaystats(gp)
%DISPLAYSTATS GPTIPS function to display run stats periodically.
%
% DISPLAYSTATS(GP) updates the screen with run stats at the interval
% specified in GP.RUN.VERBOSE
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also: UPDATESTATS
%only display info if required
if ~gp.runcontrol.verbose || gp.runcontrol.quiet || mod(gp.state.count-1,gp.runcontrol.verbose)
return
end
gen=gp.state.count-1;
disp(['Generation ' num2str(gen)]);
disp(['Best fitness: ' num2str(gp.results.best.fitness)]);
disp(['Mean fitness: ' num2str(gp.state.meanfitness)]);
disp(['Best nodecount: ' num2str(gp.results.best.numnodes)]);
disp(' ');
gptips1.0/evalfitness.m
function [gp]=evalfitness(gp)
%EVALFITNESS GPTIPS function to call the user specified fitness function.
%
% [GP]=EVALFITNESS(GP) evaluates the the fitnesses of individuals stored
% in the GP structure and updates various other fields of GP accordingly.
%
% (c) Dominic Searson 2009
%
% v1.0
%
% See also TREE2EVALSTR
% Loop through population and calculate fitnesses
for i=1:gp.runcontrol.pop_size
% update state to reflect the index of the individual that is about to
% be evaluated
gp.state.current_individual=i;
%First preprocess the cell array of string expressions into a form that
%Matlab can evaluate
evalstr=tree2evalstr(gp.pop{i},gp);
%store number of nodes (sum total for all genes)
gp.fitness.numnodes(i,1)=getnumnodes(gp.pop{i});
% Evaluate gp individual using fitness function
% (the try catch is to assign a poor fitness value
% to trees that violate Matlab's
% daft 'Nesting of {, [, and ( cannot exceed a depth of 32.' error.
try
[fitness,gp]=feval(gp.fitness.fitfun,evalstr,gp);
gp.fitness.values(i)=fitness;
catch
if ~strncmpi(lasterr,'Nesting of {',12);
error(lasterr);
...
Add a 3rd field help that contains a short help string for each of t.pdfinfo245627
Add a 3rd field help that contains a short help string for each of the commands you were to
implement in assignment #3. Make sure that your array(s) are big enough to handle 5 extra items
beyond your initialization. To save time only include help for exercises 4, 5, 6 and 8 in this
assignment, and use No help for the other entries.
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
void ctrlCHandler(int signum)
{
fprintf(stderr,"Command server terminated using C\n");
exit(1);
}
char * fExport(char *cmd, char *tokensleft[])
{
setenv(tokensleft[0],tokensleft[1],1);
return "Command 'export' was received";
}
char * fChdir(char *cmd,char *tokensleft[])
{
int ch=chdir(tokensleft[0]);
if(ch<0)
perror("chdir change of directory not successful\n");
else
printf("chdir change of directory successful\n");
return "Command 'chdir' was received\n";
}
char * fAccess(char *cmd,char *tokensleft[])
{
int exists =0;
for(int i=0;tokensleft[i]; i++) {
exists =0;
if(access(tokensleft[i],F_OK)==0){
exists = 1;
printf("file %s exists\n",tokensleft[i]);
}else{
printf("file %s does not exists\n",tokensleft[i]);
}
if (exists == 1){
if(access(tokensleft[i],R_OK)==0) {
printf("file %s is readable\n",tokensleft[i]);
}else{printf("file %s is not readable\n",tokensleft[i]);}
if(access(tokensleft[i],W_OK)==0) {
printf("file %s is writeable\n",tokensleft[i]);
}else{
printf("file %s is not writeable\n",tokensleft[i]);
}
if(access(tokensleft[i],X_OK)==0) {
printf("file %s is executeable\n",tokensleft[i]);
}else{
printf("file %s is not executeable\n",tokensleft[i]);
}
}// exists if
} //for
return "Command 'acsess' was received\n";
}
char * fChmod(char *cmd,char *tokensleft[])
{
unsigned int octalPerm;
sscanf(tokensleft[0],"%o",&octalPerm);
for(int i=1;tokensleft[i]; i++) {
if(chmod(tokensleft[i],octalPerm)==0 ){
chmod(tokensleft[i],octalPerm);
}else{
printf("Error: %s \n",strerror(errno));
}
}
return "Command 'chmod' was received";
}
char * fPath(char *cmd,char *tokensleft[])
{
char *pathLink;
char actualPath[PATH_MAX+1];
char *pointer;
char *bName;
char *dName;
for(int i=0;tokensleft[i]; i++) {
pathLink = tokensleft[i];
pointer =realpath(pathLink,actualPath);
bName = basename(actualPath);
dName = dirname(tokensleft[i]);
if (pointer){
printf("The Real path of %s is: %s\n",tokensleft[i],actualPath);
printf("The Dir name path of %s is: %s\n",tokensleft[i],dName);
printf("The Base name of %s is: %s\n",tokensleft[i],bName);
}else{
printf("Error: %s \n",strerror(errno));
}
}
return "Command 'path' was received";
}
char * fTouch(char *cmd,char *tokensleft[])
{
extern int optind,optopt,opterr;
struct FLAG{
bool aFlag;
bool mFlag;
} flags = { false, false };
int t1 = time(NULL), t2 = time(NULL);
int argc = 0;
int flag;
for (int i = 0; tokensleft[i]; i++) {
argc++;
}
while ((flag = getopt(argc, tokensleft, "m.
I am Marianna P. I am a C Exam Expert at programmingexamhelp.com. I hold a Bachelor of Information Technology from, the California Institute of Technology, United States. I have been helping students with their exams for the past 7 years. You can hire me to take your exam in C.
Visit programmingexamhelp.com or email support@programmingexamhelp.com. You can also call on +1 678 648 4277 for any assistance with the C Exam.
Can you give an example of a binary heap programCan you give an .pdfarorasales234
Can you give an example of a binary heap program
Can you give an example of a binary heap program
Solution
/*
* C Program to Implement a Heap & provide Insertion & Deletion Operation
*/
#include
int array[100], n;
main()
{
int choice, num;
n = 0;/*Represents number of nodes in the heap*/
while(1)
{
printf(\"1.Insert the element \ \");
printf(\"2.Delete the element \ \");
printf(\"3.Display all elements \ \");
printf(\"4.Quit \ \");
printf(\"Enter your choice : \");
scanf(\"%d\", &choice);
switch(choice)
{
case 1:
printf(\"Enter the element to be inserted to the list : \");
scanf(\"%d\", &num);
insert(num, n);
n = n + 1;
break;
case 2:
printf(\"Enter the elements to be deleted from the list: \");
scanf(\"%d\", &num);
delete(num);
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf(\"Invalid choice \ \");
}/*End of switch */
}/*End of while */
}/*End of main()*/
display()
{
int i;
if (n == 0)
{
printf(\"Heap is empty \ \");
return;
}
for (i = 0; i < n; i++)
printf(\"%d \", array[i]);
printf(\"\ \");
}/*End of display()*/
insert(int num, int location)
{
int parentnode;
while (location > 0)
{
parentnode =(location - 1)/2;
if (num <= array[parentnode])
{
array[location] = num;
return;
}
array[location] = array[parentnode];
location = parentnode;
}/*End of while*/
array[0] = num; /*assign number to the root node */
}/*End of insert()*/
delete(int num)
{
int left, right, i, temp, parentnode;
for (i = 0; i < num; i++) {
if (num == array[i])
break;
}
if (num != array[i])
{
printf(\"%d not found in heap list\ \", num);
return;
}
array[i] = array[n - 1];
n = n - 1;
parentnode =(i - 1) / 2; /*find parentnode of node i */
if (array[i] > array[parentnode])
{
insert(array[i], i);
return;
}
left = 2 * i + 1; /*left child of i*/
right = 2 * i + 2; /* right child of i*/
while (right < n)
{
if (array[i] >= array[left] && array[i] >= array[right])
return;
if (array[right] <= array[left])
{
temp = array[i];
array[i] = array[left];
array[left] = temp;
i = left;
}
else
{
temp = array[i];
array[i] = array[right];
array[right] = temp;
i = right;
}
left = 2 * i + 1;
right = 2 * i + 2;
}/*End of while*/
if (left == n - 1 && array[i]) {
temp = array[i];
array[i] = array[left];
array[left] = temp;
}
}
Output:.
I am Simon M. I am a C Homework Expert at programminghomeworkhelp.com. I hold a Ph.D. in Programming, from Glasgow University, UK. I have been helping students with their homework for the past 10 years. I solve homework related to C.
Visit programminghomeworkhelp.com or email support@programminghomeworkhelp.com.
You can also call on +1 678 648 4277 for any assistance with C Homework.
Using standard libraries like stdio and sdtlib.h and using stats.h a.pdffashiongallery1
Unlike the Federal income tax, most states do not require some form of state income tax.
True
False
Solution
Correct answer is True
Unlike Federal income tax, most states do not require some form of state income tax - This
statement is true as fililng of Fedral income tax return is mandatory for almost everybody but
some US states like Alaska, Florida, Navada, South Dakota, Texas, Washington and Wayoming
do not require filing of state income tax..
Learning ResourcesRequired ReadingsToseland, R. W., & Ri.docxfestockton
Learning Resources
Required Readings
Toseland, R. W., & Rivas, R. F. (2017).
An introduction to group work practice
(8th ed.). Boston, MA: Pearson.
Chapter 11, “Task Groups: Foundation Methods” (pp. 336-363)
Chapter 12, “Task Groups: Specialized Methods” (pp. 364–395)
Van Velsor, P. (2009). Task groups in the school setting: Promoting children’s social and emotional learning.
Journal for Specialists in Group Work
,
34
(3), 276–292.
Document:
Group Wiki Project Guidelines (PDF)
Recommended Resources
Holosko, M. J., Dulmus, C. N., & Sowers, K. M. (2013). Social work practice with individuals and families: Evidence-informed assessments and interventions. Hoboken, NJ: John Wiley & Sons, Inc.
Chapter 1 “Assessment of Children”
Chapter 2 “Intervention with Children”
Discussion: Task Groups
Group work is a commonly used method within school settings. Because peer interaction is important in the emotional and social development of children, the task group can serve as a wonderful therapeutic setting and tool; however, many factors should be considered when implementing this type of intervention.
For this Discussion, read the Van Velsor (2009) article.
By Day 3
Post
your understanding of task groups as an intervention for children. Use the model for effective problem solving to compare and contrast (how to identify the problem, develop goals, collect data). How does this model differ from a traditional treatment group? What are the advantages and possible disadvantages of this model? Describe how you might use this model for adults. What populations would most benefit from this model?
.
LeamosEscribamos Completa el párrafo con las formas correctas de lo.docxfestockton
Leamos/Escribamos Completa el párrafo con las formas correctas de los verbos en paréntesis. Usa el pretérito o el imperfecto.
Yo __1__ (criarse) en el campo, pero mi familia __2__
(mudarse) a la ciudad cuando yo tenía doce años. Hablábamos
aymara en mi pueblo, y mi mamá no __3__ (expresarse) bien en
español. Mis hermanos y yo __4__ (comunicarse) sin problema
porque habíamos estudiado español en el colegio. Con dificultad
nosotros __5__ (acostumbrarse) al estilo de vida.Yo __6__
(preocuparse) por todo. No me __7__ (gustar) el ruido de los
carros. Pero poco a poco, nostros __8__ (asimilar) el modo de
ser de la gente de la cuidad.Yo __9__ (graduarse) de la
universidad hace poco, mi hermano mayor ahora es arquitecto, y
mi hermano menor __10__ (casarse) el mes pasado.
.
More Related Content
Similar to assign4-2.DS_Storeassign4-2assign4_part2mymem.h#include.docx
I am Marianna P. I am a C Exam Expert at programmingexamhelp.com. I hold a Bachelor of Information Technology from, the California Institute of Technology, United States. I have been helping students with their exams for the past 7 years. You can hire me to take your exam in C.
Visit programmingexamhelp.com or email support@programmingexamhelp.com. You can also call on +1 678 648 4277 for any assistance with the C Exam.
Can you give an example of a binary heap programCan you give an .pdfarorasales234
Can you give an example of a binary heap program
Can you give an example of a binary heap program
Solution
/*
* C Program to Implement a Heap & provide Insertion & Deletion Operation
*/
#include
int array[100], n;
main()
{
int choice, num;
n = 0;/*Represents number of nodes in the heap*/
while(1)
{
printf(\"1.Insert the element \ \");
printf(\"2.Delete the element \ \");
printf(\"3.Display all elements \ \");
printf(\"4.Quit \ \");
printf(\"Enter your choice : \");
scanf(\"%d\", &choice);
switch(choice)
{
case 1:
printf(\"Enter the element to be inserted to the list : \");
scanf(\"%d\", &num);
insert(num, n);
n = n + 1;
break;
case 2:
printf(\"Enter the elements to be deleted from the list: \");
scanf(\"%d\", &num);
delete(num);
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf(\"Invalid choice \ \");
}/*End of switch */
}/*End of while */
}/*End of main()*/
display()
{
int i;
if (n == 0)
{
printf(\"Heap is empty \ \");
return;
}
for (i = 0; i < n; i++)
printf(\"%d \", array[i]);
printf(\"\ \");
}/*End of display()*/
insert(int num, int location)
{
int parentnode;
while (location > 0)
{
parentnode =(location - 1)/2;
if (num <= array[parentnode])
{
array[location] = num;
return;
}
array[location] = array[parentnode];
location = parentnode;
}/*End of while*/
array[0] = num; /*assign number to the root node */
}/*End of insert()*/
delete(int num)
{
int left, right, i, temp, parentnode;
for (i = 0; i < num; i++) {
if (num == array[i])
break;
}
if (num != array[i])
{
printf(\"%d not found in heap list\ \", num);
return;
}
array[i] = array[n - 1];
n = n - 1;
parentnode =(i - 1) / 2; /*find parentnode of node i */
if (array[i] > array[parentnode])
{
insert(array[i], i);
return;
}
left = 2 * i + 1; /*left child of i*/
right = 2 * i + 2; /* right child of i*/
while (right < n)
{
if (array[i] >= array[left] && array[i] >= array[right])
return;
if (array[right] <= array[left])
{
temp = array[i];
array[i] = array[left];
array[left] = temp;
i = left;
}
else
{
temp = array[i];
array[i] = array[right];
array[right] = temp;
i = right;
}
left = 2 * i + 1;
right = 2 * i + 2;
}/*End of while*/
if (left == n - 1 && array[i]) {
temp = array[i];
array[i] = array[left];
array[left] = temp;
}
}
Output:.
I am Simon M. I am a C Homework Expert at programminghomeworkhelp.com. I hold a Ph.D. in Programming, from Glasgow University, UK. I have been helping students with their homework for the past 10 years. I solve homework related to C.
Visit programminghomeworkhelp.com or email support@programminghomeworkhelp.com.
You can also call on +1 678 648 4277 for any assistance with C Homework.
Using standard libraries like stdio and sdtlib.h and using stats.h a.pdffashiongallery1
Unlike the Federal income tax, most states do not require some form of state income tax.
True
False
Solution
Correct answer is True
Unlike Federal income tax, most states do not require some form of state income tax - This
statement is true as fililng of Fedral income tax return is mandatory for almost everybody but
some US states like Alaska, Florida, Navada, South Dakota, Texas, Washington and Wayoming
do not require filing of state income tax..
Learning ResourcesRequired ReadingsToseland, R. W., & Ri.docxfestockton
Learning Resources
Required Readings
Toseland, R. W., & Rivas, R. F. (2017).
An introduction to group work practice
(8th ed.). Boston, MA: Pearson.
Chapter 11, “Task Groups: Foundation Methods” (pp. 336-363)
Chapter 12, “Task Groups: Specialized Methods” (pp. 364–395)
Van Velsor, P. (2009). Task groups in the school setting: Promoting children’s social and emotional learning.
Journal for Specialists in Group Work
,
34
(3), 276–292.
Document:
Group Wiki Project Guidelines (PDF)
Recommended Resources
Holosko, M. J., Dulmus, C. N., & Sowers, K. M. (2013). Social work practice with individuals and families: Evidence-informed assessments and interventions. Hoboken, NJ: John Wiley & Sons, Inc.
Chapter 1 “Assessment of Children”
Chapter 2 “Intervention with Children”
Discussion: Task Groups
Group work is a commonly used method within school settings. Because peer interaction is important in the emotional and social development of children, the task group can serve as a wonderful therapeutic setting and tool; however, many factors should be considered when implementing this type of intervention.
For this Discussion, read the Van Velsor (2009) article.
By Day 3
Post
your understanding of task groups as an intervention for children. Use the model for effective problem solving to compare and contrast (how to identify the problem, develop goals, collect data). How does this model differ from a traditional treatment group? What are the advantages and possible disadvantages of this model? Describe how you might use this model for adults. What populations would most benefit from this model?
.
LeamosEscribamos Completa el párrafo con las formas correctas de lo.docxfestockton
Leamos/Escribamos Completa el párrafo con las formas correctas de los verbos en paréntesis. Usa el pretérito o el imperfecto.
Yo __1__ (criarse) en el campo, pero mi familia __2__
(mudarse) a la ciudad cuando yo tenía doce años. Hablábamos
aymara en mi pueblo, y mi mamá no __3__ (expresarse) bien en
español. Mis hermanos y yo __4__ (comunicarse) sin problema
porque habíamos estudiado español en el colegio. Con dificultad
nosotros __5__ (acostumbrarse) al estilo de vida.Yo __6__
(preocuparse) por todo. No me __7__ (gustar) el ruido de los
carros. Pero poco a poco, nostros __8__ (asimilar) el modo de
ser de la gente de la cuidad.Yo __9__ (graduarse) de la
universidad hace poco, mi hermano mayor ahora es arquitecto, y
mi hermano menor __10__ (casarse) el mes pasado.
.
Leadership via vision is necessary for success. Discuss in detail .docxfestockton
Leadership via "vision" is necessary for success. Discuss in detail the qualities that a leader must exhibit in order to be considered visionary and, further, how these qualities may be learned and developed. Provide research and share insight on the determination of a specific leadership theory associated with leadership via vision. Cite your posting in proper APA format and ensure that your posting provides a minimum of 5 paragraphs.
.
Learning about Language by Observing and ListeningThe real.docxfestockton
Learning about Language by Observing and Listening
The real voyage of discovery consists not in seeking
new landscapes, but in having new eyes. Marcel Proust
The UCSD experience encompasses academic as well as social learning. Therefore, we learn not only from our courses, but from the people we meet on campus and the experiences we have with them. Life is a journey of self-discovery. As individuals, we are constantly seeking to determine who we are and where we belong in the world. Throughout this process, language is both a bridge and a barrier to communication and human growth.
The general subject matter for this essay is language or language communities. The source of your information will be what you observe and hear by listening to others. The goal is to do a project based on what our own minds can comprehend from diligent observation, note-taking, and reasoning. You should arrive at a reasoned (not emotional) conclusion. The conclusion/result of your experiment is your thesis and should be presented in the opening paragraph in one sentence. Secondary material should not be brought into this essay. Thus, this is not an essay that needs to be the result of academic texts or online sources. The research is what you see and how you interpret what you see and hear. It will be up to you to determine what particular focus your essay will take and wahat meaning you wish to convey to your reader. Do the exploratory writing activities on pages 73-76. These activities will guide you through an analysis of some of the reflections you completed in the first part of your book. Once you determine your focus, you will use the information you have already gathered and additional information you will research to clarify your ideas and provide evidence for the points you wish to make.
If you prefer a more direct prompt, the suggested topics listed below might be helpful to you. Choose one of the following topics to establish a focus and direction.
1) From your observations and conversations, what assumptions and stereotypes do we make about people based on language and behavior? What did you learn from the experiment?
2) You may examine body language as well as verbal language. Explore nonverbal communication in a group. What conclusions can you come to regarding the group based on nonverbal behavior?
3) Did you observe language differences between men and women here at UCSD Notice the ways in which men and women treat one another. Observe the language you hear on campus.
How do women greet one another? How do men greet each other? Do not just note the similarities or differences. Explain and interpret the information.
4) Observe and identify a code language on campus, on your job, or in your personal arena. How is language used? Is it effective? Analyze.
5) Have you become keenly aware of code switching? Who utilizes this language? In your observations and conversations, did you find code switching to be an acceptable form of lang.
Learning Accomplishment Profile-Diagnostic Spanish Language Edit.docxfestockton
Learning Accomplishment Profile-Diagnostic Spanish Language Edition
The Ages and Stages Questionnaires-Social Emotional (ASQ-SE)
Learning Accomplishment Profile-3 (LAP-3)
Mullen Scales of Early Learning
Purpose of the screening-what can an early childhood professional do with the results? What should happen next?
.
Learning about Language by Observing and ListeningThe real voy.docxfestockton
Learning about Language by Observing and Listening
The real voyage of discovery consists not in seeking
new landscapes, but in having new eyes. Marcel Proust
The UCSD experience encompasses academic as well as social learning. Therefore, we learn not only from our courses, but from the people we meet on campus and the experiences we have with them. Life is a journey of self-discovery. As individuals, we are constantly seeking to determine who we are and where we belong in the world. Throughout this process, language is both a bridge and a barrier to communication and human growth.
The general subject matter for this essay is language or language communities. The source of your information will be what you observe and hear by listening to others. The goal is to do a project based on what our own minds can comprehend from diligent observation, note-taking, and reasoning. You should arrive at a reasoned (not emotional) conclusion. The conclusion/result of your experiment is your thesis and should be presented in the opening paragraph in one sentence. Secondary material should not be brought into this essay. Thus, this is not an essay that needs to be the result of academic texts or online sources. The research is what you see and how you interpret what you see and hear. It will be up to you to determine what particular focus your essay will take and wahat meaning you wish to convey to your reader. Do the exploratory writing activities on pages 73-76. These activities will guide you through an analysis of some of the reflections you completed in the first part of your book. Once you determine your focus, you will use the information you have already gathered and additional information you will research to clarify your ideas and provide evidence for the points you wish to make.
If you prefer a more direct prompt, the suggested topics listed below might be helpful to you. Choose one of the following topics to establish a focus and direction.
1) From your observations and conversations, what assumptions and stereotypes do we make about people based on language and behavior? What did you learn from the experiment?
2) You may examine body language as well as verbal language. Explore nonverbal communication in a group. What conclusions can you come to regarding the group based on nonverbal behavior?
3) Did you observe language differences between men and women here at UCSD Notice the ways in which men and women treat one another. Observe the language you hear on campus.
How do women greet one another? How do men greet each other? Do not just note the similarities or differences. Explain and interpret the information.
4) Observe and identify a code language on campus, on your job, or in your personal arena. How is language used? Is it effective? Analyze.
5) Have you become keenly aware of code switching? Who utilizes this language? In your observations and conversations, did you find code switching to be an accepta.
LEARNING OUTCOMES1. Have knowledge and understanding of the pri.docxfestockton
LEARNING OUTCOMES:
1. Have knowledge and understanding of the principles of Constitutional and Administrative Law, and of the way in which these principles have developed.
2. Deal with issues relating to Constitutional and Administrative Law both systematically and creatively, recognising potential alternative conclusions for particular situations and providing supporting reasons for such conclusions.
3. Demonstrate self-direction and originality in tackling and solving problems relating to Constitutional and Administrative Law.
4. Research primary and secondary sources of Constitutional and Administrative Law.
5. Communicate thoughts and ideas in writing and/or orally, using the English language and legal terminology with care, clarity and accuracy.
6. Manage time effectively.
QUESTION:
A recently elected Government, concerned about rising gun crime by drug dealers, has introduced a Bill into Parliament to bring back the death penalty for any person convicted of causing death by the use of a firearm and which is also related to an illegal drug trade.
Human Rights UK (HRUK), part of a worldwide protest organisation called ‘Global Human Rights’ is opposed to the death penalty in any circumstances. HRUK has many thousands of members across the UK. The organisation is split into county groups and there is a thriving branch of over 1200 members in Penfield.
Sam Jones, the leader of the Penfield branch, has proposed a local demonstration against the Bill to take place on the 1
st
May 2014. The demonstration includes a march from the Town Hall in Penfield City Centre to the local War Memorial followed by speeches from senior members of the organisation.
The Chief Constable of Penfield Police, having been informed of the proposed protest is concerned about rumours that a small counter protest has been organised to disrupt the protest by a far right group opposed to human rights. He has issued a Notice to HRUK and Sam Jones under the Public Order Act 1986 which imposes the following conditions on the HRUK demonstration planned for 1
st
May 2014:-
Notice from the Chief Constable of Penfield Police:
1) any demonstration to be held by the HRUK between 1st March 2014 and 1
st
October 2014 should be held in Penfield Country Park, at least 25 miles from Penfield City Centre;
2) the maximum number of demonstrators shall be 25;
3) the maximum duration of the demonstration shall be 2 hours;
4) there should be no public speeches and;
5) that in the event of any counter demonstration or hostility shown towards HRUK members, the Penfield Police reserve the right to cancel the demonstration immediately
Advise, giving reasons, whether Sam Jones and/or HRUK can use the Human Rights Act 1998 to challenge the decision of the Chief Constable.
.
Leadership Style What do people do when they are leadingAssignme.docxfestockton
Leadership Style: What do people do when they are leading?
Assignment: Leadership Style: What Do People Do When They Are Leading?
Due Week 9 and worth 100 points
Choose one (1) of the following CEOs for this assignment: Ursula Burns (Xerox). Use the Internet to investigate the leadership style and effectiveness of the selected CEO.
Write a five to six (5-6) page paper in which you:
Provide a brief (one [1] paragraph) background of the CEO.
Analyze the CEO’s leadership style and philosophy, and how the CEO’s leadership style aligns with the culture.
Examine the CEO’s personal and organizational values.
Evaluate how the values of the CEO are likely to influence ethical behavior within the organization.
Determine the CEO’s three (3) greatest strengths and three (3) greatest weaknesses.
Select the quality that you believe contributes most to this leader’s success. Support your reasoning.
Assess how communication and collaboration, and power and politics influence group (i.e., the organization’s) dynamics.
Use at least five (5) quality academic resources in this assignment. Note: Wikipedia and other Websites do not qualify as academic resources.
Your assignment must follow these formatting requirements:
Be typed, double spaced, using Times New Roman font (size 12), with one-inch margins on all sides; citations and references must follow APA or school-specific format. Check with your professor for any additional instructions.
Include a cover page containing the title of the assignment, the student’s name, the professor’s name, the course title, and the date. The cover page and the reference page are not included in the required assignment page length.
The specific course learning outcomes associated with this assignment are:
Analyze the formation and dynamics of group behavior and work teams, including the application of power in groups.
Outline various individual and group decision-making processes and key factors affecting these processes.
Examine the primary conflict levels within organization and the process for negotiating resolutions.
Examine how power and influence empower and affect office politics, political interpretations, and political behavior.
Use technology and information resources to research issues in organizational behavior.
Write clearly and concisely about organizational behavior using proper writing me
.
Leadership Throughout HistoryHistory is filled with tales of leade.docxfestockton
Leadership Throughout History
History is filled with tales of leaders who were brave, selfless, and achieved glorious accomplishments. Your text discusses how leadership theory has been categorized throughout time, from the culture of ancient Egypt thousands of years ago, to the “toolbox” style of today.
The first category, known as the “Great Man” phase, focused on the traits that make an effective leader. This period ranges from circa 450 B.C. to the 1940s, and includes classic examples such as the aforementioned Egyptian period and the expansive influence of the Roman Empire.
The second category, known as the Behavior phase, spanned the 1940s to the 1960s, and focused on determining the types of behavior that leaders utilized to influence and affect others.
The final category is the Situational phase. This line of research began in the 1970s and is still present today. It suggests that leaders have a broad understanding of the various types of leadership styles, and can choose the appropriate one to handle a given situation.
I
n this Journal, discuss each phase, do research and provide examples of influential leaders from each phase, and explain how and why they were so influential.
Your Journal entry should be at least 500 words, and cite appropriate references in APA format.
.
Lean Inventory Management1. Why do you think lean inventory manage.docxfestockton
Lean Inventory Management
1. Why do you think lean inventory management can decrease transportation, capital expenses, and inventory storage?
2. List some products in your personal or family "inventory." How do you manage them? (For instance, do you constantly run to the store for milk? Do you throw out a lot of milk because of spoilage?) How can lean inventory change your way of managing these SKUs?
3. Identify a goods-producing or service-providing organization and discuss how it might make aggregate planning decisions.
4. Provide an argument for or against adopting a chase strategy for a major airline call center.
.
Leadership varies widely by culture and personality. An internationa.docxfestockton
Leadership varies widely by culture and personality. An international organization with locations in several countries must balance the local customs and cultures with those of the primary culture of the organizations’ headquarters. Using the Germany as the headquarters of an international Internet retail organization serving the USA and Canada research and discuss the differences that leaders would have to navigate in approach and adapting to different standards of behavior and culture within the countries.
.
Leadership is the ability to influence people toward the attainment .docxfestockton
Leadership is the ability to influence people toward the attainment of goals. The changing of the environment in which most organizations are operating has significantly influenced leadership systems in recent years, and has contributed to a shift in how we think about and practice leadership.
Analyze how leadership is changing in today’s organizations, including Level 5 leadership, servant leadership, and transformational leadership. Please discuss in 200-250 words.
.
Lawday. Court of Brightwaltham holden on Monday next after Ascension.docxfestockton
Lawday. Court of Brightwaltham holden on Monday next after Ascension Day in the twenty-first year of King Edward (A.D. 1293).
The tithingman of Conholt with his whole tithing present that all is well save that William of Mescombe has stopped up a . . . [the word is indecipherable in the manuscript, but Maitland thinks it is a watercourse] wrongfully. Therefore he is in mercy (12 d.). Also they say that Edith of Upton has cut down trees in the enclosure and the seisin of the lord contrary to a prohibition, and they say that she has no property and has fled into foreign parts, (amercement, 12 d.).
Adam Scot is made tithingman and sworn to a faithful exercise of his office.
John son of Hugh Poleyn enters on the land which Randolph Tailor held saving the right of everyone and gives for entry-money 4 marks and will pay 1 mark at Michaelmas in the twenty-second year of King Edward, 1 mark at Christmas next following, 1 mark at Easter, and 1 mark at Michaelmas next following, and for the due making of all these payments the said Hugh Poleyn finds sureties, to wit, Adam Scot, John Gosselyn, William of Mescombe, John Gyote. And because the said John is a minor the wardship of the said lands and tenements is delivered to his father the said Hugh Poleyn until he be of full age, on the terms of his performing the services due and accustomed for the same. Also there is granted to the said Hugh the crop now growing on the sown land, and the heriot due on this entry, for a half-mark payable at Michaelmas next on the security of the above-named sureties.
(a) Hugh Poleyn gives the lord 2 s. that he may have the judgment of the court as to his right in a certain tenement in Upton which J. son of Randolph Tailor claims as his right. And upon this the whole township of Brightwaltham sworn along with the whole township of Conholt say upon their oath that Hugh Poleyn has better right to hold the said tenement than anyone else has, and that he is the next heir by right of blood.
(The Conholt case as to the tenure of Edith wife of Robert Tailor according to the inquest made by the jurors. One Alan Poleyn held a tenement in Conholt upon servile terms and had a wife Cristina by name. The said Alan died when Richard was the farmer [of the manor]. Thereupon came the friends of the said Cristina and procured for her a part of the land by way of dower making a false suggestion and as though [the land] were of free condition, and this was to the great prejudice of the lord Abbot. Upon this came one Richard Aleyn and espoused the said Cristina and begot upon her one Randolph. Then Richard died, and the said Cristina of her own motion enfeoffed Randolph her son of the said tenement. Then Cristina died, and Randolph being in seisin of the said tenement espoused Edith the present demanding; and after Randolph's death Edith married Robert Tailor. Now you can see and give your counsel about the right of the said Edith. And know this, that if I had at hand the court-rolls of the.
Leaders face many hurdles when leading in multiple countries. There .docxfestockton
Leaders face many hurdles when leading in multiple countries. There are several examples of disastrous public relations fallout that have occurred when companies have outsourced work to other nations. When determining where to move offshore as a company, the leaders of the organization must make several decisions.
Using course theories and current multinational organizations that have locations in several countries, convey your own thoughts on the subject and address the following:
What leadership considerations must an organization weigh in selecting another country to open a location such as a manufacturing plant?
How might leaders need to change leadership styles to manage multinational locations?
What public relations issues might arise from such a decision?
How would you recommend such a company to demonstrate their social responsibility to their headquarters country as well as any offshore locations?
.
Last year Angelina Jolie had a double mastectomy because of re.docxfestockton
Last year Angelina Jolie had a double mastectomy because of results from a genetic test. Describe the science of the test and the reason for her decision. Do you agree with her choice, and do you agree with her decision to go public about her choice?
1 page essay with at least 1 reference
.
Leaders face many hurdles when leading in multiple countries. Ther.docxfestockton
Leaders face many hurdles when leading in multiple countries. There are several examples of disastrous public relations fallout that have occurred when companies have outsourced work to other nations. When determining where to move offshore as a company, the leaders of the organization must make several decisions.
Using course theories and current multinational organizations that have locations in several countries, convey your own thoughts on the subject and address the following:
What leadership considerations must an organization weigh in selecting another country to open a location such as a manufacturing plant?
How might leaders need to change leadership styles to manage multinational locations?
What public relations issues might arise from such a decision?
How would you recommend such a company to demonstrate their social responsibility to their headquarters country as well as any offshore locations?
Please submit your assignment.
This assignment will be assessed using the rubric provided
here
.
For assistance with your assignment, please use your text, Web resources, and all course materials.
.
Leaders today must be able to create a compelling vision for the org.docxfestockton
Leaders today must be able to create a compelling vision for the organization. They also must be able to create an aligned strategy and then execute it. Visions have two parts, the envisioned future and the core values that support that vision of the future. The ability to create a compelling vision is the primary distinction between leadership and management. Leaders need to create a vision that will frame the decisions and behavior of the organization and keep it focused on the future while also delivering on the short-term goals.
Respond to the following:
Assess your current leaders. These leaders could be those at your current or previous organizations or your educational institutions.
How effective are they at creating and communicating the organization vision?
How effective are they at developing a strategy and communicating it throughout the organization?
How effective are they at upholding the values of the organization?
Support your positions with specific examples or by citing credible sources.
.
Law enforcement professionals and investigators use digital fore.docxfestockton
Law enforcement professionals and investigators use digital forensic methods to solve crimes every day. Locate one current news article that explains how investigators may have used these techniques to solve a crime. Explain the crime that was solved, and the methods used to determine how the crime was committed. Some examples of crimes solved may include locating missing children, finding criminals who have fled the scene of a crime, or unsolved crimes from the past that have been solved due to the use of new techniques (such as DNA testing).
Your written assignment should be 3-4 paragraphs in your own words and should include a reference citation for your source of information.
.
LAW and Economics 4 questionsLaw And EconomicsTextsCoote.docxfestockton
LAW and Economics 4 questions
Law And Economics
Texts
Cooter, Robert and Thomas Ulen. 2011. Law and Economics. Sixth Edition. Boston: Pearson Addison Wesley
(Chapter 1-4)
Polinksky, A. Mitchell. 2011. An Introduction to Law and Economics. Fourth Edition. New York: Aspen Publishers.
(Chapters 1-2)
Posner, Richard A. 2007. Economic Analysis of Law. Seventh Edition. Boston: Little, Brown and Company.
(Chapter 1)
2.) Discuss the adverse impacts of monopoly upon market outcomes. Discuss the impact of government’s monopoly power over coercion.
6.) Suppose the local government determines that the price of food is too high and imposes a ceiling on the market price of food that is below the equilibrium price in that locality. Predict some of the consequences of the ceiling.
10.) Consider the right to smoke or to be free from smoke in the following situations:
1. smoking in a public area.
2. smoking in hotel rooms.
3. smoking in a private residence.
4. smoking on commercial airline flights.
In which situations do you think the transaction costs are so high that they
preclude private bargaining. In what cases are they low enough to allow private
bargains to occur? Explain your answer
14.)From an economic point of view, why is stare decisis an important rule of
decision making for the courts?
.
A Strategic Approach: GenAI in EducationPeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
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.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
2. void initmem(strategies strategy, size_t sz);
void *mymalloc(size_t requested);
void myfree(void* block);
int mem_holes();
int mem_allocated();
int mem_free();
int mem_total();
int mem_largest_free();
int mem_small_free(int size);
char mem_is_alloc(void *ptr);
void* mem_pool();
void print_memory();
void print_memory_status();
void try_mymem(int argc, char **argv);
assign4-2/assign4_part2/memorytests.c
#include <errno.h>
#include <stdlib.h>
3. #include <string.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <unistd.h>
#include "mymem.h"
#include "testrunner.h"
/* performs a randomized test:
totalSize == the total size of the memory pool, as passed to
initmem2
totalSize must be less than 10,000 * minBlockSize
fillRatio == when the allocated memory is >= fillRatio *
totalSize, a block is freed;
otherwise, a new block is allocated.
If a block cannot be allocated, this is tallied and a
random block is freed immediately thereafter in the next
iteration
minBlockSize, maxBlockSize == size for allocated blocks
4. is picked uniformly at random between these two numbers,
inclusive
*/
void do_randomized_test(int strategyToUse, int totalSize, float
fillRatio, int minBlockSize, int maxBlockSize, int iterations)
{
void * pointers[10000];
int storedPointers = 0;
int strategy;
int lbound = 1;
int ubound = 4;
int smallBlockSize = maxBlockSize/10;
if (strategyToUse>0)
lbound=ubound=strategyToUse;
FILE *log;
log = fopen("tests.log","a");
if(log == NULL) {
5. perror("Can't append to log file.n");
return;
}
fprintf(log,"Running randomized tests: pool size == %d,
fill ratio == %f, block size is from %d to %d, %d
iterationsn",totalSize,fillRatio,minBlockSize,maxBlockSize,iter
ations);
fclose(log);
for (strategy = lbound; strategy <= ubound; strategy++)
{
double sum_largest_free = 0;
double sum_hole_size = 0;
double sum_allocated = 0;
int failed_allocations = 0;
double sum_small = 0;
struct timespec execstart, execend;
int force_free = 0;
6. int i;
storedPointers = 0;
initmem(strategy,totalSize);
clock_gettime(CLOCK_REALTIME, &execstart);
for (i = 0; i < iterations; i++)
{
if ( (i % 10000)==0 )
srand ( time(NULL) );
if (!force_free && (mem_free() > (totalSize *
(1-fillRatio))))
{
int newBlockSize =
(rand()%(maxBlockSize-minBlockSize+1))+minBlockSize;
/* allocate */
void * pointer = mymalloc(newBlockSize);
if (pointer != NULL)
9. log = fopen("tests.log","a");
if(log == NULL) {
perror("Can't append to log file.n");
return;
}
fprintf(log,"t=== %s
===n",strategy_name(strategy));
fprintf(log,"tTest took %.2fms.n", (execend.tv_sec -
execstart.tv_sec) * 1000 + (execend.tv_nsec - execstart.tv_nsec)
/ 1000000.0);
fprintf(log,"tAverage hole size:
%fn",sum_hole_size/iterations);
fprintf(log,"tAverage largest free block:
%fn",sum_largest_free/iterations);
fprintf(log,"tAverage allocated bytes:
%fn",sum_allocated/iterations);
fprintf(log,"tAverage number of small blocks:
%fn",sum_small/iterations);
fprintf(log,"tFailed allocations:
%dn",failed_allocations);
fclose(log);
10. }
}
/* run randomized tests against the various strategies with
various parameters */
int do_stress_tests(int argc, char **argv)
{
int strategy = strategyFromString(*(argv+1));
unlink("tests.log"); // We want a new log file
do_randomized_test(strategy,10000,0.25,1,1000,10000);
do_randomized_test(strategy,10000,0.25,1,2000,10000);
do_randomized_test(strategy,10000,0.25,1000,2000,10000)
;
do_randomized_test(strategy,10000,0.25,1,3000,10000);
do_randomized_test(strategy,10000,0.25,1,4000,10000);
12. segfaulting */
}
/* basic sequential allocation of single byte blocks */
int test_alloc_1(int argc, char **argv) {
strategies strategy;
int lbound = 1;
int ubound = 4;
if (strategyFromString(*(argv+1))>0)
lbound=ubound=strategyFromString(*(argv+1));
for (strategy = lbound; strategy <= ubound; strategy++)
{
int correct_holes = 0;
int correct_alloc = 100;
int correct_largest_free = 0;
int i;
13. void* lastPointer = NULL;
initmem(strategy,100);
for (i = 0; i < 100; i++)
{
void* pointer = mymalloc(1);
if ( i > 0 && pointer != (lastPointer+1) )
{
printf("Allocation with %s was not
sequential at %i; expected %p, actual %pn",
strategy_name(strategy), i,lastPointer+1,pointer);
return 1;
}
lastPointer = pointer;
}
if (mem_holes() != correct_holes)
{
printf("Holes not counted as %d with %sn",
correct_holes, strategy_name(strategy));
14. return 1;
}
if (mem_allocated() != correct_alloc)
{
printf("Allocated memory not reported as %d
with %sn", correct_alloc, strategy_name(strategy));
return 1;
}
if (mem_largest_free() != correct_largest_free)
{
printf("Largest memory block free not reported
as %d with %sn", correct_largest_free,
strategy_name(strategy));
return 1;
}
}
15. return 0;
}
/* alloc, alloc, free, alloc */
int test_alloc_2(int argc, char **argv) {
strategies strategy;
int lbound = 1;
int ubound = 4;
if (strategyFromString(*(argv+1))>0)
lbound=ubound=strategyFromString(*(argv+1));
for (strategy = lbound; strategy <= ubound; strategy++)
{
int correct_holes;
int correct_alloc;
16. int correct_largest_free;
int correct_small;
void* first;
void* second;
void* third;
int correctThird;
initmem(strategy,100);
first = mymalloc(10);
second = mymalloc(1);
myfree(first);
third = mymalloc(1);
if (second != (first+10))
{
printf("Second allocation failed; allocated at
incorrect offset with strategy %s", strategy_name(strategy));
return 1;
18. correctThird = (third == first);
correct_holes = 2;
correct_largest_free = 89;
break;
case Next:
correctThird = (third == second+1);
correct_holes = 2;
correct_largest_free = 88;
break;
case NotSet:
break;
}
if (!correctThird)
{
printf("Third allocation failed; allocated at
incorrect offset with %s", strategy_name(strategy));
return 1;
19. }
if (mem_holes() != correct_holes)
{
printf("Holes counted as %d, should be %d with
%sn", mem_holes(), correct_holes, strategy_name(strategy));
return 1;
}
if (mem_small_free(9) != correct_small)
{
printf("Small holes counted as %d, should be %d
with %sn", mem_small_free(9), correct_small,
strategy_name(strategy));
return 1;
}
if (mem_allocated() != correct_alloc)
{
printf("Memory reported as %d, should be %d
20. with %sn", mem_allocated(0), correct_alloc,
strategy_name(strategy));
return 1;
}
if (mem_largest_free() != correct_largest_free)
{
printf("Largest memory block free reported as
%d, should be %d with %sn", mem_largest_free(),
correct_largest_free, strategy_name(strategy));
return 1;
}
}
return 0;
}
/* basic sequential allocation followed by 50 frees */
21. int test_alloc_3(int argc, char **argv) {
strategies strategy;
int lbound = 1;
int ubound = 4;
if (strategyFromString(*(argv+1))>0)
lbound=ubound=strategyFromString(*(argv+1));
for (strategy = lbound; strategy <= ubound; strategy++)
{
int correct_holes = 50;
int correct_alloc = 50;
int correct_largest_free = 1;
int i;
void* lastPointer = NULL;
initmem(strategy,100);
for (i = 0; i < 100; i++)
22. {
void* pointer = mymalloc(1);
if ( i > 0 && pointer != (lastPointer+1) )
{
printf("Allocation with %s was not
sequential at %i; expected %p, actual %pn",
strategy_name(strategy), i,lastPointer+1,pointer);
return 1;
}
lastPointer = pointer;
}
for (i = 1; i < 100; i+= 2)
{
myfree(mem_pool() + i);
}
if (mem_holes() != correct_holes)
{
23. printf("Holes not counted as %d with %sn",
correct_holes, strategy_name(strategy));
return 1;
}
if (mem_allocated() != correct_alloc)
{
printf("Memory not reported as %d with %sn",
correct_alloc, strategy_name(strategy));
return 1;
}
if (mem_largest_free() != correct_largest_free)
{
printf("Largest memory block free not reported
as %d with %sn", correct_largest_free,
strategy_name(strategy));
return 1;
}
24. for(i=0;i<100;i++) {
if(mem_is_alloc(mem_pool()+i) == i%2) {
printf("Byte %d in memory claims to ",i);
if(i%2)
printf("not ");
printf("be allocated. It should ");
if(!i%2)
printf("not ");
printf("be allocated.n");
return 1;
}
}
}
return 0;
}
25. /* basic sequential allocation followed by 50 frees, then another
50 allocs */
int test_alloc_4(int argc, char **argv) {
strategies strategy;
int lbound = 1;
int ubound = 4;
if (strategyFromString(*(argv+1))>0)
lbound=ubound=strategyFromString(*(argv+1));
for (strategy = lbound; strategy <= ubound; strategy++)
{
int correct_holes = 0;
int correct_alloc = 100;
int correct_largest_free = 0;
int i;
void* lastPointer = NULL;
26. initmem(strategy,100);
for (i = 0; i < 100; i++)
{
void* pointer = mymalloc(1);
if ( i > 0 && pointer != (lastPointer+1) )
{
printf("Allocation with %s was not
sequential at %i; expected %p, actual %pn",
strategy_name(strategy), i,lastPointer+1,pointer);
return 1;
}
lastPointer = pointer;
}
for (i = 1; i < 100; i+= 2)
{
myfree(mem_pool() + i);
}
27. for (i = 1; i < 100; i+=2)
{
void* pointer = mymalloc(1);
if ( i > 1 && pointer != (lastPointer+2) )
{
printf("Second allocation with %s was not
sequential at %i; expected %p, actual %pn",
strategy_name(strategy), i,lastPointer+1,pointer);
return 1;
}
lastPointer = pointer;
}
if (mem_holes() != correct_holes)
{
printf("Holes not counted as %d with %sn",
correct_holes, strategy_name(strategy));
return 1;
}
28. if (mem_allocated() != correct_alloc)
{
printf("Memory not reported as %d with %sn",
correct_alloc, strategy_name(strategy));
return 1;
}
if (mem_largest_free() != correct_largest_free)
{
printf("Largest memory block free not reported
as %d with %sn", correct_largest_free,
strategy_name(strategy));
return 1;
}
}
return 0;
}
29. int run_memory_tests(int argc, char **argv)
{
if (argc < 3)
{
printf("Usage: mem -test <test> <strategy> n");
return 0;
}
set_testrunner_default_timeout(20);
/* Tests can be invoked by matching their name or their
suite name or 'all'*/
testentry_t tests[] = {
{"alloc1","suite1",test_alloc_1},
{"alloc2","suite2",test_alloc_2},
{"alloc3","suite1",test_alloc_3},
{"alloc4","suite2",test_alloc_4},
{"stress","suite3",do_stress_tests},
};
30. return
run_testrunner(argc,argv,tests,sizeof(tests)/sizeof(testentry_t));
}
int main(int argc, char **argv)
{
if( argc < 2) {
printf("Usage: mem -test <test> <strategy> | mem -try <arg1>
<arg2> ... n");
exit(-1);
}
else if (!strcmp(argv[1],"-test"))
return run_memory_tests(argc-1,argv+1);
else if (!strcmp(argv[1],"-try")) {
try_mymem(argc-1,argv+1);
return 0;
} else {
printf("Usage: mem -test <test> <strategy> | mem -try <arg1>
31. <arg2> ... n");
exit(-1);
}
}
assign4-2/assign4_part2/testrunner.h
typedef int (*test_fp) (int, char **);
typedef struct
{
char *name;
char *suite;
test_fp test_function;
} testentry_t;
int run_testrunner(int argc, char **argv, testentry_t *entries,int
entry_count);
void set_testrunner_default_timeout(int s);
void set_testrunner_timeout(int s);
assign4-2/assign4_part2/README.txt
LMP2: Memory Management
=======================
This machine problem will focus on memory. You will
implement your own
32. version of malloc() and free(), using a variety of allocation
strategies.
You will be implementing a memory manager for a block of
memory. You will
implement routines for allocating and deallocating memory, and
keeping track of
what memory is in use. You will implement four strategies for
selecting in
which block to place a new requested memory black:
1) First-fit: select the first suitable block with smallest
address.
2) Best-fit: select the smallest suitable block.
3) Worst-fit: select the largest suitable block.
4) Next-fit: select the first suitable block after
the last block allocated (with wraparound
from end to beginning).
Here, "suitable" means "free, and large enough to fit the new
data".
Here are the functions you will need to implement:
initmem():
Initialize memory structures.
mymalloc():
Like malloc(), this allocates a new block of memory.
myfree():
Like free(), this deallocates a block of memory.
mem_holes():
How many free blocks are in memory?
33. mem_allocated():
How much memory is currently allocated?
mem_free():
How much memory is NOT allocated?
mem_largest_free():
How large is the largest free block?
mem_small_free():
How many small unallocated blocks are currently in memory?
mem_is_alloc():
Is a particular byte allocated or not?
We have given you a structure to use to implement these
functions. It is a
doubly-linked list of blocks in memory (both allocated and free
blocks). Every
malloc and free can create new blocks, or combine existing
blocks. You may
modify this structure, or even use a different one entirely.
However, do not
change function prototypes or files other than mymem.c.
IMPORTANT NOTE: Regardless of how you implement
memory management, make sure
that there are no adjacent free blocks. Any such blocks should
be merged into
one large block.
We have also given you a few functions to help you monitor
what happens when you
call your functions. Most important is the try_mymem()
function. If you run
34. your code with "mem -try <args>", it will call this function,
which you can use
to demonstrate the effects of your memory operations. These
functions have no
effect on test code, so use them to your advantage.
Running your code:
After running "make", run
1) "mem" to see the available tests and strategies.
2) "mem -test <test> <strategy>" to test your code with our
tests.
3) "mem -try <args>" to run your code with your own tests
(the try_mymem function).
You can also use "make test" and "make stage1-test" for testing.
"make
stage1-test" only runs the tests relevant to stage 1.
As in previous MPs, running "mem -test -f0 ..." will allow tests
to run even
after previous tests have failed. Similarly, using "all" for a test
or strategy
name runs all of the tests or strategies. Note that if "all" is
selected as the
strategy, the 4 tests are shown as one.
One of the tests, "stress", runs an assortment of randomized
tests on each
strategy. The results of the tests are placed in "tests.out" . You
may want to
view this file to see the relative performance of each strategy.
Stage 1
35. -------
Implement all the above functions, for the first-fit strategy. Use
"mem -test
all first" to test your implementation.
Stage 2
-------
A) Implement the other three strategies: worst-fit, best-fit, and
next-fit. The
strategy is passed to initmem(), and stored in the global variable
"myStrategy".
Some of your functions will need to check this variable to
implement the
correct strategy.
You can test your code with "mem -test all worst", etc., or test
all 4 together
with "mem -test all all". The latter command does not test the
strategies
separately; your code passes the test only if all four strategies
pass.
Questions
=========
1) Why is it so important that adjacent free blocks not be left as
such? What
would happen if they were permitted?
2) Which function(s) need to be concerned about adjacent free
blocks?
36. 3) Name one advantage of each strategy.
4) Run the stress test on all strategies, and look at the results
(tests.out).
What is the significance of "Average largest free block"?
Which strategy
generally has the best performance in this metric? Why do you
think this is?
5) In the stress test results (see Question 4), what is the
significance of
"Average number of small blocks"? Which strategy generally
has the best
performance in this metric? Why do you think this is?
6) Eventually, the many mallocs and frees produces many small
blocks scattered
across the memory pool. There may be enough space to allocate
a new block, but
not in one place. It is possible to compact the memory, so all
the free blocks
are moved to one large free block. How would you implement
this in the system
you have built?
7) If you did implement memory compaction, what changes
would you need to make
in how such a system is invoked (i.e. from a user's perspective)?
8) How would you use the system you have built to implement
realloc? (Brief
explanation; no code)
9) Which function(s) need to know which strategy is being
used? Briefly explain
why this/these and not others.
37. 10) Give one advantage of implementing memory management
using a linked list
over a bit array, where every bit tells whether its corresponding
byte is
allocated.
assign4-2/assign4_part2/mymem.c
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "mymem.h"
#include <time.h>
/* The main structure for implementing memory allocation.
* You may change this to fit your implementation.
*/
struct memoryList
38. {
// doubly-linked list
struct memoryList *last;
struct memoryList *next;
int size; // How many bytes in this block?
char alloc; // 1 if this block is allocated,
// 0 if this block is free.
void *ptr; // location of block in memory pool.
};
strategies myStrategy = NotSet; // Current strategy
size_t mySize;
void *myMemory = NULL;
static struct memoryList *head;
39. static struct memoryList *next;
/* initmem must be called prior to mymalloc and myfree.
initmem may be called more than once in a given exeuction;
when this occurs, all memory you previously malloc'ed
*must* be freed,
including any existing bookkeeping data.
strategy must be one of the following:
- "best" (best-fit)
- "worst" (worst-fit)
- "first" (first-fit)
- "next" (next-fit)
sz specifies the number of bytes that will be available, in
total, for all mymalloc requests.
*/
40. void initmem(strategies strategy, size_t sz)
{
myStrategy = strategy;
/* all implementations will need an actual block of
memory to use */
mySize = sz;
if (myMemory != NULL) free(myMemory); /* in case this
is not the first time initmem2 is called */
/* TODO: release any other memory you were using for
bookkeeping when doing a re-initialization! */
myMemory = malloc(sz);
/* TODO: Initialize memory management structure. */
41. }
/* Allocate a block of memory with the requested size.
* If the requested block is not available, mymalloc returns
NULL.
* Otherwise, it returns a pointer to the newly allocated block.
* Restriction: requested >= 1
*/
void *mymalloc(size_t requested)
{
assert((int)myStrategy > 0);
switch (myStrategy)
{
case NotSet:
return NULL;
case First:
42. return NULL;
case Best:
return NULL;
case Worst:
return NULL;
case Next:
return NULL;
}
return NULL;
}
/* Frees a block of memory previously allocated by mymalloc.
*/
void myfree(void* block)
{
return;
}
43. /****** Memory status/property functions ******
* Implement these functions.
* Note that when we refer to "memory" here, we mean the
* memory pool this module manages via
initmem/mymalloc/myfree.
*/
/* Get the number of contiguous areas of free space in memory.
*/
int mem_holes()
{
return 0;
}
/* Get the number of bytes allocated */
int mem_allocated()
{
return 0;
}
44. /* Number of non-allocated bytes */
int mem_free()
{
return 0;
}
/* Number of bytes in the largest contiguous area of unallocated
memory */
int mem_largest_free()
{
return 0;
}
/* Number of free blocks smaller than "size" bytes. */
int mem_small_free(int size)
{
return 0;
45. }
char mem_is_alloc(void *ptr)
{
return 0;
}
/*
* Feel free to use these functions, but do not modify them.
* The test code uses them, but you may ind them useful.
*/
//Returns a pointer to the memory pool.
void *mem_pool()
{
return myMemory;
}
46. // Returns the total number of bytes in the memory pool. */
int mem_total()
{
return mySize;
}
// Get string name for a strategy.
char *strategy_name(strategies strategy)
{
switch (strategy)
{
case Best:
return "best";
case Worst:
return "worst";
case First:
47. return "first";
case Next:
return "next";
default:
return "unknown";
}
}
// Get strategy from name.
strategies strategyFromString(char * strategy)
{
if (!strcmp(strategy,"best"))
{
return Best;
}
else if (!strcmp(strategy,"worst"))
{
return Worst;
48. }
else if (!strcmp(strategy,"first"))
{
return First;
}
else if (!strcmp(strategy,"next"))
{
return Next;
}
else
{
return 0;
}
}
/*
* These functions are for you to modify however you see fit.
These will not
49. * be used in tests, but you may find them useful for debugging.
*/
/* Use this function to print out the current contents of memory.
*/
void print_memory()
{
return;
}
/* Use this function to track memory allocation performance.
* This function does not depend on your implementation,
* but on the functions you wrote above.
*/
void print_memory_status()
{
printf("%d out of %d bytes
allocated.n",mem_allocated(),mem_total());
printf("%d bytes are free in %d holes; maximum
50. allocatable block is %d
bytes.n",mem_free(),mem_holes(),mem_largest_free());
printf("Average hole size is
%f.nn",((float)mem_free())/mem_holes());
}
/* Use this function to see what happens when your malloc and
free
* implementations are called. Run "mem -try <args>" to call
this function.
* We have given you a simple example to start.
*/
void try_mymem(int argc, char **argv) {
strategies strat;
void *a, *b, *c, *d, *e;
if(argc > 1)
strat = strategyFromString(argv[1]);
else
strat = First;
51. /* A simple example.
Each algorithm should produce a different layout. */
initmem(strat,500);
a = mymalloc(100);
b = mymalloc(100);
c = mymalloc(100);
myfree(b);
d = mymalloc(50);
myfree(a);
e = mymalloc(25);
print_memory();
print_memory_status();
}
54. /* --- Helper macros and functions --- */
#define DIE(mesg)
{fprintf(stderr,"n%s(%d):%sn",__fname__,__LINE__,mesg);
exit(1);}
static int eql( char*s1, char*s2) {return
s1&&s2&&!strcmp(s1,s2);}
/* Callback function for qsort on strings */
static int mystrcmp( const void *p1, const void *p2) {
return eql( ( char*)p1, ( char*)p2);
}
/* Stats of all tests run so far */
typedef struct
{
int ran, passed, failed;
} stats_t;
55. /* -- 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, char **argv)
{
56. char fname[255];
int wait_status;
pid_t wait_val;
struct sigaction action;
assert(!child_pid);
assert(test && test->test_function && test->name);
set_testrunner_timeout(default_timeout_seconds);
errno=0;
child_pid = fork ();
if (child_pid == -1) {
fprintf(stderr,"-fork failed so running test inline-");
return test->test_function (argc, argv);
}
58. 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)
59. 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;
}
}
/*
* 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.
68. test: mem
./mem -test -f0 all all
stage1-test: mem
./mem -test -f0 all first
pretty:
indent *.c *.h -kr
assign4-2/assign4_part2/tests.log
Running randomized tests: pool size == 10000, fill ratio ==
0.250000, block size is from 1 to 1000, 10000 iterations
=== best ===
Test took 0.18ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.16ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
69. Failed allocations: 0
=== first ===
Test took 0.15ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.15ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.250000, block size is from 1 to 2000, 10000 iterations
=== best ===
Test took 0.19ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.15ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.14ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
70. Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.18ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.250000, block size is from 1000 to 2000, 10000 iterations
=== best ===
Test took 0.19ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.19ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.17ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.17ms.
Average hole size: 0.000000
Average largest free block: 0.000000
71. Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.250000, block size is from 1 to 3000, 10000 iterations
=== best ===
Test took 0.19ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.17ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.17ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.17ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.250000, block size is from 1 to 4000, 10000 iterations
=== best ===
72. Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.18ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.19ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.19ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.250000, block size is from 1 to 5000, 10000 iterations
=== best ===
Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
73. === worst ===
Test took 0.21ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.500000, block size is from 1 to 1000, 10000 iterations
=== best ===
Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
74. Failed allocations: 0
=== first ===
Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.20ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.500000, block size is from 1 to 2000, 10000 iterations
=== best ===
Test took 0.13ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.12ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.12ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
75. Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.12ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.500000, block size is from 1000 to 2000, 10000 iterations
=== best ===
Test took 0.12ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.12ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.12ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.11ms.
Average hole size: 0.000000
Average largest free block: 0.000000
76. Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.500000, block size is from 1 to 3000, 10000 iterations
=== best ===
Test took 0.11ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.500000, block size is from 1 to 4000, 10000 iterations
=== best ===
77. Test took 0.11ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.13ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.12ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.500000, block size is from 1 to 5000, 10000 iterations
=== best ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
78. === worst ===
Test took 0.09ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.500000, block size is from 1000 to 1000, 10000 iterations
=== best ===
Test took 0.09ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
79. Failed allocations: 0
=== first ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.750000, block size is from 1 to 1000, 10000 iterations
=== best ===
Test took 0.09ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
80. Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.750000, block size is from 500 to 1000, 10000 iterations
=== best ===
Test took 0.09ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.09ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.09ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
81. Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.750000, block size is from 1 to 2000, 10000 iterations
=== best ===
Test took 0.10ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
Running randomized tests: pool size == 10000, fill ratio ==
0.900000, block size is from 1 to 500, 10000 iterations
=== best ===
82. Test took 0.09ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== worst ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== first ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
=== next ===
Test took 0.08ms.
Average hole size: 0.000000
Average largest free block: 0.000000
Average allocated bytes: 0.000000
Average number of small blocks: 0.000000
Failed allocations: 0
assign4-2/assign4_part1/setup.sh
#!/bin/sh
#*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************
rm -rf ./testdata
mkdir -p
83. ./testdata/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20
echo -n "Hello" > ./testdata/hello.txt
echo -n "OldFile" > ./testdata/oldfile.txt
cp ./testdata/hello.txt ./testdata/1/2/3/4/5/6/7/8/9/10/
cp ./testdata/oldfile.txt ./testdata/1/2/3/4/5/6/7/8/9/
touch -m -d 20050101 ./testdata/oldfile.txt
touch -a -d 20050103 ./testdata/oldfile.txt
if [ ! -f /tmp/bigtestscratchfile2forLMP1 ] ; then
echo "Creating large file (first time only)"
cat /usr/lib/*.so >/tmp/bigtestscratchfile2forLMP1
chmod 644 /tmp/bigtestscratchfile2forLMP1
fi
ln -s /tmp/bigtestscratchfile2forLMP1 ./testdata/bigfile
exit 0
assign4-2/assign4_part1/restart.c
/*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <string.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/wait.h>
#include "restart.h"
#define BLKSIZE PIPE_BUF
#define MILLION 1000000L
#define D_MILLION 1000000.0
84. /* Private functions */
static int gettimeout(struct timeval end, struct timeval
*timeoutp)
{
gettimeofday(timeoutp, NULL);
timeoutp->tv_sec = end.tv_sec - timeoutp->tv_sec;
timeoutp->tv_usec = end.tv_usec - timeoutp->tv_usec;
if (timeoutp->tv_usec >= MILLION) {
timeoutp->tv_sec++;
timeoutp->tv_usec -= MILLION;
}
if (timeoutp->tv_usec < 0) {
timeoutp->tv_sec--;
timeoutp->tv_usec += MILLION;
}
if ((timeoutp->tv_sec < 0) ||
((timeoutp->tv_sec == 0) && (timeoutp->tv_usec == 0))) {
errno = ETIME;
return -1;
}
return 0;
}
/* Restart versions of traditional functions */
int r_close(int fildes)
{
int retval;
while (retval = close(fildes), retval == -1 && errno ==
EINTR);
return retval;
}
int r_dup2(int fildes, int fildes2)
85. {
int retval;
while (retval = dup2(fildes, fildes2), retval == -1 && errno
== EINTR);
return retval;
}
int r_open2(const char *path, int oflag)
{
int retval;
while (retval = open(path, oflag), retval == -1 && errno ==
EINTR);
return retval;
}
int r_open3(const char *path, int oflag, mode_t mode)
{
int retval;
while (retval = open(path, oflag, mode), retval == -1
&& errno == EINTR);
return retval;
}
ssize_t r_read(int fd, void *buf, size_t size)
{
ssize_t retval;
while (retval = read(fd, buf, size), retval == -1 && errno ==
EINTR);
return retval;
}
pid_t r_wait(int *stat_loc)
{
pid_t retval;
while (((retval = wait(stat_loc)) == -1) && (errno ==
97. strcat(names_found, name);
strcat(names_found, "|");
next_line = strtok_r(NULL, "n", &last);
}
quit_if(!strstr(names_found, "|1|"));
quit_if(!strstr(names_found, "|.|"));
quit_if(!strstr(names_found, "|..|"));
quit_if(!strstr(names_found, "|hello.txt|"));
quit_if(!strstr(names_found, "|oldfile.txt|"));
quit_if(!strstr(names_found, "|bigfile|"));
quit_if(entries != 6);
return 0;
}
/* ---------- Suite 4 Tests --------------- */
/* Test file_checksum */
int test_file_checksum(int argc, const char **argv)
{
setup();
char hello[] = "Hello";
unsigned short cksum = checksum(hello, strlen(hello), 0);
quit_if(IOERR_INVALID_ARGS != file_checksum(NULL));
quit_if(cksum != file_checksum(HELLO_FILE));
return 0;
}
/* in setup.sh()
mkdir -p
./testdata/1/2/3/4/5/6/7/8/9/10/11/12/13/14/15/16/17/18/19/20
cp ./testdata/hello.txt ./testdata/1/2/3/4/5/6/7/8/9/10/
cp ./testdata/oldfile.txt ./testdata/1/2/3/4/5/6/7/8/9/
This checksum algorithm commutes so we can calculate the the
final checksum as follows...
*/
98. /* Test dir_checksum */
int test_dir_checksum(int argc, const char **argv)
{
setup();
char dname[10];
int i;
unsigned short cksum;
int cksum2;
quit_if(IOERR_INVALID_ARGS != dir_checksum(NULL));
cksum = checksum("OldFile", 7, checksum("Hello", 5, 0));
for (i = 2; i <= 20; i++) {
sprintf(dname, "%d", i);
cksum = checksum(dname, strlen(dname), cksum);
}
cksum2 = dir_checksum(SUBDIR1_DIR);
quit_if(0 > cksum2);
quit_if(cksum != cksum2);
return 0;
}
/*
* Main entry point for test harness
*/
int run_lmp1_tests(int argc, const char **argv)
{
/* Tests can be invoked by matching their name or their suite
name or 'all' */
testentry_t tests[] = {
{"read", "suite1", test_file_read},
{"info", "suite1", test_file_info},
{"write", "suite1", test_file_write},
100. #if 1
#define VERBOSE(p) (p)
#else
#define VERBOSE(p) (0)
#endif
int file_read(char *path, int offset, void *buffer, size_t
bufbytes)
{
return IOERR_NOT_YET_IMPLEMENTED;
}
int file_info(char *path, void *buffer, size_t bufbytes)
{
if (!path || !buffer || bufbytes < 1)
return IOERR_INVALID_ARGS;
return IOERR_NOT_YET_IMPLEMENTED;
}
int file_write(char *path, int offset, void *buffer, size_t
bufbytes)
{
return IOERR_NOT_YET_IMPLEMENTED;
}
int file_create(char *path, char *pattern, int repeatcount)
{
return IOERR_NOT_YET_IMPLEMENTED;
}
int file_remove(char *path)
{
return IOERR_NOT_YET_IMPLEMENTED;
}
int dir_create(char *path)
101. {
return IOERR_NOT_YET_IMPLEMENTED;
}
int dir_list(char *path, void *buffer, size_t bufbytes)
{
return IOERR_NOT_YET_IMPLEMENTED;
}
int file_checksum(char *path)
{
return IOERR_NOT_YET_IMPLEMENTED;
}
int dir_checksum(char *path)
{
return IOERR_NOT_YET_IMPLEMENTED;
}
assign4-2/assign4_part1/util.c
/*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************/
/* execl*/
#include <unistd.h>
/* errno */
#include <errno.h>
/* waitpid,WEXITSTATUS*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <wait.h>
/* fprintf*/
#include <stdio.h>
#include <string.h>
102. #include "util.h"
/* Print a detailed error message to the given file descriptor.
The pointers f,mesg,src can be null. */
void print_error(FILE * f, int errn, char *mesg, char *src, int
line)
{
char errmesg[255];
*errmesg = '0';
if (strerror_r(errn, errmesg, sizeof(errmesg)))
strcpy(errmesg, "Unknown");
fprintf(f ? f : stderr, "nFAILED AT %s(%d); %s%s.
errno=%d(%s)n",
src ? src : "notset", line, mesg ? "because " : "",
mesg ? mesg : "", errn, errmesg);
}
/* Print a detailed error message and then exit with a status
value of 1.*/
void quit_with_message(int errn, char *mesg, char *src, int
line)
{
print_error(stderr, errn, mesg, src, line);
exit(1);
}
/* Calculate a very simple checksum for a character buffer.*/
unsigned short checksum(char *buffer, size_t sz, unsigned short
val)
{
if ((!buffer) || (!sz))
return val;
while ((sz--) > 0) {
val += *(buffer++);
}
104. /*
* This is a file system benchmark which attempts to study
bottlenecks -
* it is named 'Bonnie' after Bonnie Raitt, who knows how to
use one.
*
* Commentary on Bonnie's operations may be found at
* http://www.textuality.com/bonnie/intro.html
*
* COPYRIGHT NOTICE:
* Copyright (c) Tim Bray, 1990-1996.
*
*/
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#if defined(SysV)
#include <limits.h>
#include <sys/times.h>
#else
#include <sys/resource.h>
#endif
#define IntSize (sizeof(int))
/*
* N.B. in seeker_reports, CPU appears and Start/End time, but
not Elapsed,
105. * so position 1 is re-used; icky data coupling.
*/
#define CPU (0)
#define Elapsed (1)
#define StartTime (1)
#define EndTime (2)
#define Seeks (4000)
#define UpdateSeek (10)
#define SeekProcCount (3)
#define Chunk (16384)
/* labels for the tests, used as an array index */
typedef enum {
Putc, ReWrite, FastWrite, Getc, FastRead, Lseek, TestCount
} tests_t;
static double cpu_so_far();
static void doseek(off_t where, int fd, int update);
static void get_delta_t(tests_t test);
static void io_error(char *message);
static void newfile(char *name, int *fd, FILE * *stream, int
create);
static void fill_file_char();
static void fill_file_block();
static void file_read_rewrite_block();
static void file_read_getc();
static void file_read_chunk();
#if defined(SysV)
/* System V wrappers for randomizers */
static long random();
static void srandom(int seed);
#endif
static void report(char *machine, off_t size);
106. static double time_so_far();
static void timestamp();
static void usage();
/*
* Housekeeping variables to build up timestamps for the tests;
* global to make it easy to keep track of the progress of time.
* all of this could have been done with non-global variables,
* but the code is easier to read this way and I don't anticipate
* much software engineering down the road
*/
static int basetime; /* when we started */
static double delta[(int) TestCount][2]; /* array of DeltaT
values */
static double last_cpustamp = 0.0; /* for computing delta-t */
static double last_timestamp = 0.0; /* for computing delta-t */
char name[Chunk];
FILE *stream;
int fd;
off_t words;
off_t size;
int buf[Chunk / IntSize];
int bufindex;
int chars[256];
int next;
/* entry point for LMP1 */
int bonnie_main(int argc, char **argv)
{
int child;
char *dir;
double first_start;
double last_stop;
int lseek_count = 0;
char *machine;
107. int seek_control[2];
int seek_feedback[2];
char seek_tickets[Seeks + SeekProcCount];
double seeker_report[3];
fd = -1;
basetime = (int) time((time_t *) NULL);
size = 100;
dir = ".";
machine = "";
/* parse the argument sent from the command line */
for (next = 1; next < argc; next++) {
if (strcmp(argv[next], "-s") == 0)
size = atol(argv[++next]);
else if (strcmp(argv[next], "-m") == 0)
machine = argv[++next];
else
usage();
}
if (size < 1) {
usage();
}
/*
CHECK SYSTEM CAPABILITY:
We proceed to check the size of files because 32-bit
machines has a limit
*/
if (sizeof(off_t) <= 4 && size > 2047) {
fprintf(stderr, "File too large for 32-bit machine, sorryn");
exit(1);
}
sprintf(name, "%s/LMP1.%d", dir, getpid());
108. /* The size is in Megabytes, and is rounded down to
multiples of Chunk */
size *= (1024 * 1024);
size = Chunk * (size / Chunk);
fprintf(stderr, "File '%s', size: %ldn", name, size);
fill_file_char(name, &fd, &stream); /* For specific details
please go down to the body of this function */
file_read_rewrite_block(name, &fd, &stream); /* For
specific details please go down to the body of this function */
fill_file_block(name, &fd, &stream); /* For specific details
please go down to the body of this function */
file_read_getc(name, &fd, &stream); /* For specific details
please go down to the body of this function */
/* use the frequency count */
for (words = 0; words < 256; words++)
sprintf((char *) buf, "%d", chars[words]);
file_read_chunk(name, &fd, &stream); /* For specific
details please go down to the body of this function */
/* use the frequency count */
for (words = 0; words < 256; words++)
sprintf((char *) buf, "%d", chars[words]);
/*
* Now test random seeks; first, set up for communicating
with children.
* The object of this e game is to do "Seeks" lseek() calls as
quickly
* as possible. So we'll farm them out among
SeekProcCount processes.
* We'll control them by writing 1-byte tickets down a pipe
which
* the children all read. We write "Seeks" bytes with val 1,
109. whichever
* child happens to get them does it and the right number of
seeks get
* done.
* The idea is that since the write() of the tickets is probably
* atomic, the parent process likely won't get scheduled
while the
* children are seeking away. If you draw a picture of the
likely
* timelines for three children, it seems likely that the seeks
will
* overlap very nicely with the process scheduling with the
effect
* that there will *always* be a seek() outstanding on the
file.
* Question: should the file be opened *before* the fork, so
that
* all the children are lseeking on the same underlying file
object?
*/
if (pipe(seek_feedback) == -1 || pipe(seek_control) == -1)
io_error("pipe");
for (next = 0; next < Seeks; next++)
seek_tickets[next] = 1;
for (; next < (Seeks + SeekProcCount); next++)
seek_tickets[next] = 0;
/* launch some parallel seek processes */
for (next = 0; next < SeekProcCount; next++) { /* for each
seek proc */
if ((child = fork()) == -1)
io_error("fork");
else if (child == 0) { /* child process */
/* set up and wait for the go-ahead */
close(seek_feedback[0]);
close(seek_control[1]);
110. newfile(name, &fd, &stream, 0);
srandom(getpid());
fprintf(stderr, "Seeker %d...", next + 1);
/* wait for the go-ahead */
if (read(seek_control[0], seek_tickets, 1) != 1)
io_error("read ticket");
timestamp();
seeker_report[StartTime] = time_so_far();
/* loop until we read a 0 ticket back from our parent */
while (seek_tickets[0]) { /* until Mom says stop */
doseek((long) (random() % (size / Chunk)), fd,
((lseek_count++ % UpdateSeek) == 0));
if (read(seek_control[0], seek_tickets, 1) != 1)
io_error("read ticket");
} /* until Mom says stop */
if (close(fd) == -1)
io_error("close after seek");
/* report to parent */
get_delta_t(Lseek);
seeker_report[EndTime] = time_so_far();
seeker_report[CPU] = delta[(int) Lseek][CPU];
if (write
(seek_feedback[1], seeker_report,
sizeof(seeker_report)) != sizeof(seeker_report))
io_error("pipe write");
exit(0);
} /* child process */
} /* for each seek proc */
/*
* Back in the parent; in an effort to ensure the children get
an even
* start, wait a few seconds for them to get scheduled, open
111. their
* files & so on.
*/
close(seek_feedback[1]);
close(seek_control[0]);
sleep(5);
fprintf(stderr, "start 'em...");
if (write(seek_control[1], seek_tickets, sizeof(seek_tickets))
!=
sizeof(seek_tickets))
io_error("write tickets");
/* read back from children */
for (next = 0; next < SeekProcCount; next++) { /* for each
child */
if (read
(seek_feedback[0], (char *) seeker_report,
sizeof(seeker_report)) != sizeof(seeker_report))
io_error("pipe read");
/*
* each child writes back its CPU, start & end times. The
elapsed time
* to do all the seeks is the time the first child started
until the
* time the last child stopped
*/
delta[(int) Lseek][CPU] += seeker_report[CPU];
if (next == 0) {/* first time */
first_start = seeker_report[StartTime];
last_stop = seeker_report[EndTime];
} /* first time */
else { /* not first time */
first_start = (first_start < seeker_report[StartTime]) ?
first_start : seeker_report[StartTime];
last_stop = (last_stop > seeker_report[EndTime]) ?
112. last_stop : seeker_report[EndTime];
} /* not first time */
if (wait(&child) == -1)
io_error("wait");
fprintf(stderr, "done...");
} /* for each child */
fprintf(stderr, "n");
delta[(int) Lseek][Elapsed] = last_stop - first_start;
report(machine, size);
unlink(name);
return EXIT_SUCCESS;
}
/****************************************************
*****************/
/* FUNCTION report */
/****************************************************
*****************/
/* INPUT: Machine description and size of file
*/
/****************************************************
*****************/
/* PROCESS: */
/* 1. Print in the monitor the results from the */
/* operations the program supports. */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void report(char *machine, off_t size)
{
printf(" ");
114. delta[(int) FastRead][CPU] / delta[(int)
FastRead][Elapsed] *
100.0);
printf("%5.1f %4.1fn",
((double) Seeks) / delta[(int) Lseek][Elapsed],
delta[(int) Lseek][CPU] / delta[(int) Lseek][Elapsed] *
100.0);
}
/****************************************************
*****************/
/* FUNCTION newfile */
/****************************************************
*****************/
/* INPUT: Name of the file, File Descriptor, Buffer, Create Flag
*/
/****************************************************
*****************/
/* PROCESS: */
/* 1. If Create Flag is one */
/* i) Checks if the file is unlinked */
/* a) If it is not returns error */
/* ii) Obatain File Descriptor with proper parameters
*/
/* and flags.NOTE: Use man pages to view the specific
*/
/* parameters open uses. Make sure you understand
*/
/* the return values, and see the errors the function */
/* returns) */
/* Else Create flag is not equal to zero */
/* Obtain file descriptor with proper parameters and
*/
/* flags.(NOTE: Use man pages to view the specific
*/
115. /* parameters open uses. Make sure you understand
*/
/* the return values, and see the errors the function */
/* returns) */
/* 2. Fill buffer when calling fdopen with proper */
/* parameters and flags.(NOTE: Use man pages to view
the */
/* specific parameters open uses. Make sure you
understand */
/* the return values, and see the errors the function */
/* returns) */
/* 3. Check stream */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void newfile(char *name, int *fd, FILE ** stream, int
create)
{
if (create) {
if (unlink(name) == -1 && *fd != -1)
io_error("unlink");
*fd = open(name, O_RDWR | O_CREAT | O_EXCL,
0777);
} else
*fd = open(name, O_RDWR, 0777);
if (*fd == -1)
io_error(name);
*stream = fdopen(*fd, "r+");
if (*stream == NULL)
io_error("fdopen");
}
116. /****************************************************
*****************/
/* FUNCTION fill_file_char */
/****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Open file */
/* 2. Record timestamp */
/* 3. For cycle to fill the file one character at a time*/
/* until it reaches the EndOfFile(EOF) */
/* 4. Close file */
/* 5. Call get_delta_t to find the performance of putc */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void fill_file_char()
{
fprintf(stderr, "FUNCTION fill_file_char() start...");
newfile(name, &fd, &stream, 1);
timestamp();
for (words = 0; words < size; words++)
if (putc(words & 0x7f, stream) == EOF)
io_error("putc");
if (fclose(stream) == -1)
io_error("fclose after putc");
get_delta_t(Putc);
fprintf(stderr, "...done FUNCTION file_fill_char()n");
}
117. /****************************************************
*****************/
/* FUNCTION fill_file_block */
/****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Open file */
/* 2. Initialize every position of the buffer */
/* 3. Record timestamp */
/* 4. FOR cycle so for each word you need to: */
/* i) properly set the buffer index so that it points */
/* at the correct position. */
/* ii) Call write.(NOTE: Use man pages to view the
*/
/* specific parameters write uses. Make sure you */
/* understand the return values, and see the errors */
/* the function returns) */
/* 4. Close file */
/* 5. Call get_delta_t to find the performance of putc */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void fill_file_block()
{
fprintf(stderr, "FUNCTION fill_file_block() start...");
newfile(name, &fd, &stream, 1);
for (words = 0; words < Chunk / IntSize; words++)
buf[words] = 0;
timestamp();
118. for (words = bufindex = 0; words < (size / Chunk); words++)
{
if (bufindex == (Chunk / IntSize))
bufindex = 0;
buf[bufindex++]++;
if (write(fd, (char *) buf, Chunk) == -1)
io_error("write(2)");
}
if (close(fd) == -1)
io_error("close after fast write");
get_delta_t(FastWrite);
fprintf(stderr, "...done FUNCTION fill_file_block()n");
}
/****************************************************
*****************/
/* FUNCTION file_read_rewrite_block */
/****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Open file */
/* 2. Call lseek. (NOTE: Use man pages to view the
*/
/* specific parameters lseek uses. Make sure you
*/
/* understand the return values, and see the errors the
*/
/* function returns) */
/* 3. Record timestamp */
/* 4. Make sure the buffer index point to zero */
/* 5. Call read. (NOTE: Use man pages to view the
*/
/* specific parameters read uses. Make sure you
119. */
/* understand the return values, and see the errors the
*/
/* function returns) */
/* 6. While we can read a block, increment the index to
*/
/* point to the the next position. Call lseek and call */
/* write.(NOTE: Use man pages to view the specific
*/
/* parameters write uses. Make sure you understand the
*/
/* return values,and see the errors the function */
/* returns) */
/* Call read until the while condition is false. */
/* 7. Close file */
/* 8. Call get_delta_t to find the performance of putc */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void file_read_rewrite_block()
{
fprintf(stderr, "FUNCTION file_read_rewrite() start...");
newfile(name, &fd, &stream, 0);
if (lseek(fd, (off_t) 0, 0) == (off_t) - 1)
io_error("lseek(2) before rewrite");
fprintf(stderr, "Rewriting");
timestamp();
bufindex = 0;
if ((words = read(fd, (char *) buf, Chunk)) == -1)
io_error("rewrite read");
while (words == Chunk) {
120. if (bufindex == Chunk / IntSize)
bufindex = 0;
buf[bufindex++]++;
if (lseek(fd, (off_t) - words, 1) == -1)
io_error("relative lseek(2)");
if (write(fd, (char *) buf, words) == -1)
io_error("re write(2)");
if ((words = read(fd, (char *) buf, Chunk)) == -1)
io_error("rwrite read");
}
if (close(fd) == -1)
io_error("close after rewrite");
get_delta_t(ReWrite);
fprintf(stderr, "...done FUNCTION
file_read_rewrite_block()n");
}
/****************************************************
*****************/
/* FUNCTION file_read_getc */
/****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Open file */
/* 2. Initialize every position of the buffer words */
/* 3. Record timestamp */
/* 4. FOR cycle to fill the file 1 byte at a time until */
/* it reaches the EndOfFile(EOF).Make sure you notice
*/
/* the increment of the index pointing at chars */
/* 7. Close file */
121. /* 8. Call get_delta_t to find the performance of getc */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void file_read_getc()
{
fprintf(stderr, "FUNCTION fill_read_getc() start...");
newfile(name, &fd, &stream, 0);
for (words = 0; words < 256; words++)
chars[words] = 0;
timestamp();
for (words = 0; words < size; words++) {
if ((next = getc(stream)) == EOF)
io_error("getc(3)");
chars[next]++;
}
if (fclose(stream) == -1)
io_error("fclose after getc");
get_delta_t(Getc);
fprintf(stderr, "...done FUNCTION file_read_getc()n");
}
/****************************************************
*****************/
/* FUNCTION file_read_chunk */
/****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
122. /* 1. Open file */
/* 2. Call lseek().(NOTE:Use man pages to view the
*/
/* specific */
/* parameters write uses. Make sure you understand the
*/
/* return values,and see the errors the function */
/* returns) */
/* 3. Record timestamp */
/* 6. DO cycle read a block.(NOTE: Use man pages to
view*/
/* the specific parameters read uses. Make sure you
*/
/* understand the return values, and see the errors the
*/
/* function returns) Call read until the while condition is
*/
/* false. */
/* 7. Close file */
/* 8. Call get_delta_t to find the performance of getc */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void file_read_chunk()
{
fprintf(stderr, "FUNCTION file_read_chunk() start...");
newfile(name, &fd, &stream, 0);
if (lseek(fd, (off_t) 0, 0) == -1)
io_error("lseek before read");
timestamp();
do {
if ((words = read(fd, (char *) buf, Chunk)) == -1)
123. io_error("read(2)");
chars[buf[abs(buf[0]) % (Chunk / IntSize)] & 0x7f]++;
} while (words);
if (close(fd) == -1)
io_error("close after read");
get_delta_t(FastRead);
fprintf(stderr, "...done FUNCTION file_read_chunk()n");
}
/****************************************************
*****************/
/* FUNCTION usage */
/****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Presents all the options the program has */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void usage()
{
fprintf(stderr, "usage: ./lmp1 [-s size-in-Mb] [-m machine-
label]n");
exit(1);
}
/****************************************************
*****************/
/* FUNCTION timestamp */
124. /****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Call time_so_far() and store it in last_timestamp */
/* 2. Call cpu_so_far() and store it in last_cpustamp */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void timestamp()
{
last_timestamp = time_so_far();
last_cpustamp = cpu_so_far();
}
/****************************************************
*****************/
/* FUNCTION get_delta_t */
/****************************************************
*****************/
/* INPUT: Receives the structure tests_t */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Identifies the procedure that was executed */
/* 2. Calls time_so_far() and deletes the value of */
/* of the global variable last_timestamp obtaining the
time */
/* the procedure spent. */
/* 3. Calls cpu_so_far() and substracts the value of */
125. /* of the global variable last_cpustamp obtaining the
*/
/* amount of CPU procedure spent. */
/****************************************************
*****************/
/* OUTPUT: doesn´t return any value because it is void
*/
/****************************************************
*****************/
static void get_delta_t(test)
tests_t test;
{
int which = (int) test;
delta[which][Elapsed] = time_so_far() - last_timestamp;
delta[which][CPU] = cpu_so_far() - last_cpustamp;
}
/****************************************************
*****************/
/* FUNCTION cpu_so_far */
/****************************************************
*****************/
/* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Identifies the System to check some variables */
/* if SysV */
/* i) Creates a structure tms. */
/* ii) returns the CPU time after adding over */
/* certain fields in the tms structure. */
/* Else */
/* i) Creates a structure rusage. */
/* ii) Calls getrusage().(NOTE: Use man pages */
/* to view the specific parameters write uses. */
126. /* Make sure you understand the return values, */
/* and see the errors the function returns). */
/* iii) returns the CPU time after adding over */
/* certain fields in the rusage structure. */
/****************************************************
*****************/
/* OUTPUT: return the CPU usage until the time it has been
called */
/****************************************************
*****************/
static double cpu_so_far()
{
#if defined(SysV)
struct tms tms;
if (times(&tms) == -1)
io_error("times");
return ((double) tms.tms_utime) / ((double)
sysconf(_SC_CLK_TCK)) +
((double) tms.tms_stime) / ((double)
sysconf(_SC_CLK_TCK));
#else
struct rusage rusage;
getrusage(RUSAGE_SELF, &rusage);
return ((double) rusage.ru_utime.tv_sec) +
(((double) rusage.ru_utime.tv_usec) / 1000000.0) +
((double) rusage.ru_stime.tv_sec) +
(((double) rusage.ru_stime.tv_usec) / 1000000.0);
#endif
}
/****************************************************
*****************/
/* FUNCTION time_so_far */
/****************************************************
*****************/
127. /* INPUT: does not receive any parameter */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Identifies the System to check some variables */
/* if SysV */
/* i) Creates a structure tms. */
/* ii) Call the times function and assign the */
/* value it returns to the variable val */
/* iii) returns the CPU time after dividing val*/
/* by the returning value from sysconf() */
/* Else */
/* i) Creates a structure timeval tp. */
/* ii) Calls gettimeofday().(NOTE:Use man
pages*/
/* to view the specific parameters */
/* gettimeofday uses. Make sure you understand
*/
/* the return values, and see the errors the */
/* function returns). */
/* iii) returns the CPU time after substractin */
/* certain fields in the tp structure. */
/****************************************************
*****************/
/* OUTPUT: return the time it has been used */
/****************************************************
*****************/
static double time_so_far()
{
#if defined(SysV)
int val;
struct tms tms;
if ((val = times(&tms)) == -1)
io_error("times");
128. return ((double) val) / ((double) sysconf(_SC_CLK_TCK));
#else
struct timeval tp;
if (gettimeofday(&tp, (struct timezone *) NULL) == -1)
io_error("gettimeofday");
return ((double) (tp.tv_sec - basetime)) +
(((double) tp.tv_usec) / 1000000.0);
#endif
}
/****************************************************
*****************/
/* FUNCTION io_error */
/****************************************************
*****************/
/* INPUT: Receives the error string */
/****************************************************
*****************/
/* PROCESS: */
/* 1. Call perror().(NOTE:Use man pages to view the
*/
/* specific parameters gettimeofday uses. Make sure you
*/
/* understand the return values, and see the errors the
*/
/* function returns). */
/* 2. Call exit().(NOTE:Use man pages to view the
*/
/* specific parameters gettimeofday uses. Make sure you
*/
/* understand the return values, and see the errors the
*/
/* function returns). */
/****************************************************
*****************/
129. /* OUTPUT: return the time it has been used */
/****************************************************
*****************/
static void io_error(char *message)
{
char buf[Chunk];
sprintf(buf, "Program: drastic I/O error (%s)", message);
perror(buf);
exit(1);
}
/*
* Do a typical-of-something random I/O. Any serious
application that
* has a random I/O bottleneck is going to be smart enough to
operate
* in a page mode.
* The 'where' argument is used as a chunk number
* To keep the cache from getting too clever, some pages must
be updated.
* However an application that updated each of many random
pages that
* it looked at is hard to imagine.
* However, it would be wrong to put the update percentage in
as a
* parameter - the effect is too nonlinear.
*/
static void doseek(off_t where, int fd, int update)
{
int buf[Chunk / IntSize];
off_t probe;
off_t size;
probe = where * Chunk;
if (lseek(fd, probe, 0) != probe)
130. io_error("lseek in doseek");
if ((size = read(fd, (char *) buf, Chunk)) == -1)
io_error("read in doseek");
/* every so often, update a block */
if (update) { /* update this block */
/* touch a word */
buf[((int) random() % (size / IntSize - 2)) + 1]--;
if (lseek(fd, (long) probe, 0) != probe)
io_error("lseek in doseek update");
if (write(fd, (char *) buf, size) == -1)
io_error("write in doseek");
} /* update this block */
}
#if defined(SysV)
static char randseed[32];
static void srandom(int seed)
{
sprintf(randseed, "%06d", seed);
}
static long random()
{
return nrand48(randseed);
}
#endif
assign4-2/assign4_part1/testrunner.h
/*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************/
typedef int (*test_fp) (int, const char **);
131. 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);
assign4-2/assign4_part1/teardown.sh
#!/bin/sh
#*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************
rm -rf ./testdata
assign4-2/assign4_part1/restart.h
/*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************/
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#ifndef ETIME
#define ETIME ETIMEDOUT
#endif
struct timeval add2currenttime(double seconds);
132. int copyfile(int fromfd, int tofd);
int r_close(int fildes);
int r_dup2(int fildes, int fildes2);
int r_open2(const char *path, int oflag);
int r_open3(const char *path, int oflag, mode_t mode);
ssize_t r_read(int fd, void *buf, size_t size);
pid_t r_wait(int *stat_loc);
pid_t r_waitpid(pid_t pid, int *stat_loc, int options);
ssize_t r_write(int fd, void *buf, size_t size);
ssize_t readblock(int fd, void *buf, size_t size);
int readline(int fd, char *buf, int nbytes);
ssize_t readtimed(int fd, void *buf, size_t nbyte, double
seconds);
int readwrite(int fromfd, int tofd);
int readwriteblock(int fromfd, int tofd, char *buf, int size);
int waitfdtimed(int fd, struct timeval end);
assign4-2/assign4_part1/util.h
/*************** YOU SHOULD NOT MODIFY ANYTHING
IN THIS FILE ***************/
#include <stdlib.h>
/* stdlib required for size_t */
#define quit_if_ne(p1,p2) {if((p1) != (p2))
quit_with_message((int)errno,"" #p1 "!=" #p2
,__FILE__,__LINE__);}
#define quit_if(mutley) {if(mutley)
quit_with_message((int)errno, #mutley,__FILE__,__LINE__);}
#define quit(mesg)
{quit_with_message((int)errno,mesg,__FILE__,__LINE__);}
void quit_with_message(int errn, char *mesg, char *src, int
line);
133. unsigned short checksum(char *buffer, size_t sz, unsigned short
val);
assign4-2/assign4_part1/fileio.h
#include <stdlib.h>
#define IOERR_INVALID_ARGS (-1)
#define IOERR_INVALID_PATH (-2)
#define IOERR_POSIX (-3)
#define IOERR_BUFFER_TOO_SMALL (-4)
#define IOERR_NOT_YET_IMPLEMENTED (-5)
/* You will implement all of the following functions in fileio.c.
*/
/*
ERROR HANDLING
These functions will support basic error handling:
If the arguments are bad (e.g., a pointer is NULL), then the
function should immediately return
IOERR_INVALID_ARGS.
If a POSIX error occurs, the function should return
IOERR_POSIX,
unless the error is due to a bad path, in which case the return
value is IOERR_INVALID_PATH.
These functions do not return if a POSIX function is
interrupted by
a signal; only dirlist returns IOERR_BUFFER_TOO_SMALL
(see below).
You may find some of the library functions in restart.c
useful.
134. COMMON PARAMETERS
path - file to be read
offest - where to start reading/writing from
buffer - buffer to write bytes into
bufbytes - maximum number of bytes to read
FUNCTION DESCRIPTIONS
int file_read(char *path, int offset, void *buffer, size_t
bufbytes);
Reads bytes from a file into the buffer.
Return value: >=0 number of bytes read, <0 ERROR (see
above)
int file_info(char *path, void *buffer, size_t bufbytes)
Writes into buffer a string that describes meta information
about
the file. The string is in format:
"Size:NNN Accessed:NNN Modified:NNN Type X"
X can be 'f' or 'd' (file or directory, respectively)
Size is in bytes
Accessed and Modified - accessed and modified times
(seconds since epoch)
int file_write(char *path, int offset, void *buffer, size_t
bufbytes);
Writes bytes from 'buffer' into file 'path' at position 'offset'.
Return value: >0 number of bytes written, <0 ERROR (see
above)
int file_create(char *path, char *pattern, int repeatcount);
Creates a new file with the string 'pattern' repeated
'repeatcount'
times.
Return value:0 Success , <0 ERROR (see above)
135. int file_remove(char *path);
Removes an existing file if it exists.
Return value: 0 file removed, <0 ERROR (see above)
int dir_create(char *path);
Creates a new directory.
Return value: 0 directory created, <0 ERROR (see above)
int dir_list(char *path, void *buffer, size_t bufbytes);
Writes a list file and directory names inside path (including
"."
and ".." entries). Each entry is line terminated with the
newline
character 'n'.
Return value: 0 success, <0 ERROR (see above)
Returns IOERR_BUFFER_TOO_SMALL if the buffer is not
large enough to
write all entries.
Hint: man opendir, readdir, closedir
int file_checksum(char *path)
Calculates a checksum value calculated by summing all the
bytes of a
file using an unsigned short.
Return value: >=0 checksum value, <0 ERROR (see above)
Hint: use the checksum function in util.c
int dir_checksum(char *path);
Recursively calculated a checksum: checksums of regular
files are
calculated using file_checksum; directory entries are
traversed,
also the subdirectory names are included in the checksum
calculation
See lmp1_tests.c for details of what we are looking for.
Return value: >=0 checksum value, <0 ERROR (see above)